Default implementation for BroadcastRadio AIDL HAL

Default implementation for BroadcastRadio AIDL HAL is based on
default implementation for HIDL 2.0, with necessary data type
conversion. The callback for IBroadcastRadio interface is
initialized as nullptr.

Bug: 170336130
Test: m -j
Change-Id: Id521573116c565c42af16333cad73c5dd0583420
diff --git a/broadcastradio/aidl/default/Android.bp b/broadcastradio/aidl/default/Android.bp
new file mode 100644
index 0000000..720aa8a
--- /dev/null
+++ b/broadcastradio/aidl/default/Android.bp
@@ -0,0 +1,54 @@
+//
+// Copyright (C) 2022 The Android Open Source Project
+//
+// 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.
+//
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "hardware_interfaces_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
+cc_binary {
+    name: "android.hardware.broadcastradio-service.default",
+    relative_install_path: "hw",
+    init_rc: ["broadcastradio-default.rc"],
+    vintf_fragments: ["broadcastradio-default.xml"],
+    vendor: true,
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+    ],
+    srcs: [
+        "BroadcastRadio.cpp",
+        "main.cpp",
+        "VirtualProgram.cpp",
+        "VirtualRadio.cpp",
+    ],
+    static_libs: [
+        "android.hardware.broadcastradio@common-utils-aidl-lib",
+        "android.hardware.broadcastradio@common-utils-lib",
+    ],
+    shared_libs: [
+        "android.hardware.broadcastradio-V1-ndk",
+        "libbase",
+        "libbinder_ndk",
+        "liblog",
+        "libcutils",
+    ],
+}
diff --git a/broadcastradio/aidl/default/BroadcastRadio.cpp b/broadcastradio/aidl/default/BroadcastRadio.cpp
new file mode 100644
index 0000000..57c5133
--- /dev/null
+++ b/broadcastradio/aidl/default/BroadcastRadio.cpp
@@ -0,0 +1,473 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#include "BroadcastRadio.h"
+#include <broadcastradio-utils-aidl/Utils.h>
+#include "resources.h"
+
+#include <aidl/android/hardware/broadcastradio/IdentifierType.h>
+#include <aidl/android/hardware/broadcastradio/Result.h>
+
+#include <android-base/logging.h>
+
+namespace aidl::android::hardware::broadcastradio {
+
+using ::aidl::android::hardware::broadcastradio::utils::resultToInt;
+using ::aidl::android::hardware::broadcastradio::utils::tunesTo;
+using ::ndk::ScopedAStatus;
+using ::std::literals::chrono_literals::operator""ms;
+using ::std::literals::chrono_literals::operator""s;
+using ::std::lock_guard;
+using ::std::mutex;
+using ::std::string;
+using ::std::vector;
+
+namespace {
+
+inline constexpr std::chrono::milliseconds kSeekDelayTimeMs = 200ms;
+inline constexpr std::chrono::milliseconds kStepDelayTimeMs = 100ms;
+inline constexpr std::chrono::milliseconds kTuneDelayTimeMs = 150ms;
+inline constexpr std::chrono::seconds kListDelayTimeS = 1s;
+
+// clang-format off
+const AmFmRegionConfig kDefaultAmFmConfig = {
+        {
+                {87500, 108000, 100, 100},  // FM
+                {153, 282, 3, 9},           // AM LW
+                {531, 1620, 9, 9},          // AM MW
+                {1600, 30000, 1, 5},        // AM SW
+        },
+        AmFmRegionConfig::DEEMPHASIS_D50,
+        AmFmRegionConfig::RDS};
+// clang-format on
+
+Properties initProperties(const VirtualRadio& virtualRadio) {
+    Properties prop = {};
+
+    prop.maker = "Android";
+    prop.product = virtualRadio.getName();
+    prop.supportedIdentifierTypes = vector<IdentifierType>({
+            IdentifierType::AMFM_FREQUENCY_KHZ,
+            IdentifierType::RDS_PI,
+            IdentifierType::HD_STATION_ID_EXT,
+            IdentifierType::DAB_SID_EXT,
+    });
+    prop.vendorInfo = vector<VendorKeyValue>({
+            {"com.android.sample", "sample"},
+    });
+
+    return prop;
+}
+
+// Makes ProgramInfo that does not point to any particular program
+ProgramInfo makeSampleProgramInfo(const ProgramSelector& selector) {
+    ProgramInfo info = {};
+    info.selector = selector;
+    info.logicallyTunedTo =
+            utils::makeIdentifier(IdentifierType::AMFM_FREQUENCY_KHZ,
+                                  utils::getId(selector, IdentifierType::AMFM_FREQUENCY_KHZ));
+    info.physicallyTunedTo = info.logicallyTunedTo;
+    return info;
+}
+
+}  // namespace
+
+BroadcastRadio::BroadcastRadio(const VirtualRadio& virtualRadio)
+    : mVirtualRadio(virtualRadio),
+      mAmFmConfig(kDefaultAmFmConfig),
+      mProperties(initProperties(virtualRadio)) {
+    const auto& ranges = kDefaultAmFmConfig.ranges;
+    if (ranges.size() > 0) {
+        ProgramSelector sel = utils::makeSelectorAmfm(ranges[0].lowerBound);
+        VirtualProgram virtualProgram = {};
+        if (mVirtualRadio.getProgram(sel, &virtualProgram)) {
+            mCurrentProgram = virtualProgram.selector;
+        } else {
+            mCurrentProgram = sel;
+        }
+    }
+}
+
+BroadcastRadio::~BroadcastRadio() {
+    mThread.reset();
+}
+
+ScopedAStatus BroadcastRadio::getAmFmRegionConfig(bool full, AmFmRegionConfig* returnConfigs) {
+    if (full) {
+        *returnConfigs = {};
+        returnConfigs->ranges = vector<AmFmBandRange>({
+                {65000, 108000, 10, 0},  // FM
+                {150, 30000, 1, 0},      // AM
+        });
+        returnConfigs->fmDeemphasis =
+                AmFmRegionConfig::DEEMPHASIS_D50 | AmFmRegionConfig::DEEMPHASIS_D75;
+        returnConfigs->fmRds = AmFmRegionConfig::RDS | AmFmRegionConfig::RBDS;
+        return ScopedAStatus::ok();
+    }
+    lock_guard<mutex> lk(mMutex);
+    *returnConfigs = mAmFmConfig;
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::getDabRegionConfig(vector<DabTableEntry>* returnConfigs) {
+    *returnConfigs = {
+            {"5A", 174928},  {"7D", 194064},  {"8A", 195936},  {"8B", 197648},  {"9A", 202928},
+            {"9B", 204640},  {"9C", 206352},  {"10B", 211648}, {"10C", 213360}, {"10D", 215072},
+            {"11A", 216928}, {"11B", 218640}, {"11C", 220352}, {"11D", 222064}, {"12A", 223936},
+            {"12B", 225648}, {"12C", 227360}, {"12D", 229072},
+    };
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::getImage(int32_t id, vector<uint8_t>* returnImage) {
+    LOG(DEBUG) << __func__ << ": fetching image " << std::hex << id;
+
+    if (id == resources::kDemoPngId) {
+        *returnImage = vector<uint8_t>(resources::kDemoPng, std::end(resources::kDemoPng));
+        return ScopedAStatus::ok();
+    }
+
+    LOG(WARNING) << __func__ << ": image of id " << std::hex << id << " doesn't exist";
+    *returnImage = {};
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::getProperties(Properties* returnProperties) {
+    lock_guard<mutex> lk(mMutex);
+    *returnProperties = mProperties;
+    return ScopedAStatus::ok();
+}
+
+ProgramInfo BroadcastRadio::tuneInternalLocked(const ProgramSelector& sel) {
+    LOG(DEBUG) << __func__ << ": tune (internal) to " << sel.toString();
+
+    VirtualProgram virtualProgram = {};
+    ProgramInfo programInfo;
+    if (mVirtualRadio.getProgram(sel, &virtualProgram)) {
+        mCurrentProgram = virtualProgram.selector;
+        programInfo = virtualProgram;
+    } else {
+        mCurrentProgram = sel;
+        programInfo = makeSampleProgramInfo(sel);
+    }
+    mIsTuneCompleted = true;
+
+    return programInfo;
+}
+
+ScopedAStatus BroadcastRadio::setTunerCallback(const std::shared_ptr<ITunerCallback>& callback) {
+    LOG(DEBUG) << __func__ << ": setTunerCallback";
+
+    if (callback == nullptr) {
+        return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+                resultToInt(Result::INVALID_ARGUMENTS), "cannot set tuner callback to null");
+    }
+
+    lock_guard<mutex> lk(mMutex);
+    mCallback = callback;
+
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::unsetTunerCallback() {
+    LOG(DEBUG) << __func__ << ": unsetTunerCallback";
+
+    lock_guard<mutex> lk(mMutex);
+    mCallback = nullptr;
+
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::tune(const ProgramSelector& program) {
+    LOG(DEBUG) << __func__ << ": tune to " << program.toString() << "...";
+
+    lock_guard<mutex> lk(mMutex);
+    if (mCallback == nullptr) {
+        LOG(ERROR) << __func__ << ": callback is not registered.";
+        return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+                resultToInt(Result::INVALID_STATE), "callback is not registered");
+    }
+
+    if (!utils::isSupported(mProperties, program)) {
+        LOG(WARNING) << __func__ << ": selector not supported: " << program.toString();
+        return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+                resultToInt(Result::NOT_SUPPORTED), "selector is not supported");
+    }
+
+    if (!utils::isValid(program)) {
+        LOG(ERROR) << __func__ << ": selector is not valid: " << program.toString();
+        return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+                resultToInt(Result::INVALID_ARGUMENTS), "selector is not valid");
+    }
+
+    cancelLocked();
+
+    mIsTuneCompleted = false;
+    std::shared_ptr<ITunerCallback> callback = mCallback;
+    auto task = [this, program, callback]() {
+        ProgramInfo programInfo = {};
+        {
+            lock_guard<mutex> lk(mMutex);
+            programInfo = tuneInternalLocked(program);
+        }
+        callback->onCurrentProgramInfoChanged(programInfo);
+    };
+    mThread->schedule(task, kTuneDelayTimeMs);
+
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::seek(bool directionUp, bool skipSubChannel) {
+    LOG(DEBUG) << __func__ << ": seek " << (directionUp ? "up" : "down") << " with skipSubChannel? "
+               << (skipSubChannel ? "yes" : "no") << "...";
+
+    lock_guard<mutex> lk(mMutex);
+    if (mCallback == nullptr) {
+        LOG(ERROR) << __func__ << ": callback is not registered.";
+        return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+                resultToInt(Result::INVALID_STATE), "callback is not registered");
+    }
+
+    cancelLocked();
+
+    const auto& list = mVirtualRadio.getProgramList();
+    std::shared_ptr<ITunerCallback> callback = mCallback;
+    if (list.empty()) {
+        mIsTuneCompleted = false;
+        auto task = [callback]() {
+            LOG(DEBUG) << "seek: program list is empty, seek couldn't stop";
+
+            callback->onTuneFailed(Result::TIMEOUT, {});
+        };
+        mThread->schedule(task, kSeekDelayTimeMs);
+
+        return ScopedAStatus::ok();
+    }
+
+    // The list is not sorted here since it has already stored in VirtualRadio.
+    // If the list is not sorted in advance, it should be sorted here.
+    const auto& current = mCurrentProgram;
+    auto found = std::lower_bound(list.begin(), list.end(), VirtualProgram({current}));
+    if (directionUp) {
+        if (found < list.end() - 1) {
+            if (tunesTo(current, found->selector)) found++;
+        } else {
+            found = list.begin();
+        }
+    } else {
+        if (found > list.begin() && found != list.end()) {
+            found--;
+        } else {
+            found = list.end() - 1;
+        }
+    }
+    const ProgramSelector tuneTo = found->selector;
+
+    mIsTuneCompleted = false;
+    auto task = [this, tuneTo, callback]() {
+        ProgramInfo programInfo = {};
+        {
+            lock_guard<mutex> lk(mMutex);
+            programInfo = tuneInternalLocked(tuneTo);
+        }
+        callback->onCurrentProgramInfoChanged(programInfo);
+    };
+    mThread->schedule(task, kSeekDelayTimeMs);
+
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::step(bool directionUp) {
+    LOG(DEBUG) << __func__ << ": step " << (directionUp ? "up" : "down") << "...";
+
+    lock_guard<mutex> lk(mMutex);
+    if (mCallback == nullptr) {
+        LOG(ERROR) << __func__ << ": callback is not registered.";
+        return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+                resultToInt(Result::INVALID_STATE), "callback is not registered");
+    }
+
+    cancelLocked();
+
+    if (!utils::hasId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ)) {
+        LOG(WARNING) << __func__ << ": can't step in anything else than AM/FM";
+        return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+                resultToInt(Result::NOT_SUPPORTED), "cannot step in anything else than AM/FM");
+    }
+
+    int64_t stepTo = utils::getId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ);
+    std::optional<AmFmBandRange> range = getAmFmRangeLocked();
+    if (!range) {
+        LOG(ERROR) << __func__ << ": can't find current band or tune operation is in process";
+        ScopedAStatus::fromServiceSpecificErrorWithMessage(
+                resultToInt(Result::INTERNAL_ERROR),
+                "can't find current band or tune operation is in process");
+    }
+
+    if (directionUp) {
+        stepTo += range->spacing;
+    } else {
+        stepTo -= range->spacing;
+    }
+    if (stepTo > range->upperBound) {
+        stepTo = range->lowerBound;
+    }
+    if (stepTo < range->lowerBound) {
+        stepTo = range->upperBound;
+    }
+
+    mIsTuneCompleted = false;
+    std::shared_ptr<ITunerCallback> callback = mCallback;
+    auto task = [this, stepTo, callback]() {
+        ProgramInfo programInfo;
+        {
+            lock_guard<mutex> lk(mMutex);
+            programInfo = tuneInternalLocked(utils::makeSelectorAmfm(stepTo));
+        }
+        callback->onCurrentProgramInfoChanged(programInfo);
+    };
+    mThread->schedule(task, kStepDelayTimeMs);
+
+    return ScopedAStatus::ok();
+}
+
+void BroadcastRadio::cancelLocked() {
+    LOG(DEBUG) << __func__ << ": cancelling current operations...";
+
+    mThread->cancelAll();
+    if (mCurrentProgram.primaryId.type != IdentifierType::INVALID) {
+        mIsTuneCompleted = true;
+    }
+}
+
+ScopedAStatus BroadcastRadio::cancel() {
+    LOG(DEBUG) << __func__ << ": cancel pending tune, seek and step...";
+
+    lock_guard<mutex> lk(mMutex);
+    cancelLocked();
+
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::startProgramListUpdates(const ProgramFilter& filter) {
+    LOG(DEBUG) << __func__ << ": requested program list updates, filter = " << filter.toString()
+               << "...";
+
+    auto filterCb = [&filter](const VirtualProgram& program) {
+        return utils::satisfies(filter, program.selector);
+    };
+
+    lock_guard<mutex> lk(mMutex);
+
+    const auto& list = mVirtualRadio.getProgramList();
+    vector<VirtualProgram> filteredList;
+    std::copy_if(list.begin(), list.end(), std::back_inserter(filteredList), filterCb);
+
+    auto task = [this, filteredList]() {
+        std::shared_ptr<ITunerCallback> callback;
+        {
+            lock_guard<mutex> lk(mMutex);
+            if (mCallback == nullptr) {
+                LOG(WARNING) << "Callback is null when updating program List";
+                return;
+            }
+            callback = mCallback;
+        }
+
+        ProgramListChunk chunk = {};
+        chunk.purge = true;
+        chunk.complete = true;
+        chunk.modified = vector<ProgramInfo>(filteredList.begin(), filteredList.end());
+
+        callback->onProgramListUpdated(chunk);
+    };
+    mThread->schedule(task, kListDelayTimeS);
+
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::stopProgramListUpdates() {
+    LOG(DEBUG) << __func__ << ": requested program list updates to stop...";
+    // TODO(b/243681584) Implement stop program list updates method
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::isConfigFlagSet(ConfigFlag flag, [[maybe_unused]] bool* returnIsSet) {
+    LOG(DEBUG) << __func__ << ": flag = " << toString(flag);
+
+    LOG(INFO) << __func__ << ": getting ConfigFlag is not supported";
+    return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+            resultToInt(Result::NOT_SUPPORTED), "getting ConfigFlag is not supported");
+}
+
+ScopedAStatus BroadcastRadio::setConfigFlag(ConfigFlag flag, bool value) {
+    LOG(DEBUG) << __func__ << ": flag = " << toString(flag) << ", value = " << value;
+
+    LOG(INFO) << __func__ << ": setting ConfigFlag is not supported";
+    return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+            resultToInt(Result::NOT_SUPPORTED), "setting ConfigFlag is not supported");
+}
+
+ScopedAStatus BroadcastRadio::setParameters(
+        [[maybe_unused]] const vector<VendorKeyValue>& parameters,
+        vector<VendorKeyValue>* returnParameters) {
+    // TODO(b/243682330) Support vendor parameter functionality
+    *returnParameters = {};
+    return ScopedAStatus::ok();
+}
+
+ScopedAStatus BroadcastRadio::getParameters([[maybe_unused]] const vector<string>& keys,
+                                            vector<VendorKeyValue>* returnParameters) {
+    // TODO(b/243682330) Support vendor parameter functionality
+    *returnParameters = {};
+    return ScopedAStatus::ok();
+}
+
+std::optional<AmFmBandRange> BroadcastRadio::getAmFmRangeLocked() const {
+    if (!mIsTuneCompleted) {
+        LOG(WARNING) << __func__ << ": tune operation is in process";
+        return {};
+    }
+    if (!utils::hasId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ)) {
+        LOG(WARNING) << __func__ << ": current program does not has AMFM_FREQUENCY_KHZ identifier";
+        return {};
+    }
+
+    int64_t freq = utils::getId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ);
+    for (const auto& range : mAmFmConfig.ranges) {
+        if (range.lowerBound <= freq && range.upperBound >= freq) {
+            return range;
+        }
+    }
+
+    return {};
+}
+
+ScopedAStatus BroadcastRadio::registerAnnouncementListener(
+        [[maybe_unused]] const std::shared_ptr<IAnnouncementListener>& listener,
+        const vector<AnnouncementType>& enabled, std::shared_ptr<ICloseHandle>* returnCloseHandle) {
+    LOG(DEBUG) << __func__ << ": registering announcement listener for "
+               << utils::vectorToString(enabled);
+
+    // TODO(b/243683842) Support announcement listener
+    *returnCloseHandle = nullptr;
+    LOG(INFO) << __func__ << ": registering announcementListener is not supported";
+    return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+            resultToInt(Result::NOT_SUPPORTED),
+            "registering announcementListener is not supported");
+}
+
+}  // namespace aidl::android::hardware::broadcastradio
diff --git a/broadcastradio/aidl/default/BroadcastRadio.h b/broadcastradio/aidl/default/BroadcastRadio.h
new file mode 100644
index 0000000..52d394e
--- /dev/null
+++ b/broadcastradio/aidl/default/BroadcastRadio.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include "VirtualRadio.h"
+
+#include <aidl/android/hardware/broadcastradio/AmFmBandRange.h>
+#include <aidl/android/hardware/broadcastradio/AmFmRegionConfig.h>
+#include <aidl/android/hardware/broadcastradio/AnnouncementType.h>
+#include <aidl/android/hardware/broadcastradio/BnBroadcastRadio.h>
+#include <aidl/android/hardware/broadcastradio/DabTableEntry.h>
+#include <aidl/android/hardware/broadcastradio/IAnnouncementListener.h>
+#include <aidl/android/hardware/broadcastradio/ICloseHandle.h>
+#include <aidl/android/hardware/broadcastradio/ITunerCallback.h>
+#include <aidl/android/hardware/broadcastradio/Properties.h>
+#include <broadcastradio-utils/WorkerThread.h>
+
+#include <android-base/thread_annotations.h>
+
+#include <optional>
+
+namespace aidl::android::hardware::broadcastradio {
+
+class BroadcastRadio final : public BnBroadcastRadio {
+  public:
+    explicit BroadcastRadio(const VirtualRadio& virtualRadio);
+    ~BroadcastRadio();
+    ndk::ScopedAStatus getAmFmRegionConfig(bool full, AmFmRegionConfig* returnConfigs) override;
+    ndk::ScopedAStatus getDabRegionConfig(std::vector<DabTableEntry>* returnConfigs) override;
+    ndk::ScopedAStatus getImage(int32_t id, std::vector<uint8_t>* returnImage) override;
+    ndk::ScopedAStatus getProperties(Properties* returnProperties) override;
+
+    ndk::ScopedAStatus setTunerCallback(const std::shared_ptr<ITunerCallback>& callback) override;
+    ndk::ScopedAStatus unsetTunerCallback() override;
+    ndk::ScopedAStatus tune(const ProgramSelector& program) override;
+    ndk::ScopedAStatus seek(bool directionUp, bool skipSubChannel) override;
+    ndk::ScopedAStatus step(bool directionUp) override;
+    ndk::ScopedAStatus cancel() override;
+    ndk::ScopedAStatus startProgramListUpdates(const ProgramFilter& filter) override;
+    ndk::ScopedAStatus stopProgramListUpdates() override;
+    ndk::ScopedAStatus isConfigFlagSet(ConfigFlag flag, bool* returnIsSet) override;
+    ndk::ScopedAStatus setConfigFlag(ConfigFlag flag, bool in_value) override;
+    ndk::ScopedAStatus setParameters(const std::vector<VendorKeyValue>& parameters,
+                                     std::vector<VendorKeyValue>* returnParameters) override;
+    ndk::ScopedAStatus getParameters(const std::vector<std::string>& keys,
+                                     std::vector<VendorKeyValue>* returnParameters) override;
+    ndk::ScopedAStatus registerAnnouncementListener(
+            const std::shared_ptr<IAnnouncementListener>& listener,
+            const std::vector<AnnouncementType>& enabled,
+            std::shared_ptr<ICloseHandle>* returnCloseHandle) override;
+
+  private:
+    const VirtualRadio& mVirtualRadio;
+    std::mutex mMutex;
+    AmFmRegionConfig mAmFmConfig GUARDED_BY(mMutex);
+    std::unique_ptr<::android::WorkerThread> mThread GUARDED_BY(mMutex) =
+            std::unique_ptr<::android::WorkerThread>(new ::android::WorkerThread());
+    bool mIsTuneCompleted GUARDED_BY(mMutex) = true;
+    Properties mProperties GUARDED_BY(mMutex);
+    ProgramSelector mCurrentProgram GUARDED_BY(mMutex) = {};
+    std::shared_ptr<ITunerCallback> mCallback GUARDED_BY(mMutex);
+
+    std::optional<AmFmBandRange> getAmFmRangeLocked() const;
+    void cancelLocked();
+    ProgramInfo tuneInternalLocked(const ProgramSelector& sel);
+};
+
+}  // namespace aidl::android::hardware::broadcastradio
diff --git a/broadcastradio/aidl/default/VirtualProgram.cpp b/broadcastradio/aidl/default/VirtualProgram.cpp
new file mode 100644
index 0000000..0df0a82
--- /dev/null
+++ b/broadcastradio/aidl/default/VirtualProgram.cpp
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#include "VirtualProgram.h"
+
+#include <broadcastradio-utils-aidl/Utils.h>
+#include "resources.h"
+
+#include <android-base/logging.h>
+
+namespace aidl::android::hardware::broadcastradio {
+
+using ::std::vector;
+
+VirtualProgram::operator ProgramInfo() const {
+    ProgramInfo info = {};
+
+    info.selector = selector;
+
+    IdentifierType programType = selector.primaryId.type;
+    bool isDigital = (programType != IdentifierType::AMFM_FREQUENCY_KHZ &&
+                      programType != IdentifierType::RDS_PI);
+
+    auto selectId = [&info](const IdentifierType& type) {
+        return utils::makeIdentifier(type, utils::getId(info.selector, type));
+    };
+
+    switch (programType) {
+        case IdentifierType::AMFM_FREQUENCY_KHZ:
+            info.logicallyTunedTo = info.physicallyTunedTo =
+                    selectId(IdentifierType::AMFM_FREQUENCY_KHZ);
+            break;
+        case IdentifierType::RDS_PI:
+            info.logicallyTunedTo = selectId(IdentifierType::RDS_PI);
+            info.physicallyTunedTo = selectId(IdentifierType::AMFM_FREQUENCY_KHZ);
+            break;
+        case IdentifierType::HD_STATION_ID_EXT:
+            info.logicallyTunedTo = selectId(IdentifierType::HD_STATION_ID_EXT);
+            info.physicallyTunedTo = selectId(IdentifierType::AMFM_FREQUENCY_KHZ);
+            break;
+        case IdentifierType::DAB_SID_EXT:
+            info.logicallyTunedTo = selectId(IdentifierType::DAB_SID_EXT);
+            info.physicallyTunedTo = selectId(IdentifierType::DAB_ENSEMBLE);
+            break;
+        case IdentifierType::DRMO_SERVICE_ID:
+            info.logicallyTunedTo = selectId(IdentifierType::DRMO_SERVICE_ID);
+            info.physicallyTunedTo = selectId(IdentifierType::DRMO_FREQUENCY_KHZ);
+            break;
+        case IdentifierType::SXM_SERVICE_ID:
+            info.logicallyTunedTo = selectId(IdentifierType::SXM_SERVICE_ID);
+            info.physicallyTunedTo = selectId(IdentifierType::SXM_CHANNEL);
+            break;
+        default:
+            LOG(FATAL) << "unsupported program type: " << toString(programType);
+            return {};
+    }
+
+    info.infoFlags |= (ProgramInfo::FLAG_TUNABLE | ProgramInfo::FLAG_STEREO);
+    info.signalQuality = isDigital ? kSignalQualityDigital : kSignalQualityNonDigital;
+
+    info.metadata = vector<Metadata>({
+            Metadata::make<Metadata::rdsPs>(programName),
+            Metadata::make<Metadata::songTitle>(songTitle),
+            Metadata::make<Metadata::songArtist>(songArtist),
+            Metadata::make<Metadata::stationIcon>(resources::kDemoPngId),
+            Metadata::make<Metadata::albumArt>(resources::kDemoPngId),
+    });
+
+    info.vendorInfo = vector<VendorKeyValue>({
+            {"com.android.sample", "sample"},
+            {"com.android.sample.VirtualProgram", "VirtualProgram"},
+    });
+
+    return info;
+}
+
+bool operator<(const VirtualProgram& lhs, const VirtualProgram& rhs) {
+    auto& l = lhs.selector;
+    auto& r = rhs.selector;
+
+    // Two programs with the same primaryId are considered the same.
+    if (l.primaryId.type != r.primaryId.type) return l.primaryId.type < r.primaryId.type;
+
+    return l.primaryId.value < r.primaryId.value;
+}
+
+}  // namespace aidl::android::hardware::broadcastradio
diff --git a/broadcastradio/aidl/default/VirtualProgram.h b/broadcastradio/aidl/default/VirtualProgram.h
new file mode 100644
index 0000000..0c20721
--- /dev/null
+++ b/broadcastradio/aidl/default/VirtualProgram.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include <aidl/android/hardware/broadcastradio/IdentifierType.h>
+#include <aidl/android/hardware/broadcastradio/ProgramInfo.h>
+#include <aidl/android/hardware/broadcastradio/ProgramSelector.h>
+
+namespace aidl::android::hardware::broadcastradio {
+
+constexpr int kSignalQualityDigital = 100;
+constexpr int kSignalQualityNonDigital = 80;
+/**
+ * A radio program mock.
+ *
+ * This represents broadcast waves flying over the air,
+ * not an entry for a captured station in the radio tuner memory.
+ */
+struct VirtualProgram {
+    ProgramSelector selector;
+
+    std::string programName = "";
+    std::string songArtist = "";
+    std::string songTitle = "";
+
+    operator ProgramInfo() const;
+
+    /**
+     * Defines order in which virtual programs appear on the "air" with
+     * ITunerSession::scan().
+     *
+     * It's for default implementation purposes, may not be complete or correct.
+     */
+    friend bool operator<(const VirtualProgram& lhs, const VirtualProgram& rhs);
+};
+
+}  // namespace aidl::android::hardware::broadcastradio
diff --git a/broadcastradio/aidl/default/VirtualRadio.cpp b/broadcastradio/aidl/default/VirtualRadio.cpp
new file mode 100644
index 0000000..851543b
--- /dev/null
+++ b/broadcastradio/aidl/default/VirtualRadio.cpp
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#include "VirtualRadio.h"
+#include <broadcastradio-utils-aidl/Utils.h>
+
+namespace aidl::android::hardware::broadcastradio {
+
+using ::aidl::android::hardware::broadcastradio::utils::makeSelectorAmfm;
+using ::aidl::android::hardware::broadcastradio::utils::makeSelectorDab;
+using ::std::string;
+using ::std::vector;
+
+VirtualRadio::VirtualRadio(const string& name, const vector<VirtualProgram>& initialList)
+    : mName(name), mPrograms(initialList) {
+    sort(mPrograms.begin(), mPrograms.end());
+}
+
+string VirtualRadio::getName() const {
+    return mName;
+}
+
+const vector<VirtualProgram>& VirtualRadio::getProgramList() const {
+    return mPrograms;
+}
+
+bool VirtualRadio::getProgram(const ProgramSelector& selector, VirtualProgram* programOut) const {
+    for (const auto& program : mPrograms) {
+        if (utils::tunesTo(selector, program.selector)) {
+            *programOut = program;
+            return true;
+        }
+    }
+    return false;
+}
+
+// get singleton of AMFM Virtual Radio
+const VirtualRadio& VirtualRadio::getAmFmRadio() {
+    // clang-format off
+    static VirtualRadio amFmRadioMock(
+        "AM/FM radio mock",
+        {
+            {makeSelectorAmfm(94900), "Wild 94.9", "Drake ft. Rihanna", "Too Good"},
+            {makeSelectorAmfm(96500), "KOIT", "Celine Dion", "All By Myself"},
+            {makeSelectorAmfm(97300), "Alice@97.3", "Drops of Jupiter", "Train"},
+            {makeSelectorAmfm(99700), "99.7 Now!", "The Chainsmokers", "Closer"},
+            {makeSelectorAmfm(101300), "101-3 KISS-FM", "Justin Timberlake", "Rock Your Body"},
+            {makeSelectorAmfm(103700), "iHeart80s @ 103.7", "Michael Jackson", "Billie Jean"},
+            {makeSelectorAmfm(106100), "106 KMEL", "Drake", "Marvins Room"},
+            {makeSelectorAmfm(700), "700 AM", "Artist700", "Title700"},
+            {makeSelectorAmfm(1700), "1700 AM", "Artist1700", "Title1700"},
+        });
+    // clang-format on
+    return amFmRadioMock;
+}
+
+// get singleton of DAB Virtual Radio
+const VirtualRadio& VirtualRadio::getDabRadio() {
+    // clang-format off
+    static VirtualRadio dabRadioMock(
+        "DAB radio mock",
+        {
+            {makeSelectorDab(0xA00001u, 0x0001u), "BBC Radio 1", "Khalid", "Talk"},
+            {makeSelectorDab(0xB00001u, 0x1001u), "Classic FM", "Jean Sibelius", "Andante Festivo"},
+            {makeSelectorDab(0xB00002u, 0x1001u), "Absolute Radio", "Coldplay", "Clocks"},
+        });
+    // clang-format on
+    return dabRadioMock;
+}
+
+}  // namespace aidl::android::hardware::broadcastradio
diff --git a/broadcastradio/aidl/default/VirtualRadio.h b/broadcastradio/aidl/default/VirtualRadio.h
new file mode 100644
index 0000000..ae039c4
--- /dev/null
+++ b/broadcastradio/aidl/default/VirtualRadio.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include "VirtualProgram.h"
+
+#include <vector>
+
+namespace aidl::android::hardware::broadcastradio {
+
+/**
+ * A radio frequency space mock.
+ *
+ * This represents all broadcast waves in the air for a given radio technology,
+ * not a captured station list in the radio tuner memory.
+ *
+ * It's meant to abstract out radio content from default tuner implementation.
+ */
+class VirtualRadio final {
+  public:
+    VirtualRadio(const std::string& name, const std::vector<VirtualProgram>& initialList);
+    std::string getName() const;
+    const std::vector<VirtualProgram>& getProgramList() const;
+    bool getProgram(const ProgramSelector& selector, VirtualProgram* program) const;
+
+    static const VirtualRadio& getAmFmRadio();
+    static const VirtualRadio& getDabRadio();
+
+  private:
+    const std::string mName;
+    std::vector<VirtualProgram> mPrograms;
+};
+
+}  // namespace aidl::android::hardware::broadcastradio
diff --git a/broadcastradio/aidl/default/broadcastradio-default.rc b/broadcastradio/aidl/default/broadcastradio-default.rc
new file mode 100644
index 0000000..49389e6
--- /dev/null
+++ b/broadcastradio/aidl/default/broadcastradio-default.rc
@@ -0,0 +1,6 @@
+service vendor.broadcastradio-default /vendor/bin/hw/android.hardware.broadcastradio-service.default
+    interface aidl android.hardware.broadcastradio.IBroadcastRadio/amfm
+    interface aidl android.hardware.broadcastradio.IBroadcastRadio/dab
+    class hal
+    user audioserver
+    group audio
diff --git a/broadcastradio/aidl/default/broadcastradio-default.xml b/broadcastradio/aidl/default/broadcastradio-default.xml
new file mode 100644
index 0000000..1555822
--- /dev/null
+++ b/broadcastradio/aidl/default/broadcastradio-default.xml
@@ -0,0 +1,7 @@
+<manifest version="1.0" type="device">
+    <hal format="aidl">
+        <name>android.hardware.broadcastradio</name>
+        <fqname>IBroadcastRadio/amfm</fqname>
+        <fqname>IBroadcastRadio/dab</fqname>
+    </hal>
+</manifest>
diff --git a/broadcastradio/aidl/default/main.cpp b/broadcastradio/aidl/default/main.cpp
new file mode 100644
index 0000000..6bf20d5
--- /dev/null
+++ b/broadcastradio/aidl/default/main.cpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#include "BroadcastRadio.h"
+#include "VirtualRadio.h"
+
+#include <android-base/logging.h>
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+
+using ::aidl::android::hardware::broadcastradio::BroadcastRadio;
+using ::aidl::android::hardware::broadcastradio::VirtualRadio;
+
+int main() {
+    android::base::SetDefaultTag("BcRadioAidlDef");
+    ABinderProcess_setThreadPoolMaxThreadCount(4);
+    ABinderProcess_startThreadPool();
+
+    const VirtualRadio& amFmRadioMock = VirtualRadio::getAmFmRadio();
+    std::shared_ptr<BroadcastRadio> broadcastRadio =
+            ::ndk::SharedRefBase::make<BroadcastRadio>(amFmRadioMock);
+    const std::string instanceAmFm = std::string() + BroadcastRadio::descriptor + "/amfm";
+    binder_status_t statusAmFm =
+            AServiceManager_addService(broadcastRadio->asBinder().get(), instanceAmFm.c_str());
+    CHECK_EQ(statusAmFm, STATUS_OK)
+            << "Failed to register Broadcast Radio AM/FM HAL implementation";
+
+    const VirtualRadio& dabRadioMock = VirtualRadio::getDabRadio();
+    std::shared_ptr<BroadcastRadio> dabRadio =
+            ::ndk::SharedRefBase::make<BroadcastRadio>(dabRadioMock);
+    const std::string instanceDab = std::string() + BroadcastRadio::descriptor + "/dab";
+    binder_status_t statusDab =
+            AServiceManager_addService(dabRadio->asBinder().get(), instanceDab.c_str());
+    CHECK_EQ(statusDab, STATUS_OK) << "Failed to register Broadcast Radio DAB HAL implementation";
+
+    ABinderProcess_joinThreadPool();
+    return EXIT_FAILURE;  // should not reach
+}
diff --git a/broadcastradio/aidl/default/resources.h b/broadcastradio/aidl/default/resources.h
new file mode 100644
index 0000000..beffc76
--- /dev/null
+++ b/broadcastradio/aidl/default/resources.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include <aidl/android/hardware/broadcastradio/ProgramSelector.h>
+
+namespace aidl::android::hardware::broadcastradio::resources {
+
+constexpr int32_t kDemoPngId = 123456;
+constexpr uint8_t kDemoPng[] = {
+        0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
+        0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25,
+        0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x5d, 0x49, 0x44, 0x41, 0x54, 0x68, 0xde, 0xed, 0xd9,
+        0xc1, 0x09, 0x00, 0x30, 0x08, 0x04, 0xc1, 0x33, 0xfd, 0xf7, 0x6c, 0x6a, 0xc8, 0x23, 0x04,
+        0xc9, 0x6c, 0x01, 0xc2, 0x20, 0xbe, 0x4c, 0x86, 0x57, 0x49, 0xba, 0xfb, 0xd6, 0xf4, 0xba,
+        0x3e, 0x7f, 0x4d, 0xdf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x8f, 0x00, 0xbd, 0xce, 0x7f,
+        0xc0, 0x11, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0xb8, 0x0d, 0x32, 0xd4, 0x0c, 0x77, 0xbd,
+        0xfb, 0xc1, 0xce, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82};
+
+}  // namespace aidl::android::hardware::broadcastradio::resources
diff --git a/broadcastradio/common/utilsaidl/Android.bp b/broadcastradio/common/utilsaidl/Android.bp
new file mode 100644
index 0000000..fa6de19
--- /dev/null
+++ b/broadcastradio/common/utilsaidl/Android.bp
@@ -0,0 +1,50 @@
+//
+// Copyright (C) 2022 The Android Open Source Project
+//
+// 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.
+//
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "hardware_interfaces_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
+cc_library_static {
+    name: "android.hardware.broadcastradio@common-utils-aidl-lib",
+    vendor_available: true,
+    relative_install_path: "hw",
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+        "-Wno-error=implicit-fallthrough",
+    ],
+    cppflags: [
+        "-std=c++1z",
+    ],
+    srcs: [
+        "Utils.cpp",
+    ],
+    export_include_dirs: ["include"],
+    shared_libs: [
+        "android.hardware.broadcastradio-V1-ndk",
+        "libbase",
+    ],
+    static_libs: [
+        "libmath",
+    ],
+}
diff --git a/broadcastradio/common/utilsaidl/Utils.cpp b/broadcastradio/common/utilsaidl/Utils.cpp
new file mode 100644
index 0000000..a284651
--- /dev/null
+++ b/broadcastradio/common/utilsaidl/Utils.cpp
@@ -0,0 +1,477 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#define LOG_TAG "BcRadioAidlDef.utils"
+
+#include "broadcastradio-utils-aidl/Utils.h"
+
+#include <android-base/logging.h>
+
+#include <math/HashCombine.h>
+
+namespace aidl::android::hardware::broadcastradio {
+
+namespace utils {
+
+namespace {
+
+using ::std::string;
+using ::std::vector;
+
+const int64_t kValueForNotFoundIdentifier = 0;
+
+bool bothHaveId(const ProgramSelector& a, const ProgramSelector& b, const IdentifierType& type) {
+    return hasId(a, type) && hasId(b, type);
+}
+
+bool haveEqualIds(const ProgramSelector& a, const ProgramSelector& b, const IdentifierType& type) {
+    if (!bothHaveId(a, b, type)) {
+        return false;
+    }
+    /* We should check all Ids of a given type (ie. other AF),
+     * but it doesn't matter for default implementation.
+     */
+    return getId(a, type) == getId(b, type);
+}
+
+int getHdSubchannel(const ProgramSelector& sel) {
+    int64_t hdSidExt = getId(sel, IdentifierType::HD_STATION_ID_EXT, /* defaultValue */ 0);
+    hdSidExt >>= 32;        // Station ID number
+    return hdSidExt & 0xF;  // HD Radio subchannel
+}
+
+bool maybeGetId(const ProgramSelector& sel, const IdentifierType& type, int64_t* val) {
+    // iterate through primaryId and secondaryIds
+    for (auto it = begin(sel); it != end(sel); it++) {
+        if (it->type == type) {
+            if (val != nullptr) {
+                *val = it->value;
+            }
+            return true;
+        }
+    }
+
+    return false;
+}
+
+}  // namespace
+
+IdentifierIterator::IdentifierIterator(const ProgramSelector& sel) : IdentifierIterator(sel, 0) {}
+
+IdentifierIterator::IdentifierIterator(const ProgramSelector& sel, size_t pos)
+    : mSel(sel), mPos(pos) {}
+
+const IdentifierIterator IdentifierIterator::operator++(int) {
+    IdentifierIterator i = *this;
+    mPos++;
+    return i;
+}
+
+IdentifierIterator& IdentifierIterator::operator++() {
+    ++mPos;
+    return *this;
+}
+
+IdentifierIterator::refType IdentifierIterator::operator*() const {
+    if (mPos == 0) {
+        return getSelector().primaryId;
+    }
+
+    // mPos is 1-based for secondary identifiers
+    DCHECK(mPos <= getSelector().secondaryIds.size());
+    return getSelector().secondaryIds[mPos - 1];
+}
+
+bool IdentifierIterator::operator==(const IdentifierIterator& rhs) const {
+    // Check, if both iterators points at the same selector.
+    if (reinterpret_cast<intptr_t>(&getSelector()) !=
+        reinterpret_cast<intptr_t>(&rhs.getSelector())) {
+        return false;
+    }
+
+    return mPos == rhs.mPos;
+}
+
+int32_t resultToInt(Result result) {
+    return static_cast<int32_t>(result);
+}
+
+FrequencyBand getBand(int64_t freq) {
+    // keep in sync with
+    // frameworks/base/services/core/java/com/android/server/broadcastradio/aidl/Utils.java
+    if (freq < 30) return FrequencyBand::UNKNOWN;
+    if (freq < 500) return FrequencyBand::AM_LW;
+    if (freq < 1705) return FrequencyBand::AM_MW;
+    if (freq < 30000) return FrequencyBand::AM_SW;
+    if (freq < 60000) return FrequencyBand::UNKNOWN;
+    if (freq < 110000) return FrequencyBand::FM;
+    return FrequencyBand::UNKNOWN;
+}
+
+bool tunesTo(const ProgramSelector& a, const ProgramSelector& b) {
+    IdentifierType type = b.primaryId.type;
+
+    switch (type) {
+        case IdentifierType::HD_STATION_ID_EXT:
+        case IdentifierType::RDS_PI:
+        case IdentifierType::AMFM_FREQUENCY_KHZ:
+            if (haveEqualIds(a, b, IdentifierType::HD_STATION_ID_EXT)) return true;
+            if (haveEqualIds(a, b, IdentifierType::RDS_PI)) return true;
+            return getHdSubchannel(b) == 0 &&
+                   haveEqualIds(a, b, IdentifierType::AMFM_FREQUENCY_KHZ);
+        case IdentifierType::DAB_SID_EXT:
+            return haveEqualIds(a, b, IdentifierType::DAB_SID_EXT);
+        case IdentifierType::DRMO_SERVICE_ID:
+            return haveEqualIds(a, b, IdentifierType::DRMO_SERVICE_ID);
+        case IdentifierType::SXM_SERVICE_ID:
+            return haveEqualIds(a, b, IdentifierType::SXM_SERVICE_ID);
+        default:  // includes all vendor types
+            LOG(WARNING) << "unsupported program type: " << toString(type);
+            return false;
+    }
+}
+
+bool hasId(const ProgramSelector& sel, const IdentifierType& type) {
+    return maybeGetId(sel, type, /* val */ nullptr);
+}
+
+int64_t getId(const ProgramSelector& sel, const IdentifierType& type) {
+    int64_t val;
+
+    if (maybeGetId(sel, type, &val)) {
+        return val;
+    }
+
+    LOG(WARNING) << "identifier not found: " << toString(type);
+    return kValueForNotFoundIdentifier;
+}
+
+int64_t getId(const ProgramSelector& sel, const IdentifierType& type, int64_t defaultValue) {
+    if (!hasId(sel, type)) {
+        return defaultValue;
+    }
+    return getId(sel, type);
+}
+
+vector<int> getAllIds(const ProgramSelector& sel, const IdentifierType& type) {
+    vector<int> ret;
+
+    // iterate through primaryId and secondaryIds
+    for (auto it = begin(sel); it != end(sel); it++) {
+        if (it->type == type) {
+            ret.push_back(it->value);
+        }
+    }
+
+    return ret;
+}
+
+bool isSupported(const Properties& prop, const ProgramSelector& sel) {
+    for (auto it = prop.supportedIdentifierTypes.begin(); it != prop.supportedIdentifierTypes.end();
+         it++) {
+        if (hasId(sel, *it)) {
+            return true;
+        }
+    }
+    return false;
+}
+
+bool isValid(const ProgramIdentifier& id) {
+    int64_t val = id.value;
+    bool valid = true;
+
+    auto expect = [&valid](bool condition, const string& message) {
+        if (!condition) {
+            valid = false;
+            LOG(ERROR) << "identifier not valid, expected " << message;
+        }
+    };
+
+    switch (id.type) {
+        case IdentifierType::INVALID:
+            expect(false, "IdentifierType::INVALID");
+            break;
+        case IdentifierType::DAB_FREQUENCY_KHZ:
+            expect(val > 100000u, "f > 100MHz");
+            [[fallthrough]];
+        case IdentifierType::AMFM_FREQUENCY_KHZ:
+        case IdentifierType::DRMO_FREQUENCY_KHZ:
+            expect(val > 100u, "f > 100kHz");
+            expect(val < 10000000u, "f < 10GHz");
+            break;
+        case IdentifierType::RDS_PI:
+            expect(val != 0u, "RDS PI != 0");
+            expect(val <= 0xFFFFu, "16bit id");
+            break;
+        case IdentifierType::HD_STATION_ID_EXT: {
+            int64_t stationId = val & 0xFFFFFFFF;  // 32bit
+            val >>= 32;
+            int64_t subchannel = val & 0xF;  // 4bit
+            val >>= 4;
+            int64_t freq = val & 0x3FFFF;  // 18bit
+            expect(stationId != 0u, "HD station id != 0");
+            expect(subchannel < 8u, "HD subch < 8");
+            expect(freq > 100u, "f > 100kHz");
+            expect(freq < 10000000u, "f < 10GHz");
+            break;
+        }
+        case IdentifierType::HD_STATION_NAME: {
+            while (val > 0) {
+                char ch = static_cast<char>(val & 0xFF);
+                val >>= 8;
+                expect((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'),
+                       "HD_STATION_NAME does not match [A-Z0-9]+");
+            }
+            break;
+        }
+        case IdentifierType::DAB_SID_EXT: {
+            int64_t sid = val & 0xFFFF;  // 16bit
+            val >>= 16;
+            int64_t ecc = val & 0xFF;  // 8bit
+            expect(sid != 0u, "DAB SId != 0");
+            expect(ecc >= 0xA0u && ecc <= 0xF6u, "Invalid ECC, see ETSI TS 101 756 V2.1.1");
+            break;
+        }
+        case IdentifierType::DAB_ENSEMBLE:
+            expect(val != 0u, "DAB ensemble != 0");
+            expect(val <= 0xFFFFu, "16bit id");
+            break;
+        case IdentifierType::DAB_SCID:
+            expect(val > 0xFu, "12bit SCId (not 4bit SCIdS)");
+            expect(val <= 0xFFFu, "12bit id");
+            break;
+        case IdentifierType::DRMO_SERVICE_ID:
+            expect(val != 0u, "DRM SId != 0");
+            expect(val <= 0xFFFFFFu, "24bit id");
+            break;
+        case IdentifierType::SXM_SERVICE_ID:
+            expect(val != 0u, "SXM SId != 0");
+            expect(val <= 0xFFFFFFFFu, "32bit id");
+            break;
+        case IdentifierType::SXM_CHANNEL:
+            expect(val < 1000u, "SXM channel < 1000");
+            break;
+        case IdentifierType::VENDOR_START:
+        case IdentifierType::VENDOR_END:
+            // skip
+            break;
+    }
+
+    return valid;
+}
+
+bool isValid(const ProgramSelector& sel) {
+    // iterate through primaryId and secondaryIds
+    for (auto it = begin(sel); it != end(sel); it++) {
+        if (!isValid(*it)) {
+            return false;
+        }
+    }
+    return true;
+}
+
+ProgramIdentifier makeIdentifier(IdentifierType type, int64_t value) {
+    return {type, value};
+}
+
+ProgramSelector makeSelectorAmfm(int32_t frequency) {
+    ProgramSelector sel = {};
+    sel.primaryId = makeIdentifier(IdentifierType::AMFM_FREQUENCY_KHZ, frequency);
+    return sel;
+}
+
+ProgramSelector makeSelectorDab(int32_t sidExt, int32_t ensemble) {
+    ProgramSelector sel = {};
+    // TODO(243686545): Have a helper function to create the sidExt instead of
+    // passing the whole identifier here. Something like makeDabSidExt.
+    sel.primaryId = makeIdentifier(IdentifierType::DAB_SID_EXT, sidExt);
+    vector<ProgramIdentifier> secondaryIds = {
+            makeIdentifier(IdentifierType::DAB_ENSEMBLE, ensemble),
+            // TODO(243686545): Include frequency here when the helper method to
+            // translate between ensemble and frequency is implemented.
+    };
+    sel.secondaryIds = std::move(secondaryIds);
+    return sel;
+}
+
+bool satisfies(const ProgramFilter& filter, const ProgramSelector& sel) {
+    if (filter.identifierTypes.size() > 0) {
+        auto typeEquals = [](const ProgramIdentifier& id, IdentifierType type) {
+            return id.type == type;
+        };
+        auto it = std::find_first_of(begin(sel), end(sel), filter.identifierTypes.begin(),
+                                     filter.identifierTypes.end(), typeEquals);
+        if (it == end(sel)) {
+            return false;
+        }
+    }
+
+    if (filter.identifiers.size() > 0) {
+        auto it = std::find_first_of(begin(sel), end(sel), filter.identifiers.begin(),
+                                     filter.identifiers.end());
+        if (it == end(sel)) {
+            return false;
+        }
+    }
+
+    if (!filter.includeCategories && sel.primaryId.type == IdentifierType::DAB_ENSEMBLE) {
+        return false;
+    }
+
+    return true;
+}
+
+size_t ProgramInfoHasher::operator()(const ProgramInfo& info) const {
+    const ProgramIdentifier& id = info.selector.primaryId;
+
+    // This is not the best hash implementation, but good enough for default HAL
+    // implementation and tests.
+    size_t h = 0;
+    ::android::hashCombineSingle(h, id.type);
+    ::android::hashCombineSingle(h, id.value);
+    return h;
+}
+
+bool ProgramInfoKeyEqual::operator()(const ProgramInfo& info1, const ProgramInfo& info2) const {
+    const ProgramIdentifier& id1 = info1.selector.primaryId;
+    const ProgramIdentifier& id2 = info2.selector.primaryId;
+    return id1.type == id2.type && id1.value == id2.value;
+}
+
+void updateProgramList(const ProgramListChunk& chunk, ProgramInfoSet* list) {
+    if (chunk.purge) {
+        list->clear();
+    }
+
+    list->insert(chunk.modified.begin(), chunk.modified.end());
+
+    if (!chunk.removed.has_value()) {
+        return;
+    }
+
+    for (auto& id : chunk.removed.value()) {
+        if (id.has_value()) {
+            ProgramInfo info = {};
+            info.selector.primaryId = id.value();
+            list->erase(info);
+        }
+    }
+}
+
+std::optional<std::string> getMetadataString(const ProgramInfo& info, const Metadata::Tag& tag) {
+    auto isRdsPs = [tag](const Metadata& item) { return item.getTag() == tag; };
+
+    auto it = std::find_if(info.metadata.begin(), info.metadata.end(), isRdsPs);
+    if (it == info.metadata.end()) {
+        return std::nullopt;
+    }
+
+    std::string metadataString;
+    switch (it->getTag()) {
+        case Metadata::rdsPs:
+            metadataString = it->get<Metadata::rdsPs>();
+            break;
+        case Metadata::rdsPty:
+            metadataString = std::to_string(it->get<Metadata::rdsPty>());
+            break;
+        case Metadata::rbdsPty:
+            metadataString = std::to_string(it->get<Metadata::rbdsPty>());
+            break;
+        case Metadata::rdsRt:
+            metadataString = it->get<Metadata::rdsRt>();
+            break;
+        case Metadata::songTitle:
+            metadataString = it->get<Metadata::songTitle>();
+            break;
+        case Metadata::songArtist:
+            metadataString = it->get<Metadata::songArtist>();
+            break;
+        case Metadata::songAlbum:
+            metadataString = it->get<Metadata::songAlbum>();
+            break;
+        case Metadata::stationIcon:
+            metadataString = std::to_string(it->get<Metadata::stationIcon>());
+            break;
+        case Metadata::albumArt:
+            metadataString = std::to_string(it->get<Metadata::albumArt>());
+            break;
+        case Metadata::programName:
+            metadataString = it->get<Metadata::programName>();
+            break;
+        case Metadata::dabEnsembleName:
+            metadataString = it->get<Metadata::dabEnsembleName>();
+            break;
+        case Metadata::dabEnsembleNameShort:
+            metadataString = it->get<Metadata::dabEnsembleNameShort>();
+            break;
+        case Metadata::dabServiceName:
+            metadataString = it->get<Metadata::dabServiceName>();
+            break;
+        case Metadata::dabServiceNameShort:
+            metadataString = it->get<Metadata::dabServiceNameShort>();
+            break;
+        case Metadata::dabComponentName:
+            metadataString = it->get<Metadata::dabComponentName>();
+            break;
+        case Metadata::dabComponentNameShort:
+            metadataString = it->get<Metadata::dabComponentNameShort>();
+            break;
+        default:
+            LOG(ERROR) << "Metadata " << it->toString() << " is not converted.";
+            return std::nullopt;
+    }
+    return metadataString;
+}
+
+ProgramIdentifier makeHdRadioStationName(const string& name) {
+    constexpr size_t maxlen = 8;
+
+    string shortName;
+    shortName.reserve(maxlen);
+
+    const auto& loc = std::locale::classic();
+    for (const char& ch : name) {
+        if (!std::isalnum(ch, loc)) {
+            continue;
+        }
+        shortName.push_back(std::toupper(ch, loc));
+        if (shortName.length() >= maxlen) {
+            break;
+        }
+    }
+
+    // Short name is converted to HD_STATION_NAME by encoding each char into its ASCII value in
+    // in little-endian order. For example, "Abc" is converted to 0x434241.
+    int64_t val = 0;
+    for (auto rit = shortName.rbegin(); rit != shortName.rend(); ++rit) {
+        val <<= 8;
+        val |= static_cast<char>(*rit);
+    }
+
+    return makeIdentifier(IdentifierType::HD_STATION_NAME, val);
+}
+
+}  // namespace utils
+
+utils::IdentifierIterator begin(const ProgramSelector& sel) {
+    return utils::IdentifierIterator(sel);
+}
+
+utils::IdentifierIterator end(const ProgramSelector& sel) {
+    return utils::IdentifierIterator(sel) + 1 /* primary id */ + sel.secondaryIds.size();
+}
+
+}  // namespace aidl::android::hardware::broadcastradio
diff --git a/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h b/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h
new file mode 100644
index 0000000..c79c5c5
--- /dev/null
+++ b/broadcastradio/common/utilsaidl/include/broadcastradio-utils-aidl/Utils.h
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include <aidl/android/hardware/broadcastradio/IdentifierType.h>
+#include <aidl/android/hardware/broadcastradio/Metadata.h>
+#include <aidl/android/hardware/broadcastradio/ProgramFilter.h>
+#include <aidl/android/hardware/broadcastradio/ProgramIdentifier.h>
+#include <aidl/android/hardware/broadcastradio/ProgramInfo.h>
+#include <aidl/android/hardware/broadcastradio/ProgramListChunk.h>
+#include <aidl/android/hardware/broadcastradio/ProgramSelector.h>
+#include <aidl/android/hardware/broadcastradio/Properties.h>
+#include <aidl/android/hardware/broadcastradio/Result.h>
+
+#include <numeric>
+#include <optional>
+#include <thread>
+#include <unordered_set>
+
+namespace aidl::android::hardware::broadcastradio {
+
+namespace utils {
+
+enum class FrequencyBand {
+    UNKNOWN,
+    FM,
+    AM_LW,
+    AM_MW,
+    AM_SW,
+};
+
+class IdentifierIterator final
+    : public std::iterator<std::random_access_iterator_tag, ProgramIdentifier, ssize_t,
+                           const ProgramIdentifier*, const ProgramIdentifier&> {
+    using ptrType = typename std::iterator_traits<IdentifierIterator>::pointer;
+    using refType = typename std::iterator_traits<IdentifierIterator>::reference;
+    using diffType = typename std::iterator_traits<IdentifierIterator>::difference_type;
+
+  public:
+    explicit IdentifierIterator(const ProgramSelector& sel);
+
+    const IdentifierIterator operator++(int);
+    IdentifierIterator& operator++();
+    refType operator*() const;
+    inline ptrType operator->() const { return &operator*(); }
+    IdentifierIterator operator+(diffType v) const { return IdentifierIterator(mSel, mPos + v); }
+    bool operator==(const IdentifierIterator& rhs) const;
+    inline bool operator!=(const IdentifierIterator& rhs) const { return !operator==(rhs); };
+
+  private:
+    explicit IdentifierIterator(const ProgramSelector& sel, size_t pos);
+
+    std::reference_wrapper<const ProgramSelector> mSel;
+
+    const ProgramSelector& getSelector() const { return mSel.get(); }
+
+    /** 0 is the primary identifier, 1-n are secondary identifiers. */
+    size_t mPos = 0;
+};
+
+/**
+ * Convert Result to int
+ */
+int32_t resultToInt(Result result);
+
+/**
+ * Guesses band from the frequency value.
+ *
+ * The band bounds are not exact to cover multiple regions.
+ * The function is biased towards success, i.e. it never returns
+ * FrequencyBand::UNKNOWN for correct frequency, but a result for
+ * incorrect one is undefined (it doesn't have to return UNKNOWN).
+ */
+FrequencyBand getBand(int64_t frequency);
+
+/**
+ * Checks, if {@code pointer} tunes to {@channel}.
+ *
+ * For example, having a channel {AMFM_FREQUENCY_KHZ = 103.3}:
+ * - selector {AMFM_FREQUENCY_KHZ = 103.3, HD_SUBCHANNEL = 0} can tune to this channel;
+ * - selector {AMFM_FREQUENCY_KHZ = 103.3, HD_SUBCHANNEL = 1} can't.
+ *
+ * @param pointer selector we're trying to match against channel.
+ * @param channel existing channel.
+ */
+bool tunesTo(const ProgramSelector& pointer, const ProgramSelector& channel);
+
+/**
+ * Checks whether a given program selector has the given ID (either primary or secondary).
+ */
+bool hasId(const ProgramSelector& sel, const IdentifierType& type);
+
+/**
+ * Returns ID (either primary or secondary) for a given program selector.
+ *
+ * If the selector does not contain given type, returns kValueForNotFoundIdentifier
+ * and emits a warning.
+ */
+int64_t getId(const ProgramSelector& sel, const IdentifierType& type);
+
+/**
+ * Returns ID (either primary or secondary) for a given program selector.
+ *
+ * If the selector does not contain given type, returns default value.
+ */
+int64_t getId(const ProgramSelector& sel, const IdentifierType& type, int64_t defaultValue);
+
+/**
+ * Returns all IDs of a given type.
+ */
+std::vector<int> getAllIds(const ProgramSelector& sel, const IdentifierType& type);
+
+/**
+ * Checks, if a given selector is supported by the radio module.
+ *
+ * @param prop Module description.
+ * @param sel The selector to check.
+ * @return True, if the selector is supported, false otherwise.
+ */
+bool isSupported(const Properties& prop, const ProgramSelector& sel);
+
+bool isValid(const ProgramIdentifier& id);
+bool isValid(const ProgramSelector& sel);
+
+ProgramIdentifier makeIdentifier(IdentifierType type, int64_t value);
+ProgramSelector makeSelectorAmfm(int32_t frequency);
+ProgramSelector makeSelectorDab(int32_t sidExt, int32_t ensemble);
+
+bool satisfies(const ProgramFilter& filter, const ProgramSelector& sel);
+
+struct ProgramInfoHasher {
+    size_t operator()(const ProgramInfo& info) const;
+};
+
+struct ProgramInfoKeyEqual {
+    bool operator()(const ProgramInfo& info1, const ProgramInfo& info2) const;
+};
+
+typedef std::unordered_set<ProgramInfo, ProgramInfoHasher, ProgramInfoKeyEqual> ProgramInfoSet;
+
+void updateProgramList(const ProgramListChunk& chunk, ProgramInfoSet* list);
+
+std::optional<std::string> getMetadataString(const ProgramInfo& info, const Metadata::Tag& tag);
+
+ProgramIdentifier makeHdRadioStationName(const std::string& name);
+
+template <typename aidl_type>
+inline std::string vectorToString(const std::vector<aidl_type>& in_values) {
+    return std::accumulate(std::begin(in_values), std::end(in_values), std::string{},
+                           [](const std::string& ls, const aidl_type& rs) {
+                               return ls + (ls.empty() ? "" : ",") + toString(rs);
+                           });
+}
+
+}  // namespace utils
+
+utils::IdentifierIterator begin(const ProgramSelector& sel);
+utils::IdentifierIterator end(const ProgramSelector& sel);
+
+}  // namespace aidl::android::hardware::broadcastradio