Merge "Convert VtsHalGraphicsComposerV2_*TargetTest to be parameterized test"
diff --git a/Android.bp b/Android.bp
index 70e0574..f64968f 100644
--- a/Android.bp
+++ b/Android.bp
@@ -26,7 +26,7 @@
],
header_libs: [
- "libhidl_gtest_helpers",
+ "libhidl_gtest_helper",
],
group_static_libs: true,
diff --git a/CleanSpec.mk b/CleanSpec.mk
index da2635e..76594fb 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -81,3 +81,6 @@
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/vndk-Q/android.hardware.configstore@1.2.so)
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/android.hardware.configstore@1.2.so)
$(call add-clean-step, rm -f $(PRODUCT_OUT)/etc/init/android.hardware.audio@2.0-service.rc $(PRODUCT_OUT)/vendor/bin/hw/android.hardware.audio@2.0-service)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/vendor/bin/hw/android.hardware.cas@1.1*)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/vendor/etc/init/android.hardware.cas@1.1*)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/vendor/etc/vintf/manifest/android.hardware.cas@1.1*)
diff --git a/atrace/1.0/vts/functional/Android.bp b/atrace/1.0/vts/functional/Android.bp
index d3f4276..ae24968 100644
--- a/atrace/1.0/vts/functional/Android.bp
+++ b/atrace/1.0/vts/functional/Android.bp
@@ -19,5 +19,5 @@
defaults: ["VtsHalTargetTestDefaults"],
srcs: ["VtsHalAtraceV1_0TargetTest.cpp"],
static_libs: ["android.hardware.atrace@1.0"],
- test_suites: ["general-tests"],
+ test_suites: ["general-tests", "vts-core"],
}
diff --git a/atrace/1.0/vts/functional/VtsHalAtraceV1_0TargetTest.cpp b/atrace/1.0/vts/functional/VtsHalAtraceV1_0TargetTest.cpp
index c62c2f0..2eaa03e 100644
--- a/atrace/1.0/vts/functional/VtsHalAtraceV1_0TargetTest.cpp
+++ b/atrace/1.0/vts/functional/VtsHalAtraceV1_0TargetTest.cpp
@@ -18,8 +18,9 @@
#include <android/hardware/atrace/1.0/IAtraceDevice.h>
-#include <VtsHalHidlTargetTestBase.h>
-#include <VtsHalHidlTargetTestEnvBase.h>
+#include <gtest/gtest.h>
+#include <hidl/GtestPrinter.h>
+#include <hidl/ServiceManagement.h>
using ::android::sp;
using ::android::hardware::hidl_string;
@@ -28,29 +29,13 @@
using ::android::hardware::atrace::V1_0::IAtraceDevice;
using ::android::hardware::atrace::V1_0::Status;
-// Test environment for Boot HIDL HAL.
-class AtraceHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
- public:
- // get the test environment singleton
- static AtraceHidlEnvironment* Instance() {
- static AtraceHidlEnvironment* instance = new AtraceHidlEnvironment;
- return instance;
- }
-
- virtual void registerTestServices() override { registerTestService<IAtraceDevice>(); }
-
- private:
- AtraceHidlEnvironment() {}
-};
-
/**
* There is no expected behaviour that can be tested so these tests check the
* HAL doesn't crash with different execution orders.
*/
-struct AtraceHidlTest : public ::testing::VtsHalHidlTargetTestBase {
+struct AtraceHidlTest : public ::testing::TestWithParam<std::string> {
virtual void SetUp() override {
- atrace = ::testing::VtsHalHidlTargetTestBase::getService<IAtraceDevice>(
- AtraceHidlEnvironment::Instance()->getServiceName<IAtraceDevice>());
+ atrace = IAtraceDevice::getService(GetParam());
ASSERT_NE(atrace, nullptr);
}
@@ -82,13 +67,13 @@
}
/* list categories from vendors. */
-TEST_F(AtraceHidlTest, listCategories) {
+TEST_P(AtraceHidlTest, listCategories) {
hidl_vec<hidl_string> vnd_categories = getVendorCategoryName(atrace);
EXPECT_NE(0, vnd_categories.size());
}
/* enable categories. */
-TEST_F(AtraceHidlTest, enableCategories) {
+TEST_P(AtraceHidlTest, enableCategories) {
hidl_vec<hidl_string> vnd_categories = getVendorCategoryName(atrace);
// empty Category with ERROR_INVALID_ARGUMENT
hidl_vec<hidl_string> empty_categories;
@@ -102,17 +87,13 @@
}
/* enable categories. */
-TEST_F(AtraceHidlTest, disableAllCategories) {
+TEST_P(AtraceHidlTest, disableAllCategories) {
auto ret = atrace->disableAllCategories();
ASSERT_TRUE(ret.isOk());
EXPECT_EQ(Status::SUCCESS, ret);
}
-int main(int argc, char** argv) {
- ::testing::AddGlobalTestEnvironment(AtraceHidlEnvironment::Instance());
- ::testing::InitGoogleTest(&argc, argv);
- AtraceHidlEnvironment::Instance()->init(&argc, argv);
- int status = RUN_ALL_TESTS();
- ALOGI("Test result = %d", status);
- return status;
-}
+INSTANTIATE_TEST_SUITE_P(
+ PerInstance, AtraceHidlTest,
+ testing::ValuesIn(android::hardware::getAllHalInstanceNames(IAtraceDevice::descriptor)),
+ android::hardware::PrintInstanceNameToString);
diff --git a/cas/1.2/Android.bp b/cas/1.2/Android.bp
new file mode 100644
index 0000000..af98b2e
--- /dev/null
+++ b/cas/1.2/Android.bp
@@ -0,0 +1,21 @@
+// This file is autogenerated by hidl-gen -Landroidbp.
+
+hidl_interface {
+ name: "android.hardware.cas@1.2",
+ root: "android.hardware",
+ vndk: {
+ enabled: true,
+ },
+ srcs: [
+ "ICas.hal",
+ "ICasListener.hal",
+ "IMediaCasService.hal",
+ "types.hal",
+ ],
+ interfaces: [
+ "android.hardware.cas@1.0",
+ "android.hardware.cas@1.1",
+ "android.hidl.base@1.0",
+ ],
+ gen_java: true,
+}
diff --git a/cas/1.2/ICas.hal b/cas/1.2/ICas.hal
new file mode 100644
index 0000000..23edc50
--- /dev/null
+++ b/cas/1.2/ICas.hal
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.cas@1.2;
+
+import @1.0::HidlCasSessionId;
+import @1.1::ICas;
+import ScramblingMode;
+import SessionIntent;
+import Status;
+
+/**
+ * ICas is the API to control the cas system and is accessible from both
+ * Java and native level. It is used to manage sessions, provision/refresh
+ * the cas system, and process the EMM/ECM messages. It also allows bi-directional,
+ * scheme-specific communications between the client and the cas system.
+ */
+interface ICas extends @1.1::ICas {
+ /**
+ * Open a session to descramble one or more streams by specifying intention
+ * and scrambling mode.
+ *
+ * @param intent the intention of the session to be opened.
+ * @param mode the scrambling mode the session will use.
+ * @return status the status of the call.
+ * @return sessionId the id of the newly opened session.
+ */
+ openSession_1_2(SessionIntent intent, ScramblingMode mode)
+ generates (Status status, HidlCasSessionId sessionId);
+};
diff --git a/cas/1.2/ICasListener.hal b/cas/1.2/ICasListener.hal
new file mode 100644
index 0000000..9a8be20
--- /dev/null
+++ b/cas/1.2/ICasListener.hal
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.cas@1.2;
+
+import @1.1::ICasListener;
+import StatusEvent;
+
+interface ICasListener extends @1.1::ICasListener {
+ /**
+ * Notify the listener that the status of CAS system has changed.
+ *
+ * @param event the event type of status change.
+ * @param number value for status event.
+ * For PLUGIN_PHYSICAL_MODULE_CHANGED event:
+ * the positive number presents how many plugins are inserted;
+ * the negative number presents how many plugins are removed.
+ * Client must enumerate plugins after receive the event.
+ * For PLUGIN_SESSION_NUMBER_CHANGED event:
+ * the number presents how many sessions are supported
+ * in the plugin.
+ */
+ onStatusUpdate(StatusEvent event, int32_t number);
+};
diff --git a/cas/1.2/IMediaCasService.hal b/cas/1.2/IMediaCasService.hal
new file mode 100644
index 0000000..a0bec7e
--- /dev/null
+++ b/cas/1.2/IMediaCasService.hal
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.cas@1.2;
+
+import ICas;
+import ICasListener;
+import @1.1::IMediaCasService;
+
+/**
+ * IMediaCasService is the main entry point for interacting with a vendor's
+ * cas HAL to create cas and descrambler plugin instances. A cas plugin instance
+ * opens cas sessions which are used to obtain keys for a descrambler session,
+ * which can in turn be used to descramble protected video content.
+ *
+ * The 1.2 must always create 1.2 ICas interfaces, which are
+ * returned via the 1.1 createPluginExt method.
+ *
+ * To use 1.2 features the caller must cast the returned interface to a
+ * 1.2 HAL, using V1_2::ICas::castFrom().
+ */
+interface IMediaCasService extends @1.1::IMediaCasService {};
diff --git a/cas/1.2/default/Android.bp b/cas/1.2/default/Android.bp
new file mode 100644
index 0000000..9e53148
--- /dev/null
+++ b/cas/1.2/default/Android.bp
@@ -0,0 +1,49 @@
+cc_defaults {
+ name: "cas_service_defaults@1.2",
+ defaults: ["hidl_defaults"],
+ vendor: true,
+ relative_install_path: "hw",
+ srcs: [
+ "CasImpl.cpp",
+ "DescramblerImpl.cpp",
+ "MediaCasService.cpp",
+ "service.cpp",
+ "SharedLibrary.cpp",
+ "TypeConvert.cpp",
+ ],
+
+ compile_multilib: "32",
+
+ shared_libs: [
+ "android.hardware.cas@1.0",
+ "android.hardware.cas@1.1",
+ "android.hardware.cas@1.2",
+ "android.hardware.cas.native@1.0",
+ "android.hidl.memory@1.0",
+ "libbinder",
+ "libhidlbase",
+ "libhidlmemory",
+ "liblog",
+ "libutils",
+ ],
+ header_libs: [
+ "libstagefright_foundation_headers",
+ "media_plugin_headers",
+ ],
+}
+
+cc_binary {
+ name: "android.hardware.cas@1.2-service",
+ vintf_fragments: ["android.hardware.cas@1.2-service.xml"],
+ defaults: ["cas_service_defaults@1.2"],
+ init_rc: ["android.hardware.cas@1.2-service.rc"],
+}
+
+cc_binary {
+ name: "android.hardware.cas@1.2-service-lazy",
+ vintf_fragments: ["android.hardware.cas@1.2-service-lazy.xml"],
+ overrides: ["android.hardware.cas@1.2-service"],
+ defaults: ["cas_service_defaults@1.2"],
+ init_rc: ["android.hardware.cas@1.2-service-lazy.rc"],
+ cflags: ["-DLAZY_SERVICE"],
+}
diff --git a/cas/1.2/default/CasImpl.cpp b/cas/1.2/default/CasImpl.cpp
new file mode 100644
index 0000000..46dd251
--- /dev/null
+++ b/cas/1.2/default/CasImpl.cpp
@@ -0,0 +1,271 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ icensed 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_NDEBUG 0
+#define LOG_TAG "android.hardware.cas@1.1-CasImpl"
+
+#include <android/hardware/cas/1.1/ICasListener.h>
+#include <android/hardware/cas/1.2/ICasListener.h>
+#include <media/cas/CasAPI.h>
+#include <utils/Log.h>
+
+#include "CasImpl.h"
+#include "SharedLibrary.h"
+#include "TypeConvert.h"
+
+namespace android {
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+CasImpl::CasImpl(const sp<ICasListener>& listener) : mListener(listener) {
+ ALOGV("CTOR");
+}
+
+CasImpl::~CasImpl() {
+ ALOGV("DTOR");
+ release();
+}
+
+// static
+void CasImpl::OnEvent(void* appData, int32_t event, int32_t arg, uint8_t* data, size_t size) {
+ if (appData == NULL) {
+ ALOGE("Invalid appData!");
+ return;
+ }
+ CasImpl* casImpl = static_cast<CasImpl*>(appData);
+ casImpl->onEvent(event, arg, data, size);
+}
+
+// static
+void CasImpl::CallBackExt(void* appData, int32_t event, int32_t arg, uint8_t* data, size_t size,
+ const CasSessionId* sessionId) {
+ if (appData == NULL) {
+ ALOGE("Invalid appData!");
+ return;
+ }
+ CasImpl* casImpl = static_cast<CasImpl*>(appData);
+ casImpl->onEvent(sessionId, event, arg, data, size);
+}
+
+// static
+void CasImpl::StatusUpdate(void* appData, int32_t event, int32_t arg) {
+ if (appData == NULL) {
+ ALOGE("Invalid appData!");
+ return;
+ }
+ CasImpl* casImpl = static_cast<CasImpl*>(appData);
+ casImpl->onStatusUpdate(event, arg);
+}
+
+void CasImpl::init(const sp<SharedLibrary>& library, CasPlugin* plugin) {
+ mLibrary = library;
+ std::shared_ptr<CasPlugin> holder(plugin);
+ std::atomic_store(&mPluginHolder, holder);
+}
+
+void CasImpl::onEvent(int32_t event, int32_t arg, uint8_t* data, size_t size) {
+ if (mListener == NULL) {
+ return;
+ }
+
+ HidlCasData eventData;
+ if (data != NULL) {
+ eventData.setToExternal(data, size);
+ }
+
+ mListener->onEvent(event, arg, eventData);
+}
+
+void CasImpl::onEvent(const CasSessionId* sessionId, int32_t event, int32_t arg, uint8_t* data,
+ size_t size) {
+ if (mListener == NULL) {
+ return;
+ }
+
+ HidlCasData eventData;
+ if (data != NULL) {
+ eventData.setToExternal(data, size);
+ }
+
+ if (sessionId != NULL) {
+ mListener->onSessionEvent(*sessionId, event, arg, eventData);
+ } else {
+ mListener->onEvent(event, arg, eventData);
+ }
+}
+
+void CasImpl::onStatusUpdate(int32_t event, int32_t arg) {
+ if (mListener == NULL) {
+ return;
+ }
+ sp<V1_2::ICasListener> listenerV1_2 = V1_2::ICasListener::castFrom(mListener);
+
+ if (listenerV1_2 != NULL) {
+ listenerV1_2->onStatusUpdate(static_cast<StatusEvent>(event), arg);
+ }
+}
+
+Return<Status> CasImpl::setPluginStatusUpdateCallback() {
+ ALOGV("%s", __FUNCTION__);
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+ return toStatus(holder->setStatusCallback(&CasImpl::StatusUpdate));
+}
+
+Return<Status> CasImpl::setPrivateData(const HidlCasData& pvtData) {
+ ALOGV("%s", __FUNCTION__);
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+ return toStatus(holder->setPrivateData(pvtData));
+}
+
+Return<void> CasImpl::openSession(openSession_cb _hidl_cb) {
+ ALOGV("%s", __FUNCTION__);
+ CasSessionId sessionId;
+
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ status_t err = INVALID_OPERATION;
+ if (holder.get() != nullptr) {
+ err = holder->openSession(&sessionId);
+ holder.reset();
+ }
+
+ _hidl_cb(toStatus(err), sessionId);
+
+ return Void();
+}
+
+Return<void> CasImpl::openSession_1_2(const SessionIntent intent, const ScramblingMode mode,
+ openSession_1_2_cb _hidl_cb) {
+ ALOGV("%s", __FUNCTION__);
+ CasSessionId sessionId;
+
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ status_t err = INVALID_OPERATION;
+ if (holder.get() != nullptr) {
+ err = holder->openSession(static_cast<uint32_t>(intent), static_cast<uint32_t>(mode),
+ &sessionId);
+ holder.reset();
+ }
+
+ _hidl_cb(toStatus_1_2(err), sessionId);
+
+ return Void();
+}
+
+Return<Status> CasImpl::setSessionPrivateData(const HidlCasSessionId& sessionId,
+ const HidlCasData& pvtData) {
+ ALOGV("%s: sessionId=%s", __FUNCTION__, sessionIdToString(sessionId).string());
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+ return toStatus(holder->setSessionPrivateData(sessionId, pvtData));
+}
+
+Return<Status> CasImpl::closeSession(const HidlCasSessionId& sessionId) {
+ ALOGV("%s: sessionId=%s", __FUNCTION__, sessionIdToString(sessionId).string());
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+ return toStatus(holder->closeSession(sessionId));
+}
+
+Return<Status> CasImpl::processEcm(const HidlCasSessionId& sessionId, const HidlCasData& ecm) {
+ ALOGV("%s: sessionId=%s", __FUNCTION__, sessionIdToString(sessionId).string());
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+
+ return toStatus(holder->processEcm(sessionId, ecm));
+}
+
+Return<Status> CasImpl::processEmm(const HidlCasData& emm) {
+ ALOGV("%s", __FUNCTION__);
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+
+ return toStatus(holder->processEmm(emm));
+}
+
+Return<Status> CasImpl::sendEvent(int32_t event, int32_t arg, const HidlCasData& eventData) {
+ ALOGV("%s", __FUNCTION__);
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+
+ status_t err = holder->sendEvent(event, arg, eventData);
+ return toStatus(err);
+}
+
+Return<Status> CasImpl::sendSessionEvent(const HidlCasSessionId& sessionId, int32_t event,
+ int32_t arg, const HidlCasData& eventData) {
+ ALOGV("%s", __FUNCTION__);
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+
+ status_t err = holder->sendSessionEvent(sessionId, event, arg, eventData);
+ return toStatus(err);
+}
+
+Return<Status> CasImpl::provision(const hidl_string& provisionString) {
+ ALOGV("%s: provisionString=%s", __FUNCTION__, provisionString.c_str());
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+
+ return toStatus(holder->provision(String8(provisionString.c_str())));
+}
+
+Return<Status> CasImpl::refreshEntitlements(int32_t refreshType, const HidlCasData& refreshData) {
+ ALOGV("%s", __FUNCTION__);
+ std::shared_ptr<CasPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+
+ status_t err = holder->refreshEntitlements(refreshType, refreshData);
+ return toStatus(err);
+}
+
+Return<Status> CasImpl::release() {
+ ALOGV("%s: plugin=%p", __FUNCTION__, mPluginHolder.get());
+
+ std::shared_ptr<CasPlugin> holder(nullptr);
+ std::atomic_store(&mPluginHolder, holder);
+
+ return Status::OK;
+}
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
diff --git a/cas/1.2/default/CasImpl.h b/cas/1.2/default/CasImpl.h
new file mode 100644
index 0000000..4325c20
--- /dev/null
+++ b/cas/1.2/default/CasImpl.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_HARDWARE_CAS_V1_1_CAS_IMPL_H_
+#define ANDROID_HARDWARE_CAS_V1_1_CAS_IMPL_H_
+
+#include <android/hardware/cas/1.1/ICas.h>
+#include <android/hardware/cas/1.2/ICas.h>
+#include <media/stagefright/foundation/ABase.h>
+
+namespace android {
+struct CasPlugin;
+
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+struct ICasListener;
+namespace implementation {
+
+using ::android::hardware::cas::V1_0::HidlCasData;
+using ::android::hardware::cas::V1_0::HidlCasSessionId;
+using ::android::hardware::cas::V1_0::Status;
+using ::android::hardware::cas::V1_2::ScramblingMode;
+using ::android::hardware::cas::V1_2::SessionIntent;
+using ::android::hardware::cas::V1_2::StatusEvent;
+
+class SharedLibrary;
+
+class CasImpl : public V1_2::ICas {
+ public:
+ CasImpl(const sp<ICasListener>& listener);
+ virtual ~CasImpl();
+
+ static void OnEvent(void* appData, int32_t event, int32_t arg, uint8_t* data, size_t size);
+
+ static void CallBackExt(void* appData, int32_t event, int32_t arg, uint8_t* data, size_t size,
+ const CasSessionId* sessionId);
+
+ static void StatusUpdate(void* appData, int32_t event, int32_t arg);
+
+ void init(const sp<SharedLibrary>& library, CasPlugin* plugin);
+ void onEvent(int32_t event, int32_t arg, uint8_t* data, size_t size);
+
+ void onEvent(const CasSessionId* sessionId, int32_t event, int32_t arg, uint8_t* data,
+ size_t size);
+
+ void onStatusUpdate(int32_t event, int32_t arg);
+
+ // ICas inherits
+
+ Return<Status> setPluginStatusUpdateCallback();
+
+ virtual Return<Status> setPrivateData(const HidlCasData& pvtData) override;
+
+ virtual Return<void> openSession(openSession_cb _hidl_cb) override;
+
+ virtual Return<void> openSession_1_2(const SessionIntent intent, const ScramblingMode mode,
+ openSession_1_2_cb _hidl_cb) override;
+
+ virtual Return<Status> closeSession(const HidlCasSessionId& sessionId) override;
+
+ virtual Return<Status> setSessionPrivateData(const HidlCasSessionId& sessionId,
+ const HidlCasData& pvtData) override;
+
+ virtual Return<Status> processEcm(const HidlCasSessionId& sessionId,
+ const HidlCasData& ecm) override;
+
+ virtual Return<Status> processEmm(const HidlCasData& emm) override;
+
+ virtual Return<Status> sendEvent(int32_t event, int32_t arg,
+ const HidlCasData& eventData) override;
+
+ virtual Return<Status> sendSessionEvent(const HidlCasSessionId& sessionId, int32_t event,
+ int32_t arg, const HidlCasData& eventData) override;
+
+ virtual Return<Status> provision(const hidl_string& provisionString) override;
+
+ virtual Return<Status> refreshEntitlements(int32_t refreshType,
+ const HidlCasData& refreshData) override;
+
+ virtual Return<Status> release() override;
+
+ private:
+ struct PluginHolder;
+ sp<SharedLibrary> mLibrary;
+ std::shared_ptr<CasPlugin> mPluginHolder;
+ sp<ICasListener> mListener;
+
+ DISALLOW_EVIL_CONSTRUCTORS(CasImpl);
+};
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_CAS_V1_1_CAS_IMPL_H_
diff --git a/cas/1.2/default/DescramblerImpl.cpp b/cas/1.2/default/DescramblerImpl.cpp
new file mode 100644
index 0000000..36dc1a5
--- /dev/null
+++ b/cas/1.2/default/DescramblerImpl.cpp
@@ -0,0 +1,195 @@
+/*
+ * Copyright (C) 2019 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_NDEBUG 0
+#define LOG_TAG "android.hardware.cas@1.1-DescramblerImpl"
+
+#include <hidlmemory/mapping.h>
+#include <media/cas/DescramblerAPI.h>
+#include <media/hardware/CryptoAPI.h>
+#include <media/stagefright/foundation/AUtils.h>
+#include <utils/Log.h>
+
+#include "DescramblerImpl.h"
+#include "SharedLibrary.h"
+#include "TypeConvert.h"
+
+namespace android {
+using hidl::memory::V1_0::IMemory;
+
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+#define CHECK_SUBSAMPLE_DEF(type) \
+ static_assert(sizeof(SubSample) == sizeof(type::SubSample), "SubSample: size doesn't match"); \
+ static_assert(offsetof(SubSample, numBytesOfClearData) == \
+ offsetof(type::SubSample, mNumBytesOfClearData), \
+ "SubSample: numBytesOfClearData offset doesn't match"); \
+ static_assert(offsetof(SubSample, numBytesOfEncryptedData) == \
+ offsetof(type::SubSample, mNumBytesOfEncryptedData), \
+ "SubSample: numBytesOfEncryptedData offset doesn't match")
+
+CHECK_SUBSAMPLE_DEF(DescramblerPlugin);
+CHECK_SUBSAMPLE_DEF(CryptoPlugin);
+
+DescramblerImpl::DescramblerImpl(const sp<SharedLibrary>& library, DescramblerPlugin* plugin)
+ : mLibrary(library), mPluginHolder(plugin) {
+ ALOGV("CTOR: plugin=%p", mPluginHolder.get());
+}
+
+DescramblerImpl::~DescramblerImpl() {
+ ALOGV("DTOR: plugin=%p", mPluginHolder.get());
+ release();
+}
+
+Return<Status> DescramblerImpl::setMediaCasSession(const HidlCasSessionId& sessionId) {
+ ALOGV("%s: sessionId=%s", __FUNCTION__, sessionIdToString(sessionId).string());
+
+ std::shared_ptr<DescramblerPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return toStatus(INVALID_OPERATION);
+ }
+
+ return toStatus(holder->setMediaCasSession(sessionId));
+}
+
+Return<bool> DescramblerImpl::requiresSecureDecoderComponent(const hidl_string& mime) {
+ std::shared_ptr<DescramblerPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ return false;
+ }
+
+ return holder->requiresSecureDecoderComponent(String8(mime.c_str()));
+}
+
+static inline bool validateRangeForSize(uint64_t offset, uint64_t length, uint64_t size) {
+ return isInRange<uint64_t, uint64_t>(0, size, offset, length);
+}
+
+Return<void> DescramblerImpl::descramble(ScramblingControl scramblingControl,
+ const hidl_vec<SubSample>& subSamples,
+ const SharedBuffer& srcBuffer, uint64_t srcOffset,
+ const DestinationBuffer& dstBuffer, uint64_t dstOffset,
+ descramble_cb _hidl_cb) {
+ ALOGV("%s", __FUNCTION__);
+
+ // hidl_memory's size is stored in uint64_t, but mapMemory's mmap will map
+ // size in size_t. If size is over SIZE_MAX, mapMemory mapMemory could succeed
+ // but the mapped memory's actual size will be smaller than the reported size.
+ if (srcBuffer.heapBase.size() > SIZE_MAX) {
+ ALOGE("Invalid hidl_memory size: %llu", srcBuffer.heapBase.size());
+ android_errorWriteLog(0x534e4554, "79376389");
+ _hidl_cb(toStatus(BAD_VALUE), 0, NULL);
+ return Void();
+ }
+
+ sp<IMemory> srcMem = mapMemory(srcBuffer.heapBase);
+
+ // Validate if the offset and size in the SharedBuffer is consistent with the
+ // mapped ashmem, since the offset and size is controlled by client.
+ if (srcMem == NULL) {
+ ALOGE("Failed to map src buffer.");
+ _hidl_cb(toStatus(BAD_VALUE), 0, NULL);
+ return Void();
+ }
+ if (!validateRangeForSize(srcBuffer.offset, srcBuffer.size, (uint64_t)srcMem->getSize())) {
+ ALOGE("Invalid src buffer range: offset %llu, size %llu, srcMem size %llu",
+ srcBuffer.offset, srcBuffer.size, (uint64_t)srcMem->getSize());
+ android_errorWriteLog(0x534e4554, "67962232");
+ _hidl_cb(toStatus(BAD_VALUE), 0, NULL);
+ return Void();
+ }
+
+ // use 64-bit here to catch bad subsample size that might be overflowing.
+ uint64_t totalBytesInSubSamples = 0;
+ for (size_t i = 0; i < subSamples.size(); i++) {
+ totalBytesInSubSamples +=
+ (uint64_t)subSamples[i].numBytesOfClearData + subSamples[i].numBytesOfEncryptedData;
+ }
+ // Further validate if the specified srcOffset and requested total subsample size
+ // is consistent with the source shared buffer size.
+ if (!validateRangeForSize(srcOffset, totalBytesInSubSamples, srcBuffer.size)) {
+ ALOGE("Invalid srcOffset and subsample size: "
+ "srcOffset %llu, totalBytesInSubSamples %llu, srcBuffer size %llu",
+ srcOffset, totalBytesInSubSamples, srcBuffer.size);
+ android_errorWriteLog(0x534e4554, "67962232");
+ _hidl_cb(toStatus(BAD_VALUE), 0, NULL);
+ return Void();
+ }
+
+ void* srcPtr = (uint8_t*)(void*)srcMem->getPointer() + srcBuffer.offset;
+ void* dstPtr = NULL;
+ if (dstBuffer.type == BufferType::SHARED_MEMORY) {
+ // When using shared memory, src buffer is also used as dst,
+ // we don't map it again here.
+ dstPtr = srcPtr;
+
+ // In this case the dst and src would be the same buffer, need to validate
+ // dstOffset against the buffer size too.
+ if (!validateRangeForSize(dstOffset, totalBytesInSubSamples, srcBuffer.size)) {
+ ALOGE("Invalid dstOffset and subsample size: "
+ "dstOffset %llu, totalBytesInSubSamples %llu, srcBuffer size %llu",
+ dstOffset, totalBytesInSubSamples, srcBuffer.size);
+ android_errorWriteLog(0x534e4554, "67962232");
+ _hidl_cb(toStatus(BAD_VALUE), 0, NULL);
+ return Void();
+ }
+ } else {
+ native_handle_t* handle =
+ const_cast<native_handle_t*>(dstBuffer.secureMemory.getNativeHandle());
+ dstPtr = static_cast<void*>(handle);
+ }
+
+ // Get a local copy of the shared_ptr for the plugin. Note that before
+ // calling the HIDL callback, this shared_ptr must be manually reset,
+ // since the client side could proceed as soon as the callback is called
+ // without waiting for this method to go out of scope.
+ std::shared_ptr<DescramblerPlugin> holder = std::atomic_load(&mPluginHolder);
+ if (holder.get() == nullptr) {
+ _hidl_cb(toStatus(INVALID_OPERATION), 0, NULL);
+ return Void();
+ }
+
+ // Casting hidl SubSample to DescramblerPlugin::SubSample, but need
+ // to ensure structs are actually idential
+
+ int32_t result =
+ holder->descramble(dstBuffer.type != BufferType::SHARED_MEMORY,
+ (DescramblerPlugin::ScramblingControl)scramblingControl,
+ subSamples.size(), (DescramblerPlugin::SubSample*)subSamples.data(),
+ srcPtr, srcOffset, dstPtr, dstOffset, NULL);
+
+ holder.reset();
+ _hidl_cb(toStatus(result >= 0 ? OK : result), result, NULL);
+ return Void();
+}
+
+Return<Status> DescramblerImpl::release() {
+ ALOGV("%s: plugin=%p", __FUNCTION__, mPluginHolder.get());
+
+ std::shared_ptr<DescramblerPlugin> holder(nullptr);
+ std::atomic_store(&mPluginHolder, holder);
+
+ return Status::OK;
+}
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
diff --git a/cas/1.2/default/DescramblerImpl.h b/cas/1.2/default/DescramblerImpl.h
new file mode 100644
index 0000000..011eace
--- /dev/null
+++ b/cas/1.2/default/DescramblerImpl.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_HARDWARE_CAS_V1_1_DESCRAMBLER_IMPL_H_
+#define ANDROID_HARDWARE_CAS_V1_1_DESCRAMBLER_IMPL_H_
+
+#include <android/hardware/cas/native/1.0/IDescrambler.h>
+#include <media/stagefright/foundation/ABase.h>
+
+namespace android {
+struct DescramblerPlugin;
+using namespace hardware::cas::native::V1_0;
+
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+using ::android::hardware::cas::V1_0::HidlCasSessionId;
+using ::android::hardware::cas::V1_0::Status;
+
+class SharedLibrary;
+
+class DescramblerImpl : public IDescrambler {
+ public:
+ DescramblerImpl(const sp<SharedLibrary>& library, DescramblerPlugin* plugin);
+ virtual ~DescramblerImpl();
+
+ virtual Return<Status> setMediaCasSession(const HidlCasSessionId& sessionId) override;
+
+ virtual Return<bool> requiresSecureDecoderComponent(const hidl_string& mime) override;
+
+ virtual Return<void> descramble(ScramblingControl scramblingControl,
+ const hidl_vec<SubSample>& subSamples,
+ const SharedBuffer& srcBuffer, uint64_t srcOffset,
+ const DestinationBuffer& dstBuffer, uint64_t dstOffset,
+ descramble_cb _hidl_cb) override;
+
+ virtual Return<Status> release() override;
+
+ private:
+ sp<SharedLibrary> mLibrary;
+ std::shared_ptr<DescramblerPlugin> mPluginHolder;
+
+ DISALLOW_EVIL_CONSTRUCTORS(DescramblerImpl);
+};
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_CAS_V1_1_DESCRAMBLER_IMPL_H_
diff --git a/cas/1.2/default/FactoryLoader.h b/cas/1.2/default/FactoryLoader.h
new file mode 100644
index 0000000..7403f86
--- /dev/null
+++ b/cas/1.2/default/FactoryLoader.h
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_HARDWARE_CAS_V1_1_FACTORY_LOADER_H_
+#define ANDROID_HARDWARE_CAS_V1_1_FACTORY_LOADER_H_
+
+#include <dirent.h>
+#include <dlfcn.h>
+#include <media/cas/CasAPI.h>
+#include <utils/KeyedVector.h>
+#include <utils/Mutex.h>
+#include "SharedLibrary.h"
+
+using namespace std;
+
+namespace android {
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+using ::android::hardware::cas::V1_0::HidlCasPluginDescriptor;
+
+template <class T>
+class FactoryLoader {
+ public:
+ FactoryLoader(const char* name) : mFactory(NULL), mCreateFactoryFuncName(name) {}
+
+ virtual ~FactoryLoader() { closeFactory(); }
+
+ bool findFactoryForScheme(int32_t CA_system_id, sp<SharedLibrary>* library = NULL,
+ T** factory = NULL);
+
+ bool enumeratePlugins(vector<HidlCasPluginDescriptor>* results);
+
+ private:
+ typedef T* (*CreateFactoryFunc)();
+
+ Mutex mMapLock;
+ T* mFactory;
+ const char* mCreateFactoryFuncName;
+ sp<SharedLibrary> mLibrary;
+ KeyedVector<int32_t, String8> mCASystemIdToLibraryPathMap;
+ KeyedVector<String8, wp<SharedLibrary>> mLibraryPathToOpenLibraryMap;
+
+ bool loadFactoryForSchemeFromPath(const String8& path, int32_t CA_system_id,
+ sp<SharedLibrary>* library, T** factory);
+
+ bool queryPluginsFromPath(const String8& path, vector<HidlCasPluginDescriptor>* results);
+
+ bool openFactory(const String8& path);
+ void closeFactory();
+};
+
+template <class T>
+bool FactoryLoader<T>::findFactoryForScheme(int32_t CA_system_id, sp<SharedLibrary>* library,
+ T** factory) {
+ if (library != NULL) {
+ library->clear();
+ }
+ if (factory != NULL) {
+ *factory = NULL;
+ }
+
+ Mutex::Autolock autoLock(mMapLock);
+
+ // first check cache
+ ssize_t index = mCASystemIdToLibraryPathMap.indexOfKey(CA_system_id);
+ if (index >= 0) {
+ return loadFactoryForSchemeFromPath(mCASystemIdToLibraryPathMap[index], CA_system_id,
+ library, factory);
+ }
+
+ // no luck, have to search
+ String8 dirPath("/vendor/lib/mediacas");
+ DIR* pDir = opendir(dirPath.string());
+
+ if (pDir == NULL) {
+ ALOGE("Failed to open plugin directory %s", dirPath.string());
+ return false;
+ }
+
+ struct dirent* pEntry;
+ while ((pEntry = readdir(pDir))) {
+ String8 pluginPath = dirPath + "/" + pEntry->d_name;
+ if (pluginPath.getPathExtension() == ".so") {
+ if (loadFactoryForSchemeFromPath(pluginPath, CA_system_id, library, factory)) {
+ mCASystemIdToLibraryPathMap.add(CA_system_id, pluginPath);
+ closedir(pDir);
+
+ return true;
+ }
+ }
+ }
+
+ closedir(pDir);
+
+ ALOGE("Failed to find plugin");
+ return false;
+}
+
+template <class T>
+bool FactoryLoader<T>::enumeratePlugins(vector<HidlCasPluginDescriptor>* results) {
+ ALOGI("enumeratePlugins");
+
+ results->clear();
+
+ String8 dirPath("/vendor/lib/mediacas");
+ DIR* pDir = opendir(dirPath.string());
+
+ if (pDir == NULL) {
+ ALOGE("Failed to open plugin directory %s", dirPath.string());
+ return false;
+ }
+
+ Mutex::Autolock autoLock(mMapLock);
+
+ struct dirent* pEntry;
+ while ((pEntry = readdir(pDir))) {
+ String8 pluginPath = dirPath + "/" + pEntry->d_name;
+ if (pluginPath.getPathExtension() == ".so") {
+ queryPluginsFromPath(pluginPath, results);
+ }
+ }
+ return true;
+}
+
+template <class T>
+bool FactoryLoader<T>::loadFactoryForSchemeFromPath(const String8& path, int32_t CA_system_id,
+ sp<SharedLibrary>* library, T** factory) {
+ closeFactory();
+
+ if (!openFactory(path) || !mFactory->isSystemIdSupported(CA_system_id)) {
+ closeFactory();
+ return false;
+ }
+
+ if (library != NULL) {
+ *library = mLibrary;
+ }
+ if (factory != NULL) {
+ *factory = mFactory;
+ }
+ return true;
+}
+
+template <class T>
+bool FactoryLoader<T>::queryPluginsFromPath(const String8& path,
+ vector<HidlCasPluginDescriptor>* results) {
+ closeFactory();
+
+ vector<CasPluginDescriptor> descriptors;
+ if (!openFactory(path) || mFactory->queryPlugins(&descriptors) != OK) {
+ closeFactory();
+ return false;
+ }
+
+ for (auto it = descriptors.begin(); it != descriptors.end(); it++) {
+ results->push_back(
+ HidlCasPluginDescriptor{.caSystemId = it->CA_system_id, .name = it->name.c_str()});
+ }
+ return true;
+}
+
+template <class T>
+bool FactoryLoader<T>::openFactory(const String8& path) {
+ // get strong pointer to open shared library
+ ssize_t index = mLibraryPathToOpenLibraryMap.indexOfKey(path);
+ if (index >= 0) {
+ mLibrary = mLibraryPathToOpenLibraryMap[index].promote();
+ } else {
+ index = mLibraryPathToOpenLibraryMap.add(path, NULL);
+ }
+
+ if (!mLibrary.get()) {
+ mLibrary = new SharedLibrary(path);
+ if (!*mLibrary) {
+ return false;
+ }
+
+ mLibraryPathToOpenLibraryMap.replaceValueAt(index, mLibrary);
+ }
+
+ CreateFactoryFunc createFactory = (CreateFactoryFunc)mLibrary->lookup(mCreateFactoryFuncName);
+ if (createFactory == NULL || (mFactory = createFactory()) == NULL) {
+ return false;
+ }
+ return true;
+}
+
+template <class T>
+void FactoryLoader<T>::closeFactory() {
+ delete mFactory;
+ mFactory = NULL;
+ mLibrary.clear();
+}
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_CAS_V1_1_FACTORY_LOADER_H_
diff --git a/cas/1.2/default/MediaCasService.cpp b/cas/1.2/default/MediaCasService.cpp
new file mode 100644
index 0000000..4ecd52b
--- /dev/null
+++ b/cas/1.2/default/MediaCasService.cpp
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2019 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_NDEBUG 0
+#define LOG_TAG "android.hardware.cas@1.1-MediaCasService"
+
+#include <android/hardware/cas/1.1/ICasListener.h>
+#include <android/hardware/cas/1.2/ICasListener.h>
+#include <media/cas/CasAPI.h>
+#include <media/cas/DescramblerAPI.h>
+#include <utils/Log.h>
+
+#include "CasImpl.h"
+#include "DescramblerImpl.h"
+#include "MediaCasService.h"
+
+namespace android {
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+class Wrapper : public V1_1::ICasListener {
+ public:
+ static sp<V1_1::ICasListener> wrap(sp<V1_0::ICasListener> impl) {
+ sp<V1_1::ICasListener> cast = V1_1::ICasListener::castFrom(impl);
+ if (cast == NULL) {
+ cast = new Wrapper(impl);
+ }
+ return cast;
+ }
+
+ virtual Return<void> onEvent(int32_t event, int32_t arg,
+ const hidl_vec<uint8_t>& data) override {
+ mImpl->onEvent(event, arg, data);
+ return Void();
+ }
+
+ virtual Return<void> onSessionEvent(const hidl_vec<uint8_t>& /* sessionId */,
+ int32_t /* event */, int32_t /* arg */,
+ const hidl_vec<uint8_t>& /*data*/) override {
+ ALOGV("Do nothing on Session Event for cas@1.0 client in cas@1.1");
+ return Void();
+ }
+
+ private:
+ Wrapper(sp<V1_0::ICasListener> impl) : mImpl(impl){};
+ sp<V1_0::ICasListener> mImpl;
+};
+
+MediaCasService::MediaCasService()
+ : mCasLoader("createCasFactory"), mDescramblerLoader("createDescramblerFactory") {}
+
+MediaCasService::~MediaCasService() {}
+
+Return<void> MediaCasService::enumeratePlugins(enumeratePlugins_cb _hidl_cb) {
+ ALOGV("%s", __FUNCTION__);
+
+ vector<HidlCasPluginDescriptor> results;
+ mCasLoader.enumeratePlugins(&results);
+
+ _hidl_cb(results);
+ return Void();
+}
+
+Return<bool> MediaCasService::isSystemIdSupported(int32_t CA_system_id) {
+ ALOGV("isSystemIdSupported: CA_system_id=%d", CA_system_id);
+
+ return mCasLoader.findFactoryForScheme(CA_system_id);
+}
+
+Return<sp<V1_0::ICas>> MediaCasService::createPlugin(int32_t CA_system_id,
+ const sp<V1_0::ICasListener>& listener) {
+ ALOGV("%s:Use createPluginExt to create plugin in cas@1.1", __FUNCTION__);
+
+ sp<ICas> result;
+
+ sp<V1_1::ICasListener> listenerV1_1 = Wrapper::wrap(listener);
+
+ result = createPluginExt(CA_system_id, listenerV1_1);
+
+ return result;
+}
+
+Return<sp<ICas>> MediaCasService::createPluginExt(int32_t CA_system_id,
+ const sp<ICasListener>& listener) {
+ ALOGV("%s: CA_system_id=%d", __FUNCTION__, CA_system_id);
+ if (listener == NULL) ALOGV("%s: Listener is NULL", __FUNCTION__);
+
+ sp<V1_2::ICas> result;
+
+ CasFactory* factory;
+ sp<SharedLibrary> library;
+ if (mCasLoader.findFactoryForScheme(CA_system_id, &library, &factory)) {
+ CasPlugin* plugin = NULL;
+ sp<CasImpl> casImpl = new CasImpl(listener);
+ if (factory->createPlugin(CA_system_id, casImpl.get(), &CasImpl::CallBackExt, &plugin) ==
+ OK &&
+ plugin != NULL) {
+ casImpl->init(library, plugin);
+ result = casImpl;
+
+ sp<V1_2::ICasListener> listenerV1_2 = V1_2::ICasListener::castFrom(listener);
+ if (listenerV1_2 != NULL) {
+ casImpl->setPluginStatusUpdateCallback();
+ }
+ }
+ }
+
+ return result;
+}
+
+Return<bool> MediaCasService::isDescramblerSupported(int32_t CA_system_id) {
+ ALOGV("%s: CA_system_id=%d", __FUNCTION__, CA_system_id);
+
+ return mDescramblerLoader.findFactoryForScheme(CA_system_id);
+}
+
+Return<sp<IDescramblerBase>> MediaCasService::createDescrambler(int32_t CA_system_id) {
+ ALOGV("%s: CA_system_id=%d", __FUNCTION__, CA_system_id);
+
+ sp<IDescrambler> result;
+
+ DescramblerFactory* factory;
+ sp<SharedLibrary> library;
+ if (mDescramblerLoader.findFactoryForScheme(CA_system_id, &library, &factory)) {
+ DescramblerPlugin* plugin = NULL;
+ if (factory->createPlugin(CA_system_id, &plugin) == OK && plugin != NULL) {
+ result = new DescramblerImpl(library, plugin);
+ }
+ }
+
+ return result;
+}
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
diff --git a/cas/1.2/default/MediaCasService.h b/cas/1.2/default/MediaCasService.h
new file mode 100644
index 0000000..01e11db
--- /dev/null
+++ b/cas/1.2/default/MediaCasService.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_HARDWARE_CAS_V1_1_MEDIA_CAS_SERVICE_H_
+#define ANDROID_HARDWARE_CAS_V1_1_MEDIA_CAS_SERVICE_H_
+
+#include <android/hardware/cas/1.1/IMediaCasService.h>
+#include <android/hardware/cas/1.2/IMediaCasService.h>
+
+#include "FactoryLoader.h"
+
+namespace android {
+struct CasFactory;
+struct DescramblerFactory;
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+using ::android::hardware::cas::V1_0::HidlCasPluginDescriptor;
+using ::android::hardware::cas::V1_0::IDescramblerBase;
+
+class MediaCasService : public V1_2::IMediaCasService {
+ public:
+ MediaCasService();
+
+ virtual Return<void> enumeratePlugins(enumeratePlugins_cb _hidl_cb) override;
+
+ virtual Return<bool> isSystemIdSupported(int32_t CA_system_id) override;
+
+ virtual Return<sp<V1_0::ICas>> createPlugin(int32_t CA_system_id,
+ const sp<V1_0::ICasListener>& listener) override;
+
+ virtual Return<sp<ICas>> createPluginExt(int32_t CA_system_id,
+ const sp<ICasListener>& listener) override;
+
+ virtual Return<bool> isDescramblerSupported(int32_t CA_system_id) override;
+
+ virtual Return<sp<IDescramblerBase>> createDescrambler(int32_t CA_system_id) override;
+
+ private:
+ FactoryLoader<CasFactory> mCasLoader;
+ FactoryLoader<DescramblerFactory> mDescramblerLoader;
+
+ virtual ~MediaCasService();
+};
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_CAS_V1_1_MEDIA_CAS_SERVICE_H_
diff --git a/cas/1.2/default/SharedLibrary.cpp b/cas/1.2/default/SharedLibrary.cpp
new file mode 100644
index 0000000..ffe4bb9
--- /dev/null
+++ b/cas/1.2/default/SharedLibrary.cpp
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2019 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_NDEBUG 0
+#define LOG_TAG "android.hardware.cas@1.1-SharedLibrary"
+
+#include "SharedLibrary.h"
+#include <dlfcn.h>
+#include <media/stagefright/foundation/ADebug.h>
+#include <utils/Log.h>
+
+namespace android {
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+SharedLibrary::SharedLibrary(const String8& path) {
+ mLibHandle = dlopen(path.string(), RTLD_NOW);
+}
+
+SharedLibrary::~SharedLibrary() {
+ if (mLibHandle != NULL) {
+ dlclose(mLibHandle);
+ mLibHandle = NULL;
+ }
+}
+
+bool SharedLibrary::operator!() const {
+ return mLibHandle == NULL;
+}
+
+void* SharedLibrary::lookup(const char* symbol) const {
+ if (!mLibHandle) {
+ return NULL;
+ }
+ // Clear last error before we load the symbol again,
+ // in case the caller didn't retrieve it.
+ (void)dlerror();
+ return dlsym(mLibHandle, symbol);
+}
+
+const char* SharedLibrary::lastError() const {
+ const char* error = dlerror();
+ return error ? error : "No errors or unknown error";
+}
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
diff --git a/cas/1.2/default/SharedLibrary.h b/cas/1.2/default/SharedLibrary.h
new file mode 100644
index 0000000..b85f557
--- /dev/null
+++ b/cas/1.2/default/SharedLibrary.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_HARDWARE_CAS_V1_1_SHARED_LIBRARY_H_
+#define ANDROID_HARDWARE_CAS_V1_1_SHARED_LIBRARY_H_
+
+#include <media/stagefright/foundation/ABase.h>
+#include <utils/RefBase.h>
+#include <utils/String8.h>
+
+namespace android {
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+class SharedLibrary : public RefBase {
+ public:
+ explicit SharedLibrary(const String8& path);
+ ~SharedLibrary();
+
+ bool operator!() const;
+ void* lookup(const char* symbol) const;
+ const char* lastError() const;
+
+ private:
+ void* mLibHandle;
+ DISALLOW_EVIL_CONSTRUCTORS(SharedLibrary);
+};
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_CAS_V1_1_SHARED_LIBRARY_H_
diff --git a/cas/1.2/default/TypeConvert.cpp b/cas/1.2/default/TypeConvert.cpp
new file mode 100644
index 0000000..c4bd0dd
--- /dev/null
+++ b/cas/1.2/default/TypeConvert.cpp
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2019 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_NDEBUG 0
+#define LOG_TAG "android.hardware.cas@1.1-TypeConvert"
+
+#include "TypeConvert.h"
+#include <utils/Log.h>
+
+namespace android {
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+Status toStatus(status_t legacyStatus) {
+ Status status;
+ switch (legacyStatus) {
+ case android::OK:
+ status = Status::OK;
+ break;
+ case android::ERROR_CAS_NO_LICENSE:
+ status = Status::ERROR_CAS_NO_LICENSE;
+ break;
+ case android::ERROR_CAS_LICENSE_EXPIRED:
+ status = Status::ERROR_CAS_LICENSE_EXPIRED;
+ break;
+ case android::ERROR_CAS_SESSION_NOT_OPENED:
+ status = Status::ERROR_CAS_SESSION_NOT_OPENED;
+ break;
+ case android::ERROR_CAS_CANNOT_HANDLE:
+ status = Status::ERROR_CAS_CANNOT_HANDLE;
+ break;
+ case android::ERROR_CAS_TAMPER_DETECTED:
+ status = Status::ERROR_CAS_INVALID_STATE;
+ break;
+ case android::BAD_VALUE:
+ status = Status::BAD_VALUE;
+ break;
+ case android::ERROR_CAS_NOT_PROVISIONED:
+ status = Status::ERROR_CAS_NOT_PROVISIONED;
+ break;
+ case android::ERROR_CAS_RESOURCE_BUSY:
+ status = Status::ERROR_CAS_RESOURCE_BUSY;
+ break;
+ case android::ERROR_CAS_INSUFFICIENT_OUTPUT_PROTECTION:
+ status = Status::ERROR_CAS_INSUFFICIENT_OUTPUT_PROTECTION;
+ break;
+ case android::ERROR_CAS_DEVICE_REVOKED:
+ status = Status::ERROR_CAS_DEVICE_REVOKED;
+ break;
+ case android::ERROR_CAS_DECRYPT_UNIT_NOT_INITIALIZED:
+ status = Status::ERROR_CAS_DECRYPT_UNIT_NOT_INITIALIZED;
+ break;
+ case android::ERROR_CAS_DECRYPT:
+ status = Status::ERROR_CAS_DECRYPT;
+ break;
+ default:
+ ALOGW("Unable to convert legacy status: %d, defaulting to UNKNOWN", legacyStatus);
+ status = Status::ERROR_CAS_UNKNOWN;
+ break;
+ }
+ return status;
+}
+
+V1_2::Status toStatus_1_2(status_t legacyStatus) {
+ V1_2::Status status = static_cast<V1_2::Status>(toStatus(legacyStatus));
+ if (status == V1_2::Status::ERROR_CAS_UNKNOWN) {
+ switch (legacyStatus) {
+ case android::ERROR_CAS_NEED_ACTIVATION:
+ status = V1_2::Status::ERROR_CAS_NEED_ACTIVATION;
+ break;
+ case android::ERROR_CAS_NEED_PAIRING:
+ status = V1_2::Status::ERROR_CAS_NEED_PAIRING;
+ break;
+ case android::ERROR_CAS_NO_CARD:
+ status = V1_2::Status::ERROR_CAS_NO_CARD;
+ break;
+ case android::ERROR_CAS_CARD_MUTE:
+ status = V1_2::Status::ERROR_CAS_CARD_MUTE;
+ break;
+ case android::ERROR_CAS_CARD_INVALID:
+ status = V1_2::Status::ERROR_CAS_CARD_INVALID;
+ break;
+ case android::ERROR_CAS_BLACKOUT:
+ status = V1_2::Status::ERROR_CAS_BLACKOUT;
+ break;
+ }
+ }
+ return status;
+}
+
+String8 sessionIdToString(const CasSessionId& sessionId) {
+ String8 result;
+ for (size_t i = 0; i < sessionId.size(); i++) {
+ result.appendFormat("%02x ", sessionId[i]);
+ }
+ if (result.isEmpty()) {
+ result.append("(null)");
+ }
+ return result;
+}
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
diff --git a/cas/1.2/default/TypeConvert.h b/cas/1.2/default/TypeConvert.h
new file mode 100644
index 0000000..018f310
--- /dev/null
+++ b/cas/1.2/default/TypeConvert.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_HARDWARE_CAS_V1_1_TYPE_CONVERT_H
+#define ANDROID_HARDWARE_CAS_V1_1_TYPE_CONVERT_H
+
+#include <android/hardware/cas/1.0/types.h>
+#include <android/hardware/cas/1.2/types.h>
+#include <media/cas/CasAPI.h>
+#include <media/stagefright/MediaErrors.h>
+#include <utils/String8.h>
+
+namespace android {
+namespace hardware {
+namespace cas {
+namespace V1_1 {
+namespace implementation {
+
+using ::android::hardware::cas::V1_0::Status;
+
+Status toStatus(status_t legacyStatus);
+
+V1_2::Status toStatus_1_2(status_t legacyStatus);
+
+String8 sessionIdToString(const CasSessionId& sessionId);
+
+} // namespace implementation
+} // namespace V1_1
+} // namespace cas
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_CAS_V1_1_TYPE_CONVERT_H
diff --git a/cas/1.2/default/android.hardware.cas@1.2-service-lazy.rc b/cas/1.2/default/android.hardware.cas@1.2-service-lazy.rc
new file mode 100644
index 0000000..1c75100
--- /dev/null
+++ b/cas/1.2/default/android.hardware.cas@1.2-service-lazy.rc
@@ -0,0 +1,11 @@
+service vendor.cas-hal-1-2 /vendor/bin/hw/android.hardware.cas@1.2-service-lazy
+ interface android.hardware.cas@1.0::IMediaCasService default
+ interface android.hardware.cas@1.1::IMediaCasService default
+ interface android.hardware.cas@1.2::IMediaCasService default
+ oneshot
+ disabled
+ class hal
+ user media
+ group mediadrm drmrpc
+ ioprio rt 4
+ writepid /dev/cpuset/foreground/tasks
diff --git a/cas/1.2/default/android.hardware.cas@1.2-service-lazy.xml b/cas/1.2/default/android.hardware.cas@1.2-service-lazy.xml
new file mode 100644
index 0000000..9b36406
--- /dev/null
+++ b/cas/1.2/default/android.hardware.cas@1.2-service-lazy.xml
@@ -0,0 +1,11 @@
+<manifest version="1.0" type="device">
+ <hal format="hidl">
+ <name>android.hardware.cas</name>
+ <transport>hwbinder</transport>
+ <version>1.2</version>
+ <interface>
+ <name>IMediaCasService</name>
+ <instance>default</instance>
+ </interface>
+ </hal>
+</manifest>
diff --git a/cas/1.2/default/android.hardware.cas@1.2-service.rc b/cas/1.2/default/android.hardware.cas@1.2-service.rc
new file mode 100644
index 0000000..d1c853e
--- /dev/null
+++ b/cas/1.2/default/android.hardware.cas@1.2-service.rc
@@ -0,0 +1,6 @@
+service vendor.cas-hal-1-2 /vendor/bin/hw/android.hardware.cas@1.2-service
+ class hal
+ user media
+ group mediadrm drmrpc
+ ioprio rt 4
+ writepid /dev/cpuset/foreground/tasks
diff --git a/cas/1.2/default/android.hardware.cas@1.2-service.xml b/cas/1.2/default/android.hardware.cas@1.2-service.xml
new file mode 100644
index 0000000..9b36406
--- /dev/null
+++ b/cas/1.2/default/android.hardware.cas@1.2-service.xml
@@ -0,0 +1,11 @@
+<manifest version="1.0" type="device">
+ <hal format="hidl">
+ <name>android.hardware.cas</name>
+ <transport>hwbinder</transport>
+ <version>1.2</version>
+ <interface>
+ <name>IMediaCasService</name>
+ <instance>default</instance>
+ </interface>
+ </hal>
+</manifest>
diff --git a/cas/1.2/default/service.cpp b/cas/1.2/default/service.cpp
new file mode 100644
index 0000000..a623447
--- /dev/null
+++ b/cas/1.2/default/service.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2017 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_NDEBUG 0
+#ifdef LAZY_SERVICE
+#define LOG_TAG "android.hardware.cas@1.1-service-lazy"
+#else
+#define LOG_TAG "android.hardware.cas@1.1-service"
+#endif
+
+#include <binder/ProcessState.h>
+#include <hidl/HidlTransportSupport.h>
+#include <hidl/LegacySupport.h>
+
+#include "MediaCasService.h"
+
+using android::hardware::configureRpcThreadpool;
+using android::hardware::joinRpcThreadpool;
+using android::hardware::LazyServiceRegistrar;
+using android::hardware::cas::V1_1::implementation::MediaCasService;
+using android::hardware::cas::V1_2::IMediaCasService;
+
+#ifdef LAZY_SERVICE
+const bool kLazyService = true;
+#else
+const bool kLazyService = false;
+#endif
+
+int main() {
+ configureRpcThreadpool(8, true /* callerWillJoin */);
+
+ // Setup hwbinder service
+ android::sp<IMediaCasService> service = new MediaCasService();
+ android::status_t status;
+ if (kLazyService) {
+ auto serviceRegistrar = LazyServiceRegistrar::getInstance();
+ status = serviceRegistrar.registerService(service);
+ } else {
+ status = service->registerAsService();
+ }
+ LOG_ALWAYS_FATAL_IF(status != android::OK, "Error while registering cas service: %d", status);
+
+ joinRpcThreadpool();
+ return 0;
+}
diff --git a/cas/1.2/types.hal b/cas/1.2/types.hal
new file mode 100644
index 0000000..40c06cf
--- /dev/null
+++ b/cas/1.2/types.hal
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.cas@1.2;
+
+import android.hardware.cas@1.0;
+import android.hardware.cas@1.1;
+
+enum Status : @1.0::Status {
+ /**
+ * ERROR_CAS_NEED_ACTIVATION is used to trigger device activation process.
+ */
+ ERROR_CAS_NEED_ACTIVATION,
+ /**
+ * ERROR_CAS_NEED_PAIRING is used to trigger pairing process.
+ */
+ ERROR_CAS_NEED_PAIRING,
+ /**
+ * ERROR_CAS_NO_CARD is used to report no smart card for descrambling.
+ */
+ ERROR_CAS_NO_CARD,
+ /**
+ * ERROR_CAS_CARD_MUTE is used to report smart card is muted for
+ * descrambling.
+ */
+ ERROR_CAS_CARD_MUTE,
+ /**
+ * ERROR_CAS_CARD_INVALID is used to report smart card isn't valid.
+ */
+ ERROR_CAS_CARD_INVALID,
+ /**
+ * ERROR_CAS_BLACKOUT is used to report geographical blackout.
+ */
+ ERROR_CAS_BLACKOUT,
+};
+
+/**
+ * The intented usage for the session.
+ */
+enum SessionIntent : uint32_t {
+ /**
+ * Live Stream.
+ */
+ LIVE,
+ /**
+ * Playback Recorded Stream.
+ */
+ PLAYBACK,
+ /**
+ * Record Live Stream.
+ */
+ RECORD,
+ /**
+ * View the content with Time Shift capability
+ */
+ TIMESHIFT,
+};
+
+/**
+ * The Scrambling Mode.
+ */
+enum ScramblingMode : uint32_t {
+ RESERVED = 0,
+ /**
+ * DVB (Digital Video Broadcasting) CSA1 (Common Scrambling Algorithm 1) is
+ * the default mode and shall be used when the scrambling descriptor
+ * is not present in the program map section. DVB scrambling mode is
+ * specified in ETSI EN 300 468 specification.
+ */
+ DVB_CSA1,
+ DVB_CSA2,
+ /**
+ * DVB-CSA3 in standard mode.
+ */
+ DVB_CSA3_STANDARD,
+ /**
+ * DVB-CSA3 in minimally enhanced mode.
+ */
+ DVB_CSA3_MINIMAL,
+ /**
+ * DVB-CSA3 in fully enhanced mode.
+ */
+ DVB_CSA3_ENHANCE,
+ /**
+ * DVB-CISSA version 1.
+ */
+ DVB_CISSA_V1,
+ /**
+ * ATIS-0800006 IIF Default Scrambling Algorithm (IDSA).
+ */
+ DVB_IDSA,
+ /**
+ * a symmetric key algorithm.
+ */
+ MULTI2,
+ /**
+ * Advanced Encryption System (AES) 128-bit Encryption mode.
+ */
+ AES128,
+ /**
+ * Advanced Encryption System (AES) Electronic Code Book (ECB) mode.
+ */
+ AES_ECB,
+ /**
+ * Advanced Encryption System (AES) Society of Cable Telecommunications
+ * Engineers (SCTE) 52 mode.
+ */
+ AES_SCTE52,
+ /**
+ * Triple Data Encryption Algorithm (TDES) Electronic Code Book (ECB) mode.
+ */
+ TDES_ECB,
+ /**
+ * Triple Data Encryption Algorithm (TDES) Society of Cable Telecommunications
+ * Engineers (SCTE) 52 mode.
+ */
+ TDES_SCTE52,
+ };
+
+/**
+ * The Event Type for status change.
+ */
+enum StatusEvent : uint8_t {
+ /**
+ * The status of CAS plugin was changed due to physical module insertion or
+ * removal. Client must call enumeratePlugins to update plugins' status.
+ */
+ PLUGIN_PHYSICAL_MODULE_CHANGED,
+ /**
+ * The status of supported session number was changed due to physical module
+ * insertion or removal. Client must update session resource according to
+ * latest StatusMessage from the StatusEvent. The plugin supports unlimited
+ * sesssion by default.
+ */
+ PLUGIN_SESSION_NUMBER_CHANGED,
+};
diff --git a/cas/1.2/vts/functional/Android.bp b/cas/1.2/vts/functional/Android.bp
new file mode 100644
index 0000000..9bc372c
--- /dev/null
+++ b/cas/1.2/vts/functional/Android.bp
@@ -0,0 +1,36 @@
+//
+// Copyright (C) 2019 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.
+//
+
+cc_test {
+ name: "VtsHalCasV1_2TargetTest",
+ defaults: ["VtsHalTargetTestDefaults"],
+ srcs: ["VtsHalCasV1_2TargetTest.cpp"],
+ static_libs: [
+ "android.hardware.cas@1.0",
+ "android.hardware.cas@1.1",
+ "android.hardware.cas@1.2",
+ "android.hardware.cas.native@1.0",
+ "android.hidl.allocator@1.0",
+ "android.hidl.memory@1.0",
+ "libhidlallocatorutils",
+ "libhidlmemory",
+ ],
+ shared_libs: [
+ "libbinder",
+ ],
+ test_suites: ["general-tests"],
+}
+
diff --git a/cas/1.2/vts/functional/OWNERS b/cas/1.2/vts/functional/OWNERS
new file mode 100644
index 0000000..29246ed
--- /dev/null
+++ b/cas/1.2/vts/functional/OWNERS
@@ -0,0 +1,3 @@
+nchalko@google.com
+chz@google.com
+quxiangfang@google.com
diff --git a/cas/1.2/vts/functional/VtsHalCasV1_2TargetTest.cpp b/cas/1.2/vts/functional/VtsHalCasV1_2TargetTest.cpp
new file mode 100644
index 0000000..8439ceb
--- /dev/null
+++ b/cas/1.2/vts/functional/VtsHalCasV1_2TargetTest.cpp
@@ -0,0 +1,619 @@
+/*
+ * Copyright (C) 2019 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 "mediacas_hidl_hal_test"
+
+#include <VtsHalHidlTargetTestBase.h>
+#include <VtsHalHidlTargetTestEnvBase.h>
+#include <android-base/logging.h>
+#include <android/hardware/cas/1.0/IDescramblerBase.h>
+#include <android/hardware/cas/1.0/types.h>
+#include <android/hardware/cas/1.2/ICas.h>
+#include <android/hardware/cas/1.2/ICasListener.h>
+#include <android/hardware/cas/1.2/IMediaCasService.h>
+#include <android/hardware/cas/1.2/types.h>
+#include <android/hardware/cas/native/1.0/IDescrambler.h>
+#include <android/hardware/cas/native/1.0/types.h>
+#include <binder/MemoryDealer.h>
+#include <hidl/HidlSupport.h>
+#include <hidl/HidlTransportSupport.h>
+#include <hidl/Status.h>
+#include <hidlmemory/FrameworkUtils.h>
+#include <utils/Condition.h>
+#include <utils/Mutex.h>
+
+#define CLEAR_KEY_SYSTEM_ID 0xF6D8
+#define INVALID_SYSTEM_ID 0
+#define WAIT_TIMEOUT 3000000000
+
+#define PROVISION_STR \
+ "{ " \
+ " \"id\": 21140844, " \
+ " \"name\": \"Test Title\", " \
+ " \"lowercase_organization_name\": \"Android\", " \
+ " \"asset_key\": { " \
+ " \"encryption_key\": \"nezAr3CHFrmBR9R8Tedotw==\" " \
+ " }, " \
+ " \"cas_type\": 1, " \
+ " \"track_types\": [ ] " \
+ "} "
+
+using android::Condition;
+using android::IMemory;
+using android::IMemoryHeap;
+using android::MemoryDealer;
+using android::Mutex;
+using android::sp;
+using android::hardware::fromHeap;
+using android::hardware::hidl_string;
+using android::hardware::hidl_vec;
+using android::hardware::HidlMemory;
+using android::hardware::Return;
+using android::hardware::Void;
+using android::hardware::cas::native::V1_0::BufferType;
+using android::hardware::cas::native::V1_0::DestinationBuffer;
+using android::hardware::cas::native::V1_0::IDescrambler;
+using android::hardware::cas::native::V1_0::ScramblingControl;
+using android::hardware::cas::native::V1_0::SharedBuffer;
+using android::hardware::cas::native::V1_0::SubSample;
+using android::hardware::cas::V1_0::HidlCasPluginDescriptor;
+using android::hardware::cas::V1_0::IDescramblerBase;
+using android::hardware::cas::V1_0::Status;
+using android::hardware::cas::V1_2::ICas;
+using android::hardware::cas::V1_2::ICasListener;
+using android::hardware::cas::V1_2::IMediaCasService;
+using android::hardware::cas::V1_2::ScramblingMode;
+using android::hardware::cas::V1_2::SessionIntent;
+using android::hardware::cas::V1_2::StatusEvent;
+
+namespace {
+
+const uint8_t kEcmBinaryBuffer[] = {
+ 0x00, 0x00, 0x01, 0xf0, 0x00, 0x50, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x46, 0x00,
+ 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x27, 0x10, 0x02, 0x00,
+ 0x01, 0x77, 0x01, 0x42, 0x95, 0x6c, 0x0e, 0xe3, 0x91, 0xbc, 0xfd, 0x05, 0xb1, 0x60, 0x4f,
+ 0x17, 0x82, 0xa4, 0x86, 0x9b, 0x23, 0x56, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
+ 0x27, 0x10, 0x02, 0x00, 0x01, 0x77, 0x01, 0x42, 0x95, 0x6c, 0xd7, 0x43, 0x62, 0xf8, 0x1c,
+ 0x62, 0x19, 0x05, 0xc7, 0x3a, 0x42, 0xcd, 0xfd, 0xd9, 0x13, 0x48,
+};
+
+const SubSample kSubSamples[] = {{162, 0}, {0, 184}, {0, 184}};
+
+const uint8_t kInBinaryBuffer[] = {
+ 0x00, 0x00, 0x00, 0x01, 0x09, 0xf0, 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x1e, 0xdb,
+ 0x01, 0x40, 0x16, 0xec, 0x04, 0x40, 0x00, 0x00, 0x03, 0x00, 0x40, 0x00, 0x00, 0x0f, 0x03,
+ 0xc5, 0x8b, 0xb8, 0x00, 0x00, 0x00, 0x01, 0x68, 0xca, 0x8c, 0xb2, 0x00, 0x00, 0x01, 0x06,
+ 0x05, 0xff, 0xff, 0x70, 0xdc, 0x45, 0xe9, 0xbd, 0xe6, 0xd9, 0x48, 0xb7, 0x96, 0x2c, 0xd8,
+ 0x20, 0xd9, 0x23, 0xee, 0xef, 0x78, 0x32, 0x36, 0x34, 0x20, 0x2d, 0x20, 0x63, 0x6f, 0x72,
+ 0x65, 0x20, 0x31, 0x34, 0x32, 0x20, 0x2d, 0x20, 0x48, 0x2e, 0x32, 0x36, 0x34, 0x2f, 0x4d,
+ 0x50, 0x45, 0x47, 0x2d, 0x34, 0x20, 0x41, 0x56, 0x43, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x63,
+ 0x20, 0x2d, 0x20, 0x43, 0x6f, 0x70, 0x79, 0x6c, 0x65, 0x66, 0x74, 0x20, 0x32, 0x30, 0x30,
+ 0x33, 0x2d, 0x32, 0x30, 0x31, 0x34, 0x20, 0x2d, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f,
+ 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6c, 0x61, 0x6e, 0x2e, 0x6f,
+ 0x72, 0x67, 0x2f, 0x78, 0x32, 0x36, 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x6e, 0x45, 0x21,
+ 0x82, 0x38, 0xf0, 0x9d, 0x7d, 0x96, 0xe6, 0x94, 0xae, 0xe2, 0x87, 0x8f, 0x04, 0x49, 0xe5,
+ 0xf6, 0x8c, 0x8b, 0x9a, 0x10, 0x18, 0xba, 0x94, 0xe9, 0x22, 0x31, 0x04, 0x7e, 0x60, 0x5b,
+ 0xc4, 0x24, 0x00, 0x90, 0x62, 0x0d, 0xdc, 0x85, 0x74, 0x75, 0x78, 0xd0, 0x14, 0x08, 0xcb,
+ 0x02, 0x1d, 0x7d, 0x9d, 0x34, 0xe8, 0x81, 0xb9, 0xf7, 0x09, 0x28, 0x79, 0x29, 0x8d, 0xe3,
+ 0x14, 0xed, 0x5f, 0xca, 0xaf, 0xf4, 0x1c, 0x49, 0x15, 0xe1, 0x80, 0x29, 0x61, 0x76, 0x80,
+ 0x43, 0xf8, 0x58, 0x53, 0x40, 0xd7, 0x31, 0x6d, 0x61, 0x81, 0x41, 0xe9, 0x77, 0x9f, 0x9c,
+ 0xe1, 0x6d, 0xf2, 0xee, 0xd9, 0xc8, 0x67, 0xd2, 0x5f, 0x48, 0x73, 0xe3, 0x5c, 0xcd, 0xa7,
+ 0x45, 0x58, 0xbb, 0xdd, 0x28, 0x1d, 0x68, 0xfc, 0xb4, 0xc6, 0xf6, 0x92, 0xf6, 0x30, 0x03,
+ 0xaa, 0xe4, 0x32, 0xf6, 0x34, 0x51, 0x4b, 0x0f, 0x8c, 0xf9, 0xac, 0x98, 0x22, 0xfb, 0x49,
+ 0xc8, 0xbf, 0xca, 0x8c, 0x80, 0x86, 0x5d, 0xd7, 0xa4, 0x52, 0xb1, 0xd9, 0xa6, 0x04, 0x4e,
+ 0xb3, 0x2d, 0x1f, 0xb8, 0x35, 0xcc, 0x45, 0x6d, 0x9c, 0x20, 0xa7, 0xa4, 0x34, 0x59, 0x72,
+ 0xe3, 0xae, 0xba, 0x49, 0xde, 0xd1, 0xaa, 0xee, 0x3d, 0x77, 0xfc, 0x5d, 0xc6, 0x1f, 0x9d,
+ 0xac, 0xc2, 0x15, 0x66, 0xb8, 0xe1, 0x54, 0x4e, 0x74, 0x93, 0xdb, 0x9a, 0x24, 0x15, 0x6e,
+ 0x20, 0xa3, 0x67, 0x3e, 0x5a, 0x24, 0x41, 0x5e, 0xb0, 0xe6, 0x35, 0x87, 0x1b, 0xc8, 0x7a,
+ 0xf9, 0x77, 0x65, 0xe0, 0x01, 0xf2, 0x4c, 0xe4, 0x2b, 0xa9, 0x64, 0x96, 0x96, 0x0b, 0x46,
+ 0xca, 0xea, 0x79, 0x0e, 0x78, 0xa3, 0x5f, 0x43, 0xfc, 0x47, 0x6a, 0x12, 0xfa, 0xc4, 0x33,
+ 0x0e, 0x88, 0x1c, 0x19, 0x3a, 0x00, 0xc3, 0x4e, 0xb5, 0xd8, 0xfa, 0x8e, 0xf1, 0xbc, 0x3d,
+ 0xb2, 0x7e, 0x50, 0x8d, 0x67, 0xc3, 0x6b, 0xed, 0xe2, 0xea, 0xa6, 0x1f, 0x25, 0x24, 0x7c,
+ 0x94, 0x74, 0x50, 0x49, 0xe3, 0xc6, 0x58, 0x2e, 0xfd, 0x28, 0xb4, 0xc6, 0x73, 0xb1, 0x53,
+ 0x74, 0x27, 0x94, 0x5c, 0xdf, 0x69, 0xb7, 0xa1, 0xd7, 0xf5, 0xd3, 0x8a, 0x2c, 0x2d, 0xb4,
+ 0x5e, 0x8a, 0x16, 0x14, 0x54, 0x64, 0x6e, 0x00, 0x6b, 0x11, 0x59, 0x8a, 0x63, 0x38, 0x80,
+ 0x76, 0xc3, 0xd5, 0x59, 0xf7, 0x3f, 0xd2, 0xfa, 0xa5, 0xca, 0x82, 0xff, 0x4a, 0x62, 0xf0,
+ 0xe3, 0x42, 0xf9, 0x3b, 0x38, 0x27, 0x8a, 0x89, 0xaa, 0x50, 0x55, 0x4b, 0x29, 0xf1, 0x46,
+ 0x7c, 0x75, 0xef, 0x65, 0xaf, 0x9b, 0x0d, 0x6d, 0xda, 0x25, 0x94, 0x14, 0xc1, 0x1b, 0xf0,
+ 0xc5, 0x4c, 0x24, 0x0e, 0x65,
+};
+
+const uint8_t kOutRefBinaryBuffer[] = {
+ 0x00, 0x00, 0x00, 0x01, 0x09, 0xf0, 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x1e, 0xdb,
+ 0x01, 0x40, 0x16, 0xec, 0x04, 0x40, 0x00, 0x00, 0x03, 0x00, 0x40, 0x00, 0x00, 0x0f, 0x03,
+ 0xc5, 0x8b, 0xb8, 0x00, 0x00, 0x00, 0x01, 0x68, 0xca, 0x8c, 0xb2, 0x00, 0x00, 0x01, 0x06,
+ 0x05, 0xff, 0xff, 0x70, 0xdc, 0x45, 0xe9, 0xbd, 0xe6, 0xd9, 0x48, 0xb7, 0x96, 0x2c, 0xd8,
+ 0x20, 0xd9, 0x23, 0xee, 0xef, 0x78, 0x32, 0x36, 0x34, 0x20, 0x2d, 0x20, 0x63, 0x6f, 0x72,
+ 0x65, 0x20, 0x31, 0x34, 0x32, 0x20, 0x2d, 0x20, 0x48, 0x2e, 0x32, 0x36, 0x34, 0x2f, 0x4d,
+ 0x50, 0x45, 0x47, 0x2d, 0x34, 0x20, 0x41, 0x56, 0x43, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x63,
+ 0x20, 0x2d, 0x20, 0x43, 0x6f, 0x70, 0x79, 0x6c, 0x65, 0x66, 0x74, 0x20, 0x32, 0x30, 0x30,
+ 0x33, 0x2d, 0x32, 0x30, 0x31, 0x34, 0x20, 0x2d, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f,
+ 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6c, 0x61, 0x6e, 0x2e, 0x6f,
+ 0x72, 0x67, 0x2f, 0x78, 0x32, 0x36, 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x20, 0x2d, 0x20,
+ 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x20, 0x63, 0x61, 0x62, 0x61, 0x63, 0x3d,
+ 0x30, 0x20, 0x72, 0x65, 0x66, 0x3d, 0x32, 0x20, 0x64, 0x65, 0x62, 0x6c, 0x6f, 0x63, 0x6b,
+ 0x3d, 0x31, 0x3a, 0x30, 0x3a, 0x30, 0x20, 0x61, 0x6e, 0x61, 0x6c, 0x79, 0x73, 0x65, 0x3d,
+ 0x30, 0x78, 0x31, 0x3a, 0x30, 0x78, 0x31, 0x31, 0x31, 0x20, 0x6d, 0x65, 0x3d, 0x68, 0x65,
+ 0x78, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x65, 0x3d, 0x37, 0x20, 0x70, 0x73, 0x79, 0x3d, 0x31,
+ 0x20, 0x70, 0x73, 0x79, 0x5f, 0x72, 0x64, 0x3d, 0x31, 0x2e, 0x30, 0x30, 0x3a, 0x30, 0x2e,
+ 0x30, 0x30, 0x20, 0x6d, 0x69, 0x78, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x66, 0x3d, 0x31, 0x20,
+ 0x6d, 0x65, 0x5f, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x3d, 0x31, 0x36, 0x20, 0x63, 0x68, 0x72,
+ 0x6f, 0x6d, 0x61, 0x5f, 0x6d, 0x65, 0x3d, 0x31, 0x20, 0x74, 0x72, 0x65, 0x6c, 0x6c, 0x69,
+ 0x73, 0x3d, 0x31, 0x20, 0x38, 0x78, 0x38, 0x64, 0x63, 0x74, 0x3d, 0x30, 0x20, 0x63, 0x71,
+ 0x6d, 0x3d, 0x30, 0x20, 0x64, 0x65, 0x61, 0x64, 0x7a, 0x6f, 0x6e, 0x65, 0x3d, 0x32, 0x31,
+ 0x2c, 0x31, 0x31, 0x20, 0x66, 0x61, 0x73, 0x74, 0x5f, 0x70, 0x73, 0x6b, 0x69, 0x70, 0x3d,
+ 0x31, 0x20, 0x63, 0x68, 0x72, 0x6f, 0x6d, 0x61, 0x5f, 0x71, 0x70, 0x5f, 0x6f, 0x66, 0x66,
+ 0x73, 0x65, 0x74, 0x3d, 0x2d, 0x32, 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d,
+ 0x36, 0x30, 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x61, 0x68, 0x65, 0x61, 0x64, 0x5f, 0x74, 0x68,
+ 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, 0x35, 0x20, 0x73, 0x6c, 0x69, 0x63, 0x65, 0x64, 0x5f,
+ 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, 0x30, 0x20, 0x6e, 0x72, 0x3d, 0x30, 0x20,
+ 0x64, 0x65, 0x63, 0x69, 0x6d, 0x61, 0x74, 0x65, 0x3d, 0x31, 0x20, 0x69, 0x6e, 0x74, 0x65,
+ 0x72, 0x6c, 0x61, 0x63, 0x65, 0x64, 0x3d, 0x30, 0x20, 0x62, 0x6c, 0x75, 0x72, 0x61, 0x79,
+ 0x5f, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x3d, 0x30, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74,
+ 0x72, 0x61, 0x69, 0x6e, 0x65, 0x64, 0x5f, 0x69, 0x6e, 0x74, 0x72, 0x61, 0x3d, 0x30, 0x20,
+ 0x62, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x3d, 0x30, 0x20, 0x77, 0x65, 0x69, 0x67, 0x68,
+ 0x74, 0x70, 0x3d, 0x30, 0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, 0x74, 0x3d, 0x32, 0x35, 0x30,
+ 0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x3d, 0x32, 0x35, 0x20,
+ 0x73, 0x63, 0x65, 0x6e, 0x65,
+};
+
+class MediaCasListener : public ICasListener {
+ public:
+ virtual Return<void> onEvent(int32_t event, int32_t arg,
+ const hidl_vec<uint8_t>& data) override {
+ android::Mutex::Autolock autoLock(mMsgLock);
+ mEvent = event;
+ mEventArg = arg;
+ mEventData = data;
+
+ mEventReceived = true;
+ mMsgCondition.signal();
+ return Void();
+ }
+
+ virtual Return<void> onSessionEvent(const hidl_vec<uint8_t>& sessionId, int32_t event,
+ int32_t arg, const hidl_vec<uint8_t>& data) override {
+ android::Mutex::Autolock autoLock(mMsgLock);
+ mSessionId = sessionId;
+ mEvent = event;
+ mEventArg = arg;
+ mEventData = data;
+
+ mEventReceived = true;
+ mMsgCondition.signal();
+ return Void();
+ }
+
+ virtual Return<void> onStatusUpdate(StatusEvent event, int32_t arg) override {
+ android::Mutex::Autolock autoLock(mMsgLock);
+ mStatusEvent = event;
+ mEventArg = arg;
+
+ mEventReceived = true;
+ mMsgCondition.signal();
+ return Void();
+ }
+
+ void testEventEcho(sp<ICas>& mediaCas, int32_t& event, int32_t& eventArg,
+ hidl_vec<uint8_t>& eventData);
+
+ void testSessionEventEcho(sp<ICas>& mediaCas, const hidl_vec<uint8_t>& sessionId,
+ int32_t& event, int32_t& eventArg, hidl_vec<uint8_t>& eventData);
+
+ void testStatusUpdate(sp<ICas>& mediaCas, std::vector<uint8_t>* sessionId, SessionIntent intent,
+ ScramblingMode mode);
+
+ private:
+ int32_t mEvent = -1;
+ int32_t mEventArg = -1;
+ StatusEvent mStatusEvent;
+ bool mEventReceived = false;
+ hidl_vec<uint8_t> mEventData;
+ hidl_vec<uint8_t> mSessionId;
+ android::Mutex mMsgLock;
+ android::Condition mMsgCondition;
+};
+
+void MediaCasListener::testEventEcho(sp<ICas>& mediaCas, int32_t& event, int32_t& eventArg,
+ hidl_vec<uint8_t>& eventData) {
+ mEventReceived = false;
+ auto returnStatus = mediaCas->sendEvent(event, eventArg, eventData);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ android::Mutex::Autolock autoLock(mMsgLock);
+ while (!mEventReceived) {
+ if (-ETIMEDOUT == mMsgCondition.waitRelative(mMsgLock, WAIT_TIMEOUT)) {
+ EXPECT_TRUE(false) << "event not received within timeout";
+ return;
+ }
+ }
+
+ EXPECT_EQ(mEvent, event);
+ EXPECT_EQ(mEventArg, eventArg);
+ EXPECT_TRUE(mEventData == eventData);
+}
+
+void MediaCasListener::testSessionEventEcho(sp<ICas>& mediaCas, const hidl_vec<uint8_t>& sessionId,
+ int32_t& event, int32_t& eventArg,
+ hidl_vec<uint8_t>& eventData) {
+ mEventReceived = false;
+ auto returnStatus = mediaCas->sendSessionEvent(sessionId, event, eventArg, eventData);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ android::Mutex::Autolock autoLock(mMsgLock);
+ while (!mEventReceived) {
+ if (-ETIMEDOUT == mMsgCondition.waitRelative(mMsgLock, WAIT_TIMEOUT)) {
+ EXPECT_TRUE(false) << "event not received within timeout";
+ return;
+ }
+ }
+
+ EXPECT_TRUE(mSessionId == sessionId);
+ EXPECT_EQ(mEvent, event);
+ EXPECT_EQ(mEventArg, eventArg);
+ EXPECT_TRUE(mEventData == eventData);
+}
+
+void MediaCasListener::testStatusUpdate(sp<ICas>& mediaCas, std::vector<uint8_t>* sessionId,
+ SessionIntent intent, ScramblingMode mode) {
+ mEventReceived = false;
+ android::hardware::cas::V1_2::Status sessionStatus;
+ auto returnVoid = mediaCas->openSession_1_2(
+ intent, mode,
+ [&](android::hardware::cas::V1_2::Status status, const hidl_vec<uint8_t>& id) {
+ sessionStatus = status;
+ *sessionId = id;
+ });
+ EXPECT_TRUE(returnVoid.isOk());
+ EXPECT_EQ(android::hardware::cas::V1_2::Status::OK, sessionStatus);
+
+ android::Mutex::Autolock autoLock(mMsgLock);
+ while (!mEventReceived) {
+ if (-ETIMEDOUT == mMsgCondition.waitRelative(mMsgLock, WAIT_TIMEOUT)) {
+ EXPECT_TRUE(false) << "event not received within timeout";
+ return;
+ }
+ }
+ EXPECT_EQ(mStatusEvent, static_cast<StatusEvent>(intent));
+ EXPECT_EQ(mEventArg, static_cast<int32_t>(mode));
+}
+
+// Test environment for Cas HIDL HAL.
+class CasHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
+ public:
+ // get the test environment singleton
+ static CasHidlEnvironment* Instance() {
+ static CasHidlEnvironment* instance = new CasHidlEnvironment;
+ return instance;
+ }
+
+ virtual void registerTestServices() override { registerTestService<IMediaCasService>(); }
+};
+
+class MediaCasHidlTest : public ::testing::VtsHalHidlTargetTestBase {
+ public:
+ virtual void SetUp() override {
+ mService = ::testing::VtsHalHidlTargetTestBase::getService<IMediaCasService>(
+ CasHidlEnvironment::Instance()->getServiceName<IMediaCasService>());
+ ASSERT_NE(mService, nullptr);
+ }
+
+ sp<IMediaCasService> mService;
+
+ protected:
+ static void description(const std::string& description) {
+ RecordProperty("description", description);
+ }
+
+ sp<ICas> mMediaCas;
+ sp<IDescramblerBase> mDescramblerBase;
+ sp<MediaCasListener> mCasListener;
+ typedef struct _OobInputTestParams {
+ const SubSample* subSamples;
+ uint32_t numSubSamples;
+ size_t imemSizeActual;
+ uint64_t imemOffset;
+ uint64_t imemSize;
+ uint64_t srcOffset;
+ uint64_t dstOffset;
+ } OobInputTestParams;
+
+ ::testing::AssertionResult createCasPlugin(int32_t caSystemId);
+ ::testing::AssertionResult openCasSession(std::vector<uint8_t>* sessionId);
+ ::testing::AssertionResult openCasSession_1_2(std::vector<uint8_t>* sessionId,
+ SessionIntent intent, ScramblingMode mode);
+ ::testing::AssertionResult descrambleTestInputBuffer(const sp<IDescrambler>& descrambler,
+ Status* descrambleStatus,
+ sp<IMemory>* hidlInMemory);
+ ::testing::AssertionResult descrambleTestOobInput(const sp<IDescrambler>& descrambler,
+ Status* descrambleStatus,
+ const OobInputTestParams& params);
+};
+
+::testing::AssertionResult MediaCasHidlTest::createCasPlugin(int32_t caSystemId) {
+ auto status = mService->isSystemIdSupported(caSystemId);
+ if (!status.isOk() || !status) {
+ return ::testing::AssertionFailure();
+ }
+ status = mService->isDescramblerSupported(caSystemId);
+ if (!status.isOk() || !status) {
+ return ::testing::AssertionFailure();
+ }
+
+ mCasListener = new MediaCasListener();
+ auto pluginStatus = mService->createPluginExt(caSystemId, mCasListener);
+ if (!pluginStatus.isOk()) {
+ return ::testing::AssertionFailure();
+ }
+ mMediaCas = ICas::castFrom(pluginStatus);
+ if (mMediaCas == nullptr) {
+ return ::testing::AssertionFailure();
+ }
+
+ auto descramblerStatus = mService->createDescrambler(caSystemId);
+ if (!descramblerStatus.isOk()) {
+ return ::testing::AssertionFailure();
+ }
+ mDescramblerBase = descramblerStatus;
+ return ::testing::AssertionResult(mDescramblerBase != nullptr);
+}
+
+::testing::AssertionResult MediaCasHidlTest::openCasSession(std::vector<uint8_t>* sessionId) {
+ Status sessionStatus;
+ auto returnVoid = mMediaCas->openSession([&](Status status, const hidl_vec<uint8_t>& id) {
+ sessionStatus = status;
+ *sessionId = id;
+ });
+ return ::testing::AssertionResult(returnVoid.isOk() && (Status::OK == sessionStatus));
+}
+
+::testing::AssertionResult MediaCasHidlTest::descrambleTestInputBuffer(
+ const sp<IDescrambler>& descrambler, Status* descrambleStatus, sp<IMemory>* inMemory) {
+ hidl_vec<SubSample> hidlSubSamples;
+ hidlSubSamples.setToExternal(const_cast<SubSample*>(kSubSamples),
+ (sizeof(kSubSamples) / sizeof(SubSample)), false /*own*/);
+
+ sp<MemoryDealer> dealer = new MemoryDealer(sizeof(kInBinaryBuffer), "vts-cas");
+ if (nullptr == dealer.get()) {
+ ALOGE("couldn't get MemoryDealer!");
+ return ::testing::AssertionFailure();
+ }
+
+ sp<IMemory> mem = dealer->allocate(sizeof(kInBinaryBuffer));
+ if (nullptr == mem.get()) {
+ ALOGE("couldn't allocate IMemory!");
+ return ::testing::AssertionFailure();
+ }
+ *inMemory = mem;
+
+ // build HidlMemory from memory heap
+ ssize_t offset;
+ size_t size;
+ sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
+ if (nullptr == heap.get()) {
+ ALOGE("couldn't get memory heap!");
+ return ::testing::AssertionFailure();
+ }
+
+ uint8_t* ipBuffer = static_cast<uint8_t*>(static_cast<void*>(mem->unsecurePointer()));
+ memcpy(ipBuffer, kInBinaryBuffer, sizeof(kInBinaryBuffer));
+
+ // hidlMemory is not to be passed out of scope!
+ sp<HidlMemory> hidlMemory = fromHeap(heap);
+
+ SharedBuffer srcBuffer = {
+ .heapBase = *hidlMemory, .offset = (uint64_t)offset, .size = (uint64_t)size};
+
+ DestinationBuffer dstBuffer;
+ dstBuffer.type = BufferType::SHARED_MEMORY;
+ dstBuffer.nonsecureMemory = srcBuffer;
+
+ uint32_t outBytes;
+ hidl_string detailedError;
+ auto returnVoid = descrambler->descramble(
+ ScramblingControl::EVENKEY /*2*/, hidlSubSamples, srcBuffer, 0, dstBuffer, 0,
+ [&](Status status, uint32_t bytesWritten, const hidl_string& detailedErr) {
+ *descrambleStatus = status;
+ outBytes = bytesWritten;
+ detailedError = detailedErr;
+ });
+ if (!returnVoid.isOk() || *descrambleStatus != Status::OK) {
+ ALOGI("descramble failed, trans=%s, status=%d, outBytes=%u, error=%s",
+ returnVoid.description().c_str(), *descrambleStatus, outBytes, detailedError.c_str());
+ }
+ return ::testing::AssertionResult(returnVoid.isOk());
+}
+
+::testing::AssertionResult MediaCasHidlTest::descrambleTestOobInput(
+ const sp<IDescrambler>& descrambler, Status* descrambleStatus,
+ const OobInputTestParams& params) {
+ hidl_vec<SubSample> hidlSubSamples;
+ hidlSubSamples.setToExternal(const_cast<SubSample*>(params.subSamples), params.numSubSamples,
+ false /*own*/);
+
+ sp<MemoryDealer> dealer = new MemoryDealer(params.imemSizeActual, "vts-cas");
+ if (nullptr == dealer.get()) {
+ ALOGE("couldn't get MemoryDealer!");
+ return ::testing::AssertionFailure();
+ }
+
+ sp<IMemory> mem = dealer->allocate(params.imemSizeActual);
+ if (nullptr == mem.get()) {
+ ALOGE("couldn't allocate IMemory!");
+ return ::testing::AssertionFailure();
+ }
+
+ // build HidlMemory from memory heap
+ ssize_t offset;
+ size_t size;
+ sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
+ if (nullptr == heap.get()) {
+ ALOGE("couldn't get memory heap!");
+ return ::testing::AssertionFailure();
+ }
+
+ // hidlMemory is not to be passed out of scope!
+ sp<HidlMemory> hidlMemory = fromHeap(heap);
+
+ SharedBuffer srcBuffer = {
+ .heapBase = *hidlMemory,
+ .offset = (uint64_t)offset + params.imemOffset,
+ .size = (uint64_t)params.imemSize,
+ };
+
+ DestinationBuffer dstBuffer;
+ dstBuffer.type = BufferType::SHARED_MEMORY;
+ dstBuffer.nonsecureMemory = srcBuffer;
+
+ uint32_t outBytes;
+ hidl_string detailedError;
+ auto returnVoid = descrambler->descramble(
+ ScramblingControl::EVENKEY /*2*/, hidlSubSamples, srcBuffer, params.srcOffset,
+ dstBuffer, params.dstOffset,
+ [&](Status status, uint32_t bytesWritten, const hidl_string& detailedErr) {
+ *descrambleStatus = status;
+ outBytes = bytesWritten;
+ detailedError = detailedErr;
+ });
+ if (!returnVoid.isOk() || *descrambleStatus != Status::OK) {
+ ALOGI("descramble failed, trans=%s, status=%d, outBytes=%u, error=%s",
+ returnVoid.description().c_str(), *descrambleStatus, outBytes, detailedError.c_str());
+ }
+ return ::testing::AssertionResult(returnVoid.isOk());
+}
+
+TEST_F(MediaCasHidlTest, TestClearKeyApisWithSession) {
+ description("Test that valid call sequences with SessionEvent send and receive");
+
+ ASSERT_TRUE(createCasPlugin(CLEAR_KEY_SYSTEM_ID));
+
+ auto returnStatus = mMediaCas->provision(hidl_string(PROVISION_STR));
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ hidl_vec<uint8_t> hidlPvtData;
+ hidlPvtData.resize(256);
+ returnStatus = mMediaCas->setPrivateData(hidlPvtData);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ std::vector<uint8_t> sessionId;
+ ASSERT_TRUE(openCasSession(&sessionId));
+ returnStatus = mMediaCas->setSessionPrivateData(sessionId, hidlPvtData);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ std::vector<uint8_t> streamSessionId;
+ ASSERT_TRUE(openCasSession(&streamSessionId));
+ returnStatus = mMediaCas->setSessionPrivateData(streamSessionId, hidlPvtData);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ returnStatus = mDescramblerBase->setMediaCasSession(sessionId);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ returnStatus = mDescramblerBase->setMediaCasSession(streamSessionId);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ hidl_vec<uint8_t> hidlNullPtr;
+ hidlNullPtr.setToExternal(static_cast<uint8_t*>(nullptr), 0);
+ returnStatus = mMediaCas->refreshEntitlements(3, hidlNullPtr);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ uint8_t refreshData[] = {0, 1, 2, 3};
+ hidl_vec<uint8_t> hidlRefreshData;
+ hidlRefreshData.setToExternal(static_cast<uint8_t*>(refreshData), sizeof(refreshData));
+ returnStatus = mMediaCas->refreshEntitlements(10, hidlRefreshData);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ int32_t eventID = 1;
+ int32_t eventArg = 2;
+ mCasListener->testEventEcho(mMediaCas, eventID, eventArg, hidlNullPtr);
+ mCasListener->testSessionEventEcho(mMediaCas, sessionId, eventID, eventArg, hidlNullPtr);
+
+ eventID = 3;
+ eventArg = 4;
+ uint8_t eventData[] = {'e', 'v', 'e', 'n', 't', 'd', 'a', 't', 'a'};
+ hidl_vec<uint8_t> hidlEventData;
+ hidlEventData.setToExternal(static_cast<uint8_t*>(eventData), sizeof(eventData));
+ mCasListener->testEventEcho(mMediaCas, eventID, eventArg, hidlEventData);
+ mCasListener->testSessionEventEcho(mMediaCas, sessionId, eventID, eventArg, hidlEventData);
+
+ SessionIntent intent = SessionIntent::LIVE;
+ ScramblingMode mode = ScramblingMode::DVB_CSA1;
+ mCasListener->testStatusUpdate(mMediaCas, &sessionId, intent, mode);
+
+ uint8_t clearKeyEmmData[] = {'c', 'l', 'e', 'a', 'r', 'k', 'e', 'y', 'e', 'm', 'm'};
+ hidl_vec<uint8_t> hidlClearKeyEmm;
+ hidlClearKeyEmm.setToExternal(static_cast<uint8_t*>(clearKeyEmmData), sizeof(clearKeyEmmData));
+ returnStatus = mMediaCas->processEmm(hidlClearKeyEmm);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ hidl_vec<uint8_t> hidlEcm;
+ hidlEcm.setToExternal(const_cast<uint8_t*>(kEcmBinaryBuffer), sizeof(kEcmBinaryBuffer));
+ returnStatus = mMediaCas->processEcm(sessionId, hidlEcm);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+ returnStatus = mMediaCas->processEcm(streamSessionId, hidlEcm);
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ EXPECT_FALSE(mDescramblerBase->requiresSecureDecoderComponent("video/avc"));
+
+ sp<IDescrambler> descrambler;
+ descrambler = IDescrambler::castFrom(mDescramblerBase);
+ ASSERT_NE(descrambler, nullptr);
+
+ Status descrambleStatus = Status::OK;
+ sp<IMemory> dataMemory;
+
+ ASSERT_TRUE(descrambleTestInputBuffer(descrambler, &descrambleStatus, &dataMemory));
+ EXPECT_EQ(Status::OK, descrambleStatus);
+
+ ASSERT_NE(nullptr, dataMemory.get());
+ uint8_t* opBuffer = static_cast<uint8_t*>(static_cast<void*>(dataMemory->unsecurePointer()));
+
+ int compareResult =
+ memcmp(static_cast<const void*>(opBuffer),
+ static_cast<const void*>(kOutRefBinaryBuffer), sizeof(kOutRefBinaryBuffer));
+ EXPECT_EQ(0, compareResult);
+
+ returnStatus = mDescramblerBase->release();
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+
+ returnStatus = mMediaCas->release();
+ EXPECT_TRUE(returnStatus.isOk());
+ EXPECT_EQ(Status::OK, returnStatus);
+}
+
+} // anonymous namespace
+
+int main(int argc, char** argv) {
+ ::testing::AddGlobalTestEnvironment(CasHidlEnvironment::Instance());
+ ::testing::InitGoogleTest(&argc, argv);
+ CasHidlEnvironment::Instance()->init(&argc, argv);
+ int status = RUN_ALL_TESTS();
+ LOG(INFO) << "Test result = " << status;
+ return status;
+}
diff --git a/current.txt b/current.txt
index 3ccc531..e22db18 100644
--- a/current.txt
+++ b/current.txt
@@ -587,6 +587,9 @@
# HALs released in Android R
07d0a252b2d8fa35887908a996ba395cf392968395fc30afab791f46e0c22a52 android.hardware.boot@1.1::IBootControl
74049a402be913963edfdd80828a53736570e9d8124a1bf18166b6ed46a6b0ab android.hardware.boot@1.1::types
+ce8dbe76eb9ee94b46ef98f725be992e760a5751073d4f4912484026541371f3 android.hardware.health@2.1::IHealth
+26f04510a0b57aba5167c5c0a7c2f077c2acbb98b81902a072517829fd9fd67f android.hardware.health@2.1::IHealthInfoCallback
+db47f4ceceb1f06c656f39caa70c557b0f8471ef59fd58611bea667ffca20101 android.hardware.health@2.1::types
34515afa2bb792d3c6d8495a5f5d907d179c8507ca5e55c10050d02ae1d516ef android.hardware.neuralnetworks@1.3::IDevice
b74fe72cfe438f50e772e6a307657ff449d5bde83c15dd1f140ff2edbe73499c android.hardware.neuralnetworks@1.3::types
544049dcda3f943ad67d83d5277f06681a3782982a9af5a78b5d4e8d295d061a android.hardware.vibrator@1.4::IVibrator
diff --git a/graphics/composer/2.4/Android.bp b/graphics/composer/2.4/Android.bp
index 0e1bc09..5f700be 100644
--- a/graphics/composer/2.4/Android.bp
+++ b/graphics/composer/2.4/Android.bp
@@ -7,7 +7,9 @@
enabled: true,
},
srcs: [
+ "types.hal",
"IComposer.hal",
+ "IComposerCallback.hal",
"IComposerClient.hal",
],
interfaces: [
diff --git a/graphics/composer/2.4/IComposerCallback.hal b/graphics/composer/2.4/IComposerCallback.hal
new file mode 100644
index 0000000..5c3f8bd
--- /dev/null
+++ b/graphics/composer/2.4/IComposerCallback.hal
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2019 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 android.hardware.graphics.composer@2.4;
+
+import @2.1::Display;
+import @2.1::IComposerCallback;
+
+interface IComposerCallback extends @2.1::IComposerCallback {
+ /**
+ * Notifies the client that a vsync event has occurred. This callback must
+ * only be triggered when vsync is enabled for this display (through
+ * setVsyncEnabled).
+ *
+ * @param display is the display which has received a vsync event
+ * @param timestamp is the CLOCK_MONOTONIC time at which the vsync event
+ * occurred, in nanoseconds.
+ * @param vsyncPeriodNanos is the display vsync period in nanoseconds i.e. the next onVsync_2_4
+ * is expected to be called vsyncPeriodNanos nanoseconds after this call.
+ */
+ oneway onVsync_2_4(Display display, int64_t timestamp, VsyncPeriodNanos vsyncPeriodNanos);
+};
diff --git a/graphics/composer/2.4/IComposerClient.hal b/graphics/composer/2.4/IComposerClient.hal
index 60445f5..c2102d5 100644
--- a/graphics/composer/2.4/IComposerClient.hal
+++ b/graphics/composer/2.4/IComposerClient.hal
@@ -16,6 +16,8 @@
package android.hardware.graphics.composer@2.4;
+import IComposerCallback;
+import @2.1::Config;
import @2.1::Display;
import @2.1::Error;
import @2.3::IComposerClient;
@@ -50,6 +52,32 @@
};
/**
+ * Constraints for changing vsync period.
+ */
+ struct VsyncPeriodChangeConstraints {
+ /**
+ * Time in CLOCK_MONOTONIC after which the vsync period may change
+ * (i.e., the vsync period must not change before this time).
+ */
+ int64_t desiredTimeNanos;
+ /**
+ * If true, requires that the vsync period change must happen seamlessly without
+ * a noticeable visual artifact.
+ */
+ bool seamlessRequired;
+ };
+
+ /**
+ * Provides a IComposerCallback object for the device to call.
+ *
+ * This function must be called only once.
+ *
+ * @param callback is the IComposerCallback object.
+ */
+ @entry
+ registerCallback_2_4(IComposerCallback callback);
+
+ /**
* Provides a list of supported capabilities (as described in the
* definition of DisplayCapability above). This list must not change after
* initialization.
@@ -69,4 +97,63 @@
* @return type is the connection type of the display.
*/
getDisplayConnectionType(Display display) generates (Error error, DisplayConnectionType type);
+
+ /**
+ * Provides a list of the vsync periods supported by the display in the given configuration
+ *
+ * @param display is the display for which the vsync periods are queried.
+ * @param config is the display configuration for which the vsync periods are queried.
+ *
+ * @return error is NONE upon success. Otherwise,
+ * BAD_DISPLAY when an invalid display handle was passed in.
+ * BAD_CONFIG when an invalid config handle was passed in.
+ * @return supportedVsyncPeriods is a list of supported vsync periods.
+ */
+ getSupportedDisplayVsyncPeriods(Display display, Config config)
+ generates (Error error, vec<VsyncPeriodNanos> supportedVsyncPeriods);
+
+ /**
+ * Retrieves which vsync period the display is currently using.
+ *
+ * If no display configuration is currently active, this function must
+ * return BAD_CONFIG. If the vsync period is about to change due to a
+ * setActiveConfigAndVsyncPeriod call, this function must return the current vsync period
+ * until the change takes place.
+ *
+ * @param display is the display for which the vsync period is queried.
+ * @return error is NONE upon success. Otherwise,
+ * BAD_DISPLAY when an invalid display handle was passed in.
+ * BAD_CONFIG when no configuration is currently active.
+ * @return vsyncPeriodNanos is the current vsync period of the display.
+ */
+ getDisplayVsyncPeriod(Display display)
+ generates (Error error, VsyncPeriodNanos vsyncPeriodNanos);
+
+ /**
+ * Sets the active configuration and the refresh rate for this display.
+ * If the config is the same as the current config, only the vsync period shall change.
+ * Upon returning, the given display configuration, except vsync period, must be active and
+ * remain so until either this function is called again or the display is disconnected.
+ * When the display starts to refresh at the new vsync period, onVsync_2_4 callback must be
+ * called with the new vsync period.
+ *
+ * @param display is the display for which the active config is set.
+ * @param config is the new display configuration.
+ * @param vsyncPeriodNanos is the new display vsync period.
+ * @param vsyncPeriodChangeConstraints are the constraints required for changing vsync period.
+ *
+ * @return error is NONE upon success. Otherwise,
+ * BAD_DISPLAY when an invalid display handle was passed in.
+ * BAD_CONFIG when the configuration handle passed in is not valid
+ * for this display.
+ * BAD_VSYNC_PERIOD when an invalid vsync period is passed in.
+ * SEAMLESS_NOT_POSSIBLE when seamlessRequired was true but the display cannot achieve
+ * the vsync period change without a noticeable visual artifact.
+ * @return newVsyncAppliedTime is the time in CLOCK_MONOTONIC when the new display will start to
+ * refresh at the new vsync period.
+ */
+ setActiveConfigAndVsyncPeriod(Display display, Config config,
+ VsyncPeriodNanos vsyncPeriodNanos,
+ VsyncPeriodChangeConstraints vsyncPeriodChangeConstraints)
+ generates (Error error, int64_t newVsyncAppliedTime);
};
diff --git a/graphics/composer/2.4/types.hal b/graphics/composer/2.4/types.hal
new file mode 100644
index 0000000..b45d7a6
--- /dev/null
+++ b/graphics/composer/2.4/types.hal
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2019 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 android.hardware.graphics.composer@2.4;
+
+import @2.1::Error;
+
+enum Error : @2.1::Error {
+ /**
+ * Invalid vsync period
+ */
+ BAD_VSYNC_PERIOD = 9,
+ /**
+ * Seamless requirements cannot be met
+ */
+ SEAMLESS_NOT_POSSIBLE = 10,
+};
+
+typedef uint32_t VsyncPeriodNanos;
diff --git a/graphics/composer/2.4/utils/command-buffer/include/composer-command-buffer/2.4/ComposerCommandBuffer.h b/graphics/composer/2.4/utils/command-buffer/include/composer-command-buffer/2.4/ComposerCommandBuffer.h
index 6b64c16..cb391be 100644
--- a/graphics/composer/2.4/utils/command-buffer/include/composer-command-buffer/2.4/ComposerCommandBuffer.h
+++ b/graphics/composer/2.4/utils/command-buffer/include/composer-command-buffer/2.4/ComposerCommandBuffer.h
@@ -34,7 +34,7 @@
namespace V2_4 {
using android::hardware::MessageQueue;
-using android::hardware::graphics::composer::V2_1::Error;
+using android::hardware::graphics::composer::V2_4::Error;
using android::hardware::graphics::composer::V2_4::IComposerClient;
// This class helps build a command queue. Note that all sizes/lengths are in
diff --git a/graphics/composer/2.4/utils/hal/include/composer-hal/2.4/ComposerClient.h b/graphics/composer/2.4/utils/hal/include/composer-hal/2.4/ComposerClient.h
index c810186..ddf209b 100644
--- a/graphics/composer/2.4/utils/hal/include/composer-hal/2.4/ComposerClient.h
+++ b/graphics/composer/2.4/utils/hal/include/composer-hal/2.4/ComposerClient.h
@@ -20,8 +20,10 @@
#warning "ComposerClient.h included without LOG_TAG"
#endif
+#include <android/hardware/graphics/composer/2.4/IComposerCallback.h>
#include <android/hardware/graphics/composer/2.4/IComposerClient.h>
#include <composer-hal/2.4/ComposerHal.h>
+#include <composer-resources/2.1/ComposerResources.h>
namespace android {
namespace hardware {
@@ -38,6 +40,54 @@
public:
ComposerClientImpl(Hal* hal) : BaseType2_3(hal) {}
+ ~ComposerClientImpl() override { mHal->unregisterEventCallback_2_4(); }
+
+ class HalEventCallback : public Hal::EventCallback_2_4 {
+ public:
+ HalEventCallback(const sp<IComposerCallback> callback,
+ V2_1::hal::ComposerResources* resources)
+ : mCallback(callback), mResources(resources) {}
+
+ void onHotplug(Display display, IComposerCallback::Connection connected) override {
+ if (connected == IComposerCallback::Connection::CONNECTED) {
+ mResources->addPhysicalDisplay(display);
+ } else if (connected == IComposerCallback::Connection::DISCONNECTED) {
+ mResources->removeDisplay(display);
+ }
+
+ auto ret = mCallback->onHotplug(display, connected);
+ ALOGE_IF(!ret.isOk(), "failed to send onHotplug: %s", ret.description().c_str());
+ }
+
+ void onRefresh(Display display) override {
+ mResources->setDisplayMustValidateState(display, true);
+ auto ret = mCallback->onRefresh(display);
+ ALOGE_IF(!ret.isOk(), "failed to send onRefresh: %s", ret.description().c_str());
+ }
+
+ void onVsync(Display display, int64_t timestamp) override {
+ auto ret = mCallback->onVsync(display, timestamp);
+ ALOGE_IF(!ret.isOk(), "failed to send onVsync: %s", ret.description().c_str());
+ }
+
+ void onVsync_2_4(Display display, int64_t timestamp,
+ VsyncPeriodNanos vsyncPeriodNanos) override {
+ auto ret = mCallback->onVsync_2_4(display, timestamp, vsyncPeriodNanos);
+ ALOGE_IF(!ret.isOk(), "failed to send onVsync_2_4: %s", ret.description().c_str());
+ }
+
+ protected:
+ const sp<IComposerCallback> mCallback;
+ V2_1::hal::ComposerResources* const mResources;
+ };
+
+ Return<void> registerCallback_2_4(const sp<IComposerCallback>& callback) override {
+ // no locking as we require this function to be called only once
+ mHalEventCallback_2_4 = std::make_unique<HalEventCallback>(callback, mResources.get());
+ mHal->registerEventCallback_2_4(mHalEventCallback_2_4.get());
+ return Void();
+ }
+
Return<void> getDisplayCapabilities_2_4(
Display display, IComposerClient::getDisplayCapabilities_2_4_cb hidl_cb) override {
std::vector<IComposerClient::DisplayCapability> capabilities;
@@ -54,6 +104,36 @@
return Void();
}
+ Return<void> getSupportedDisplayVsyncPeriods(
+ Display display, Config config,
+ IComposerClient::getSupportedDisplayVsyncPeriods_cb hidl_cb) override {
+ std::vector<VsyncPeriodNanos> supportedVsyncPeriods;
+ Error error =
+ mHal->getSupportedDisplayVsyncPeriods(display, config, &supportedVsyncPeriods);
+ hidl_cb(error, supportedVsyncPeriods);
+ return Void();
+ }
+
+ Return<void> getDisplayVsyncPeriod(Display display,
+ IComposerClient::getDisplayVsyncPeriod_cb hidl_cb) override {
+ VsyncPeriodNanos vsyncPeriods;
+ Error error = mHal->getDisplayVsyncPeriod(display, &vsyncPeriods);
+ hidl_cb(error, vsyncPeriods);
+ return Void();
+ }
+
+ Return<void> setActiveConfigAndVsyncPeriod(
+ Display display, Config config, VsyncPeriodNanos vsyncPeriodNanos,
+ const IComposerClient::VsyncPeriodChangeConstraints& vsyncPeriodChangeConstraints,
+ IComposerClient::setActiveConfigAndVsyncPeriod_cb hidl_cb) override {
+ int64_t newVsyncAppliedTime = 0;
+ Error error = mHal->setActiveConfigAndVsyncPeriod(display, config, vsyncPeriodNanos,
+ vsyncPeriodChangeConstraints,
+ &newVsyncAppliedTime);
+ hidl_cb(error, newVsyncAppliedTime);
+ return Void();
+ }
+
static std::unique_ptr<ComposerClientImpl> create(Hal* hal) {
auto client = std::make_unique<ComposerClientImpl>(hal);
return client->init() ? std::move(client) : nullptr;
@@ -63,6 +143,8 @@
using BaseType2_3 = V2_3::hal::detail::ComposerClientImpl<Interface, Hal>;
using BaseType2_1 = V2_1::hal::detail::ComposerClientImpl<Interface, Hal>;
using BaseType2_1::mHal;
+ std::unique_ptr<HalEventCallback> mHalEventCallback_2_4;
+ using BaseType2_1::mResources;
};
} // namespace detail
diff --git a/graphics/composer/2.4/utils/hal/include/composer-hal/2.4/ComposerHal.h b/graphics/composer/2.4/utils/hal/include/composer-hal/2.4/ComposerHal.h
index c3bb535..0739f62 100644
--- a/graphics/composer/2.4/utils/hal/include/composer-hal/2.4/ComposerHal.h
+++ b/graphics/composer/2.4/utils/hal/include/composer-hal/2.4/ComposerHal.h
@@ -16,6 +16,7 @@
#pragma once
+#include <android/hardware/graphics/composer/2.4/types.h>
#include <composer-hal/2.3/ComposerHal.h>
namespace android {
@@ -30,16 +31,39 @@
using common::V1_2::Dataspace;
using common::V1_2::Hdr;
using common::V1_2::PixelFormat;
+using V2_1::Config;
using V2_1::Display;
-using V2_1::Error;
using V2_1::Layer;
+using V2_4::Error;
+using V2_4::VsyncPeriodNanos;
class ComposerHal : public V2_3::hal::ComposerHal {
public:
+ class EventCallback_2_4 {
+ public:
+ virtual ~EventCallback_2_4() = default;
+ virtual void onHotplug(Display display, IComposerCallback::Connection connected) = 0;
+ virtual void onRefresh(Display display) = 0;
+ virtual void onVsync(Display display, int64_t timestamp) = 0;
+ virtual void onVsync_2_4(Display display, int64_t timestamp,
+ VsyncPeriodNanos vsyncPeriodNanos) = 0;
+ };
+
+ virtual void registerEventCallback_2_4(EventCallback_2_4* callback) = 0;
+
+ virtual void unregisterEventCallback_2_4() = 0;
+
virtual Error getDisplayCapabilities_2_4(
Display display, std::vector<IComposerClient::DisplayCapability>* outCapabilities) = 0;
virtual Error getDisplayConnectionType(Display display,
IComposerClient::DisplayConnectionType* outType) = 0;
+ virtual Error getSupportedDisplayVsyncPeriods(
+ Display display, Config config, std::vector<VsyncPeriodNanos>* outVsyncPeriod) = 0;
+ virtual Error getDisplayVsyncPeriod(Display display, VsyncPeriodNanos* outVsyncPeriod) = 0;
+ virtual Error setActiveConfigAndVsyncPeriod(
+ Display display, Config config, VsyncPeriodNanos vsyncPeriodNanos,
+ const IComposerClient::VsyncPeriodChangeConstraints& vsyncPeriodChangeConstraints,
+ int64_t* outNewVsyncAppliedTime) = 0;
};
} // namespace hal
diff --git a/graphics/composer/2.4/utils/passthrough/include/composer-passthrough/2.4/HwcHal.h b/graphics/composer/2.4/utils/passthrough/include/composer-passthrough/2.4/HwcHal.h
index fd05f66..3420c8c 100644
--- a/graphics/composer/2.4/utils/passthrough/include/composer-passthrough/2.4/HwcHal.h
+++ b/graphics/composer/2.4/utils/passthrough/include/composer-passthrough/2.4/HwcHal.h
@@ -22,6 +22,7 @@
#include <type_traits>
+#include <android/hardware/graphics/composer/2.4/IComposerClient.h>
#include <composer-hal/2.4/ComposerHal.h>
#include <composer-passthrough/2.3/HwcHal.h>
@@ -39,18 +40,49 @@
using common::V1_2::Dataspace;
using common::V1_2::Hdr;
using common::V1_2::PixelFormat;
+using V2_1::Config;
using V2_1::Display;
-using V2_1::Error;
+using V2_4::Error;
// HwcHalImpl implements V2_*::hal::ComposerHal on top of hwcomposer2
template <typename Hal>
class HwcHalImpl : public V2_3::passthrough::detail::HwcHalImpl<Hal> {
public:
+ void registerEventCallback_2_4(hal::ComposerHal::EventCallback_2_4* callback) override {
+ mEventCallback_2_4 = callback;
+
+ mDispatch.registerCallback(mDevice, HWC2_CALLBACK_HOTPLUG, this,
+ reinterpret_cast<hwc2_function_pointer_t>(hotplugHook));
+ mDispatch.registerCallback(mDevice, HWC2_CALLBACK_REFRESH, this,
+ reinterpret_cast<hwc2_function_pointer_t>(refreshHook));
+ mDispatch.registerCallback(mDevice, HWC2_CALLBACK_VSYNC, this,
+ reinterpret_cast<hwc2_function_pointer_t>(vsyncHook));
+ mDispatch.registerCallback(mDevice, HWC2_CALLBACK_VSYNC_2_4, this,
+ reinterpret_cast<hwc2_function_pointer_t>(vsync_2_4_Hook));
+ }
+
+ void unregisterEventCallback_2_4() override {
+ // we assume the callback functions
+ //
+ // - can be unregistered
+ // - can be in-flight
+ // - will never be called afterward
+ //
+ // which is likely incorrect
+ mDispatch.registerCallback(mDevice, HWC2_CALLBACK_HOTPLUG, this, nullptr);
+ mDispatch.registerCallback(mDevice, HWC2_CALLBACK_REFRESH, this, nullptr);
+ mDispatch.registerCallback(mDevice, HWC2_CALLBACK_VSYNC, this, nullptr);
+ mDispatch.registerCallback(mDevice, HWC2_CALLBACK_VSYNC_2_4, this, nullptr);
+
+ mEventCallback_2_4 = nullptr;
+ }
+
Error getDisplayCapabilities_2_4(
Display display,
std::vector<IComposerClient::DisplayCapability>* outCapabilities) override {
std::vector<V2_3::IComposerClient::DisplayCapability> capabilities;
- Error error = BaseType2_3::getDisplayCapabilities(display, &capabilities);
+ V2_3::Error error_2_3 = BaseType2_3::getDisplayCapabilities(display, &capabilities);
+ Error error = static_cast<Error>(error_2_3);
if (error != Error::NONE) {
return error;
}
@@ -74,6 +106,63 @@
return static_cast<Error>(error);
}
+ Error getSupportedDisplayVsyncPeriods(Display display, Config config,
+ std::vector<VsyncPeriodNanos>* outVsyncPeriods) override {
+ if (!mDispatch.getSupportedDisplayVsyncPeriods) {
+ return Error::UNSUPPORTED;
+ }
+
+ uint32_t count = 0;
+ int32_t error = mDispatch.getSupportedDisplayVsyncPeriods(mDevice, display, config, &count,
+ nullptr);
+ if (error != HWC2_ERROR_NONE) {
+ return static_cast<Error>(error);
+ }
+ outVsyncPeriods->resize(count);
+ error = mDispatch.getSupportedDisplayVsyncPeriods(mDevice, display, config, &count,
+ outVsyncPeriods->data());
+ if (error != HWC2_ERROR_NONE) {
+ *outVsyncPeriods = std::vector<VsyncPeriodNanos>();
+ return static_cast<Error>(error);
+ }
+ return Error::NONE;
+ }
+
+ Error getDisplayVsyncPeriod(Display display, VsyncPeriodNanos* outVsyncPeriod) override {
+ if (!mDispatch.getDisplayVsyncPeriod) {
+ return Error::UNSUPPORTED;
+ }
+
+ int32_t error = mDispatch.getDisplayVsyncPeriod(mDevice, display, outVsyncPeriod);
+ if (error != HWC2_ERROR_NONE) {
+ return static_cast<Error>(error);
+ }
+ return Error::NONE;
+ }
+
+ Error setActiveConfigAndVsyncPeriod(
+ Display display, Config config, VsyncPeriodNanos vsyncPeriodNanos,
+ const IComposerClient::VsyncPeriodChangeConstraints& vsyncPeriodChangeConstraints,
+ int64_t* outNewVsyncAppliedTime) override {
+ if (!mDispatch.setActiveConfigAndVsyncPeriod) {
+ return Error::UNSUPPORTED;
+ }
+
+ hwc_vsync_period_change_constraints_t vsync_period_change_constraints;
+ vsync_period_change_constraints.desiredTimeNanos =
+ vsyncPeriodChangeConstraints.desiredTimeNanos;
+ vsync_period_change_constraints.seamlessRequired =
+ vsyncPeriodChangeConstraints.seamlessRequired;
+
+ int32_t error = mDispatch.setActiveConfigAndVsyncPeriod(
+ mDevice, display, config, vsyncPeriodNanos, &vsync_period_change_constraints,
+ outNewVsyncAppliedTime);
+ if (error != HWC2_ERROR_NONE) {
+ return static_cast<Error>(error);
+ }
+ return Error::NONE;
+ }
+
protected:
bool initDispatch() override {
if (!BaseType2_3::initDispatch()) {
@@ -82,14 +171,51 @@
this->initOptionalDispatch(HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE,
&mDispatch.getDisplayConnectionType);
+ this->initOptionalDispatch(HWC2_FUNCTION_REGISTER_CALLBACK, &mDispatch.registerCallback);
+ this->initOptionalDispatch(HWC2_FUNCTION_GET_SUPPORTED_DISPLAY_VSYNC_PERIODS,
+ &mDispatch.getSupportedDisplayVsyncPeriods);
+ this->initOptionalDispatch(HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD,
+ &mDispatch.getDisplayVsyncPeriod);
+ this->initOptionalDispatch(HWC2_FUNCTION_SET_ACTIVE_CONFIG_AND_VSYNC_PERIOD,
+ &mDispatch.setActiveConfigAndVsyncPeriod);
return true;
}
+ static void hotplugHook(hwc2_callback_data_t callbackData, hwc2_display_t display,
+ int32_t connected) {
+ auto hal = static_cast<HwcHalImpl*>(callbackData);
+ hal->mEventCallback_2_4->onHotplug(display,
+ static_cast<IComposerCallback::Connection>(connected));
+ }
+
+ static void refreshHook(hwc2_callback_data_t callbackData, hwc2_display_t display) {
+ auto hal = static_cast<HwcHalImpl*>(callbackData);
+ hal->mEventCallback_2_4->onRefresh(display);
+ }
+
+ static void vsyncHook(hwc2_callback_data_t callbackData, hwc2_display_t display,
+ int64_t timestamp) {
+ auto hal = static_cast<HwcHalImpl*>(callbackData);
+ hal->mEventCallback_2_4->onVsync(display, timestamp);
+ }
+
+ static void vsync_2_4_Hook(hwc2_callback_data_t callbackData, hwc2_display_t display,
+ int64_t timestamp, hwc2_vsync_period_t vsyncPeriodNanos) {
+ auto hal = static_cast<HwcHalImpl*>(callbackData);
+ hal->mEventCallback_2_4->onVsync_2_4(display, timestamp, vsyncPeriodNanos);
+ }
+
private:
struct {
HWC2_PFN_GET_DISPLAY_CONNECTION_TYPE getDisplayConnectionType;
+ HWC2_PFN_REGISTER_CALLBACK registerCallback;
+ HWC2_PFN_GET_SUPPORTED_DISPLAY_VSYNC_PERIODS getSupportedDisplayVsyncPeriods;
+ HWC2_PFN_GET_DISPLAY_VSYNC_PERIOD getDisplayVsyncPeriod;
+ HWC2_PFN_SET_ACTIVE_CONFIG_AND_VSYNC_PERIOD setActiveConfigAndVsyncPeriod;
} mDispatch = {};
+ hal::ComposerHal::EventCallback_2_4* mEventCallback_2_4 = nullptr;
+
using BaseType2_1 = V2_1::passthrough::detail::HwcHalImpl<Hal>;
using BaseType2_3 = V2_3::passthrough::detail::HwcHalImpl<Hal>;
using BaseType2_1::mDevice;
diff --git a/graphics/composer/2.4/utils/vts/ComposerVts.cpp b/graphics/composer/2.4/utils/vts/ComposerVts.cpp
index 937b50e..b02a59a 100644
--- a/graphics/composer/2.4/utils/vts/ComposerVts.cpp
+++ b/graphics/composer/2.4/utils/vts/ComposerVts.cpp
@@ -25,7 +25,7 @@
namespace V2_4 {
namespace vts {
-using V2_1::Error;
+using V2_4::Error;
Composer::Composer() : Composer(::testing::VtsHalHidlTargetTestBase::getService<IComposer>()) {}
@@ -70,6 +70,40 @@
return error;
}
+Error ComposerClient::getSupportedDisplayVsyncPeriods(
+ Display display, Config config, std::vector<VsyncPeriodNanos>* outSupportedVsyncPeriods) {
+ Error error = Error::NONE;
+ mClient->getSupportedDisplayVsyncPeriods(
+ display, config, [&](const auto& tmpError, const auto& tmpSupportedVsyncPeriods) {
+ error = tmpError;
+ *outSupportedVsyncPeriods = tmpSupportedVsyncPeriods;
+ });
+ return error;
+}
+
+Error ComposerClient::getDisplayVsyncPeriod(Display display, VsyncPeriodNanos* outVsyncPeriod) {
+ Error error = Error::NONE;
+ mClient->getDisplayVsyncPeriod(display, [&](const auto& tmpError, const auto& tmpVsyncPeriod) {
+ error = tmpError;
+ *outVsyncPeriod = tmpVsyncPeriod;
+ });
+ return error;
+}
+
+Error ComposerClient::setActiveConfigAndVsyncPeriod(
+ Display display, Config config, VsyncPeriodNanos vsyncPeriodNanos,
+ const IComposerClient::VsyncPeriodChangeConstraints& vsyncPeriodChangeConstraints,
+ int64_t* outNewVsyncAppliedTime) {
+ Error error = Error::NONE;
+ mClient->setActiveConfigAndVsyncPeriod(
+ display, config, vsyncPeriodNanos, vsyncPeriodChangeConstraints,
+ [&](const auto& tmpError, const auto& tmpNewVsyncAppliedTime) {
+ error = tmpError;
+ *outNewVsyncAppliedTime = tmpNewVsyncAppliedTime;
+ });
+ return error;
+}
+
} // namespace vts
} // namespace V2_4
} // namespace composer
diff --git a/graphics/composer/2.4/utils/vts/include/composer-vts/2.4/ComposerVts.h b/graphics/composer/2.4/utils/vts/include/composer-vts/2.4/ComposerVts.h
index a7d7f86..e8a3905 100644
--- a/graphics/composer/2.4/utils/vts/include/composer-vts/2.4/ComposerVts.h
+++ b/graphics/composer/2.4/utils/vts/include/composer-vts/2.4/ComposerVts.h
@@ -37,10 +37,12 @@
using common::V1_2::Dataspace;
using common::V1_2::Hdr;
using common::V1_2::PixelFormat;
+using V2_1::Config;
using V2_1::Display;
-using V2_1::Error;
+using V2_4::Error;
using V2_4::IComposer;
using V2_4::IComposerClient;
+using V2_4::VsyncPeriodNanos;
class ComposerClient;
@@ -74,6 +76,16 @@
Error getDisplayConnectionType(Display display,
IComposerClient::DisplayConnectionType* outType);
+ Error getSupportedDisplayVsyncPeriods(Display display, Config config,
+ std::vector<VsyncPeriodNanos>* outSupportedVsyncPeriods);
+
+ Error getDisplayVsyncPeriod(Display display, VsyncPeriodNanos* outVsyncPeriods);
+
+ Error setActiveConfigAndVsyncPeriod(
+ Display display, Config config, VsyncPeriodNanos vsyncPeriodNanos,
+ const IComposerClient::VsyncPeriodChangeConstraints& vsyncPeriodChangeConstraints,
+ int64_t* outNewVsyncAppliedTime);
+
private:
const sp<IComposerClient> mClient;
};
diff --git a/graphics/composer/2.4/vts/functional/VtsHalGraphicsComposerV2_4TargetTest.cpp b/graphics/composer/2.4/vts/functional/VtsHalGraphicsComposerV2_4TargetTest.cpp
index 76c0039..3d967fc 100644
--- a/graphics/composer/2.4/vts/functional/VtsHalGraphicsComposerV2_4TargetTest.cpp
+++ b/graphics/composer/2.4/vts/functional/VtsHalGraphicsComposerV2_4TargetTest.cpp
@@ -17,6 +17,7 @@
#define LOG_TAG "graphics_composer_hidl_hal_test@2.4"
#include <algorithm>
+#include <thread>
#include <VtsHalHidlTargetTestBase.h>
#include <android-base/logging.h>
@@ -26,6 +27,7 @@
#include <composer-vts/2.1/TestCommandReader.h>
#include <composer-vts/2.4/ComposerVts.h>
#include <mapper-vts/2.0/MapperVts.h>
+#include <utils/Timers.h>
namespace android {
namespace hardware {
@@ -110,8 +112,27 @@
return 0;
}
+ // returns an invalid config id (one that has not been registered to a
+ // display). Currently assuming that a device will never have close to
+ // std::numeric_limit<uint64_t>::max() configs registered while running tests
+ Display GetInvalidConfigId(Display display) {
+ std::vector<Config> validConfigs = mComposerClient->getDisplayConfigs(display);
+ uint64_t id = std::numeric_limits<uint64_t>::max();
+ while (id > 0) {
+ if (std::find(validConfigs.begin(), validConfigs.end(), id) == validConfigs.end()) {
+ return id;
+ }
+ id--;
+ }
+
+ return 0;
+ }
+
void execute() { mComposerClient->execute(mReader.get(), mWriter.get()); }
+ void Test_setActiveConfigAndVsyncPeriod(
+ const IComposerClient::VsyncPeriodChangeConstraints& constraints);
+
std::unique_ptr<Composer> mComposer;
std::unique_ptr<ComposerClient> mComposerClient;
sp<V2_1::vts::GraphicsComposerCallback> mComposerCallback;
@@ -189,6 +210,162 @@
}
}
+TEST_F(GraphicsComposerHidlTest, getSupportedDisplayVsyncPeriods_BadDisplay) {
+ std::vector<VsyncPeriodNanos> supportedVsyncPeriods;
+ EXPECT_EQ(Error::BAD_DISPLAY, mComposerClient->getSupportedDisplayVsyncPeriods(
+ mInvalidDisplayId, Config(0), &supportedVsyncPeriods));
+}
+
+TEST_F(GraphicsComposerHidlTest, getSupportedDisplayVsyncPeriods_BadConfig) {
+ for (Display display : mComposerCallback->getDisplays()) {
+ Config invalidConfigId = GetInvalidConfigId(display);
+ std::vector<VsyncPeriodNanos> supportedVsyncPeriods;
+ EXPECT_EQ(Error::BAD_CONFIG, mComposerClient->getSupportedDisplayVsyncPeriods(
+ display, invalidConfigId, &supportedVsyncPeriods));
+ }
+}
+
+TEST_F(GraphicsComposerHidlTest, getSupportedDisplayVsyncPeriods) {
+ for (Display display : mComposerCallback->getDisplays()) {
+ for (Config config : mComposerClient->getDisplayConfigs(display)) {
+ std::vector<VsyncPeriodNanos> supportedVsyncPeriods;
+
+ // Get the default vsync period from the config
+ VsyncPeriodNanos defaultVsyncPeiord = mComposerClient->getDisplayAttribute(
+ display, config, IComposerClient::Attribute::VSYNC_PERIOD);
+ // Get all supported vsync periods for this config
+ EXPECT_EQ(Error::NONE, mComposerClient->getSupportedDisplayVsyncPeriods(
+ display, config, &supportedVsyncPeriods));
+ // Default vsync period must be present in the list
+ EXPECT_NE(std::find(supportedVsyncPeriods.begin(), supportedVsyncPeriods.end(),
+ defaultVsyncPeiord),
+ supportedVsyncPeriods.end());
+
+ // Each vsync period must be unique
+ std::unordered_set<VsyncPeriodNanos> vsyncPeriodSet;
+ for (VsyncPeriodNanos vsyncPeriodNanos : supportedVsyncPeriods) {
+ EXPECT_TRUE(vsyncPeriodSet.insert(vsyncPeriodNanos).second);
+ }
+ }
+ }
+}
+
+TEST_F(GraphicsComposerHidlTest, getDisplayVsyncPeriod_BadDisplay) {
+ VsyncPeriodNanos vsyncPeriodNanos;
+ EXPECT_EQ(Error::BAD_DISPLAY,
+ mComposerClient->getDisplayVsyncPeriod(mInvalidDisplayId, &vsyncPeriodNanos));
+}
+
+TEST_F(GraphicsComposerHidlTest, setActiveConfigAndVsyncPeriod_BadDisplay) {
+ int64_t newVsyncAppliedTime;
+ IComposerClient::VsyncPeriodChangeConstraints constraints;
+
+ constraints.seamlessRequired = false;
+ constraints.desiredTimeNanos = systemTime();
+
+ EXPECT_EQ(Error::BAD_DISPLAY, mComposerClient->setActiveConfigAndVsyncPeriod(
+ mInvalidDisplayId, Config(0), VsyncPeriodNanos(0),
+ constraints, &newVsyncAppliedTime));
+}
+
+TEST_F(GraphicsComposerHidlTest, setActiveConfigAndVsyncPeriod_BadConfig) {
+ int64_t newVsyncAppliedTime;
+ IComposerClient::VsyncPeriodChangeConstraints constraints;
+
+ constraints.seamlessRequired = false;
+ constraints.desiredTimeNanos = systemTime();
+
+ for (Display display : mComposerCallback->getDisplays()) {
+ Config invalidConfigId = GetInvalidConfigId(display);
+ EXPECT_EQ(Error::BAD_CONFIG, mComposerClient->setActiveConfigAndVsyncPeriod(
+ display, invalidConfigId, VsyncPeriodNanos(0),
+ constraints, &newVsyncAppliedTime));
+ }
+}
+
+TEST_F(GraphicsComposerHidlTest, setActiveConfigAndVsyncPeriod_BadVsyncPeriod) {
+ int64_t newVsyncAppliedTime;
+ IComposerClient::VsyncPeriodChangeConstraints constraints;
+
+ constraints.seamlessRequired = false;
+ constraints.desiredTimeNanos = systemTime();
+
+ for (Display display : mComposerCallback->getDisplays()) {
+ for (Config config : mComposerClient->getDisplayConfigs(display)) {
+ EXPECT_EQ(Error::BAD_VSYNC_PERIOD, mComposerClient->setActiveConfigAndVsyncPeriod(
+ display, config, VsyncPeriodNanos(0),
+ constraints, &newVsyncAppliedTime));
+ }
+ }
+}
+
+void GraphicsComposerHidlTest::Test_setActiveConfigAndVsyncPeriod(
+ const IComposerClient::VsyncPeriodChangeConstraints& constraints) {
+ int64_t newVsyncAppliedTime;
+
+ for (Display display : mComposerCallback->getDisplays()) {
+ for (Config config : mComposerClient->getDisplayConfigs(display)) {
+ std::vector<VsyncPeriodNanos> supportedVsyncPeriods;
+
+ EXPECT_EQ(Error::NONE, mComposerClient->getSupportedDisplayVsyncPeriods(
+ display, config, &supportedVsyncPeriods));
+ for (VsyncPeriodNanos newVsyncPeriod : supportedVsyncPeriods) {
+ VsyncPeriodNanos vsyncPeriodNanos;
+ EXPECT_EQ(Error::NONE,
+ mComposerClient->getDisplayVsyncPeriod(display, &vsyncPeriodNanos));
+
+ if (vsyncPeriodNanos == newVsyncPeriod) {
+ continue;
+ }
+
+ EXPECT_EQ(Error::NONE, mComposerClient->setActiveConfigAndVsyncPeriod(
+ display, config, newVsyncPeriod, constraints,
+ &newVsyncAppliedTime));
+
+ EXPECT_TRUE(newVsyncAppliedTime >= constraints.desiredTimeNanos);
+
+ // Refresh rate should change within a reasonable time
+ constexpr nsecs_t kReasonableTimeForChange = 1'000'000'000; // 1 second
+ EXPECT_TRUE(newVsyncAppliedTime - constraints.desiredTimeNanos <=
+ kReasonableTimeForChange);
+
+ while (systemTime() <= newVsyncAppliedTime) {
+ EXPECT_EQ(Error::NONE,
+ mComposerClient->getDisplayVsyncPeriod(display, &vsyncPeriodNanos));
+ if (systemTime() <= constraints.desiredTimeNanos) {
+ EXPECT_NE(vsyncPeriodNanos, newVsyncPeriod);
+ }
+
+ if (vsyncPeriodNanos == newVsyncPeriod) {
+ break;
+ }
+ std::this_thread::sleep_for(10ms);
+ }
+ EXPECT_EQ(Error::NONE,
+ mComposerClient->getDisplayVsyncPeriod(display, &vsyncPeriodNanos));
+ EXPECT_EQ(vsyncPeriodNanos, newVsyncPeriod);
+ }
+ }
+ }
+}
+
+TEST_F(GraphicsComposerHidlTest, setActiveConfigAndVsyncPeriod) {
+ IComposerClient::VsyncPeriodChangeConstraints constraints;
+
+ constraints.seamlessRequired = false;
+ constraints.desiredTimeNanos = systemTime();
+ Test_setActiveConfigAndVsyncPeriod(constraints);
+}
+
+TEST_F(GraphicsComposerHidlTest, setActiveConfigAndVsyncPeriod_delayed) {
+ IComposerClient::VsyncPeriodChangeConstraints constraints;
+
+ constexpr auto kDelayForChange = 300ms;
+ constraints.seamlessRequired = false;
+ constraints.desiredTimeNanos = systemTime() + kDelayForChange.count();
+ Test_setActiveConfigAndVsyncPeriod(constraints);
+}
+
} // namespace
} // namespace vts
} // namespace V2_4
diff --git a/health/1.0/vts/functional/Android.bp b/health/1.0/vts/functional/Android.bp
index c14dcee..be2d206 100644
--- a/health/1.0/vts/functional/Android.bp
+++ b/health/1.0/vts/functional/Android.bp
@@ -19,5 +19,5 @@
defaults: ["VtsHalTargetTestDefaults"],
srcs: ["VtsHalHealthV1_0TargetTest.cpp"],
static_libs: ["android.hardware.health@1.0"],
- test_suites: ["general-tests"],
+ test_suites: ["general-tests", "vts-core"],
}
diff --git a/health/1.0/vts/functional/VtsHalHealthV1_0TargetTest.cpp b/health/1.0/vts/functional/VtsHalHealthV1_0TargetTest.cpp
index 335d15d..b985a9f 100644
--- a/health/1.0/vts/functional/VtsHalHealthV1_0TargetTest.cpp
+++ b/health/1.0/vts/functional/VtsHalHealthV1_0TargetTest.cpp
@@ -18,11 +18,11 @@
#include <android/hardware/health/1.0/IHealth.h>
#include <android/hardware/health/1.0/types.h>
+#include <gtest/gtest.h>
+#include <hidl/GtestPrinter.h>
+#include <hidl/ServiceManagement.h>
#include <log/log.h>
-#include <VtsHalHidlTargetTestBase.h>
-#include <VtsHalHidlTargetTestEnvBase.h>
-
using HealthConfig = ::android::hardware::health::V1_0::HealthConfig;
using HealthInfo = ::android::hardware::health::V1_0::HealthInfo;
using IHealth = ::android::hardware::health::V1_0::IHealth;
@@ -30,25 +30,10 @@
using ::android::sp;
-// Test environment for Health HIDL HAL.
-class HealthHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
- public:
- // get the test environment singleton
- static HealthHidlEnvironment* Instance() {
- static HealthHidlEnvironment* instance = new HealthHidlEnvironment;
- return instance;
- }
-
- virtual void registerTestServices() override { registerTestService<IHealth>(); }
- private:
- HealthHidlEnvironment() {}
-};
-
-class HealthHidlTest : public ::testing::VtsHalHidlTargetTestBase {
+class HealthHidlTest : public ::testing::TestWithParam<std::string> {
public:
virtual void SetUp() override {
- health = ::testing::VtsHalHidlTargetTestBase::getService<IHealth>(
- HealthHidlEnvironment::Instance()->getServiceName<IHealth>());
+ health = IHealth::getService(GetParam());
ASSERT_NE(health, nullptr);
health->init(config,
[&](const auto& halConfigOut) { config = halConfigOut; });
@@ -61,7 +46,7 @@
/**
* Ensure EnergyCounter call returns positive energy counter or NOT_SUPPORTED
*/
-TEST_F(HealthHidlTest, TestEnergyCounter) {
+TEST_P(HealthHidlTest, TestEnergyCounter) {
Result result;
int64_t energy = 0;
health->energyCounter([&](Result ret, int64_t energyOut) {
@@ -73,11 +58,7 @@
ASSERT_TRUE(result != Result::SUCCESS || energy > 0);
}
-int main(int argc, char **argv) {
- ::testing::AddGlobalTestEnvironment(HealthHidlEnvironment::Instance());
- ::testing::InitGoogleTest(&argc, argv);
- HealthHidlEnvironment::Instance()->init(&argc, argv);
- int status = RUN_ALL_TESTS();
- ALOGI("Test result = %d", status);
- return status;
-}
+INSTANTIATE_TEST_SUITE_P(
+ PerInstance, HealthHidlTest,
+ testing::ValuesIn(android::hardware::getAllHalInstanceNames(IHealth::descriptor)),
+ android::hardware::PrintInstanceNameToString);
diff --git a/health/2.0/README.md b/health/2.0/README.md
index 4ecfb9a..8a7c922 100644
--- a/health/2.0/README.md
+++ b/health/2.0/README.md
@@ -1,3 +1,8 @@
+# Implement the 2.1 HAL instead!
+
+It is strongly recommended that you implement the 2.1 HAL directly. See
+`hardware/interfaces/health/2.1/README.md` for more details.
+
# Upgrading from Health 1.0 HAL
1. Remove `android.hardware.health@1.0*` from `PRODUCT_PACKAGES`
diff --git a/health/2.0/default/Health.cpp b/health/2.0/default/Health.cpp
index c0c5a40..4225fd8 100644
--- a/health/2.0/default/Health.cpp
+++ b/health/2.0/default/Health.cpp
@@ -17,11 +17,15 @@
#include <android-base/logging.h>
#include <android-base/file.h>
+#include <android/hardware/health/2.0/types.h>
#include <health2/Health.h>
#include <hal_conversion.h>
#include <hidl/HidlTransportSupport.h>
+using HealthInfo_1_0 = android::hardware::health::V1_0::HealthInfo;
+using android::hardware::health::V1_0::hal_conversion::convertFromHealthInfo;
+
extern void healthd_battery_update_internal(bool);
namespace android {
@@ -149,7 +153,9 @@
// Retrieve all information and call healthd_mode_ops->battery_update, which calls
// notifyListeners.
battery_monitor_->updateValues();
- struct BatteryProperties props = getBatteryProperties(battery_monitor_.get());
+ const HealthInfo_1_0& health_info = battery_monitor_->getHealthInfo_1_0();
+ struct BatteryProperties props;
+ convertFromHealthInfo(health_info, &props);
bool log = healthd_board_battery_update(&props);
if (log) {
battery_monitor_->logValues();
@@ -253,10 +259,7 @@
using android::hardware::health::V1_0::hal_conversion::convertToHealthInfo;
updateAndNotify(nullptr);
- struct android::BatteryProperties p = getBatteryProperties(battery_monitor_.get());
-
- V1_0::HealthInfo batteryInfo;
- convertToHealthInfo(&p, batteryInfo);
+ HealthInfo healthInfo = battery_monitor_->getHealthInfo_2_0();
std::vector<StorageInfo> info;
get_storage_info(info);
@@ -272,8 +275,6 @@
currentAvg = static_cast<int32_t>(prop.valueInt64);
}
- V2_0::HealthInfo healthInfo = {};
- healthInfo.legacy = std::move(batteryInfo);
healthInfo.batteryCurrentAverage = currentAvg;
healthInfo.diskStats = stats;
healthInfo.storageInfos = info;
diff --git a/health/2.1/README.md b/health/2.1/README.md
new file mode 100644
index 0000000..5a19d7b
--- /dev/null
+++ b/health/2.1/README.md
@@ -0,0 +1,245 @@
+# Implementing Health 2.1 HAL
+
+1. Install common binderized service. The binderized service `dlopen()`s
+ passthrough implementations on the device, so there is no need to write
+ your own.
+
+ ```mk
+ # Install default binderized implementation to vendor.
+ PRODUCT_PACKAGES += android.hardware.health@2.1-service
+ ```
+
+1. Delete existing VINTF manifest entry. Search for `android.hardware.health` in
+ your device manifest, and delete the whole `<hal>` entry for older versions
+ of the HAL. Instead, when `android.hardware.health@2.1-service` is installed,
+ a VINTF manifest fragment is installed to `/vendor/etc/vintf`, so there is
+ no need to manually specify it in your device manifest. See
+ [Manifest fragments](https://source.android.com/devices/architecture/vintf/objects#manifest-fragments)
+ for details.
+
+1. Install the proper passthrough implemetation.
+
+ 1. If you want to use default implementation:
+
+ ```mk
+ # Install default passthrough implementation to vendor.
+ PRODUCT_PACKAGES += android.hardware.health@2.1-impl
+ ```
+
+ You are done. Otherwise, go to the next step.
+
+ 1. If you want to write your own implementation,
+
+ 1. Copy skeleton implementation from the [appendix](#impl).
+
+ 1. Modify the implementation to suit your needs.
+
+ * If you have a board or device specific `libhealthd`, see
+ [Upgrading with a customized libhealthd](#update-from-1-0).
+ * If you are upgrading from 1.0 health HAL, see
+ [Upgrading from Health HAL 1.0](#update-from-1-0).
+ * If you are upgrading from a customized 2.0 health HAL
+ implementation, See
+ [Upgrading from Health HAL 2.0](#update-from-2-0).
+
+ 1. [Update necessary SELinux permissions](#selinux).
+
+ 1. [Fix `/charger` symlink](#charger-symlink).
+
+# Upgrading with a customized libhealthd or from Health HAL 1.0 {#update-from-1-0}
+
+`libhealthd` contains two functions: `healthd_board_init()` and
+`healthd_board_battery_update()`. Similarly, Health HAL 1.0 contains `init()`
+and `update()`, with an additional `energyCounter()` function.
+
+* `healthd_board_init()` / `@1.0::IHealth.init()` should be called before
+ passing the `healthd_config` struct to your `HealthImpl` class. See
+ `HIDL_FETCH_IHealth` in [`HealthImpl.cpp`](#health_impl_cpp).
+
+* `healthd_board_battery_update()` / `@1.0::IHealth.update()` should be called
+ in `HealthImpl::UpdateHealthInfo()`. Example:
+
+ ```c++
+ void HealthImpl::UpdateHealthInfo(HealthInfo* health_info) {
+ struct BatteryProperties props;
+ convertFromHealthInfo(health_info->legacy.legacy, &props);
+ healthd_board_battery_update(&props);
+ convertToHealthInfo(&props, health_info->legacy.legacy);
+ }
+ ```
+ For efficiency, you should move code in `healthd_board_battery_update` to
+ `HealthImpl::UpdateHealthInfo` and modify `health_info` directly to avoid
+ conversion to `BatteryProperties`.
+
+* Code for `@1.0::IHealth.energyCounter()` should be moved to
+ `HealthImpl::getEnergyCounter()`. Example:
+
+ ```c++
+ Return<void> Health::getEnergyCounter(getEnergyCounter_cb _hidl_cb) {
+ int64_t energy = /* ... */;
+ _hidl_cb(Result::SUCCESS, energy);
+ return Void();
+ }
+ ```
+
+# Upgrading from Health HAL 2.0 {#update-from-2-0}
+
+* If you have implemented `healthd_board_init()` and/or
+ `healthd_board_battery_update()` (instead of using `libhealthd.default`),
+ see [the section above](#update-from-1-0)
+ for instructions to convert them.
+
+* If you have implemented `get_storage_info()` and/or `get_disk_stats()`
+ (instead of using libhealthstoragedefault), implement `HealthImpl::getDiskStats`
+ and/or `HealthImpl::getStorageInfo` directly. There is no need to override
+ `HealthImpl::getHealthInfo` or `HealthImpl::getHealthInfo_2_1` because they call
+ `getDiskStats` and `getStorageInfo` to retrieve storage information.
+
+# Update necessary SELinux permissions {#selinux}
+
+For example (replace `<device>` with the device name):
+```
+# device/<manufacturer>/<device>/sepolicy/vendor/hal_health_default.te
+# Add device specific permissions to hal_health_default domain, especially
+# if a device-specific libhealthd is used and/or device-specific storage related
+# APIs are implemented.
+```
+
+# Fix `/charger` symlink {#charger-symlink}
+If you are using `/charger` in your `init.rc` scripts, it is recommended
+(required for devices running in Android R) that the path is changed to
+`/system/bin/charger` instead.
+
+Search for `service charger` in your device configuration directory to see if
+this change applies to your device. Below is an example of how the script should
+look like:
+
+```
+service charger /system/bin/charger
+ class charger
+ user system
+ group system wakelock input
+ capabilities SYS_BOOT
+ file /dev/kmsg w
+ file /sys/fs/pstore/console-ramoops-0 r
+ file /sys/fs/pstore/console-ramoops r
+ file /proc/last_kmsg r
+```
+
+# Appendix: sample code for the implementation {#impl}
+
+## `device/<manufacturer>/<device>/health/Android.bp` {#android_bp}
+
+```bp
+cc_library_shared {
+ name: "android.hardware.health@2.1-impl-<device>",
+ stem: "android.hardware.health@2.0-impl-2.1-<device>",
+
+ // Install to vendor and recovery.
+ proprietary: true,
+ recovery_available: true,
+
+ relative_install_path: "hw",
+
+ shared_libs: [
+ "libbase",
+ "libcutils",
+ "libhidlbase",
+ "liblog",
+ "libutils",
+ "android.hardware.health@2.1",
+ "android.hardware.health@2.0",
+ ],
+
+ static_libs: [
+ "android.hardware.health@1.0-convert",
+ "libbatterymonitor",
+ "libhealthloop",
+ "libhealth2impl",
+ // "libhealthd.<device>"
+ ],
+
+ srcs: [
+ "HealthImpl.cpp",
+ ],
+
+ // No vintf_fragments because both -impl and -service should have been
+ // installed.
+}
+```
+
+## `device/<manufacturer>/<device>/health/HealthImpl.cpp` {#health_impl_cpp}
+
+```c++
+#include <memory>
+#include <string_view>
+
+#include <health/utils.h>
+#include <health2impl/Health.h>
+#include <hidl/Status.h>
+
+using ::android::sp;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::health::InitHealthdConfig;
+using ::android::hardware::health::V2_1::IHealth;
+using ::android::hidl::base::V1_0::IBase;
+
+using namespace std::literals;
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+// android::hardware::health::V2_1::implementation::Health implements most
+// defaults. Uncomment functions that you need to override.
+class HealthImpl : public Health {
+ public:
+ HealthImpl(std::unique_ptr<healthd_config>&& config)
+ : Health(std::move(config)) {}
+
+ // A subclass can override this if these information should be retrieved
+ // differently.
+ // Return<void> getChargeCounter(getChargeCounter_cb _hidl_cb) override;
+ // Return<void> getCurrentNow(getCurrentNow_cb _hidl_cb) override;
+ // Return<void> getCurrentAverage(getCurrentAverage_cb _hidl_cb) override;
+ // Return<void> getCapacity(getCapacity_cb _hidl_cb) override;
+ // Return<void> getEnergyCounter(getEnergyCounter_cb _hidl_cb) override;
+ // Return<void> getChargeStatus(getChargeStatus_cb _hidl_cb) override;
+ // Return<void> getStorageInfo(getStorageInfo_cb _hidl_cb) override;
+ // Return<void> getDiskStats(getDiskStats_cb _hidl_cb) override;
+ // Return<void> getHealthInfo(getHealthInfo_cb _hidl_cb) override;
+
+ // Functions introduced in Health HAL 2.1.
+ // Return<void> getHealthConfig(getHealthConfig_cb _hidl_cb) override;
+ // Return<void> getHealthInfo_2_1(getHealthInfo_2_1_cb _hidl_cb) override;
+ // Return<void> shouldKeepScreenOn(shouldKeepScreenOn_cb _hidl_cb) override;
+
+ protected:
+ // A subclass can override this to modify any health info object before
+ // returning to clients. This is similar to healthd_board_battery_update().
+ // By default, it does nothing.
+ // void UpdateHealthInfo(HealthInfo* health_info) override;
+};
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace health
+} // namespace hardware
+} // namespace android
+
+extern "C" IHealth* HIDL_FETCH_IHealth(const char* instance) {
+ using ::android::hardware::health::V2_1::implementation::HealthImpl;
+ if (instance != "default"sv) {
+ return nullptr;
+ }
+ auto config = std::make_unique<healthd_config>();
+ InitHealthdConfig(config.get());
+
+ // healthd_board_init(config.get());
+
+ return new HealthImpl(std::move(config));
+}
+```
diff --git a/health/2.1/default/Android.bp b/health/2.1/default/Android.bp
new file mode 100644
index 0000000..3649853
--- /dev/null
+++ b/health/2.1/default/Android.bp
@@ -0,0 +1,81 @@
+// Copyright (C) 2019 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.
+
+cc_defaults {
+ name: "android.hardware.health@2.1-impl-defaults",
+ relative_install_path: "hw",
+
+ shared_libs: [
+ "libbase",
+ "libcutils",
+ "libhidlbase",
+ "liblog",
+ "libutils",
+ "android.hardware.health@2.1",
+ "android.hardware.health@2.0",
+ ],
+
+ static_libs: [
+ "android.hardware.health@1.0-convert",
+ "libbatterymonitor",
+ "libhealthloop",
+ "libhealth2impl",
+ ],
+}
+
+// Default passthrough implementation of the health@2.1 HAL.
+// Passhtrough implementations of the health@2.1 HAL must be installed in
+// vendor in order to support charger.
+// Passhtrough implementations of the health@2.1 HAL must be installed in
+// recovery in order to allow recovery to check battery status.
+// See README.md for details.
+cc_library_shared {
+ name: "android.hardware.health@2.1-impl",
+ stem: "android.hardware.health@2.0-impl-2.1",
+
+ // Only vendor and recovery variants are allowed, not core.
+ vendor: true,
+ recovery_available: true,
+
+ defaults: ["android.hardware.health@2.1-impl-defaults"],
+
+ srcs: [
+ "impl.cpp",
+ ],
+
+ // No vintf_fragments because both -impl and -service should have been
+ // installed.
+}
+
+// Default binderized service of the health@2.1 HAL.
+// This binderized implementation dlopen()s the passthrough implementation,
+// so there is no need to implement your own.
+cc_binary {
+ name: "android.hardware.health@2.1-service",
+ vendor: true,
+ defaults: ["android.hardware.health@2.1-impl-defaults"],
+ init_rc: ["android.hardware.health@2.1-service.rc"],
+
+ srcs: [
+ "service.cpp",
+ ],
+
+ vintf_fragments: [
+ "android.hardware.health@2.1.xml"
+ ],
+
+ overrides: [
+ "healthd",
+ ],
+}
diff --git a/health/2.1/default/android.hardware.health@2.1-service.rc b/health/2.1/default/android.hardware.health@2.1-service.rc
new file mode 100644
index 0000000..917f1c2
--- /dev/null
+++ b/health/2.1/default/android.hardware.health@2.1-service.rc
@@ -0,0 +1,6 @@
+service health-hal-2-1 /vendor/bin/hw/android.hardware.health@2.1-service
+ class hal
+ user system
+ group system
+ capabilities WAKE_ALARM
+ file /dev/kmsg w
diff --git a/health/2.1/default/android.hardware.health@2.1.xml b/health/2.1/default/android.hardware.health@2.1.xml
new file mode 100644
index 0000000..34fdca6
--- /dev/null
+++ b/health/2.1/default/android.hardware.health@2.1.xml
@@ -0,0 +1,7 @@
+<manifest version="1.0" type="device">
+ <hal format="hidl">
+ <name>android.hardware.health</name>
+ <transport>hwbinder</transport>
+ <fqname>@2.1::IHealth/default</fqname>
+ </hal>
+</manifest>
diff --git a/health/2.1/default/impl.cpp b/health/2.1/default/impl.cpp
new file mode 100644
index 0000000..7389a21
--- /dev/null
+++ b/health/2.1/default/impl.cpp
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2019 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 <memory>
+#include <string_view>
+
+#include <health/utils.h>
+#include <health2impl/Health.h>
+
+using ::android::sp;
+using ::android::hardware::health::InitHealthdConfig;
+using ::android::hardware::health::V2_1::IHealth;
+using ::android::hardware::health::V2_1::implementation::Health;
+
+using namespace std::literals;
+
+// Passthrough implementation of the health service. Use default configuration.
+// It does not invoke callbacks unless update() is called explicitly. No
+// background thread is spawned to handle callbacks.
+//
+// The passthrough implementation is only allowed in recovery mode, charger, and
+// opened by the hwbinder service.
+// If Android is booted normally, the hwbinder service is used instead.
+//
+// This implementation only implements the "default" instance. It rejects
+// other instance names.
+// Note that the Android framework only reads values from the "default"
+// health HAL 2.1 instance.
+extern "C" IHealth* HIDL_FETCH_IHealth(const char* instance) {
+ if (instance != "default"sv) {
+ return nullptr;
+ }
+ auto config = std::make_unique<healthd_config>();
+ InitHealthdConfig(config.get());
+
+ // This implementation uses default config. If you want to customize it
+ // (e.g. with healthd_board_init), do it here.
+
+ return new Health(std::move(config));
+}
diff --git a/health/2.1/default/service.cpp b/health/2.1/default/service.cpp
new file mode 100644
index 0000000..f8334c5
--- /dev/null
+++ b/health/2.1/default/service.cpp
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2019 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 "android.hardware.health@2.1-service"
+
+#include <android-base/logging.h>
+#include <android/hardware/health/2.1/IHealth.h>
+#include <health2impl/BinderHealth.h>
+
+using ::android::sp;
+using ::android::hardware::health::V2_1::IHealth;
+using ::android::hardware::health::V2_1::implementation::BinderHealth;
+using IHealth_2_0 = ::android::hardware::health::V2_0::IHealth;
+
+static constexpr const char* gInstanceName = "default";
+
+int main(int /* argc */, char* /* argv */[]) {
+ sp<IHealth> passthrough =
+ IHealth::castFrom(IHealth_2_0::getService(gInstanceName, true /* getStub */));
+ CHECK(passthrough != nullptr)
+ << "Cannot find passthrough implementation of health 2.1 HAL for instance "
+ << gInstanceName;
+ sp<BinderHealth> binder = new BinderHealth(gInstanceName, passthrough);
+ return binder->StartLoop();
+}
diff --git a/health/utils/libhealth2impl/Android.bp b/health/utils/libhealth2impl/Android.bp
new file mode 100644
index 0000000..14374a2
--- /dev/null
+++ b/health/utils/libhealth2impl/Android.bp
@@ -0,0 +1,51 @@
+// Copyright (C) 2019 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.
+
+// A helper library for health@2.x HAL implementation.
+// HAL implementations can link to this library and extend the Health class.
+cc_library_static {
+ name: "libhealth2impl",
+ vendor_available: true,
+ recovery_available: true,
+ srcs: [
+ "BinderHealth.cpp",
+ "HalHealthLoop.cpp",
+ "Health.cpp",
+ ],
+ shared_libs: [
+ "libbase",
+ "libcutils",
+ "libhidlbase",
+ "liblog",
+ "libutils",
+ "android.hardware.health@2.1",
+ "android.hardware.health@2.0",
+ ],
+ static_libs: [
+ "libbatterymonitor",
+ "libhealthloop",
+ "android.hardware.health@1.0-convert",
+ ],
+ cflags: [
+ "-Wall",
+ "-Werror",
+ ],
+ export_static_lib_headers: [
+ "libbatterymonitor",
+ "libhealthloop",
+ ],
+ export_include_dirs: [
+ "include",
+ ],
+}
diff --git a/health/utils/libhealth2impl/BinderHealth.cpp b/health/utils/libhealth2impl/BinderHealth.cpp
new file mode 100644
index 0000000..625d0e0
--- /dev/null
+++ b/health/utils/libhealth2impl/BinderHealth.cpp
@@ -0,0 +1,190 @@
+/*
+ * Copyright (C) 2019 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 <health2impl/BinderHealth.h>
+
+#include <android-base/logging.h>
+#include <hidl/HidlTransportSupport.h>
+#include <hwbinder/IPCThreadState.h>
+
+#include <health2impl/Callback.h>
+#include <health2impl/Health.h>
+
+using android::hardware::handleTransportPoll;
+using android::hardware::IPCThreadState;
+using android::hardware::setupTransportPolling;
+
+using android::hardware::health::V2_0::Result;
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+bool IsDeadObjectLogged(const Return<void>& ret) {
+ if (ret.isOk()) return false;
+ if (ret.isDeadObject()) return true;
+ LOG(ERROR) << "Cannot call healthInfoChanged* on callback: " << ret.description();
+ return false;
+}
+
+BinderHealth::BinderHealth(const std::string& name, const sp<IHealth>& impl)
+ : HalHealthLoop(name, impl) {
+ CHECK_NE(this, impl.get());
+ CHECK(!impl->isRemote());
+}
+
+//
+// Methods that handle callbacks.
+//
+
+Return<Result> BinderHealth::registerCallback(const sp<V2_0::IHealthInfoCallback>& callback) {
+ if (callback == nullptr) {
+ return Result::SUCCESS;
+ }
+
+ Callback* wrapped = nullptr;
+ {
+ std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
+ wrapped = callbacks_.emplace_back(Wrap(callback)).get();
+ // unlock
+ }
+
+ auto linkRet = callback->linkToDeath(this, 0u /* cookie */);
+ if (!linkRet.withDefault(false)) {
+ LOG(WARNING) << __func__ << "Cannot link to death: "
+ << (linkRet.isOk() ? "linkToDeath returns false" : linkRet.description());
+ // ignore the error
+ }
+
+ getHealthInfo_2_1([&](auto res, const auto& health_info) {
+ if (res != Result::SUCCESS) {
+ LOG(ERROR) << "Cannot call getHealthInfo_2_1: " << toString(res);
+ return;
+ }
+ auto ret = wrapped->Notify(health_info);
+ if (IsDeadObjectLogged(ret)) {
+ // Remove callback reference.
+ std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
+ auto it = std::find_if(callbacks_.begin(), callbacks_.end(),
+ [wrapped](const auto& cb) { return cb.get() == wrapped; });
+ if (it != callbacks_.end()) {
+ callbacks_.erase(it);
+ }
+ // unlock
+ }
+ });
+
+ return Result::SUCCESS;
+}
+
+bool BinderHealth::unregisterCallbackInternal(const sp<IBase>& callback) {
+ if (callback == nullptr) {
+ return false;
+ }
+
+ bool removed = false;
+ std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
+ for (auto it = callbacks_.begin(); it != callbacks_.end();) {
+ if (interfacesEqual((*it)->Get(), callback)) {
+ it = callbacks_.erase(it);
+ removed = true;
+ } else {
+ ++it;
+ }
+ }
+ (void)callback->unlinkToDeath(this).isOk(); // ignore errors
+ return removed;
+}
+
+Return<Result> BinderHealth::update() {
+ Result result = service()->update();
+ if (result != Result::SUCCESS) return result;
+ getHealthInfo_2_1([&](auto res, const auto& health_info) {
+ if (res != Result::SUCCESS) {
+ result = res;
+ return;
+ }
+ OnHealthInfoChanged(health_info);
+ });
+ return result;
+}
+
+Return<Result> BinderHealth::unregisterCallback(const sp<V2_0::IHealthInfoCallback>& callback) {
+ return unregisterCallbackInternal(callback) ? Result::SUCCESS : Result::NOT_FOUND;
+}
+
+void BinderHealth::OnHealthInfoChanged(const HealthInfo& health_info) {
+ // Notify all callbacks
+ std::unique_lock<decltype(callbacks_lock_)> lock(callbacks_lock_);
+ for (auto it = callbacks_.begin(); it != callbacks_.end();) {
+ auto ret = (*it)->Notify(health_info);
+ if (IsDeadObjectLogged(ret)) {
+ it = callbacks_.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ lock.unlock();
+
+ // adjusts uevent / wakealarm periods
+ HalHealthLoop::OnHealthInfoChanged(health_info);
+}
+
+void BinderHealth::serviceDied(uint64_t /* cookie */, const wp<IBase>& who) {
+ (void)unregisterCallbackInternal(who.promote());
+}
+
+void BinderHealth::BinderEvent(uint32_t /*epevents*/) {
+ if (binder_fd_ >= 0) {
+ handleTransportPoll(binder_fd_);
+ }
+}
+
+void BinderHealth::Init(struct healthd_config* config) {
+ // Set up epoll and get uevent / wake alarm periods
+ HalHealthLoop::Init(config);
+
+ LOG(INFO) << instance_name() << " instance initializing with healthd_config...";
+
+ binder_fd_ = setupTransportPolling();
+
+ if (binder_fd_ >= 0) {
+ auto binder_event = [](auto* health_loop, uint32_t epevents) {
+ static_cast<BinderHealth*>(health_loop)->BinderEvent(epevents);
+ };
+ if (RegisterEvent(binder_fd_, binder_event, EVENT_NO_WAKEUP_FD) != 0) {
+ PLOG(ERROR) << instance_name() << " instance: Register for binder events failed";
+ }
+ }
+
+ CHECK_EQ(registerAsService(instance_name()), android::OK)
+ << instance_name() << ": Failed to register HAL";
+
+ LOG(INFO) << instance_name() << ": Hal init done";
+}
+
+int BinderHealth::PrepareToWait(void) {
+ IPCThreadState::self()->flushCommands();
+ return HalHealthLoop::PrepareToWait();
+}
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace health
+} // namespace hardware
+} // namespace android
diff --git a/health/utils/libhealth2impl/HalHealthLoop.cpp b/health/utils/libhealth2impl/HalHealthLoop.cpp
new file mode 100644
index 0000000..3901a76
--- /dev/null
+++ b/health/utils/libhealth2impl/HalHealthLoop.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2019 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 <health2impl/HalHealthLoop.h>
+
+#include <android-base/logging.h>
+#include <hal_conversion.h>
+#include <hidl/HidlTransportSupport.h>
+#include <hwbinder/IPCThreadState.h>
+
+#include <health2impl/Health.h>
+
+using android::hardware::configureRpcThreadpool;
+using android::hardware::handleTransportPoll;
+using android::hardware::IPCThreadState;
+using android::hardware::setupTransportPolling;
+
+using android::hardware::health::V1_0::hal_conversion::convertFromHealthConfig;
+using android::hardware::health::V2_0::Result;
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+void HalHealthLoop::Init(struct healthd_config* config) {
+ // Retrieve healthd_config from the HAL.
+ service_->getHealthConfig([config](auto res, const auto& health_config) {
+ CHECK(res == Result::SUCCESS);
+
+ convertFromHealthConfig(health_config.battery, config);
+ config->boot_min_cap = health_config.bootMinCap;
+
+ // Leave screen_on empty because it is handled in GetScreenOn below.
+
+ // Leave ignorePowerSupplyNames empty because it isn't
+ // used by clients of health HAL.
+ });
+}
+
+void HalHealthLoop::Heartbeat(void) {
+ // noop
+}
+
+void HalHealthLoop::ScheduleBatteryUpdate() {
+ // ignore errors. impl may not be able to handle any callbacks, so
+ // update() may return errors.
+ Result res = service_->update();
+ if (res != Result::SUCCESS) {
+ LOG(WARNING) << "update() on the health HAL implementation failed with " << toString(res);
+ }
+
+ service_->getHealthInfo_2_1([this](auto res, const auto& health_info) {
+ CHECK(res == Result::SUCCESS)
+ << "getHealthInfo_2_1() on the health HAL implementation failed with "
+ << toString(res);
+ this->OnHealthInfoChanged(health_info);
+ });
+}
+
+int HalHealthLoop::PrepareToWait() {
+ return -1;
+}
+
+void HalHealthLoop::OnHealthInfoChanged(const HealthInfo& health_info) {
+ set_charger_online(health_info);
+ AdjustWakealarmPeriods(charger_online());
+}
+
+void HalHealthLoop::set_charger_online(const HealthInfo& health_info) {
+ const auto& props = health_info.legacy.legacy;
+ charger_online_ =
+ props.chargerAcOnline || props.chargerUsbOnline || props.chargerWirelessOnline;
+}
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace health
+} // namespace hardware
+} // namespace android
diff --git a/health/utils/libhealth2impl/Health.cpp b/health/utils/libhealth2impl/Health.cpp
new file mode 100644
index 0000000..f4684ae
--- /dev/null
+++ b/health/utils/libhealth2impl/Health.cpp
@@ -0,0 +1,267 @@
+/*
+ * Copyright (C) 2019 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 <health2impl/Health.h>
+
+#include <functional>
+#include <string_view>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android/hardware/health/1.0/types.h>
+#include <android/hardware/health/2.0/IHealthInfoCallback.h>
+#include <android/hardware/health/2.0/types.h>
+#include <android/hardware/health/2.1/IHealthInfoCallback.h>
+#include <hal_conversion.h>
+#include <healthd/healthd.h>
+#include <hidl/HidlTransportSupport.h>
+#include <hwbinder/IPCThreadState.h>
+
+#include <health2impl/Callback.h>
+#include <health2impl/HalHealthLoop.h>
+
+using android::hardware::health::V1_0::BatteryStatus;
+using android::hardware::health::V1_0::toString;
+using android::hardware::health::V1_0::hal_conversion::convertFromHealthInfo;
+using android::hardware::health::V1_0::hal_conversion::convertToHealthConfig;
+using android::hardware::health::V1_0::hal_conversion::convertToHealthInfo;
+using android::hardware::health::V2_0::Result;
+using android::hardware::health::V2_1::IHealth;
+
+using ScreenOn = decltype(healthd_config::screen_on);
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+/*
+// If you need to call healthd_board_init, construct the Health instance with
+// the healthd_config after calling healthd_board_init:
+struct healthd_config* init_config(struct healthd_config* config) {
+ healthd_board_init(config);
+ return config;
+}
+class MyHealth : public Health {
+ MyHealth(struct healthd_config* config) :
+ Health(init_config(config)) {}
+};
+*/
+
+Health::Health(std::unique_ptr<healthd_config>&& config) : healthd_config_(std::move(config)) {
+ battery_monitor_.init(healthd_config_.get());
+}
+
+//
+// Callbacks are not supported by the passthrough implementation.
+//
+
+Return<Result> Health::registerCallback(const sp<V2_0::IHealthInfoCallback>&) {
+ return Result::NOT_SUPPORTED;
+}
+
+Return<Result> Health::unregisterCallback(const sp<V2_0::IHealthInfoCallback>&) {
+ return Result::NOT_SUPPORTED;
+}
+
+Return<Result> Health::update() {
+ Result result = Result::UNKNOWN;
+ getHealthInfo_2_1([&](auto res, const auto& /* health_info */) {
+ result = res;
+ if (res != Result::SUCCESS) {
+ LOG(ERROR) << "Cannot call getHealthInfo_2_1: " << toString(res);
+ return;
+ }
+
+ battery_monitor_.logValues();
+ });
+ return result;
+}
+
+//
+// Getters.
+//
+
+template <typename T>
+static Return<void> GetProperty(BatteryMonitor* monitor, int id, T defaultValue,
+ const std::function<void(Result, T)>& callback) {
+ struct BatteryProperty prop;
+ T ret = defaultValue;
+ Result result = Result::SUCCESS;
+ status_t err = monitor->getProperty(static_cast<int>(id), &prop);
+ if (err != OK) {
+ LOG(DEBUG) << "getProperty(" << id << ")"
+ << " fails: (" << err << ") " << strerror(-err);
+ } else {
+ ret = static_cast<T>(prop.valueInt64);
+ }
+ switch (err) {
+ case OK:
+ result = Result::SUCCESS;
+ break;
+ case NAME_NOT_FOUND:
+ result = Result::NOT_SUPPORTED;
+ break;
+ default:
+ result = Result::UNKNOWN;
+ break;
+ }
+ callback(result, static_cast<T>(ret));
+ return Void();
+}
+
+Return<void> Health::getChargeCounter(getChargeCounter_cb _hidl_cb) {
+ return GetProperty<int32_t>(&battery_monitor_, BATTERY_PROP_CHARGE_COUNTER, 0, _hidl_cb);
+}
+
+Return<void> Health::getCurrentNow(getCurrentNow_cb _hidl_cb) {
+ return GetProperty<int32_t>(&battery_monitor_, BATTERY_PROP_CURRENT_NOW, 0, _hidl_cb);
+}
+
+Return<void> Health::getCurrentAverage(getCurrentAverage_cb _hidl_cb) {
+ return GetProperty<int32_t>(&battery_monitor_, BATTERY_PROP_CURRENT_AVG, 0, _hidl_cb);
+}
+
+Return<void> Health::getCapacity(getCapacity_cb _hidl_cb) {
+ return GetProperty<int32_t>(&battery_monitor_, BATTERY_PROP_CAPACITY, 0, _hidl_cb);
+}
+
+Return<void> Health::getEnergyCounter(getEnergyCounter_cb _hidl_cb) {
+ return GetProperty<int64_t>(&battery_monitor_, BATTERY_PROP_ENERGY_COUNTER, 0, _hidl_cb);
+}
+
+Return<void> Health::getChargeStatus(getChargeStatus_cb _hidl_cb) {
+ return GetProperty(&battery_monitor_, BATTERY_PROP_BATTERY_STATUS, BatteryStatus::UNKNOWN,
+ _hidl_cb);
+}
+
+Return<void> Health::getStorageInfo(getStorageInfo_cb _hidl_cb) {
+ // This implementation does not support StorageInfo. An implementation may extend this
+ // class and override this function to support storage info.
+ _hidl_cb(Result::NOT_SUPPORTED, {});
+ return Void();
+}
+
+Return<void> Health::getDiskStats(getDiskStats_cb _hidl_cb) {
+ // This implementation does not support DiskStats. An implementation may extend this
+ // class and override this function to support disk stats.
+ _hidl_cb(Result::NOT_SUPPORTED, {});
+ return Void();
+}
+
+template <typename T, typename Method>
+static inline void GetHealthInfoField(Health* service, Method func, T* out) {
+ *out = T{};
+ std::invoke(func, service, [out](Result result, const T& value) {
+ if (result == Result::SUCCESS) *out = value;
+ });
+}
+
+Return<void> Health::getHealthInfo(getHealthInfo_cb _hidl_cb) {
+ return getHealthInfo_2_1(
+ [&](auto res, const auto& health_info) { _hidl_cb(res, health_info.legacy); });
+}
+
+Return<void> Health::getHealthInfo_2_1(getHealthInfo_2_1_cb _hidl_cb) {
+ battery_monitor_.updateValues();
+
+ HealthInfo health_info = battery_monitor_.getHealthInfo_2_1();
+
+ // Fill in storage infos; these aren't retrieved by BatteryMonitor.
+ GetHealthInfoField(this, &Health::getStorageInfo, &health_info.legacy.storageInfos);
+ GetHealthInfoField(this, &Health::getDiskStats, &health_info.legacy.diskStats);
+
+ // A subclass may want to update health info struct before returning it.
+ UpdateHealthInfo(&health_info);
+
+ _hidl_cb(Result::SUCCESS, health_info);
+ return Void();
+}
+
+Return<void> Health::debug(const hidl_handle& handle, const hidl_vec<hidl_string>&) {
+ if (handle == nullptr || handle->numFds == 0) {
+ return Void();
+ }
+
+ int fd = handle->data[0];
+ battery_monitor_.dumpState(fd);
+ getHealthInfo_2_1([fd](auto res, const auto& info) {
+ android::base::WriteStringToFd("\ngetHealthInfo -> ", fd);
+ if (res == Result::SUCCESS) {
+ android::base::WriteStringToFd(toString(info), fd);
+ } else {
+ android::base::WriteStringToFd(toString(res), fd);
+ }
+ android::base::WriteStringToFd("\n", fd);
+ });
+
+ fsync(fd);
+ return Void();
+}
+
+Return<void> Health::getHealthConfig(getHealthConfig_cb _hidl_cb) {
+ HealthConfig config = {};
+ convertToHealthConfig(healthd_config_.get(), config.battery);
+ config.bootMinCap = static_cast<int32_t>(healthd_config_->boot_min_cap);
+
+ _hidl_cb(Result::SUCCESS, config);
+ return Void();
+}
+
+Return<void> Health::shouldKeepScreenOn(shouldKeepScreenOn_cb _hidl_cb) {
+ if (!healthd_config_->screen_on) {
+ _hidl_cb(Result::NOT_SUPPORTED, true);
+ return Void();
+ }
+
+ Result returned_result = Result::UNKNOWN;
+ bool screen_on = true;
+ getHealthInfo_2_1([&](auto res, const auto& health_info) {
+ returned_result = res;
+ if (returned_result != Result::SUCCESS) return;
+
+ struct BatteryProperties props = {};
+ V1_0::hal_conversion::convertFromHealthInfo(health_info.legacy.legacy, &props);
+ screen_on = healthd_config_->screen_on(&props);
+ });
+ _hidl_cb(returned_result, screen_on);
+ return Void();
+}
+
+//
+// Subclass helpers / overrides
+//
+
+void Health::UpdateHealthInfo(HealthInfo* /* health_info */) {
+ /*
+ // Sample code for a subclass to implement this:
+ // If you need to modify values (e.g. batteryChargeTimeToFullNowSeconds), do it here.
+ health_info->batteryChargeTimeToFullNowSeconds = calculate_charge_time_seconds();
+
+ // If you need to call healthd_board_battery_update:
+ struct BatteryProperties props;
+ convertFromHealthInfo(health_info.legacy.legacy, &props);
+ healthd_board_battery_update(&props);
+ convertToHealthInfo(&props, health_info.legacy.legacy);
+ */
+}
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace health
+} // namespace hardware
+} // namespace android
diff --git a/health/utils/libhealth2impl/include/health2impl/BinderHealth.h b/health/utils/libhealth2impl/include/health2impl/BinderHealth.h
new file mode 100644
index 0000000..1da5bd1
--- /dev/null
+++ b/health/utils/libhealth2impl/include/health2impl/BinderHealth.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2019 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 <android-base/unique_fd.h>
+#include <android/hardware/health/2.1/IHealth.h>
+#include <healthd/healthd.h>
+
+#include <health2impl/Callback.h>
+#include <health2impl/HalHealthLoop.h>
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+// binderized health HAL implementation.
+class BinderHealth : public HalHealthLoop, public IHealth, public hidl_death_recipient {
+ public:
+ // |impl| should be the passthrough implementation.
+ BinderHealth(const std::string& name, const sp<IHealth>& impl);
+
+ // Methods from ::android::hardware::health::V2_0::IHealth follow.
+ Return<::android::hardware::health::V2_0::Result> registerCallback(
+ const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback) override;
+ Return<::android::hardware::health::V2_0::Result> unregisterCallback(
+ const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback) override;
+ Return<::android::hardware::health::V2_0::Result> update() override;
+ Return<void> getChargeCounter(getChargeCounter_cb _hidl_cb) override {
+ return service()->getChargeCounter(_hidl_cb);
+ }
+ Return<void> getCurrentNow(getCurrentNow_cb _hidl_cb) override {
+ return service()->getCurrentNow(_hidl_cb);
+ }
+ Return<void> getCurrentAverage(getCurrentAverage_cb _hidl_cb) override {
+ return service()->getCurrentAverage(_hidl_cb);
+ }
+ Return<void> getCapacity(getCapacity_cb _hidl_cb) override {
+ return service()->getCapacity(_hidl_cb);
+ }
+ Return<void> getEnergyCounter(getEnergyCounter_cb _hidl_cb) override {
+ return service()->getEnergyCounter(_hidl_cb);
+ }
+ Return<void> getChargeStatus(getChargeStatus_cb _hidl_cb) override {
+ return service()->getChargeStatus(_hidl_cb);
+ }
+ Return<void> getStorageInfo(getStorageInfo_cb _hidl_cb) override {
+ return service()->getStorageInfo(_hidl_cb);
+ }
+ Return<void> getDiskStats(getDiskStats_cb _hidl_cb) override {
+ return service()->getDiskStats(_hidl_cb);
+ }
+ Return<void> getHealthInfo(getHealthInfo_cb _hidl_cb) override {
+ return service()->getHealthInfo(_hidl_cb);
+ }
+
+ // Methods from ::android::hardware::health::V2_1::IHealth follow.
+ Return<void> getHealthConfig(getHealthConfig_cb _hidl_cb) override {
+ return service()->getHealthConfig(_hidl_cb);
+ }
+ Return<void> getHealthInfo_2_1(getHealthInfo_2_1_cb _hidl_cb) override {
+ return service()->getHealthInfo_2_1(_hidl_cb);
+ }
+ Return<void> shouldKeepScreenOn(shouldKeepScreenOn_cb _hidl_cb) override {
+ return service()->shouldKeepScreenOn(_hidl_cb);
+ }
+
+ // Methods from ::android::hidl::base::V1_0::IBase follow.
+ Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override {
+ return service()->debug(fd, args);
+ }
+
+ // hidl_death_recipient implementation.
+ void serviceDied(uint64_t cookie, const wp<IBase>& who) override;
+
+ // Called by BinderHealthCallback.
+ void OnHealthInfoChanged(const HealthInfo& health_info) override;
+
+ protected:
+ void Init(struct healthd_config* config) override;
+ int PrepareToWait() override;
+ // A subclass may override this if it wants to handle binder events differently.
+ virtual void BinderEvent(uint32_t epevents);
+
+ private:
+ bool unregisterCallbackInternal(const sp<IBase>& callback);
+ int binder_fd_ = -1;
+ std::mutex callbacks_lock_;
+ std::vector<std::unique_ptr<Callback>> callbacks_;
+};
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace health
+} // namespace hardware
+} // namespace android
diff --git a/health/utils/libhealth2impl/include/health2impl/Callback.h b/health/utils/libhealth2impl/include/health2impl/Callback.h
new file mode 100644
index 0000000..a30480b
--- /dev/null
+++ b/health/utils/libhealth2impl/include/health2impl/Callback.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2019 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 <android/hardware/health/2.1/IHealth.h>
+#include <android/hardware/health/2.1/IHealthInfoCallback.h>
+
+using ::android::sp;
+using ::android::hardware::Return;
+using ::android::hidl::base::V1_0::IBase;
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+// Wraps an IHealthInfoCallback.
+class Callback {
+ public:
+ virtual ~Callback() {}
+ virtual Return<void> Notify(const HealthInfo&) = 0;
+ virtual sp<IBase> Get() = 0;
+};
+
+class Callback_2_0 : public Callback {
+ public:
+ Callback_2_0(const sp<V2_0::IHealthInfoCallback>& callback) : callback_(callback) {}
+ Return<void> Notify(const HealthInfo& info) override {
+ return callback_->healthInfoChanged(info.legacy);
+ }
+ sp<IBase> Get() override { return callback_; }
+
+ private:
+ sp<V2_0::IHealthInfoCallback> callback_;
+};
+
+class Callback_2_1 : public Callback {
+ public:
+ Callback_2_1(const sp<IHealthInfoCallback>& callback) : callback_(callback) {}
+ Return<void> Notify(const HealthInfo& info) override {
+ return callback_->healthInfoChanged_2_1(info);
+ }
+ sp<IBase> Get() override { return callback_; }
+
+ private:
+ sp<IHealthInfoCallback> callback_;
+};
+
+inline std::unique_ptr<Callback> Wrap(const sp<V2_0::IHealthInfoCallback>& callback_2_0) {
+ auto callback_2_1 = IHealthInfoCallback::castFrom(callback_2_0).withDefault(nullptr);
+ if (callback_2_1) return std::make_unique<Callback_2_1>(callback_2_1);
+ return std::make_unique<Callback_2_0>(callback_2_0);
+}
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace health
+} // namespace hardware
+} // namespace android
diff --git a/health/utils/libhealth2impl/include/health2impl/HalHealthLoop.h b/health/utils/libhealth2impl/include/health2impl/HalHealthLoop.h
new file mode 100644
index 0000000..d9b5580
--- /dev/null
+++ b/health/utils/libhealth2impl/include/health2impl/HalHealthLoop.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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 <optional>
+
+#include <android/hardware/health/2.1/IHealth.h>
+#include <health/HealthLoop.h>
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+// An implementation of HealthLoop for using a given health HAL. This is useful
+// for services that opens the passthrough implementation and starts the HealthLoop
+// to periodically poll data from the implementation.
+class HalHealthLoop : public HealthLoop {
+ public:
+ HalHealthLoop(const std::string& name, const sp<IHealth>& service)
+ : instance_name_(name), service_(service) {}
+
+ protected:
+ virtual void Init(struct healthd_config* config) override;
+ virtual void Heartbeat() override;
+ virtual int PrepareToWait() override;
+ virtual void ScheduleBatteryUpdate() override;
+
+ // HealthLoop periodically calls ScheduleBatteryUpdate, which calls
+ // OnHealthInfoChanged callback. A client can override this function to
+ // broadcast the health_info to interested listeners. By default, this
+ // adjust uevents / wakealarm periods.
+ virtual void OnHealthInfoChanged(const HealthInfo& health_info);
+
+ const std::string& instance_name() const { return instance_name_; }
+ const sp<IHealth>& service() const { return service_; }
+ bool charger_online() const { return charger_online_; }
+
+ // Helpers for subclasses to implement OnHealthInfoChanged.
+ void set_charger_online(const HealthInfo& health_info);
+
+ private:
+ const std::string& instance_name_;
+ sp<IHealth> service_;
+ bool charger_online_ = false;
+};
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace health
+} // namespace hardware
+} // namespace android
diff --git a/health/utils/libhealth2impl/include/health2impl/Health.h b/health/utils/libhealth2impl/include/health2impl/Health.h
new file mode 100644
index 0000000..853b0cd
--- /dev/null
+++ b/health/utils/libhealth2impl/include/health2impl/Health.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2019 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 <memory>
+#include <mutex>
+#include <vector>
+
+#include <android-base/unique_fd.h>
+#include <android/hardware/health/2.1/IHealth.h>
+#include <healthd/BatteryMonitor.h>
+#include <hidl/Status.h>
+
+#include <health2impl/Callback.h>
+
+using ::android::sp;
+using ::android::hardware::hidl_string;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hidl::base::V1_0::IBase;
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+class Health : public IHealth {
+ public:
+ Health(std::unique_ptr<healthd_config>&& config);
+
+ // Methods from ::android::hardware::health::V2_0::IHealth follow.
+ Return<::android::hardware::health::V2_0::Result> registerCallback(
+ const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback) override;
+ Return<::android::hardware::health::V2_0::Result> unregisterCallback(
+ const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback) override;
+ Return<::android::hardware::health::V2_0::Result> update() override;
+ Return<void> getChargeCounter(getChargeCounter_cb _hidl_cb) override;
+ Return<void> getCurrentNow(getCurrentNow_cb _hidl_cb) override;
+ Return<void> getCurrentAverage(getCurrentAverage_cb _hidl_cb) override;
+ Return<void> getCapacity(getCapacity_cb _hidl_cb) override;
+ Return<void> getEnergyCounter(getEnergyCounter_cb _hidl_cb) override;
+ Return<void> getChargeStatus(getChargeStatus_cb _hidl_cb) override;
+ Return<void> getStorageInfo(getStorageInfo_cb _hidl_cb) override;
+ Return<void> getDiskStats(getDiskStats_cb _hidl_cb) override;
+ Return<void> getHealthInfo(getHealthInfo_cb _hidl_cb) override;
+
+ // Methods from ::android::hardware::health::V2_1::IHealth follow.
+ Return<void> getHealthConfig(getHealthConfig_cb _hidl_cb) override;
+ Return<void> getHealthInfo_2_1(getHealthInfo_2_1_cb _hidl_cb) override;
+ Return<void> shouldKeepScreenOn(shouldKeepScreenOn_cb _hidl_cb) override;
+
+ // Methods from ::android::hidl::base::V1_0::IBase follow.
+ Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override;
+
+ protected:
+ // A subclass can override this to modify any health info object before
+ // returning to clients. This is similar to healthd_board_battery_update().
+ // By default, it does nothing.
+ virtual void UpdateHealthInfo(HealthInfo* health_info);
+
+ private:
+ bool unregisterCallbackInternal(const sp<IBase>& callback);
+
+ BatteryMonitor battery_monitor_;
+ std::unique_ptr<healthd_config> healthd_config_;
+
+ std::mutex callbacks_lock_;
+ std::vector<std::unique_ptr<Callback>> callbacks_;
+};
+
+} // namespace implementation
+} // namespace V2_1
+} // namespace health
+} // namespace hardware
+} // namespace android
diff --git a/ir/1.0/vts/functional/Android.bp b/ir/1.0/vts/functional/Android.bp
index f5c9d61..f9edebd 100644
--- a/ir/1.0/vts/functional/Android.bp
+++ b/ir/1.0/vts/functional/Android.bp
@@ -21,5 +21,5 @@
static_libs: [
"android.hardware.ir@1.0",
],
- test_suites: ["general-tests"],
+ test_suites: ["general-tests", "vts-core"],
}
diff --git a/ir/1.0/vts/functional/VtsHalIrV1_0TargetTest.cpp b/ir/1.0/vts/functional/VtsHalIrV1_0TargetTest.cpp
index 5fd2dd4..a5dbdcc 100644
--- a/ir/1.0/vts/functional/VtsHalIrV1_0TargetTest.cpp
+++ b/ir/1.0/vts/functional/VtsHalIrV1_0TargetTest.cpp
@@ -21,8 +21,9 @@
#include <android/hardware/ir/1.0/IConsumerIr.h>
#include <android/hardware/ir/1.0/types.h>
-#include <VtsHalHidlTargetTestBase.h>
-#include <VtsHalHidlTargetTestEnvBase.h>
+#include <gtest/gtest.h>
+#include <hidl/GtestPrinter.h>
+#include <hidl/ServiceManagement.h>
#include <algorithm>
using ::android::hardware::ir::V1_0::IConsumerIr;
@@ -31,26 +32,10 @@
using ::android::hardware::Return;
using ::android::sp;
-// Test environment for Ir
-class ConsumerIrHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
- public:
- // get the test environment singleton
- static ConsumerIrHidlEnvironment* Instance() {
- static ConsumerIrHidlEnvironment* instance = new ConsumerIrHidlEnvironment;
- return instance;
- }
-
- virtual void registerTestServices() override { registerTestService<IConsumerIr>(); }
- private:
- ConsumerIrHidlEnvironment() {}
-};
-
-// The main test class for IR HIDL HAL.
-class ConsumerIrHidlTest : public ::testing::VtsHalHidlTargetTestBase {
+class ConsumerIrHidlTest : public ::testing::TestWithParam<std::string> {
public:
virtual void SetUp() override {
- ir = ::testing::VtsHalHidlTargetTestBase::getService<IConsumerIr>(
- ConsumerIrHidlEnvironment::Instance()->getServiceName<IConsumerIr>());
+ ir = IConsumerIr::getService(GetParam());
ASSERT_NE(ir, nullptr);
}
@@ -60,7 +45,7 @@
};
// Test transmit() for the min and max frequency of every available range
-TEST_F(ConsumerIrHidlTest, TransmitTest) {
+TEST_P(ConsumerIrHidlTest, TransmitTest) {
bool success;
hidl_vec<ConsumerIrFreqRange> ranges;
auto cb = [&](bool s, hidl_vec<ConsumerIrFreqRange> v) {
@@ -84,7 +69,7 @@
}
// Test transmit() when called with invalid frequencies
-TEST_F(ConsumerIrHidlTest, BadFreqTest) {
+TEST_P(ConsumerIrHidlTest, BadFreqTest) {
uint32_t len = 16;
hidl_vec<int32_t> vec;
vec.resize(len);
@@ -92,11 +77,7 @@
EXPECT_FALSE(ir->transmit(-1, vec));
}
-int main(int argc, char **argv) {
- ::testing::AddGlobalTestEnvironment(ConsumerIrHidlEnvironment::Instance());
- ::testing::InitGoogleTest(&argc, argv);
- ConsumerIrHidlEnvironment::Instance()->init(&argc, argv);
- int status = RUN_ALL_TESTS();
- LOG(INFO) << "Test result = " << status;
- return status;
-}
+INSTANTIATE_TEST_SUITE_P(
+ PerInstance, ConsumerIrHidlTest,
+ testing::ValuesIn(android::hardware::getAllHalInstanceNames(IConsumerIr::descriptor)),
+ android::hardware::PrintInstanceNameToString);
diff --git a/neuralnetworks/1.3/vts/functional/Android.bp b/neuralnetworks/1.3/vts/functional/Android.bp
index 90ce852..0f2720e 100644
--- a/neuralnetworks/1.3/vts/functional/Android.bp
+++ b/neuralnetworks/1.3/vts/functional/Android.bp
@@ -15,7 +15,7 @@
//
cc_test {
- name: "VtsHalNeuralNetworksV1_3TargetTest",
+ name: "VtsHalNeuralnetworksV1_3TargetTest",
defaults: ["VtsHalTargetTestDefaults"],
srcs: [
"BasicTests.cpp",
diff --git a/neuralnetworks/TEST_MAPPING b/neuralnetworks/TEST_MAPPING
index 421922a..bbf34f7 100644
--- a/neuralnetworks/TEST_MAPPING
+++ b/neuralnetworks/TEST_MAPPING
@@ -7,7 +7,7 @@
// Just use sample-all driver for presubmit tests for faster results.
// The other sample drivers (fast-float, quant, etc.) are subsets of
// sample-all.
- "native-test-flag": "--gtest_filter=*sample_all*"
+ "include-filter": "*sample_all*"
}
]
},
@@ -18,7 +18,7 @@
// Just use sample-all driver for presubmit tests for faster results.
// The other sample drivers (fast-float, quant, etc.) are subsets of
// sample-all.
- "native-test-flag": "--gtest_filter=*sample_all*"
+ "include-filter": "*sample_all*"
}
]
},
@@ -29,7 +29,18 @@
// Just use sample-all driver for presubmit tests for faster results.
// The other sample drivers (fast-float, quant, etc.) are subsets of
// sample-all.
- "native-test-flag": "--gtest_filter=*sample_all*"
+ "include-filter": "*sample_all*"
+ }
+ ]
+ },
+ {
+ "name": "VtsHalNeuralnetworksV1_3TargetTest",
+ "options": [
+ {
+ // Just use sample-all driver for presubmit tests for faster results.
+ // The other sample drivers (fast-float, quant, etc.) are subsets of
+ // sample-all.
+ "include-filter": "*sample_all*"
}
]
}
diff --git a/tv/tuner/1.0/Android.bp b/tv/tuner/1.0/Android.bp
index 09265f7..d78f3f2 100644
--- a/tv/tuner/1.0/Android.bp
+++ b/tv/tuner/1.0/Android.bp
@@ -9,15 +9,21 @@
srcs: [
"types.hal",
"IDemux.hal",
- "IDemuxCallback.hal",
"IDescrambler.hal",
+ "IDvr.hal",
+ "IDvrCallback.hal",
+ "IFilter.hal",
+ "IFilterCallback.hal",
"IFrontend.hal",
"IFrontendCallback.hal",
"ILnb.hal",
+ "ILnbCallback.hal",
+ "ITimeFilter.hal",
"ITuner.hal",
],
interfaces: [
"android.hidl.base@1.0",
+ "android.hidl.safe_union@1.0",
],
gen_java: false,
gen_java_constants: true,
diff --git a/tv/tuner/1.0/IDemux.hal b/tv/tuner/1.0/IDemux.hal
index 7fd7e26..9e799b4 100644
--- a/tv/tuner/1.0/IDemux.hal
+++ b/tv/tuner/1.0/IDemux.hal
@@ -16,7 +16,11 @@
package android.hardware.tv.tuner@1.0;
-import IDemuxCallback;
+import IDvr;
+import IDvrCallback;
+import IFilter;
+import IFilterCallback;
+import ITimeFilter;
/**
* Demultiplexer(Demux) takes a single multiplexed input and splits it into
@@ -24,7 +28,6 @@
*
*/
interface IDemux {
-
/**
* Set a frontend resource as data input of the demux
*
@@ -39,134 +42,51 @@
setFrontendDataSource(FrontendId frontendId) generates (Result result);
/**
- * Add a filter to the demux
+ * Open a new filter in the demux
*
- * It is used by the client to add a filter to the demux.
+ * It is used by the client to open a filter in the demux.
*
* @param type the type of the filter to be added.
- * @param bufferSize the buffer size of the filter to be added. It's used to
- * create a FMQ(Fast Message Queue) to hold data output from the filter.
+ * @param bufferSize the buffer size of the filter to be opened. It's used
+ * to create a FMQ(Fast Message Queue) to hold data output from the filter.
* @param cb the callback for the filter to be used to send notifications
* back to the client.
* @return result Result status of the operation.
* SUCCESS if successful,
* INVALID_STATE if failed for wrong state.
* UNKNOWN_ERROR if failed for other reasons.
- * @return filterId the ID of the newly added filter.
+ * @return filter the filter instance of the newly added.
*/
- addFilter(DemuxFilterType type, uint32_t bufferSize, IDemuxCallback cb)
- generates (Result result, DemuxFilterId filterId);
+ openFilter(DemuxFilterType type, uint32_t bufferSize, IFilterCallback cb)
+ generates (Result result, IFilter filter);
/**
- * Get the descriptor of the filter's FMQ
+ * Open time filter of the demux
*
- * It is used by the client to get the descriptor of the filter's Fast
- * Message Queue. The data in FMQ is filtered out from MPEG transport
- * stream. The data is organized to data blocks which may have
- * different length. The length's information of one or multiple data blocks
- * is sent to client through DemuxFilterEvent.
+ * It is used by the client to open time filter of the demux.
*
- * @param filterId the ID of the filter.
* @return result Result status of the operation.
* SUCCESS if successful,
- * INVALID_ARGUMENT if failed for wrong filter ID.
+ * UNAVAILABLE if time filter is not supported.
* INVALID_STATE if failed for wrong state.
* UNKNOWN_ERROR if failed for other reasons.
- * @return queue the descriptor of the filter's FMQ
+ * @return timeFilter the time filter instance of the newly added.
*/
- getFilterQueueDesc(DemuxFilterId filterId)
- generates (Result result, fmq_sync<uint8_t> queue);
-
- /**
- * Configure the filter.
- *
- * It is used by the client to configure the filter so that it can filter out
- * intended data.
- *
- * @param filterId the ID of the filter.
- * @param settings the settings of the filter.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_ARGUMENT if failed for wrong filter ID.
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- configureFilter(DemuxFilterId filterId, DemuxFilterSettings settings)
- generates(Result result);
-
- /**
- * Start the filter.
- *
- * It is used by the client to ask the filter to start filtering data.
- *
- * @param filterId the ID of the filter.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_ARGUMENT if failed for wrong filter ID.
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- startFilter(DemuxFilterId filterId) generates (Result result);
-
- /**
- * Stop the filter.
- *
- * It is used by the client to ask the filter to stop filterring data.
- * It won't discard the data already filtered out by the filter. The filter
- * will be stopped and removed automatically if the demux is closed.
- *
- * @param filterId the ID of the filter.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_ARGUMENT if failed for wrong filter ID.
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- stopFilter(DemuxFilterId filterId) generates (Result result);
-
- /**
- * Flush the filter.
- *
- * It is used by the client to ask the filter to flush the data which is
- * already produced but not consumed yet.
- *
- * @param filterId the ID of the filter.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_ARGUMENT if failed for wrong filter ID.
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- flushFilter(DemuxFilterId filterId) generates (Result result);
-
- /**
- * Remove a filter from the demux
- *
- * It is used by the client to remove a filter from the demux.
- *
- * @param filterId the ID of the removed filter.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_ARGUMENT if failed for wrong filter ID.
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- removeFilter(DemuxFilterId filterId) generates (Result result);
+ openTimeFilter() generates (Result result, ITimeFilter timeFilter);
/**
* Get hardware sync ID for audio and video.
*
* It is used by the client to get the hardware sync ID for audio and video.
*
- * @param filterId the ID of the filter.
+ * @param filter the filter instance.
* @return result Result status of the operation.
* SUCCESS if successful,
* INVALID_ARGUMENT if failed for a wrong filter ID.
* UNKNOWN_ERROR if failed for other reasons.
* @return avSyncHwId the id of hardware A/V sync.
*/
- getAvSyncHwId(DemuxFilterId filterId)
- generates (Result result, AvSyncHwId avSyncHwId);
+ getAvSyncHwId(IFilter filter) generates (Result result, AvSyncHwId avSyncHwId);
/**
* Get current time stamp to use for A/V sync
@@ -182,8 +102,7 @@
* @return time the current time stamp of hardware A/V sync. The time stamp
* based on 90KHz has the same format as PTS (Presentation Time Stamp).
*/
- getAvSyncTime(AvSyncHwId avSyncHwId)
- generates (Result result, uint64_t time);
+ getAvSyncTime(AvSyncHwId avSyncHwId) generates (Result result, uint64_t time);
/**
* Close the Demux instance
@@ -198,218 +117,21 @@
close() generates (Result result);
/**
- * Add output to the demux
+ * Open a DVR (Digital Video Record) instance in the demux
*
- * It is used by the client to record output data from selected filters.
+ * It is used by the client to record and playback.
*
+ * @param type specify which kind of DVR to open.
* @param bufferSize the buffer size of the output to be added. It's used to
* create a FMQ(Fast Message Queue) to hold data from selected filters.
- * @param cb the callback for the demux to be used to send notifications
+ * @param cb the callback for the DVR to be used to send notifications
* back to the client.
* @return result Result status of the operation.
* SUCCESS if successful,
* OUT_OF_MEMORY if failed for not enough memory.
* UNKNOWN_ERROR if failed for other reasons.
+ * @return dvr a DVR instance.
*/
- addOutput(uint32_t bufferSize, IDemuxCallback cb) generates (Result result);
-
- /**
- * Get the descriptor of the output's FMQ
- *
- * It is used by the client to get the descriptor of the output's Fast
- * Message Queue. The data in FMQ is muxed packets output from selected
- * filters. The packet's format is specified by DemuxDataFormat in
- * DemuxOutputSettings.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * UNKNOWN_ERROR if failed for other reasons.
- * @return queue the descriptor of the output's FMQ
- */
- getOutputQueueDesc() generates (Result result, fmq_sync<uint8_t> queue);
-
- /**
- * Configure the demux's output.
- *
- * It is used by the client to configure the demux's output for recording.
- *
- * @param settings the settings of the demux's output.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- configureOutput(DemuxOutputSettings settings) generates (Result result);
-
- /**
- * Attach one filter to the demux's output.
- *
- * It is used by the client to mux one filter's output to demux's output.
- *
- * @param filterId the ID of the attached filter.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- attachOutputFilter(DemuxFilterId filterId) generates (Result result);
-
- /**
- * Detach one filter from the demux's output.
- *
- * It is used by the client to remove one filter's output from demux's
- * output.
- *
- * @param filterId the ID of the detached filter.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- detachOutputFilter(DemuxFilterId filterId) generates (Result result);
-
- /**
- * Start to take data to the demux's output.
- *
- * It is used by the client to ask the output to start to take data from
- * attached filters.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- startOutput() generates (Result result);
-
- /**
- * Stop to take data to the demux's output.
- *
- * It is used by the client to ask the output to stop to take data from
- * attached filters.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- stopOutput() generates (Result result);
-
- /**
- * Flush unconsumed data in the demux's output.
- *
- * It is used by the client to ask the demux to flush the data which is
- * already produced but not consumed yet in the demux's output.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- flushOutput() generates (Result result);
-
- /**
- * Remove the demux's output.
- *
- * It is used by the client to remove the demux's output.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- removeOutput() generates (Result result);
-
- /**
- * Add input to the demux
- *
- * It is used by the client to add the demux's input for playback content.
- *
- * @param bufferSize the buffer size of the demux's input to be added.
- * It's used to create a FMQ(Fast Message Queue) to hold input data.
- * @param cb the callback for the demux to be used to send notifications
- * back to the client.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * OUT_OF_MEMORY if failed for not enough memory.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- addInput(uint32_t bufferSize, IDemuxCallback cb) generates (Result result);
-
- /**
- * Get the descriptor of the input's FMQ
- *
- * It is used by the client to get the descriptor of the input's Fast
- * Message Queue. The data in FMQ is fed by client. Data format is specifed
- * by DemuxDataFormat in DemuxInputSettings.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * UNKNOWN_ERROR if failed for other reasons.
- * @return queue the descriptor of the output's FMQ
- */
- getInputQueueDesc() generates (Result result, fmq_sync<uint8_t> queue);
-
- /**
- * Configure the demux's input.
- *
- * It is used by the client to configure the demux's input for playback.
- *
- * @param settings the settings of the demux's input.
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- configureInput(DemuxInputSettings settings) generates (Result result);
-
- /**
- * Start to consume the data from the demux's input.
- *
- * It is used by the client to ask the demux to start to consume data from
- * the demux's input.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- startInput() generates (Result result);
-
- /**
- * Stop to consume the data from the demux's input.
- *
- * It is used by the client to ask the demux to stop to consume data from
- * the demux's input.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- stopInput() generates (Result result);
-
- /**
- * Flush unconsumed data in the demux's input.
- *
- * It is used by the client to ask the demux to flush the data which is
- * already produced but not consumed yet in the demux's input.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- flushInput() generates (Result result);
-
- /**
- * Remove the demux's input.
- *
- * It is used by the client to remove the demux's input.
- *
- * @return result Result status of the operation.
- * SUCCESS if successful,
- * INVALID_STATE if failed for wrong state.
- * UNKNOWN_ERROR if failed for other reasons.
- */
- removeInput() generates (Result result);
+ openDvr(DvrType type, uint32_t bufferSize, IDvrCallback cb)
+ generates (Result result, IDvr dvr);
};
diff --git a/tv/tuner/1.0/IDemuxCallback.hal b/tv/tuner/1.0/IDemuxCallback.hal
deleted file mode 100644
index 7bce9ef..0000000
--- a/tv/tuner/1.0/IDemuxCallback.hal
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2019 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 android.hardware.tv.tuner@1.0;
-
-interface IDemuxCallback {
- /**
- * Notify the client that a new filter event happened.
- *
- * @param filterEvent a demux filter event.
- */
- oneway onFilterEvent(DemuxFilterEvent filterEvent);
-
- /**
- * Notify the client a new status of a demux filter.
- *
- * @param filterId the demux filter ID.
- * @param status a new status of the demux filter.
- */
- oneway onFilterStatus(DemuxFilterId filterId, DemuxFilterStatus status);
-
- /**
- * Notify the client a new status of the demux's output.
- *
- * @param status a new status of the demux's output.
- */
- oneway onOutputStatus(DemuxOutputStatus status);
-
- /**
- * Notify the client a new status of the demux's input.
- *
- * @param status a new status of the demux's input.
- */
- oneway onInputStatus(DemuxInputStatus status);
-};
-
diff --git a/tv/tuner/1.0/IDescrambler.hal b/tv/tuner/1.0/IDescrambler.hal
index 61ff1df..7f98865 100644
--- a/tv/tuner/1.0/IDescrambler.hal
+++ b/tv/tuner/1.0/IDescrambler.hal
@@ -15,6 +15,9 @@
*/
package android.hardware.tv.tuner@1.0;
+
+import IFilter;
+
/**
* Descrambler is used to descramble input data.
*
@@ -59,12 +62,13 @@
* packets from different PIDs.
*
* @param pid the PID of packets to start to be descrambled.
+ * @param filter an optional filter instance to identify upper stream.
* @return result Result status of the operation.
* SUCCESS if successful,
* INVALID_STATE if failed for wrong state.
* UNKNOWN_ERROR if failed for other reasons.
*/
- addPid(DemuxTpid pid) generates (Result result);
+ addPid(DemuxPid pid, IFilter optionalSourceFilter) generates (Result result);
/**
* Remove packets' PID from the descrambler
@@ -73,12 +77,13 @@
* descrambler stop to descramble.
*
* @param pid the PID of packets to stop to be descrambled.
+ * @param filter an optional filter instance to identify upper stream.
* @return result Result status of the operation.
* SUCCESS if successful,
* INVALID_STATE if failed for wrong state.
* UNKNOWN_ERROR if failed for other reasons.
*/
- removePid(DemuxTpid pid) generates (Result result);
+ removePid(DemuxPid pid, IFilter optionalSourceFilter) generates (Result result);
/**
* Release the descrambler instance
@@ -92,4 +97,3 @@
*/
close() generates (Result result);
};
-
diff --git a/tv/tuner/1.0/IDvr.hal b/tv/tuner/1.0/IDvr.hal
new file mode 100644
index 0000000..f57e4b6
--- /dev/null
+++ b/tv/tuner/1.0/IDvr.hal
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.tv.tuner@1.0;
+
+import IFilter;
+
+/**
+ * Digtal Video Record (DVR) interface provides record control on Demux's
+ * output buffer and playback control on Demux's input buffer.
+ */
+interface IDvr {
+ /**
+ * Get the descriptor of the DVR's FMQ
+ *
+ * It is used by the client to get the descriptor of the DVR's Fast
+ * Message Queue. The FMQ is used to transfer record or playback data
+ * between the client and the HAL.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * UNKNOWN_ERROR if failed for other reasons.
+ * @return queue the descriptor of the DVR's FMQ
+ */
+ getQueueDesc() generates (Result result, fmq_sync<uint8_t> queue);
+
+ /**
+ * Configure the DVR.
+ *
+ * It is used by the client to configure the DVR interface.
+ *
+ * @param settings the settings of the DVR interface.
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ configure(DvrSettings settings) generates (Result result);
+
+ /**
+ * Attach one filter to DVR interface for recording.
+ *
+ * It is used by the client to add the data filtered out from the filter
+ * to record.
+ *
+ * @param filter the instance of the attached filter.
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ attachFilter(IFilter filter) generates (Result result);
+
+ /**
+ * Detach one filter from the DVR's recording.
+ *
+ * It is used by the client to remove the data of the filter from DVR's
+ * recording.
+ *
+ * @param filter the instance of the detached filter.
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ detachFilter(IFilter filter) generates (Result result);
+
+ /**
+ * Start DVR.
+ *
+ * It is used by the client to ask the DVR to start consuming playback data
+ * or producing data for record.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ start() generates (Result result);
+
+ /**
+ * Stop DVR.
+ *
+ * It is used by the client to ask the DVR to stop consuming playback data
+ * or producing data for record.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ stop() generates (Result result);
+
+ /**
+ * Flush DVR data.
+ *
+ * It is used by the client to ask the DVR to flush the data which is
+ * not consumed by HAL for playback or the client for record yet.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ flush() generates (Result result);
+
+ /**
+ * close the DVR instance to release resource for DVR.
+ *
+ * It is used by the client to close the DVR instance, and HAL clears
+ * underneath resource for this DVR instance. Client mustn't access the
+ * instance any more and all methods should return a failure.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ close() generates (Result result);
+};
diff --git a/tv/tuner/1.0/IDvrCallback.hal b/tv/tuner/1.0/IDvrCallback.hal
new file mode 100644
index 0000000..337eddc
--- /dev/null
+++ b/tv/tuner/1.0/IDvrCallback.hal
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.tv.tuner@1.0;
+
+interface IDvrCallback {
+ /**
+ * Notify the client a new status of the demux's record.
+ *
+ * @param status a new status of the demux's record.
+ */
+ oneway onRecordStatus(RecordStatus status);
+
+ /**
+ * Notify the client a new status of the demux's playback.
+ *
+ * @param status a new status of the demux's playback.
+ */
+ oneway onPlaybackStatus(PlaybackStatus status);
+};
diff --git a/tv/tuner/1.0/IFilter.hal b/tv/tuner/1.0/IFilter.hal
new file mode 100644
index 0000000..deaf3d4
--- /dev/null
+++ b/tv/tuner/1.0/IFilter.hal
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.tv.tuner@1.0;
+
+import IFilterCallback;
+
+/**
+ * The Filter is used to filter wanted data according to the filter's
+ * configuration.
+ */
+interface IFilter {
+ /**
+ * Get the descriptor of the filter's FMQ
+ *
+ * It is used by the client to get the descriptor of the filter's Fast
+ * Message Queue. The data in FMQ is filtered out from demux input or upper
+ * stream's filter. The data is origanized to data blocks which may have
+ * different length. The length's information of one or multiple data blocks
+ * is sent to client through DemuxFilterEvent. The data in each block
+ * follows the stardard specified by filter's type.
+ * E.X. one data block from the filter with Main_Type==TS and Sub_Type==PES
+ * is Packetized Elementary Stream from Transport Stream according to
+ * ISO/IEC 13818-1.
+ *
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * UNAVAILABLE if the filter doesn't have FMQ.
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ * @return queue the descriptor of the filter's FMQ
+ */
+ getQueueDesc() generates (Result result, fmq_sync<uint8_t> queue);
+
+ /**
+ * Configure the filter.
+ *
+ * It is used by the client to configure the filter so that it can filter out
+ * intended data.
+ *
+ * @param settings the settings of the filter.
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ configure(DemuxFilterSettings settings) generates (Result result);
+
+ /**
+ * Start the filter.
+ *
+ * It is used by the client to ask the filter to start filterring data.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ start() generates (Result result);
+
+ /**
+ * Stop the filter.
+ *
+ * It is used by the client to ask the filter to stop filterring data.
+ * It won't discard the data already filtered out by the filter. The filter
+ * will be stopped and removed automatically if the demux is closed.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ stop() generates (Result result);
+
+ /**
+ * Flush the filter.
+ *
+ * It is used by the client to ask the filter to flush the data which is
+ * already produced but not consumed yet.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ flush() generates (Result result);
+
+ /**
+ * Get the filter Id.
+ *
+ * It is used by the client to ask the hardware resource id for the filter.
+ *
+ * @param filterId the hardware resource Id for the filter.
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ getId() generates (Result result, uint32_t filterId);
+
+ /**
+ * Set the filter's data source.
+ *
+ * A filter uses demux as data source by default. If the data was packetized
+ * by multiple protocols, multiple filters may need to work together to
+ * extract all protocols' header. Then a filter's data source can be output
+ * from another filter.
+ *
+ * @param filter the filter instance which provides data input. Switch to
+ * use demux as data source if the filter instance is NULL.
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ setDataSource(IFilter filter) generates (Result result);
+
+ /**
+ * Release the Filter instance
+ *
+ * It is used by the client to release the Filter instance. HAL clear
+ * underneath resource. client mustn't access the instance any more.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ close() generates (Result result);
+};
diff --git a/tv/tuner/1.0/IFilterCallback.hal b/tv/tuner/1.0/IFilterCallback.hal
new file mode 100644
index 0000000..a0ff62e
--- /dev/null
+++ b/tv/tuner/1.0/IFilterCallback.hal
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.tv.tuner@1.0;
+
+interface IFilterCallback {
+ /**
+ * Notify the client that a new filter event happened.
+ *
+ * @param filterEvent a filter event.
+ */
+ oneway onFilterEvent(DemuxFilterEvent filterEvent);
+
+ /**
+ * Notify the client a new status of a filter.
+ *
+ * @param status a new status of the filter.
+ */
+ oneway onFilterStatus(DemuxFilterStatus status);
+};
diff --git a/tv/tuner/1.0/IFrontend.hal b/tv/tuner/1.0/IFrontend.hal
index 83e390d..756ab46 100644
--- a/tv/tuner/1.0/IFrontend.hal
+++ b/tv/tuner/1.0/IFrontend.hal
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package android.hardware.tv.tuner@1.0;
import IFrontendCallback;
@@ -128,7 +129,8 @@
* @return statuses an array of statuses which response the caller's
* request.
*/
- getStatus(vec<FrontendStatusType> statusTypes) generates (Result result, vec<FrontendStatus> statuses);
+ getStatus(vec<FrontendStatusType> statusTypes)
+ generates (Result result, vec<FrontendStatus> statuses);
/**
* Sets Low-Noise Block downconverter (LNB) for satellite frontend.
diff --git a/tv/tuner/1.0/IFrontendCallback.hal b/tv/tuner/1.0/IFrontendCallback.hal
index 8896a09..88b96c4 100644
--- a/tv/tuner/1.0/IFrontendCallback.hal
+++ b/tv/tuner/1.0/IFrontendCallback.hal
@@ -26,16 +26,6 @@
/**
* The callback function that must be called by HAL implementation to notify
- * the client of new DiSEqC message.
- *
- * @param diseqcMessage a byte array of data for DiSEqC (Digital Satellite
- * Equipment Control) message which is specified by EUTELSAT Bus Functional
- * Specification Version 4.2.
- */
- oneway onDiseqcMessage(vec<uint8_t> diseqcMessage);
-
- /**
- * The callback function that must be called by HAL implementation to notify
* the client of scan messages.
*
* @param type the type of scan message.
diff --git a/tv/tuner/1.0/ILnb.hal b/tv/tuner/1.0/ILnb.hal
index 6b7119e..5070519 100644
--- a/tv/tuner/1.0/ILnb.hal
+++ b/tv/tuner/1.0/ILnb.hal
@@ -13,8 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package android.hardware.tv.tuner@1.0;
+import ILnbCallback;
+
/**
* A Tuner LNB (low-noise block downconverter) is used by satellite frontend
* to receive the microwave signal from the satellite, amplify it, and
@@ -22,6 +25,23 @@
*/
interface ILnb {
/**
+ * Set the lnb callback.
+ *
+ * ILnbCallback is used by the client to receive events from the Lnb.
+ * Only one callback per ILnb instance is supported. The callback
+ * will be replaced if it's set again.
+ *
+ * @param callback Callback object to pass Lnb events to the system.
+ * The previously registered callback must be replaced with this one.
+ * It can be null.
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if callback can't be set at current stage,
+ * UNKNOWN_ERROR if callback setting failed for other reasons.
+ */
+ setCallback(ILnbCallback callback) generates (Result result);
+
+ /**
* Set the lnb's power voltage.
*
* @param voltage the power's voltage the Lnb to use.
@@ -30,7 +50,7 @@
* INVALID_ARGUMENT if the selected voltage isn't allowed,
* UNKNOWN_ERROR if failed for other reasons.
*/
- setVoltage(FrontendLnbVoltage voltage) generates (Result result);
+ setVoltage(LnbVoltage voltage) generates (Result result);
/**
* Set the lnb's tone mode.
@@ -41,7 +61,7 @@
* INVALID_ARGUMENT if the selected tone mode isn't allowed,
* UNKNOWN_ERROR if failed for other reasons.
*/
- setTone(FrontendLnbTone tone) generates (Result result);
+ setTone(LnbTone tone) generates (Result result);
/**
* Select the lnb's position.
@@ -52,7 +72,7 @@
* INVALID_ARGUMENT if the selected position isn't allowed,
* UNKNOWN_ERROR if failed for other reasons.
*/
- setSatellitePosition(FrontendLnbPosition position) generates (Result result);
+ setSatellitePosition(LnbPosition position) generates (Result result);
/**
* Sends DiSEqC (Digital Satellite Equipment Control) message.
diff --git a/tv/tuner/1.0/ILnbCallback.hal b/tv/tuner/1.0/ILnbCallback.hal
new file mode 100644
index 0000000..68e9c35
--- /dev/null
+++ b/tv/tuner/1.0/ILnbCallback.hal
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.tv.tuner@1.0;
+
+interface ILnbCallback {
+ /**
+ * Notify the client that a new event happened on the Lnb.
+ *
+ * @param LnbEventType the event type.
+ */
+ oneway onEvent(LnbEventType lnbEventType);
+
+ /**
+ * The callback function that must be called by HAL implementation to notify
+ * the client of new DiSEqC message.
+ *
+ * @param diseqcMessage a byte array of data for DiSEqC (Digital Satellite
+ * Equipment Control) message which is specified by EUTELSAT Bus Functional
+ * Specification Version 4.2.
+ */
+ oneway onDiseqcMessage(vec<uint8_t> diseqcMessage);
+};
diff --git a/tv/tuner/1.0/ITimeFilter.hal b/tv/tuner/1.0/ITimeFilter.hal
new file mode 100644
index 0000000..ce285db
--- /dev/null
+++ b/tv/tuner/1.0/ITimeFilter.hal
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2019 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 android.hardware.tv.tuner@1.0;
+
+/**
+ * Timer Filter is used by Demux to filter data based on time stamp.
+ */
+interface ITimeFilter {
+ /**
+ * Set time stamp for time based filter.
+ *
+ * It is used by the client to set initial time stamp and enable time
+ * filtering. The time will be incremented locally. The demux discards
+ * the content which time stamp is older than the time in the time filter.
+ *
+ * @param timeStamp initial time stamp for the time filter. It based on
+ * 90KHz has the same format as PTS (Presentation Time Stamp).
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ setTimeStamp(uint64_t timeStamp) generates (Result result);
+
+ /**
+ * Clear the time stamp in the time filter.
+ *
+ * It is used by the client to clear the time value of the time filter,
+ * then disable time filter.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ clearTimeStamp() generates (Result result);
+
+ /**
+ * Get the current time in the time filter.
+ *
+ * It is used by the client to inquiry current time in the time filter.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ * @return timeStamp current time stamp in the time filter.
+ */
+ getTimeStamp() generates (Result result, uint64_t timeStamp);
+
+ /**
+ * Get the time from the beginning of current data source.
+ *
+ * It is used by the client to inquiry the time stamp from the beginning
+ * of current data source.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * INVALID_STATE if failed for wrong state.
+ * UNKNOWN_ERROR if failed for other reasons.
+ * @return timeStamp time stamp from the beginning of current data source.
+ */
+ getSourceTime() generates (Result result, uint64_t timeStamp);
+
+ /**
+ * Close the Time Filter instance
+ *
+ * It is used by the client to release the demux instance. HAL clear
+ * underneath resource. client mustn't access the instance any more.
+ *
+ * @return result Result status of the operation.
+ * SUCCESS if successful,
+ * UNKNOWN_ERROR if failed for other reasons.
+ */
+ close() generates (Result result);
+};
diff --git a/tv/tuner/1.0/ITuner.hal b/tv/tuner/1.0/ITuner.hal
index 1cf0e38..2712c13 100644
--- a/tv/tuner/1.0/ITuner.hal
+++ b/tv/tuner/1.0/ITuner.hal
@@ -23,7 +23,7 @@
/**
* Top level interface to manage Frontend, Demux and Decrambler hardware
- * resources which are needed for Android TV.
+ * resouces which are needed for Android TV.
*/
interface ITuner {
/**
@@ -50,8 +50,7 @@
* UNKNOWN_ERROR if creation failed for other reasons.
* @return frontend the newly created frontend interface.
*/
- openFrontendById(FrontendId frontendId)
- generates (Result result, IFrontend frontend);
+ openFrontendById(FrontendId frontendId) generates (Result result, IFrontend frontend);
/**
* Create a new instance of Demux.
@@ -64,8 +63,7 @@
* @return demuxId newly created demux id.
* @return demux the newly created demux interface.
*/
- openDemux()
- generates (Result result, DemuxId demuxId, IDemux demux);
+ openDemux() generates (Result result, DemuxId demuxId, IDemux demux);
/**
* Retrieve the Demux's Capabilities.
@@ -87,8 +85,7 @@
* UNKNOWN_ERROR if creation failed for other reasons.
* @return descrambler the newly created descrambler interface.
*/
- openDescrambler()
- generates (Result result, IDescrambler descrambler);
+ openDescrambler() generates (Result result, IDescrambler descrambler);
/**
* Retrieve the frontend's information.
@@ -99,8 +96,7 @@
* UNKNOWN_ERROR if the inquiry failed for other reasons.
* @return info the frontend's information.
*/
- getFrontendInfo(FrontendId frontendId)
- generates (Result result, FrontendInfo info);
+ getFrontendInfo(FrontendId frontendId) generates (Result result, FrontendInfo info);
/**
* Get low-noise block downconverter (LNB) IDs.
@@ -126,7 +122,5 @@
* UNKNOWN_ERROR if creation failed for other reasons.
* @return lnb the newly created Lnb interface.
*/
- openLnbById(LnbId lnbId)
- generates (Result result, ILnb lnb);
+ openLnbById(LnbId lnbId) generates (Result result, ILnb lnb);
};
-
diff --git a/tv/tuner/1.0/default/Android.bp b/tv/tuner/1.0/default/Android.bp
index 0ae8bcd..989e25c 100644
--- a/tv/tuner/1.0/default/Android.bp
+++ b/tv/tuner/1.0/default/Android.bp
@@ -4,9 +4,12 @@
vendor: true,
relative_install_path: "hw",
srcs: [
+ "Filter.cpp",
"Frontend.cpp",
"Descrambler.cpp",
"Demux.cpp",
+ "Dvr.cpp",
+ "TimeFilter.cpp",
"Tuner.cpp",
"Lnb.cpp",
"service.cpp",
diff --git a/tv/tuner/1.0/default/Demux.cpp b/tv/tuner/1.0/default/Demux.cpp
index 8bb79f9..c5921f7 100644
--- a/tv/tuner/1.0/default/Demux.cpp
+++ b/tv/tuner/1.0/default/Demux.cpp
@@ -28,45 +28,6 @@
#define WAIT_TIMEOUT 3000000000
-const std::vector<uint8_t> fakeDataInputBuffer{
- 0x00, 0x00, 0x00, 0x01, 0x09, 0xf0, 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x1e, 0xdb,
- 0x01, 0x40, 0x16, 0xec, 0x04, 0x40, 0x00, 0x00, 0x03, 0x00, 0x40, 0x00, 0x00, 0x0f, 0x03,
- 0xc5, 0x8b, 0xb8, 0x00, 0x00, 0x00, 0x01, 0x68, 0xca, 0x8c, 0xb2, 0x00, 0x00, 0x01, 0x06,
- 0x05, 0xff, 0xff, 0x70, 0xdc, 0x45, 0xe9, 0xbd, 0xe6, 0xd9, 0x48, 0xb7, 0x96, 0x2c, 0xd8,
- 0x20, 0xd9, 0x23, 0xee, 0xef, 0x78, 0x32, 0x36, 0x34, 0x20, 0x2d, 0x20, 0x63, 0x6f, 0x72,
- 0x65, 0x20, 0x31, 0x34, 0x32, 0x20, 0x2d, 0x20, 0x48, 0x2e, 0x32, 0x36, 0x34, 0x2f, 0x4d,
- 0x50, 0x45, 0x47, 0x2d, 0x34, 0x20, 0x41, 0x56, 0x43, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x63,
- 0x20, 0x2d, 0x20, 0x43, 0x6f, 0x70, 0x79, 0x6c, 0x65, 0x66, 0x74, 0x20, 0x32, 0x30, 0x30,
- 0x33, 0x2d, 0x32, 0x30, 0x31, 0x34, 0x20, 0x2d, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f,
- 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6c, 0x61, 0x6e, 0x2e, 0x6f,
- 0x72, 0x67, 0x2f, 0x78, 0x32, 0x36, 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x20, 0x2d, 0x20,
- 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x20, 0x63, 0x61, 0x62, 0x61, 0x63, 0x3d,
- 0x30, 0x20, 0x72, 0x65, 0x66, 0x3d, 0x32, 0x20, 0x64, 0x65, 0x62, 0x6c, 0x6f, 0x63, 0x6b,
- 0x3d, 0x31, 0x3a, 0x30, 0x3a, 0x30, 0x20, 0x61, 0x6e, 0x61, 0x6c, 0x79, 0x73, 0x65, 0x3d,
- 0x30, 0x78, 0x31, 0x3a, 0x30, 0x78, 0x31, 0x31, 0x31, 0x20, 0x6d, 0x65, 0x3d, 0x68, 0x65,
- 0x78, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x65, 0x3d, 0x37, 0x20, 0x70, 0x73, 0x79, 0x3d, 0x31,
- 0x20, 0x70, 0x73, 0x79, 0x5f, 0x72, 0x64, 0x3d, 0x31, 0x2e, 0x30, 0x30, 0x3a, 0x30, 0x2e,
- 0x30, 0x30, 0x20, 0x6d, 0x69, 0x78, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x66, 0x3d, 0x31, 0x20,
- 0x6d, 0x65, 0x5f, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x3d, 0x31, 0x36, 0x20, 0x63, 0x68, 0x72,
- 0x6f, 0x6d, 0x61, 0x5f, 0x6d, 0x65, 0x3d, 0x31, 0x20, 0x74, 0x72, 0x65, 0x6c, 0x6c, 0x69,
- 0x73, 0x3d, 0x31, 0x20, 0x38, 0x78, 0x38, 0x64, 0x63, 0x74, 0x3d, 0x30, 0x20, 0x63, 0x71,
- 0x6d, 0x3d, 0x30, 0x20, 0x64, 0x65, 0x61, 0x64, 0x7a, 0x6f, 0x6e, 0x65, 0x3d, 0x32, 0x31,
- 0x2c, 0x31, 0x31, 0x20, 0x66, 0x61, 0x73, 0x74, 0x5f, 0x70, 0x73, 0x6b, 0x69, 0x70, 0x3d,
- 0x31, 0x20, 0x63, 0x68, 0x72, 0x6f, 0x6d, 0x61, 0x5f, 0x71, 0x70, 0x5f, 0x6f, 0x66, 0x66,
- 0x73, 0x65, 0x74, 0x3d, 0x2d, 0x32, 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d,
- 0x36, 0x30, 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x61, 0x68, 0x65, 0x61, 0x64, 0x5f, 0x74, 0x68,
- 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, 0x35, 0x20, 0x73, 0x6c, 0x69, 0x63, 0x65, 0x64, 0x5f,
- 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, 0x30, 0x20, 0x6e, 0x72, 0x3d, 0x30, 0x20,
- 0x64, 0x65, 0x63, 0x69, 0x6d, 0x61, 0x74, 0x65, 0x3d, 0x31, 0x20, 0x69, 0x6e, 0x74, 0x65,
- 0x72, 0x6c, 0x61, 0x63, 0x65, 0x64, 0x3d, 0x30, 0x20, 0x62, 0x6c, 0x75, 0x72, 0x61, 0x79,
- 0x5f, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x3d, 0x30, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74,
- 0x72, 0x61, 0x69, 0x6e, 0x65, 0x64, 0x5f, 0x69, 0x6e, 0x74, 0x72, 0x61, 0x3d, 0x30, 0x20,
- 0x62, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x3d, 0x30, 0x20, 0x77, 0x65, 0x69, 0x67, 0x68,
- 0x74, 0x70, 0x3d, 0x30, 0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, 0x74, 0x3d, 0x32, 0x35, 0x30,
- 0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x3d, 0x32, 0x35, 0x20,
- 0x73, 0x63, 0x65, 0x6e, 0x65,
-};
-
Demux::Demux(uint32_t demuxId, sp<Tuner> tuner) {
mDemuxId = demuxId;
mTunerService = tuner;
@@ -93,8 +54,8 @@
return startBroadcastInputLoop();
}
-Return<void> Demux::addFilter(DemuxFilterType type, uint32_t bufferSize,
- const sp<IDemuxCallback>& cb, addFilter_cb _hidl_cb) {
+Return<void> Demux::openFilter(const DemuxFilterType& type, uint32_t bufferSize,
+ const sp<IFilterCallback>& cb, openFilter_cb _hidl_cb) {
ALOGV("%s", __FUNCTION__);
uint32_t filterId;
@@ -105,137 +66,39 @@
mUnusedFilterIds.erase(filterId);
} else {
filterId = ++mLastUsedFilterId;
-
- mFilterCallbacks.resize(filterId + 1);
- mFilterMQs.resize(filterId + 1);
- mFilterEvents.resize(filterId + 1);
- mFilterEventFlags.resize(filterId + 1);
- mFilterThreadRunning.resize(filterId + 1);
- mFilterThreads.resize(filterId + 1);
- mFilterPids.resize(filterId + 1);
- mFilterOutputs.resize(filterId + 1);
- mFilterStatus.resize(filterId + 1);
}
mUsedFilterIds.insert(filterId);
- if ((type != DemuxFilterType::PCR || type != DemuxFilterType::TS) && cb == nullptr) {
+ if (cb == nullptr) {
ALOGW("callback can't be null");
- _hidl_cb(Result::INVALID_ARGUMENT, filterId);
+ _hidl_cb(Result::INVALID_ARGUMENT, new Filter());
return Void();
}
- // Add callback
- mFilterCallbacks[filterId] = cb;
+ sp<Filter> filter = new Filter(type, filterId, bufferSize, cb, this);
- // Mapping from the filter ID to the filter event
- DemuxFilterEvent event{
- .filterId = filterId,
- .filterType = type,
- };
- mFilterEvents[filterId] = event;
-
- if (!createFilterMQ(bufferSize, filterId)) {
- _hidl_cb(Result::UNKNOWN_ERROR, -1);
+ if (!filter->createFilterMQ()) {
+ _hidl_cb(Result::UNKNOWN_ERROR, filter);
return Void();
}
- _hidl_cb(Result::SUCCESS, filterId);
+ mFilters[filterId] = filter;
+
+ _hidl_cb(Result::SUCCESS, filter);
return Void();
}
-Return<void> Demux::getFilterQueueDesc(uint32_t filterId, getFilterQueueDesc_cb _hidl_cb) {
+Return<void> Demux::openTimeFilter(openTimeFilter_cb _hidl_cb) {
ALOGV("%s", __FUNCTION__);
- if (mUsedFilterIds.find(filterId) == mUsedFilterIds.end()) {
- ALOGW("No filter with id: %d exists to get desc", filterId);
- _hidl_cb(Result::INVALID_ARGUMENT, FilterMQ::Descriptor());
- return Void();
- }
+ sp<TimeFilter> timeFilter = new TimeFilter(this);
- _hidl_cb(Result::SUCCESS, *mFilterMQs[filterId]->getDesc());
+ _hidl_cb(Result::SUCCESS, timeFilter);
return Void();
}
-Return<Result> Demux::configureFilter(uint32_t filterId, const DemuxFilterSettings& settings) {
- ALOGV("%s", __FUNCTION__);
-
- switch (mFilterEvents[filterId].filterType) {
- case DemuxFilterType::SECTION:
- mFilterPids[filterId] = settings.section().tpid;
- break;
- case DemuxFilterType::PES:
- mFilterPids[filterId] = settings.pesData().tpid;
- break;
- case DemuxFilterType::TS:
- mFilterPids[filterId] = settings.ts().tpid;
- break;
- case DemuxFilterType::AUDIO:
- mFilterPids[filterId] = settings.audio().tpid;
- break;
- case DemuxFilterType::VIDEO:
- mFilterPids[filterId] = settings.video().tpid;
- break;
- case DemuxFilterType::RECORD:
- mFilterPids[filterId] = settings.record().tpid;
- break;
- case DemuxFilterType::PCR:
- mFilterPids[filterId] = settings.pcr().tpid;
- break;
- default:
- return Result::UNKNOWN_ERROR;
- }
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::startFilter(uint32_t filterId) {
- ALOGV("%s", __FUNCTION__);
- Result result;
-
- if (mUsedFilterIds.find(filterId) == mUsedFilterIds.end()) {
- ALOGW("No filter with id: %d exists to start filter", filterId);
- return Result::INVALID_ARGUMENT;
- }
-
- result = startFilterLoop(filterId);
-
- return result;
-}
-
-Return<Result> Demux::stopFilter(uint32_t filterId) {
- ALOGV("%s", __FUNCTION__);
-
- mFilterThreadRunning[filterId] = false;
-
- std::lock_guard<std::mutex> lock(mFilterThreadLock);
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::flushFilter(uint32_t filterId) {
- ALOGV("%s", __FUNCTION__);
-
- // temp implementation to flush the FMQ
- int size = mFilterMQs[filterId]->availableToRead();
- char* buffer = new char[size];
- mOutputMQ->read((unsigned char*)&buffer[0], size);
- delete[] buffer;
- mFilterStatus[filterId] = DemuxFilterStatus::DATA_READY;
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::removeFilter(uint32_t filterId) {
- ALOGV("%s", __FUNCTION__);
-
- // resetFilterRecords(filterId);
- mUsedFilterIds.erase(filterId);
- mUnusedFilterIds.insert(filterId);
-
- return Result::SUCCESS;
-}
-
-Return<void> Demux::getAvSyncHwId(uint32_t /* filterId */, getAvSyncHwId_cb _hidl_cb) {
+Return<void> Demux::getAvSyncHwId(const sp<IFilter>& /* filter */, getAvSyncHwId_cb _hidl_cb) {
ALOGV("%s", __FUNCTION__);
AvSyncHwId avSyncHwId = 0;
@@ -256,588 +119,81 @@
Return<Result> Demux::close() {
ALOGV("%s", __FUNCTION__);
- set<uint32_t>::iterator it;
- mInputThread = 0;
- mOutputThread = 0;
- mFilterThreads.clear();
mUnusedFilterIds.clear();
mUsedFilterIds.clear();
- mFilterCallbacks.clear();
- mFilterMQs.clear();
- mFilterEvents.clear();
- mFilterEventFlags.clear();
- mFilterOutputs.clear();
- mFilterPids.clear();
mLastUsedFilterId = -1;
return Result::SUCCESS;
}
-Return<Result> Demux::addOutput(uint32_t bufferSize, const sp<IDemuxCallback>& cb) {
+Return<void> Demux::openDvr(DvrType type, uint32_t bufferSize, const sp<IDvrCallback>& cb,
+ openDvr_cb _hidl_cb) {
ALOGV("%s", __FUNCTION__);
- // Create a synchronized FMQ that supports blocking read/write
- std::unique_ptr<FilterMQ> tmpFilterMQ =
- std::unique_ptr<FilterMQ>(new (std::nothrow) FilterMQ(bufferSize, true));
- if (!tmpFilterMQ->isValid()) {
- ALOGW("Failed to create output FMQ");
- return Result::UNKNOWN_ERROR;
- }
-
- mOutputMQ = std::move(tmpFilterMQ);
-
- if (EventFlag::createEventFlag(mOutputMQ->getEventFlagWord(), &mOutputEventFlag) != OK) {
- return Result::UNKNOWN_ERROR;
- }
-
- mOutputCallback = cb;
-
- return Result::SUCCESS;
-}
-
-Return<void> Demux::getOutputQueueDesc(getOutputQueueDesc_cb _hidl_cb) {
- ALOGV("%s", __FUNCTION__);
-
- if (!mOutputMQ) {
- _hidl_cb(Result::NOT_INITIALIZED, FilterMQ::Descriptor());
+ if (cb == nullptr) {
+ ALOGW("DVR callback can't be null");
+ _hidl_cb(Result::INVALID_ARGUMENT, new Dvr());
return Void();
}
- _hidl_cb(Result::SUCCESS, *mOutputMQ->getDesc());
- return Void();
-}
+ sp<Dvr> dvr = new Dvr(type, bufferSize, cb, this);
-Return<Result> Demux::configureOutput(const DemuxOutputSettings& settings) {
- ALOGV("%s", __FUNCTION__);
-
- mOutputConfigured = true;
- mOutputSettings = settings;
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::attachOutputFilter(uint32_t /*filterId*/) {
- ALOGV("%s", __FUNCTION__);
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::detachOutputFilter(uint32_t /* filterId */) {
- ALOGV("%s", __FUNCTION__);
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::startOutput() {
- ALOGV("%s", __FUNCTION__);
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::stopOutput() {
- ALOGV("%s", __FUNCTION__);
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::flushOutput() {
- ALOGV("%s", __FUNCTION__);
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::removeOutput() {
- ALOGV("%s", __FUNCTION__);
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::addInput(uint32_t bufferSize, const sp<IDemuxCallback>& cb) {
- ALOGV("%s", __FUNCTION__);
-
- // Create a synchronized FMQ that supports blocking read/write
- std::unique_ptr<FilterMQ> tmpInputMQ =
- std::unique_ptr<FilterMQ>(new (std::nothrow) FilterMQ(bufferSize, true));
- if (!tmpInputMQ->isValid()) {
- ALOGW("Failed to create input FMQ");
- return Result::UNKNOWN_ERROR;
- }
-
- mInputMQ = std::move(tmpInputMQ);
-
- if (EventFlag::createEventFlag(mInputMQ->getEventFlagWord(), &mInputEventFlag) != OK) {
- return Result::UNKNOWN_ERROR;
- }
-
- mInputCallback = cb;
-
- return Result::SUCCESS;
-}
-
-Return<void> Demux::getInputQueueDesc(getInputQueueDesc_cb _hidl_cb) {
- ALOGV("%s", __FUNCTION__);
-
- if (!mInputMQ) {
- _hidl_cb(Result::NOT_INITIALIZED, FilterMQ::Descriptor());
+ if (!dvr->createDvrMQ()) {
+ _hidl_cb(Result::UNKNOWN_ERROR, dvr);
return Void();
}
- _hidl_cb(Result::SUCCESS, *mInputMQ->getDesc());
+ _hidl_cb(Result::SUCCESS, dvr);
return Void();
}
-Return<Result> Demux::configureInput(const DemuxInputSettings& settings) {
+Result Demux::removeFilter(uint32_t filterId) {
ALOGV("%s", __FUNCTION__);
- mInputConfigured = true;
- mInputSettings = settings;
+ // resetFilterRecords(filterId);
+ mUsedFilterIds.erase(filterId);
+ mUnusedFilterIds.insert(filterId);
+ mFilters.erase(filterId);
return Result::SUCCESS;
}
-Return<Result> Demux::startInput() {
- ALOGV("%s", __FUNCTION__);
-
- if (!mInputCallback) {
- return Result::NOT_INITIALIZED;
- }
-
- if (!mInputConfigured) {
- return Result::INVALID_STATE;
- }
-
- pthread_create(&mInputThread, NULL, __threadLoopInput, this);
- pthread_setname_np(mInputThread, "demux_input_waiting_loop");
-
- // TODO start another thread to send filter status callback to the framework
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::stopInput() {
- ALOGV("%s", __FUNCTION__);
-
- mInputThreadRunning = false;
-
- std::lock_guard<std::mutex> lock(mInputThreadLock);
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::flushInput() {
- ALOGV("%s", __FUNCTION__);
-
- return Result::SUCCESS;
-}
-
-Return<Result> Demux::removeInput() {
- ALOGV("%s", __FUNCTION__);
-
- mInputMQ = nullptr;
-
- return Result::SUCCESS;
-}
-
-Result Demux::startFilterLoop(uint32_t filterId) {
- struct ThreadArgs* threadArgs = (struct ThreadArgs*)malloc(sizeof(struct ThreadArgs));
- threadArgs->user = this;
- threadArgs->filterId = filterId;
-
- pthread_t mFilterThread;
- pthread_create(&mFilterThread, NULL, __threadLoopFilter, (void*)threadArgs);
- mFilterThreads[filterId] = mFilterThread;
- pthread_setname_np(mFilterThread, "demux_filter_waiting_loop");
-
- return Result::SUCCESS;
-}
-
-Result Demux::startSectionFilterHandler(uint32_t filterId) {
- if (mFilterOutputs[filterId].empty()) {
- return Result::SUCCESS;
- }
- if (!writeSectionsAndCreateEvent(filterId, mFilterOutputs[filterId])) {
- ALOGD("[Demux] filter %d fails to write into FMQ. Ending thread", filterId);
- return Result::UNKNOWN_ERROR;
- }
-
- mFilterOutputs[filterId].clear();
-
- return Result::SUCCESS;
-}
-
-Result Demux::startPesFilterHandler(uint32_t filterId) {
- std::lock_guard<std::mutex> lock(mFilterEventLock);
- if (mFilterOutputs[filterId].empty()) {
- return Result::SUCCESS;
- }
-
- for (int i = 0; i < mFilterOutputs[filterId].size(); i += 188) {
- if (mPesSizeLeft == 0) {
- uint32_t prefix = (mFilterOutputs[filterId][i + 4] << 16) |
- (mFilterOutputs[filterId][i + 5] << 8) |
- mFilterOutputs[filterId][i + 6];
- ALOGD("[Demux] prefix %d", prefix);
- if (prefix == 0x000001) {
- // TODO handle mulptiple Pes filters
- mPesSizeLeft =
- (mFilterOutputs[filterId][i + 8] << 8) | mFilterOutputs[filterId][i + 9];
- mPesSizeLeft += 6;
- ALOGD("[Demux] pes data length %d", mPesSizeLeft);
- } else {
- continue;
- }
- }
-
- int endPoint = min(184, mPesSizeLeft);
- // append data and check size
- vector<uint8_t>::const_iterator first = mFilterOutputs[filterId].begin() + i + 4;
- vector<uint8_t>::const_iterator last = mFilterOutputs[filterId].begin() + i + 4 + endPoint;
- mPesOutput.insert(mPesOutput.end(), first, last);
- // size does not match then continue
- mPesSizeLeft -= endPoint;
- if (mPesSizeLeft > 0) {
- continue;
- }
- // size match then create event
- if (!writeDataToFilterMQ(mPesOutput, filterId)) {
- mFilterOutputs[filterId].clear();
- return Result::INVALID_STATE;
- }
- maySendFilterStatusCallback(filterId);
- DemuxFilterPesEvent pesEvent;
- pesEvent = {
- // temp dump meta data
- .streamId = mPesOutput[3],
- .dataLength = static_cast<uint16_t>(mPesOutput.size()),
- };
- ALOGD("[Demux] assembled pes data length %d", pesEvent.dataLength);
-
- int size = mFilterEvents[filterId].events.size();
- mFilterEvents[filterId].events.resize(size + 1);
- mFilterEvents[filterId].events[size].pes(pesEvent);
- mPesOutput.clear();
- }
-
- mFilterOutputs[filterId].clear();
-
- return Result::SUCCESS;
-}
-
-Result Demux::startTsFilterHandler() {
- // TODO handle starting TS filter
- return Result::SUCCESS;
-}
-
-Result Demux::startMediaFilterHandler(uint32_t filterId) {
- DemuxFilterMediaEvent mediaEvent;
- mediaEvent = {
- // temp dump meta data
- .pts = 0,
- .dataLength = 530,
- .secureMemory = nullptr,
- };
- mFilterEvents[filterId].events.resize(1);
- mFilterEvents[filterId].events[0].media() = mediaEvent;
-
- mFilterOutputs[filterId].clear();
- // TODO handle write FQM for media stream
- return Result::SUCCESS;
-}
-
-Result Demux::startRecordFilterHandler(uint32_t filterId) {
- DemuxFilterRecordEvent recordEvent;
- recordEvent = {
- // temp dump meta data
- .tpid = 0,
- .packetNum = 0,
- };
- recordEvent.indexMask.tsIndexMask() = 0x01;
- mFilterEvents[filterId].events.resize(1);
- mFilterEvents[filterId].events[0].ts() = recordEvent;
-
- mFilterOutputs[filterId].clear();
- return Result::SUCCESS;
-}
-
-Result Demux::startPcrFilterHandler() {
- // TODO handle starting PCR filter
- return Result::SUCCESS;
-}
-
-bool Demux::createFilterMQ(uint32_t bufferSize, uint32_t filterId) {
- ALOGV("%s", __FUNCTION__);
-
- // Create a synchronized FMQ that supports blocking read/write
- std::unique_ptr<FilterMQ> tmpFilterMQ =
- std::unique_ptr<FilterMQ>(new (std::nothrow) FilterMQ(bufferSize, true));
- if (!tmpFilterMQ->isValid()) {
- ALOGW("Failed to create FMQ of filter with id: %d", filterId);
- return false;
- }
-
- mFilterMQs[filterId] = std::move(tmpFilterMQ);
-
- EventFlag* filterEventFlag;
- if (EventFlag::createEventFlag(mFilterMQs[filterId]->getEventFlagWord(), &filterEventFlag) !=
- OK) {
- return false;
- }
- mFilterEventFlags[filterId] = filterEventFlag;
-
- return true;
-}
-
-bool Demux::writeSectionsAndCreateEvent(uint32_t filterId, vector<uint8_t> data) {
- // TODO check how many sections has been read
- std::lock_guard<std::mutex> lock(mFilterEventLock);
- if (!writeDataToFilterMQ(data, filterId)) {
- return false;
- }
- int size = mFilterEvents[filterId].events.size();
- mFilterEvents[filterId].events.resize(size + 1);
- DemuxFilterSectionEvent secEvent;
- secEvent = {
- // temp dump meta data
- .tableId = 0,
- .version = 1,
- .sectionNum = 1,
- .dataLength = static_cast<uint16_t>(data.size()),
- };
- mFilterEvents[filterId].events[size].section(secEvent);
- return true;
-}
-
-bool Demux::writeDataToFilterMQ(const std::vector<uint8_t>& data, uint32_t filterId) {
- std::lock_guard<std::mutex> lock(mWriteLock);
- if (mFilterMQs[filterId]->write(data.data(), data.size())) {
- return true;
- }
- return false;
-}
-
-bool Demux::readInputFMQ() {
- // Read input data from the input FMQ
- int size = mInputMQ->availableToRead();
- int inputPacketSize = mInputSettings.packetSize;
- vector<uint8_t> dataOutputBuffer;
- dataOutputBuffer.resize(inputPacketSize);
-
- // Dispatch the packet to the PID matching filter output buffer
- for (int i = 0; i < size / inputPacketSize; i++) {
- if (!mInputMQ->read(dataOutputBuffer.data(), inputPacketSize)) {
- return false;
- }
- startTsFilter(dataOutputBuffer);
- }
-
- return true;
-}
-
void Demux::startTsFilter(vector<uint8_t> data) {
set<uint32_t>::iterator it;
for (it = mUsedFilterIds.begin(); it != mUsedFilterIds.end(); it++) {
uint16_t pid = ((data[1] & 0x1f) << 8) | ((data[2] & 0xff));
- ALOGW("start ts filter pid: %d", pid);
- if (pid == mFilterPids[*it]) {
- mFilterOutputs[*it].insert(mFilterOutputs[*it].end(), data.begin(), data.end());
+ if (DEBUG_FILTER) {
+ ALOGW("start ts filter pid: %d", pid);
+ }
+ if (pid == mFilters[*it]->getTpid()) {
+ mFilters[*it]->updateFilterOutput(data);
}
}
}
bool Demux::startFilterDispatcher() {
- Result result;
set<uint32_t>::iterator it;
// Handle the output data per filter type
for (it = mUsedFilterIds.begin(); it != mUsedFilterIds.end(); it++) {
- switch (mFilterEvents[*it].filterType) {
- case DemuxFilterType::SECTION:
- result = startSectionFilterHandler(*it);
- break;
- case DemuxFilterType::PES:
- result = startPesFilterHandler(*it);
- break;
- case DemuxFilterType::TS:
- result = startTsFilterHandler();
- break;
- case DemuxFilterType::AUDIO:
- case DemuxFilterType::VIDEO:
- result = startMediaFilterHandler(*it);
- break;
- case DemuxFilterType::RECORD:
- result = startRecordFilterHandler(*it);
- break;
- case DemuxFilterType::PCR:
- result = startPcrFilterHandler();
- break;
- default:
- return false;
+ if (mFilters[*it]->startFilterHandler() != Result::SUCCESS) {
+ return false;
}
}
- return result == Result::SUCCESS;
+ return true;
}
-void* Demux::__threadLoopFilter(void* threadArg) {
- Demux* const self = static_cast<Demux*>(((struct ThreadArgs*)threadArg)->user);
- self->filterThreadLoop(((struct ThreadArgs*)threadArg)->filterId);
- return 0;
+Result Demux::startFilterHandler(uint32_t filterId) {
+ return mFilters[filterId]->startFilterHandler();
}
-void* Demux::__threadLoopInput(void* user) {
- Demux* const self = static_cast<Demux*>(user);
- self->inputThreadLoop();
- return 0;
+void Demux::updateFilterOutput(uint16_t filterId, vector<uint8_t> data) {
+ mFilters[filterId]->updateFilterOutput(data);
}
-void Demux::filterThreadLoop(uint32_t filterId) {
- ALOGD("[Demux] filter %d threadLoop start.", filterId);
- std::lock_guard<std::mutex> lock(mFilterThreadLock);
- mFilterThreadRunning[filterId] = true;
-
- // For the first time of filter output, implementation needs to send the filter
- // Event Callback without waiting for the DATA_CONSUMED to init the process.
- while (mFilterThreadRunning[filterId]) {
- if (mFilterEvents[filterId].events.size() == 0) {
- ALOGD("[Demux] wait for filter data output.");
- usleep(1000 * 1000);
- continue;
- }
- // After successfully write, send a callback and wait for the read to be done
- mFilterCallbacks[filterId]->onFilterEvent(mFilterEvents[filterId]);
- mFilterEvents[filterId].events.resize(0);
- mFilterStatus[filterId] = DemuxFilterStatus::DATA_READY;
- mFilterCallbacks[filterId]->onFilterStatus(filterId, mFilterStatus[filterId]);
- break;
- }
-
- while (mFilterThreadRunning[filterId]) {
- uint32_t efState = 0;
- // We do not wait for the last round of writen data to be read to finish the thread
- // because the VTS can verify the reading itself.
- for (int i = 0; i < SECTION_WRITE_COUNT; i++) {
- while (mFilterThreadRunning[filterId]) {
- status_t status = mFilterEventFlags[filterId]->wait(
- static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_CONSUMED), &efState,
- WAIT_TIMEOUT, true /* retry on spurious wake */);
- if (status != OK) {
- ALOGD("[Demux] wait for data consumed");
- continue;
- }
- break;
- }
-
- if (mFilterCallbacks[filterId] == nullptr) {
- ALOGD("[Demux] filter %d does not hava callback. Ending thread", filterId);
- break;
- }
-
- maySendFilterStatusCallback(filterId);
-
- while (mFilterThreadRunning[filterId]) {
- std::lock_guard<std::mutex> lock(mFilterEventLock);
- if (mFilterEvents[filterId].events.size() == 0) {
- continue;
- }
- // After successfully write, send a callback and wait for the read to be done
- mFilterCallbacks[filterId]->onFilterEvent(mFilterEvents[filterId]);
- mFilterEvents[filterId].events.resize(0);
- break;
- }
- // We do not wait for the last read to be done
- // VTS can verify the read result itself.
- if (i == SECTION_WRITE_COUNT - 1) {
- ALOGD("[Demux] filter %d writing done. Ending thread", filterId);
- break;
- }
- }
- mFilterThreadRunning[filterId] = false;
- }
-
- ALOGD("[Demux] filter thread ended.");
-}
-
-void Demux::inputThreadLoop() {
- ALOGD("[Demux] input threadLoop start.");
- std::lock_guard<std::mutex> lock(mInputThreadLock);
- mInputThreadRunning = true;
-
- while (mInputThreadRunning) {
- uint32_t efState = 0;
- status_t status =
- mInputEventFlag->wait(static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_READY),
- &efState, WAIT_TIMEOUT, true /* retry on spurious wake */);
- if (status != OK) {
- ALOGD("[Demux] wait for data ready on the input FMQ");
- continue;
- }
- // Our current implementation filter the data and write it into the filter FMQ immediately
- // after the DATA_READY from the VTS/framework
- if (!readInputFMQ() || !startFilterDispatcher()) {
- ALOGD("[Demux] input data failed to be filtered. Ending thread");
- break;
- }
-
- maySendInputStatusCallback();
- }
-
- mInputThreadRunning = false;
- ALOGD("[Demux] input thread ended.");
-}
-
-void Demux::maySendInputStatusCallback() {
- std::lock_guard<std::mutex> lock(mInputStatusLock);
- int availableToRead = mInputMQ->availableToRead();
- int availableToWrite = mInputMQ->availableToWrite();
-
- DemuxInputStatus newStatus =
- checkInputStatusChange(availableToWrite, availableToRead, mInputSettings.highThreshold,
- mInputSettings.lowThreshold);
- if (mIntputStatus != newStatus) {
- mInputCallback->onInputStatus(newStatus);
- mIntputStatus = newStatus;
- }
-}
-
-void Demux::maySendFilterStatusCallback(uint32_t filterId) {
- std::lock_guard<std::mutex> lock(mFilterStatusLock);
- int availableToRead = mFilterMQs[filterId]->availableToRead();
- int availableToWrite = mFilterMQs[filterId]->availableToWrite();
- int fmqSize = mFilterMQs[filterId]->getQuantumCount();
-
- DemuxFilterStatus newStatus =
- checkFilterStatusChange(filterId, availableToWrite, availableToRead,
- ceil(fmqSize * 0.75), ceil(fmqSize * 0.25));
- if (mFilterStatus[filterId] != newStatus) {
- mFilterCallbacks[filterId]->onFilterStatus(filterId, newStatus);
- mFilterStatus[filterId] = newStatus;
- }
-}
-
-DemuxInputStatus Demux::checkInputStatusChange(uint32_t availableToWrite, uint32_t availableToRead,
- uint32_t highThreshold, uint32_t lowThreshold) {
- if (availableToWrite == 0) {
- return DemuxInputStatus::SPACE_FULL;
- } else if (availableToRead > highThreshold) {
- return DemuxInputStatus::SPACE_ALMOST_FULL;
- } else if (availableToRead < lowThreshold) {
- return DemuxInputStatus::SPACE_ALMOST_EMPTY;
- } else if (availableToRead == 0) {
- return DemuxInputStatus::SPACE_EMPTY;
- }
- return mIntputStatus;
-}
-
-DemuxFilterStatus Demux::checkFilterStatusChange(uint32_t filterId, uint32_t availableToWrite,
- uint32_t availableToRead, uint32_t highThreshold,
- uint32_t lowThreshold) {
- if (availableToWrite == 0) {
- return DemuxFilterStatus::OVERFLOW;
- } else if (availableToRead > highThreshold) {
- return DemuxFilterStatus::HIGH_WATER;
- } else if (availableToRead < lowThreshold) {
- return DemuxFilterStatus::LOW_WATER;
- }
- return mFilterStatus[filterId];
+uint16_t Demux::getFilterTpid(uint32_t filterId) {
+ return mFilters[filterId]->getTpid();
}
Result Demux::startBroadcastInputLoop() {
@@ -876,6 +232,7 @@
for (int i = 0; i < writePacketAmount; i++) {
inputData.read(buffer, packetSize);
if (!inputData) {
+ mKeepFetchingDataFromFrontend = false;
mBroadcastInputThreadRunning = false;
break;
}
@@ -888,7 +245,7 @@
startTsFilter(byteBuffer);
}
startFilterDispatcher();
- sleep(1);
+ usleep(100);
}
}
@@ -898,6 +255,7 @@
}
void Demux::stopBroadcastInput() {
+ ALOGD("[Demux] stop frontend on demux");
mKeepFetchingDataFromFrontend = false;
mBroadcastInputThreadRunning = false;
std::lock_guard<std::mutex> lock(mBroadcastInputThreadLock);
diff --git a/tv/tuner/1.0/default/Demux.h b/tv/tuner/1.0/default/Demux.h
index ba0b9b0..a9756cc 100644
--- a/tv/tuner/1.0/default/Demux.h
+++ b/tv/tuner/1.0/default/Demux.h
@@ -21,7 +21,10 @@
#include <fmq/MessageQueue.h>
#include <math.h>
#include <set>
+#include "Dvr.h"
+#include "Filter.h"
#include "Frontend.h"
+#include "TimeFilter.h"
#include "Tuner.h"
using namespace std;
@@ -38,13 +41,17 @@
using ::android::hardware::MessageQueue;
using ::android::hardware::MQDescriptorSync;
using ::android::hardware::tv::tuner::V1_0::IDemux;
-using ::android::hardware::tv::tuner::V1_0::IDemuxCallback;
+using ::android::hardware::tv::tuner::V1_0::IDvrCallback;
+using ::android::hardware::tv::tuner::V1_0::IFilterCallback;
using ::android::hardware::tv::tuner::V1_0::Result;
using FilterMQ = MessageQueue<uint8_t, kSynchronizedReadWrite>;
-class Tuner;
+class Dvr;
+class Filter;
class Frontend;
+class TimeFilter;
+class Tuner;
class Demux : public IDemux {
public:
@@ -54,63 +61,27 @@
virtual Return<Result> setFrontendDataSource(uint32_t frontendId) override;
- virtual Return<Result> close() override;
+ virtual Return<void> openFilter(const DemuxFilterType& type, uint32_t bufferSize,
+ const sp<IFilterCallback>& cb, openFilter_cb _hidl_cb) override;
- virtual Return<void> addFilter(DemuxFilterType type, uint32_t bufferSize,
- const sp<IDemuxCallback>& cb, addFilter_cb _hidl_cb) override;
+ virtual Return<void> openTimeFilter(openTimeFilter_cb _hidl_cb) override;
- virtual Return<void> getFilterQueueDesc(uint32_t filterId,
- getFilterQueueDesc_cb _hidl_cb) override;
-
- virtual Return<Result> configureFilter(uint32_t filterId,
- const DemuxFilterSettings& settings) override;
-
- virtual Return<Result> startFilter(uint32_t filterId) override;
-
- virtual Return<Result> stopFilter(uint32_t filterId) override;
-
- virtual Return<Result> flushFilter(uint32_t filterId) override;
-
- virtual Return<Result> removeFilter(uint32_t filterId) override;
-
- virtual Return<void> getAvSyncHwId(uint32_t filterId, getAvSyncHwId_cb _hidl_cb) override;
+ virtual Return<void> getAvSyncHwId(const sp<IFilter>& filter,
+ getAvSyncHwId_cb _hidl_cb) override;
virtual Return<void> getAvSyncTime(AvSyncHwId avSyncHwId, getAvSyncTime_cb _hidl_cb) override;
- virtual Return<Result> addInput(uint32_t bufferSize, const sp<IDemuxCallback>& cb) override;
+ virtual Return<Result> close() override;
- virtual Return<void> getInputQueueDesc(getInputQueueDesc_cb _hidl_cb) override;
-
- virtual Return<Result> configureInput(const DemuxInputSettings& settings) override;
-
- virtual Return<Result> startInput() override;
-
- virtual Return<Result> stopInput() override;
-
- virtual Return<Result> flushInput() override;
-
- virtual Return<Result> removeInput() override;
-
- virtual Return<Result> addOutput(uint32_t bufferSize, const sp<IDemuxCallback>& cb) override;
-
- virtual Return<void> getOutputQueueDesc(getOutputQueueDesc_cb _hidl_cb) override;
-
- virtual Return<Result> configureOutput(const DemuxOutputSettings& settings) override;
-
- virtual Return<Result> attachOutputFilter(uint32_t filterId) override;
-
- virtual Return<Result> detachOutputFilter(uint32_t filterId) override;
-
- virtual Return<Result> startOutput() override;
-
- virtual Return<Result> stopOutput() override;
-
- virtual Return<Result> flushOutput() override;
-
- virtual Return<Result> removeOutput() override;
+ virtual Return<void> openDvr(DvrType type, uint32_t bufferSize, const sp<IDvrCallback>& cb,
+ openDvr_cb _hidl_cb) override;
// Functions interacts with Tuner Service
void stopBroadcastInput();
+ Result removeFilter(uint32_t filterId);
+ Result startFilterHandler(uint32_t filterId);
+ void updateFilterOutput(uint16_t filterId, vector<uint8_t> data);
+ uint16_t getFilterTpid(uint32_t filterId);
private:
// Tuner service
@@ -126,19 +97,9 @@
uint32_t filterId;
};
- /**
- * Filter handlers to handle the data filtering.
- * They are also responsible to write the filtered output into the filter FMQ
- * and update the filterEvent bound with the same filterId.
- */
- Result startSectionFilterHandler(uint32_t filterId);
- Result startPesFilterHandler(uint32_t filterId);
- Result startTsFilterHandler();
- Result startMediaFilterHandler(uint32_t filterId);
- Result startRecordFilterHandler(uint32_t filterId);
- Result startPcrFilterHandler();
- Result startFilterLoop(uint32_t filterId);
Result startBroadcastInputLoop();
+ static void* __threadLoopBroadcast(void* user);
+ void broadcastInputThreadLoop();
/**
* To create a FilterMQ with the the next available Filter ID.
@@ -147,32 +108,14 @@
*
* Return false is any of the above processes fails.
*/
- bool createFilterMQ(uint32_t bufferSize, uint32_t filterId);
- bool createMQ(FilterMQ* queue, EventFlag* eventFlag, uint32_t bufferSize);
void deleteEventFlag();
- bool writeDataToFilterMQ(const std::vector<uint8_t>& data, uint32_t filterId);
bool readDataFromMQ();
- bool writeSectionsAndCreateEvent(uint32_t filterId, vector<uint8_t> data);
- void maySendInputStatusCallback();
- void maySendFilterStatusCallback(uint32_t filterId);
- DemuxInputStatus checkInputStatusChange(uint32_t availableToWrite, uint32_t availableToRead,
- uint32_t highThreshold, uint32_t lowThreshold);
- DemuxFilterStatus checkFilterStatusChange(uint32_t filterId, uint32_t availableToWrite,
- uint32_t availableToRead, uint32_t highThreshold,
- uint32_t lowThreshold);
/**
* A dispatcher to read and dispatch input data to all the started filters.
* Each filter handler handles the data filtering/output writing/filterEvent updating.
*/
- bool readInputFMQ();
- void startTsFilter(vector<uint8_t> data);
bool startFilterDispatcher();
- static void* __threadLoopFilter(void* data);
- static void* __threadLoopInput(void* user);
- static void* __threadLoopBroadcast(void* user);
- void filterThreadLoop(uint32_t filterId);
- void inputThreadLoop();
- void broadcastInputThreadLoop();
+ void startTsFilter(vector<uint8_t> data);
uint32_t mDemuxId;
/**
@@ -196,40 +139,13 @@
* A list of created FilterMQ ptrs.
* The array number is the filter ID.
*/
- vector<uint16_t> mFilterPids;
- vector<vector<uint8_t>> mFilterOutputs;
- vector<unique_ptr<FilterMQ>> mFilterMQs;
- vector<EventFlag*> mFilterEventFlags;
- vector<DemuxFilterEvent> mFilterEvents;
- unique_ptr<FilterMQ> mInputMQ;
- unique_ptr<FilterMQ> mOutputMQ;
- EventFlag* mInputEventFlag;
- EventFlag* mOutputEventFlag;
- /**
- * Demux callbacks used on filter events or IO buffer status
- */
- vector<sp<IDemuxCallback>> mFilterCallbacks;
- sp<IDemuxCallback> mInputCallback;
- sp<IDemuxCallback> mOutputCallback;
- bool mInputConfigured = false;
- bool mOutputConfigured = false;
- DemuxInputSettings mInputSettings;
- DemuxOutputSettings mOutputSettings;
+ std::map<uint32_t, sp<Filter>> mFilters;
// Thread handlers
- pthread_t mInputThread;
- pthread_t mOutputThread;
pthread_t mBroadcastInputThread;
- vector<pthread_t> mFilterThreads;
-
- // FMQ status local records
- DemuxInputStatus mIntputStatus;
- vector<DemuxFilterStatus> mFilterStatus;
/**
* If a specific filter's writing loop is still running
*/
- vector<bool> mFilterThreadRunning;
- bool mInputThreadRunning;
bool mBroadcastInputThreadRunning;
bool mKeepFetchingDataFromFrontend;
/**
@@ -237,28 +153,16 @@
*/
std::mutex mWriteLock;
/**
- * Lock to protect writes to the filter event
- */
- // TODO make each filter separate event lock
- std::mutex mFilterEventLock;
- /**
* Lock to protect writes to the input status
*/
- std::mutex mInputStatusLock;
- std::mutex mFilterStatusLock;
std::mutex mBroadcastInputThreadLock;
- std::mutex mFilterThreadLock;
- std::mutex mInputThreadLock;
- /**
- * How many times a filter should write
- * TODO make this dynamic/random/can take as a parameter
- */
- const uint16_t SECTION_WRITE_COUNT = 10;
// temp handle single PES filter
// TODO handle mulptiple Pes filters
int mPesSizeLeft = 0;
vector<uint8_t> mPesOutput;
+
+ const bool DEBUG_FILTER = false;
};
} // namespace implementation
diff --git a/tv/tuner/1.0/default/Descrambler.cpp b/tv/tuner/1.0/default/Descrambler.cpp
index 085f2c8..e3f5b22 100644
--- a/tv/tuner/1.0/default/Descrambler.cpp
+++ b/tv/tuner/1.0/default/Descrambler.cpp
@@ -50,13 +50,15 @@
return Result::SUCCESS;
}
-Return<Result> Descrambler::addPid(uint16_t /* pid */) {
+Return<Result> Descrambler::addPid(const DemuxPid& /* pid */,
+ const sp<IFilter>& /* optionalSourceFilter */) {
ALOGV("%s", __FUNCTION__);
return Result::SUCCESS;
}
-Return<Result> Descrambler::removePid(uint16_t /* pid */) {
+Return<Result> Descrambler::removePid(const DemuxPid& /* pid */,
+ const sp<IFilter>& /* optionalSourceFilter */) {
ALOGV("%s", __FUNCTION__);
return Result::SUCCESS;
diff --git a/tv/tuner/1.0/default/Descrambler.h b/tv/tuner/1.0/default/Descrambler.h
index 436adcf..c889820 100644
--- a/tv/tuner/1.0/default/Descrambler.h
+++ b/tv/tuner/1.0/default/Descrambler.h
@@ -40,9 +40,11 @@
virtual Return<Result> setKeyToken(const hidl_vec<uint8_t>& keyToken) override;
- virtual Return<Result> addPid(uint16_t pid) override;
+ virtual Return<Result> addPid(const DemuxPid& pid,
+ const sp<IFilter>& optionalSourceFilter) override;
- virtual Return<Result> removePid(uint16_t pid) override;
+ virtual Return<Result> removePid(const DemuxPid& pid,
+ const sp<IFilter>& optionalSourceFilter) override;
virtual Return<Result> close() override;
diff --git a/tv/tuner/1.0/default/Dvr.cpp b/tv/tuner/1.0/default/Dvr.cpp
new file mode 100644
index 0000000..eb38f90
--- /dev/null
+++ b/tv/tuner/1.0/default/Dvr.cpp
@@ -0,0 +1,280 @@
+/*
+ * Copyright (C) 2019 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 "android.hardware.tv.tuner@1.0-Dvr"
+
+#include "Dvr.h"
+#include <utils/Log.h>
+
+namespace android {
+namespace hardware {
+namespace tv {
+namespace tuner {
+namespace V1_0 {
+namespace implementation {
+
+#define WAIT_TIMEOUT 3000000000
+
+Dvr::Dvr() {}
+
+Dvr::Dvr(DvrType type, uint32_t bufferSize, const sp<IDvrCallback>& cb, sp<Demux> demux) {
+ mType = type;
+ mBufferSize = bufferSize;
+ mCallback = cb;
+ mDemux = demux;
+}
+
+Dvr::~Dvr() {}
+
+Return<void> Dvr::getQueueDesc(getQueueDesc_cb _hidl_cb) {
+ ALOGV("%s", __FUNCTION__);
+
+ _hidl_cb(Result::SUCCESS, *mDvrMQ->getDesc());
+ return Void();
+}
+
+Return<Result> Dvr::configure(const DvrSettings& settings) {
+ ALOGV("%s", __FUNCTION__);
+
+ mDvrSettings = settings;
+ mDvrConfigured = true;
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Dvr::attachFilter(const sp<IFilter>& filter) {
+ ALOGV("%s", __FUNCTION__);
+
+ uint32_t filterId;
+ Result status;
+
+ filter->getId([&](Result result, uint32_t id) {
+ filterId = id;
+ status = result;
+ });
+
+ if (status != Result::SUCCESS) {
+ return status;
+ }
+
+ mFilters[filterId] = filter;
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Dvr::detachFilter(const sp<IFilter>& filter) {
+ ALOGV("%s", __FUNCTION__);
+
+ uint32_t filterId;
+ Result status;
+
+ filter->getId([&](Result result, uint32_t id) {
+ filterId = id;
+ status = result;
+ });
+
+ if (status != Result::SUCCESS) {
+ return status;
+ }
+
+ std::map<uint32_t, sp<IFilter>>::iterator it;
+
+ it = mFilters.find(filterId);
+ if (it != mFilters.end()) {
+ mFilters.erase(filterId);
+ }
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Dvr::start() {
+ ALOGV("%s", __FUNCTION__);
+
+ if (!mCallback) {
+ return Result::NOT_INITIALIZED;
+ }
+
+ if (!mDvrConfigured) {
+ return Result::INVALID_STATE;
+ }
+
+ if (mType == DvrType::PLAYBACK) {
+ pthread_create(&mDvrThread, NULL, __threadLoopPlayback, this);
+ pthread_setname_np(mDvrThread, "playback_waiting_loop");
+ } else if (mType == DvrType::RECORD) {
+ /*pthread_create(&mInputThread, NULL, __threadLoopInput, this);
+ pthread_setname_np(mInputThread, "playback_waiting_loop");*/
+ }
+
+ // TODO start another thread to send filter status callback to the framework
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Dvr::stop() {
+ ALOGV("%s", __FUNCTION__);
+
+ mDvrThreadRunning = false;
+
+ std::lock_guard<std::mutex> lock(mDvrThreadLock);
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Dvr::flush() {
+ ALOGV("%s", __FUNCTION__);
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Dvr::close() {
+ ALOGV("%s", __FUNCTION__);
+
+ return Result::SUCCESS;
+}
+
+bool Dvr::createDvrMQ() {
+ ALOGV("%s", __FUNCTION__);
+
+ // Create a synchronized FMQ that supports blocking read/write
+ std::unique_ptr<DvrMQ> tmpDvrMQ =
+ std::unique_ptr<DvrMQ>(new (std::nothrow) DvrMQ(mBufferSize, true));
+ if (!tmpDvrMQ->isValid()) {
+ ALOGW("Failed to create FMQ of DVR");
+ return false;
+ }
+
+ mDvrMQ = std::move(tmpDvrMQ);
+
+ if (EventFlag::createEventFlag(mDvrMQ->getEventFlagWord(), &mDvrEventFlag) != OK) {
+ return false;
+ }
+
+ return true;
+}
+
+void* Dvr::__threadLoopPlayback(void* user) {
+ Dvr* const self = static_cast<Dvr*>(user);
+ self->playbackThreadLoop();
+ return 0;
+}
+
+void Dvr::playbackThreadLoop() {
+ ALOGD("[Dvr] playback threadLoop start.");
+ std::lock_guard<std::mutex> lock(mDvrThreadLock);
+ mDvrThreadRunning = true;
+
+ while (mDvrThreadRunning) {
+ uint32_t efState = 0;
+ status_t status =
+ mDvrEventFlag->wait(static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_READY),
+ &efState, WAIT_TIMEOUT, true /* retry on spurious wake */);
+ if (status != OK) {
+ ALOGD("[Dvr] wait for data ready on the playback FMQ");
+ continue;
+ }
+ // Our current implementation filter the data and write it into the filter FMQ immediately
+ // after the DATA_READY from the VTS/framework
+ if (!readPlaybackFMQ() || !startFilterDispatcher()) {
+ ALOGD("[Dvr] playback data failed to be filtered. Ending thread");
+ break;
+ }
+
+ maySendPlaybackStatusCallback();
+ }
+
+ mDvrThreadRunning = false;
+ ALOGD("[Dvr] playback thread ended.");
+}
+
+void Dvr::maySendPlaybackStatusCallback() {
+ std::lock_guard<std::mutex> lock(mPlaybackStatusLock);
+ int availableToRead = mDvrMQ->availableToRead();
+ int availableToWrite = mDvrMQ->availableToWrite();
+
+ PlaybackStatus newStatus = checkPlaybackStatusChange(availableToWrite, availableToRead,
+ mDvrSettings.playback().highThreshold,
+ mDvrSettings.playback().lowThreshold);
+ if (mPlaybackStatus != newStatus) {
+ mCallback->onPlaybackStatus(newStatus);
+ mPlaybackStatus = newStatus;
+ }
+}
+
+PlaybackStatus Dvr::checkPlaybackStatusChange(uint32_t availableToWrite, uint32_t availableToRead,
+ uint32_t highThreshold, uint32_t lowThreshold) {
+ if (availableToWrite == 0) {
+ return PlaybackStatus::SPACE_FULL;
+ } else if (availableToRead > highThreshold) {
+ return PlaybackStatus::SPACE_ALMOST_FULL;
+ } else if (availableToRead < lowThreshold) {
+ return PlaybackStatus::SPACE_ALMOST_EMPTY;
+ } else if (availableToRead == 0) {
+ return PlaybackStatus::SPACE_EMPTY;
+ }
+ return mPlaybackStatus;
+}
+
+bool Dvr::readPlaybackFMQ() {
+ // Read playback data from the input FMQ
+ int size = mDvrMQ->availableToRead();
+ int playbackPacketSize = mDvrSettings.playback().packetSize;
+ vector<uint8_t> dataOutputBuffer;
+ dataOutputBuffer.resize(playbackPacketSize);
+
+ // Dispatch the packet to the PID matching filter output buffer
+ for (int i = 0; i < size / playbackPacketSize; i++) {
+ if (!mDvrMQ->read(dataOutputBuffer.data(), playbackPacketSize)) {
+ return false;
+ }
+ startTpidFilter(dataOutputBuffer);
+ }
+
+ return true;
+}
+
+void Dvr::startTpidFilter(vector<uint8_t> data) {
+ std::map<uint32_t, sp<IFilter>>::iterator it;
+ for (it = mFilters.begin(); it != mFilters.end(); it++) {
+ uint16_t pid = ((data[1] & 0x1f) << 8) | ((data[2] & 0xff));
+ if (DEBUG_DVR) {
+ ALOGW("[Dvr] start ts filter pid: %d", pid);
+ }
+ if (pid == mDemux->getFilterTpid(it->first)) {
+ mDemux->updateFilterOutput(it->first, data);
+ }
+ }
+}
+
+bool Dvr::startFilterDispatcher() {
+ std::map<uint32_t, sp<IFilter>>::iterator it;
+
+ // Handle the output data per filter type
+ for (it = mFilters.begin(); it != mFilters.end(); it++) {
+ if (mDemux->startFilterHandler(it->first) != Result::SUCCESS) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace tuner
+} // namespace tv
+} // namespace hardware
+} // namespace android
\ No newline at end of file
diff --git a/tv/tuner/1.0/default/Dvr.h b/tv/tuner/1.0/default/Dvr.h
new file mode 100644
index 0000000..fbb778c
--- /dev/null
+++ b/tv/tuner/1.0/default/Dvr.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_HARDWARE_TV_TUNER_V1_0_DVR_H_
+#define ANDROID_HARDWARE_TV_TUNER_V1_0_DVR_H_
+
+#include <android/hardware/tv/tuner/1.0/IDvr.h>
+#include <fmq/MessageQueue.h>
+#include <math.h>
+#include <set>
+#include "Demux.h"
+#include "Frontend.h"
+#include "Tuner.h"
+
+using namespace std;
+
+namespace android {
+namespace hardware {
+namespace tv {
+namespace tuner {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::EventFlag;
+using ::android::hardware::kSynchronizedReadWrite;
+using ::android::hardware::MessageQueue;
+using ::android::hardware::MQDescriptorSync;
+using ::android::hardware::tv::tuner::V1_0::IDemux;
+using ::android::hardware::tv::tuner::V1_0::IDvrCallback;
+using ::android::hardware::tv::tuner::V1_0::Result;
+
+using DvrMQ = MessageQueue<uint8_t, kSynchronizedReadWrite>;
+
+class Demux;
+class Filter;
+class Frontend;
+class Tuner;
+
+class Dvr : public IDvr {
+ public:
+ Dvr();
+
+ Dvr(DvrType type, uint32_t bufferSize, const sp<IDvrCallback>& cb, sp<Demux> demux);
+
+ ~Dvr();
+
+ virtual Return<void> getQueueDesc(getQueueDesc_cb _hidl_cb) override;
+
+ virtual Return<Result> configure(const DvrSettings& settings) override;
+
+ virtual Return<Result> attachFilter(const sp<IFilter>& filter) override;
+
+ virtual Return<Result> detachFilter(const sp<IFilter>& filter) override;
+
+ virtual Return<Result> start() override;
+
+ virtual Return<Result> stop() override;
+
+ virtual Return<Result> flush() override;
+
+ virtual Return<Result> close() override;
+
+ /**
+ * To create a DvrMQ and its Event Flag.
+ *
+ * Return false is any of the above processes fails.
+ */
+ bool createDvrMQ();
+
+ private:
+ // Demux service
+ sp<Demux> mDemux;
+
+ DvrType mType;
+ uint32_t mBufferSize;
+ sp<IDvrCallback> mCallback;
+ std::map<uint32_t, sp<IFilter>> mFilters;
+
+ void deleteEventFlag();
+ bool readDataFromMQ();
+ void maySendPlaybackStatusCallback();
+ void maySendRecordStatusCallback();
+ PlaybackStatus checkPlaybackStatusChange(uint32_t availableToWrite, uint32_t availableToRead,
+ uint32_t highThreshold, uint32_t lowThreshold);
+ /**
+ * A dispatcher to read and dispatch input data to all the started filters.
+ * Each filter handler handles the data filtering/output writing/filterEvent updating.
+ */
+ bool readPlaybackFMQ();
+ void startTpidFilter(vector<uint8_t> data);
+ bool startFilterDispatcher();
+ static void* __threadLoopPlayback(void* user);
+ static void* __threadLoopBroadcast(void* user);
+ void playbackThreadLoop();
+ void broadcastInputThreadLoop();
+
+ unique_ptr<DvrMQ> mDvrMQ;
+ EventFlag* mDvrEventFlag;
+ /**
+ * Demux callbacks used on filter events or IO buffer status
+ */
+ bool mDvrConfigured = false;
+ DvrSettings mDvrSettings;
+
+ // Thread handlers
+ pthread_t mDvrThread;
+ pthread_t mBroadcastInputThread;
+
+ // FMQ status local records
+ PlaybackStatus mPlaybackStatus;
+ /**
+ * If a specific filter's writing loop is still running
+ */
+ bool mDvrThreadRunning;
+ bool mBroadcastInputThreadRunning;
+ bool mKeepFetchingDataFromFrontend;
+ /**
+ * Lock to protect writes to the FMQs
+ */
+ std::mutex mWriteLock;
+ /**
+ * Lock to protect writes to the input status
+ */
+ std::mutex mPlaybackStatusLock;
+ std::mutex mBroadcastInputThreadLock;
+ std::mutex mDvrThreadLock;
+
+ const bool DEBUG_DVR = false;
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace tuner
+} // namespace tv
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_TV_TUNER_V1_0_DVR_H_
\ No newline at end of file
diff --git a/tv/tuner/1.0/default/Filter.cpp b/tv/tuner/1.0/default/Filter.cpp
new file mode 100644
index 0000000..3d8a977
--- /dev/null
+++ b/tv/tuner/1.0/default/Filter.cpp
@@ -0,0 +1,456 @@
+/*
+ * Copyright (C) 2019 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 "android.hardware.tv.tuner@1.0-Filter"
+
+#include "Filter.h"
+#include <utils/Log.h>
+
+namespace android {
+namespace hardware {
+namespace tv {
+namespace tuner {
+namespace V1_0 {
+namespace implementation {
+
+#define WAIT_TIMEOUT 3000000000
+
+Filter::Filter() {}
+
+Filter::Filter(DemuxFilterType type, uint32_t filterId, uint32_t bufferSize,
+ const sp<IFilterCallback>& cb, sp<Demux> demux) {
+ mType = type;
+ mFilterId = filterId;
+ mBufferSize = bufferSize;
+ mCallback = cb;
+ mDemux = demux;
+}
+
+Filter::~Filter() {}
+
+Return<void> Filter::getId(getId_cb _hidl_cb) {
+ ALOGV("%s", __FUNCTION__);
+
+ _hidl_cb(Result::SUCCESS, mFilterId);
+ return Void();
+}
+
+Return<Result> Filter::setDataSource(const sp<IFilter>& filter) {
+ ALOGV("%s", __FUNCTION__);
+
+ mDataSource = filter;
+ mIsDataSourceDemux = false;
+
+ return Result::SUCCESS;
+}
+
+Return<void> Filter::getQueueDesc(getQueueDesc_cb _hidl_cb) {
+ ALOGV("%s", __FUNCTION__);
+
+ _hidl_cb(Result::SUCCESS, *mFilterMQ->getDesc());
+ return Void();
+}
+
+Return<Result> Filter::configure(const DemuxFilterSettings& settings) {
+ ALOGV("%s", __FUNCTION__);
+
+ mFilterSettings = settings;
+ switch (mType.mainType) {
+ case DemuxFilterMainType::TS:
+ mTpid = settings.ts().tpid;
+ break;
+ case DemuxFilterMainType::MMTP:
+ /*mmtpSettings*/
+ break;
+ case DemuxFilterMainType::IP:
+ /*ipSettings*/
+ break;
+ case DemuxFilterMainType::TLV:
+ /*tlvSettings*/
+ break;
+ case DemuxFilterMainType::ALP:
+ /*alpSettings*/
+ break;
+ default:
+ break;
+ }
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Filter::start() {
+ ALOGV("%s", __FUNCTION__);
+
+ return startFilterLoop();
+}
+
+Return<Result> Filter::stop() {
+ ALOGV("%s", __FUNCTION__);
+
+ mFilterThreadRunning = false;
+
+ std::lock_guard<std::mutex> lock(mFilterThreadLock);
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Filter::flush() {
+ ALOGV("%s", __FUNCTION__);
+
+ // temp implementation to flush the FMQ
+ int size = mFilterMQ->availableToRead();
+ char* buffer = new char[size];
+ mFilterMQ->read((unsigned char*)&buffer[0], size);
+ delete[] buffer;
+ mFilterStatus = DemuxFilterStatus::DATA_READY;
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Filter::close() {
+ ALOGV("%s", __FUNCTION__);
+
+ return mDemux->removeFilter(mFilterId);
+}
+
+bool Filter::createFilterMQ() {
+ ALOGV("%s", __FUNCTION__);
+
+ // Create a synchronized FMQ that supports blocking read/write
+ std::unique_ptr<FilterMQ> tmpFilterMQ =
+ std::unique_ptr<FilterMQ>(new (std::nothrow) FilterMQ(mBufferSize, true));
+ if (!tmpFilterMQ->isValid()) {
+ ALOGW("Failed to create FMQ of filter with id: %d", mFilterId);
+ return false;
+ }
+
+ mFilterMQ = std::move(tmpFilterMQ);
+
+ if (EventFlag::createEventFlag(mFilterMQ->getEventFlagWord(), &mFilterEventFlag) != OK) {
+ return false;
+ }
+
+ return true;
+}
+
+Result Filter::startFilterLoop() {
+ pthread_create(&mFilterThread, NULL, __threadLoopFilter, this);
+ pthread_setname_np(mFilterThread, "filter_waiting_loop");
+
+ return Result::SUCCESS;
+}
+
+void* Filter::__threadLoopFilter(void* user) {
+ Filter* const self = static_cast<Filter*>(user);
+ self->filterThreadLoop();
+ return 0;
+}
+
+void Filter::filterThreadLoop() {
+ ALOGD("[Filter] filter %d threadLoop start.", mFilterId);
+ std::lock_guard<std::mutex> lock(mFilterThreadLock);
+ mFilterThreadRunning = true;
+
+ // For the first time of filter output, implementation needs to send the filter
+ // Event Callback without waiting for the DATA_CONSUMED to init the process.
+ while (mFilterThreadRunning) {
+ if (mFilterEvent.events.size() == 0) {
+ ALOGD("[Filter] wait for filter data output.");
+ usleep(1000 * 1000);
+ continue;
+ }
+ // After successfully write, send a callback and wait for the read to be done
+ mCallback->onFilterEvent(mFilterEvent);
+ mFilterEvent.events.resize(0);
+ mFilterStatus = DemuxFilterStatus::DATA_READY;
+ mCallback->onFilterStatus(mFilterStatus);
+ break;
+ }
+
+ while (mFilterThreadRunning) {
+ uint32_t efState = 0;
+ // We do not wait for the last round of written data to be read to finish the thread
+ // because the VTS can verify the reading itself.
+ for (int i = 0; i < SECTION_WRITE_COUNT; i++) {
+ while (mFilterThreadRunning) {
+ status_t status = mFilterEventFlag->wait(
+ static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_CONSUMED), &efState,
+ WAIT_TIMEOUT, true /* retry on spurious wake */);
+ if (status != OK) {
+ ALOGD("[Filter] wait for data consumed");
+ continue;
+ }
+ break;
+ }
+
+ if (mCallback == nullptr) {
+ ALOGD("[Filter] filter %d does not hava callback. Ending thread", mFilterId);
+ break;
+ }
+
+ maySendFilterStatusCallback();
+
+ while (mFilterThreadRunning) {
+ std::lock_guard<std::mutex> lock(mFilterEventLock);
+ if (mFilterEvent.events.size() == 0) {
+ continue;
+ }
+ // After successfully write, send a callback and wait for the read to be done
+ mCallback->onFilterEvent(mFilterEvent);
+ mFilterEvent.events.resize(0);
+ break;
+ }
+ // We do not wait for the last read to be done
+ // VTS can verify the read result itself.
+ if (i == SECTION_WRITE_COUNT - 1) {
+ ALOGD("[Filter] filter %d writing done. Ending thread", mFilterId);
+ break;
+ }
+ }
+ mFilterThreadRunning = false;
+ }
+
+ ALOGD("[Filter] filter thread ended.");
+}
+
+void Filter::maySendFilterStatusCallback() {
+ std::lock_guard<std::mutex> lock(mFilterStatusLock);
+ int availableToRead = mFilterMQ->availableToRead();
+ int availableToWrite = mFilterMQ->availableToWrite();
+ int fmqSize = mFilterMQ->getQuantumCount();
+
+ DemuxFilterStatus newStatus = checkFilterStatusChange(
+ availableToWrite, availableToRead, ceil(fmqSize * 0.75), ceil(fmqSize * 0.25));
+ if (mFilterStatus != newStatus) {
+ mCallback->onFilterStatus(newStatus);
+ mFilterStatus = newStatus;
+ }
+}
+
+DemuxFilterStatus Filter::checkFilterStatusChange(uint32_t availableToWrite,
+ uint32_t availableToRead, uint32_t highThreshold,
+ uint32_t lowThreshold) {
+ if (availableToWrite == 0) {
+ return DemuxFilterStatus::OVERFLOW;
+ } else if (availableToRead > highThreshold) {
+ return DemuxFilterStatus::HIGH_WATER;
+ } else if (availableToRead < lowThreshold) {
+ return DemuxFilterStatus::LOW_WATER;
+ }
+ return mFilterStatus;
+}
+
+uint16_t Filter::getTpid() {
+ return mTpid;
+}
+
+void Filter::updateFilterOutput(vector<uint8_t> data) {
+ std::lock_guard<std::mutex> lock(mFilterOutputLock);
+ ALOGD("[Filter] handler output updated");
+ mFilterOutput.insert(mFilterOutput.end(), data.begin(), data.end());
+}
+
+Result Filter::startFilterHandler() {
+ std::lock_guard<std::mutex> lock(mFilterOutputLock);
+ switch (mType.mainType) {
+ case DemuxFilterMainType::TS:
+ switch (mType.subType.tsFilterType()) {
+ case DemuxTsFilterType::UNDEFINED:
+ break;
+ case DemuxTsFilterType::SECTION:
+ startSectionFilterHandler();
+ break;
+ case DemuxTsFilterType::PES:
+ startPesFilterHandler();
+ break;
+ case DemuxTsFilterType::TS:
+ startTsFilterHandler();
+ break;
+ case DemuxTsFilterType::AUDIO:
+ case DemuxTsFilterType::VIDEO:
+ startMediaFilterHandler();
+ break;
+ case DemuxTsFilterType::PCR:
+ startPcrFilterHandler();
+ break;
+ case DemuxTsFilterType::RECORD:
+ startRecordFilterHandler();
+ break;
+ }
+ break;
+ case DemuxFilterMainType::MMTP:
+ /*mmtpSettings*/
+ break;
+ case DemuxFilterMainType::IP:
+ /*ipSettings*/
+ break;
+ case DemuxFilterMainType::TLV:
+ /*tlvSettings*/
+ break;
+ case DemuxFilterMainType::ALP:
+ /*alpSettings*/
+ break;
+ default:
+ break;
+ }
+ return Result::SUCCESS;
+}
+
+Result Filter::startSectionFilterHandler() {
+ if (mFilterOutput.empty()) {
+ return Result::SUCCESS;
+ }
+ if (!writeSectionsAndCreateEvent(mFilterOutput)) {
+ ALOGD("[Filter] filter %d fails to write into FMQ. Ending thread", mFilterId);
+ return Result::UNKNOWN_ERROR;
+ }
+
+ mFilterOutput.clear();
+
+ return Result::SUCCESS;
+}
+
+Result Filter::startPesFilterHandler() {
+ std::lock_guard<std::mutex> lock(mFilterEventLock);
+ if (mFilterOutput.empty()) {
+ return Result::SUCCESS;
+ }
+
+ for (int i = 0; i < mFilterOutput.size(); i += 188) {
+ if (mPesSizeLeft == 0) {
+ uint32_t prefix = (mFilterOutput[i + 4] << 16) | (mFilterOutput[i + 5] << 8) |
+ mFilterOutput[i + 6];
+ ALOGD("[Filter] prefix %d", prefix);
+ if (prefix == 0x000001) {
+ // TODO handle mulptiple Pes filters
+ mPesSizeLeft = (mFilterOutput[i + 8] << 8) | mFilterOutput[i + 9];
+ mPesSizeLeft += 6;
+ ALOGD("[Filter] pes data length %d", mPesSizeLeft);
+ } else {
+ continue;
+ }
+ }
+
+ int endPoint = min(184, mPesSizeLeft);
+ // append data and check size
+ vector<uint8_t>::const_iterator first = mFilterOutput.begin() + i + 4;
+ vector<uint8_t>::const_iterator last = mFilterOutput.begin() + i + 4 + endPoint;
+ mPesOutput.insert(mPesOutput.end(), first, last);
+ // size does not match then continue
+ mPesSizeLeft -= endPoint;
+ ALOGD("[Filter] pes data left %d", mPesSizeLeft);
+ if (mPesSizeLeft > 0) {
+ continue;
+ }
+ // size match then create event
+ if (!writeDataToFilterMQ(mPesOutput)) {
+ ALOGD("[Filter] pes data write failed");
+ mFilterOutput.clear();
+ return Result::INVALID_STATE;
+ }
+ maySendFilterStatusCallback();
+ DemuxFilterPesEvent pesEvent;
+ pesEvent = {
+ // temp dump meta data
+ .streamId = mPesOutput[3],
+ .dataLength = static_cast<uint16_t>(mPesOutput.size()),
+ };
+ ALOGD("[Filter] assembled pes data length %d", pesEvent.dataLength);
+
+ int size = mFilterEvent.events.size();
+ mFilterEvent.events.resize(size + 1);
+ mFilterEvent.events[size].pes(pesEvent);
+ mPesOutput.clear();
+ }
+
+ mFilterOutput.clear();
+
+ return Result::SUCCESS;
+}
+
+Result Filter::startTsFilterHandler() {
+ // TODO handle starting TS filter
+ return Result::SUCCESS;
+}
+
+Result Filter::startMediaFilterHandler() {
+ DemuxFilterMediaEvent mediaEvent;
+ mediaEvent = {
+ // temp dump meta data
+ .pts = 0,
+ .dataLength = 530,
+ .avMemory = nullptr,
+ .isSecureMemory = false,
+ };
+ mFilterEvent.events.resize(1);
+ mFilterEvent.events[0].media(mediaEvent);
+
+ mFilterOutput.clear();
+ // TODO handle write FQM for media stream
+ return Result::SUCCESS;
+}
+
+Result Filter::startRecordFilterHandler() {
+ DemuxFilterTsRecordEvent tsRecordEvent;
+ tsRecordEvent.pid.tPid(0);
+ tsRecordEvent.indexMask.tsIndexMask(0x01);
+ mFilterEvent.events.resize(1);
+ mFilterEvent.events[0].tsRecord(tsRecordEvent);
+
+ mFilterOutput.clear();
+ return Result::SUCCESS;
+}
+
+Result Filter::startPcrFilterHandler() {
+ // TODO handle starting PCR filter
+ return Result::SUCCESS;
+}
+
+bool Filter::writeSectionsAndCreateEvent(vector<uint8_t> data) {
+ // TODO check how many sections has been read
+ ALOGD("[Filter] section hander");
+ std::lock_guard<std::mutex> lock(mFilterEventLock);
+ if (!writeDataToFilterMQ(data)) {
+ return false;
+ }
+ int size = mFilterEvent.events.size();
+ mFilterEvent.events.resize(size + 1);
+ DemuxFilterSectionEvent secEvent;
+ secEvent = {
+ // temp dump meta data
+ .tableId = 0,
+ .version = 1,
+ .sectionNum = 1,
+ .dataLength = static_cast<uint16_t>(data.size()),
+ };
+ mFilterEvent.events[size].section(secEvent);
+ return true;
+}
+
+bool Filter::writeDataToFilterMQ(const std::vector<uint8_t>& data) {
+ std::lock_guard<std::mutex> lock(mWriteLock);
+ if (mFilterMQ->write(data.data(), data.size())) {
+ return true;
+ }
+ return false;
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace tuner
+} // namespace tv
+} // namespace hardware
+} // namespace android
\ No newline at end of file
diff --git a/tv/tuner/1.0/default/Filter.h b/tv/tuner/1.0/default/Filter.h
new file mode 100644
index 0000000..21d4297
--- /dev/null
+++ b/tv/tuner/1.0/default/Filter.h
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_HARDWARE_TV_TUNER_V1_0_FILTER_H_
+#define ANDROID_HARDWARE_TV_TUNER_V1_0_FILTER_H_
+
+#include <android/hardware/tv/tuner/1.0/IFilter.h>
+#include <fmq/MessageQueue.h>
+#include <math.h>
+#include <set>
+#include "Demux.h"
+#include "Frontend.h"
+
+using namespace std;
+
+namespace android {
+namespace hardware {
+namespace tv {
+namespace tuner {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::EventFlag;
+using ::android::hardware::kSynchronizedReadWrite;
+using ::android::hardware::MessageQueue;
+using ::android::hardware::MQDescriptorSync;
+using ::android::hardware::tv::tuner::V1_0::IDemux;
+using ::android::hardware::tv::tuner::V1_0::IFilterCallback;
+using ::android::hardware::tv::tuner::V1_0::Result;
+
+using FilterMQ = MessageQueue<uint8_t, kSynchronizedReadWrite>;
+
+class Demux;
+
+class Filter : public IFilter {
+ public:
+ Filter();
+
+ Filter(DemuxFilterType type, uint32_t filterId, uint32_t bufferSize,
+ const sp<IFilterCallback>& cb, sp<Demux> demux);
+
+ ~Filter();
+
+ virtual Return<void> getId(getId_cb _hidl_cb) override;
+
+ virtual Return<Result> setDataSource(const sp<IFilter>& filter) override;
+
+ virtual Return<void> getQueueDesc(getQueueDesc_cb _hidl_cb) override;
+
+ virtual Return<Result> configure(const DemuxFilterSettings& settings) override;
+
+ virtual Return<Result> start() override;
+
+ virtual Return<Result> stop() override;
+
+ virtual Return<Result> flush() override;
+
+ virtual Return<Result> close() override;
+
+ /**
+ * To create a FilterMQ and its Event Flag.
+ *
+ * Return false is any of the above processes fails.
+ */
+ bool createFilterMQ();
+ uint16_t getTpid();
+ void updateFilterOutput(vector<uint8_t> data);
+ Result startFilterHandler();
+
+ private:
+ // Tuner service
+ sp<Demux> mDemux;
+ /**
+ * Filter callbacks used on filter events or FMQ status
+ */
+ sp<IFilterCallback> mCallback;
+
+ uint32_t mFilterId;
+ uint32_t mBufferSize;
+ DemuxFilterType mType;
+ DemuxFilterSettings mFilterSettings;
+
+ uint16_t mTpid;
+ sp<IFilter> mDataSource;
+ bool mIsDataSourceDemux = true;
+ vector<uint8_t> mFilterOutput;
+ unique_ptr<FilterMQ> mFilterMQ;
+ EventFlag* mFilterEventFlag;
+ DemuxFilterEvent mFilterEvent;
+
+ // Thread handlers
+ pthread_t mFilterThread;
+
+ // FMQ status local records
+ DemuxFilterStatus mFilterStatus;
+ /**
+ * If a specific filter's writing loop is still running
+ */
+ bool mFilterThreadRunning;
+ bool mKeepFetchingDataFromFrontend;
+
+ /**
+ * How many times a filter should write
+ * TODO make this dynamic/random/can take as a parameter
+ */
+ const uint16_t SECTION_WRITE_COUNT = 10;
+
+ /**
+ * Filter handlers to handle the data filtering.
+ * They are also responsible to write the filtered output into the filter FMQ
+ * and update the filterEvent bound with the same filterId.
+ */
+ Result startSectionFilterHandler();
+ Result startPesFilterHandler();
+ Result startTsFilterHandler();
+ Result startMediaFilterHandler();
+ Result startRecordFilterHandler();
+ Result startPcrFilterHandler();
+ Result startFilterLoop();
+
+ void deleteEventFlag();
+ bool writeDataToFilterMQ(const std::vector<uint8_t>& data);
+ bool readDataFromMQ();
+ bool writeSectionsAndCreateEvent(vector<uint8_t> data);
+ void maySendFilterStatusCallback();
+ DemuxFilterStatus checkFilterStatusChange(uint32_t availableToWrite, uint32_t availableToRead,
+ uint32_t highThreshold, uint32_t lowThreshold);
+ /**
+ * A dispatcher to read and dispatch input data to all the started filters.
+ * Each filter handler handles the data filtering/output writing/filterEvent updating.
+ */
+ void startTsFilter(vector<uint8_t> data);
+ bool startFilterDispatcher();
+ static void* __threadLoopFilter(void* user);
+ void filterThreadLoop();
+
+ /**
+ * Lock to protect writes to the FMQs
+ */
+ std::mutex mWriteLock;
+ /**
+ * Lock to protect writes to the filter event
+ */
+ // TODO make each filter separate event lock
+ std::mutex mFilterEventLock;
+ /**
+ * Lock to protect writes to the input status
+ */
+ std::mutex mFilterStatusLock;
+ std::mutex mFilterThreadLock;
+ std::mutex mFilterOutputLock;
+
+ // temp handle single PES filter
+ // TODO handle mulptiple Pes filters
+ int mPesSizeLeft = 0;
+ vector<uint8_t> mPesOutput;
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace tuner
+} // namespace tv
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_TV_TUNER_V1_0_FILTER_H_
\ No newline at end of file
diff --git a/tv/tuner/1.0/default/Frontend.h b/tv/tuner/1.0/default/Frontend.h
index 07fa7b9..eab43a3 100644
--- a/tv/tuner/1.0/default/Frontend.h
+++ b/tv/tuner/1.0/default/Frontend.h
@@ -75,7 +75,7 @@
FrontendType mType = FrontendType::UNDEFINED;
FrontendId mId = 0;
- const string FRONTEND_STREAM_FILE = "/vendor/etc/test1.ts";
+ const string FRONTEND_STREAM_FILE = "/vendor/etc/dumpTs3.ts";
string mSourceStreamFile;
std::ifstream mFrontendData;
};
diff --git a/tv/tuner/1.0/default/Lnb.cpp b/tv/tuner/1.0/default/Lnb.cpp
index 1446f7f..51931d6 100644
--- a/tv/tuner/1.0/default/Lnb.cpp
+++ b/tv/tuner/1.0/default/Lnb.cpp
@@ -30,19 +30,25 @@
Lnb::~Lnb() {}
-Return<Result> Lnb::setVoltage(FrontendLnbVoltage /* voltage */) {
+Return<Result> Lnb::setCallback(const sp<ILnbCallback>& /* callback */) {
ALOGV("%s", __FUNCTION__);
return Result::SUCCESS;
}
-Return<Result> Lnb::setTone(FrontendLnbTone /* tone */) {
+Return<Result> Lnb::setVoltage(LnbVoltage /* voltage */) {
ALOGV("%s", __FUNCTION__);
return Result::SUCCESS;
}
-Return<Result> Lnb::setSatellitePosition(FrontendLnbPosition /* position */) {
+Return<Result> Lnb::setTone(LnbTone /* tone */) {
+ ALOGV("%s", __FUNCTION__);
+
+ return Result::SUCCESS;
+}
+
+Return<Result> Lnb::setSatellitePosition(LnbPosition /* position */) {
ALOGV("%s", __FUNCTION__);
return Result::SUCCESS;
diff --git a/tv/tuner/1.0/default/Lnb.h b/tv/tuner/1.0/default/Lnb.h
index 4c251f7..f285cb9 100644
--- a/tv/tuner/1.0/default/Lnb.h
+++ b/tv/tuner/1.0/default/Lnb.h
@@ -29,20 +29,23 @@
namespace V1_0 {
namespace implementation {
-using ::android::hardware::tv::tuner::V1_0::FrontendLnbPosition;
-using ::android::hardware::tv::tuner::V1_0::FrontendLnbTone;
-using ::android::hardware::tv::tuner::V1_0::FrontendLnbVoltage;
+using ::android::hardware::tv::tuner::V1_0::ILnbCallback;
+using ::android::hardware::tv::tuner::V1_0::LnbPosition;
+using ::android::hardware::tv::tuner::V1_0::LnbTone;
+using ::android::hardware::tv::tuner::V1_0::LnbVoltage;
using ::android::hardware::tv::tuner::V1_0::Result;
class Lnb : public ILnb {
public:
Lnb();
- virtual Return<Result> setVoltage(FrontendLnbVoltage voltage) override;
+ virtual Return<Result> setCallback(const sp<ILnbCallback>& callback) override;
- virtual Return<Result> setTone(FrontendLnbTone tone) override;
+ virtual Return<Result> setVoltage(LnbVoltage voltage) override;
- virtual Return<Result> setSatellitePosition(FrontendLnbPosition position) override;
+ virtual Return<Result> setTone(LnbTone tone) override;
+
+ virtual Return<Result> setSatellitePosition(LnbPosition position) override;
virtual Return<Result> sendDiseqcMessage(const hidl_vec<uint8_t>& diseqcMessage) override;
diff --git a/tv/tuner/1.0/default/TimeFilter.cpp b/tv/tuner/1.0/default/TimeFilter.cpp
new file mode 100644
index 0000000..0b1fd1c
--- /dev/null
+++ b/tv/tuner/1.0/default/TimeFilter.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2019 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 "android.hardware.tv.tuner@1.0-TimeFilter"
+
+#include "TimeFilter.h"
+#include <utils/Log.h>
+
+namespace android {
+namespace hardware {
+namespace tv {
+namespace tuner {
+namespace V1_0 {
+namespace implementation {
+
+TimeFilter::TimeFilter() {}
+
+TimeFilter::TimeFilter(sp<Demux> demux) {
+ mDemux = demux;
+}
+
+TimeFilter::~TimeFilter() {}
+
+Return<Result> TimeFilter::setTimeStamp(uint64_t /* timeStamp */) {
+ ALOGV("%s", __FUNCTION__);
+
+ return Result::SUCCESS;
+}
+
+Return<Result> TimeFilter::clearTimeStamp() {
+ ALOGV("%s", __FUNCTION__);
+
+ return Result::SUCCESS;
+}
+
+Return<void> TimeFilter::getTimeStamp(getTimeStamp_cb _hidl_cb) {
+ ALOGV("%s", __FUNCTION__);
+
+ uint64_t timeStamp = 0;
+
+ _hidl_cb(Result::SUCCESS, timeStamp);
+ return Void();
+}
+
+Return<void> TimeFilter::getSourceTime(getSourceTime_cb _hidl_cb) {
+ ALOGV("%s", __FUNCTION__);
+
+ uint64_t time = 0;
+
+ _hidl_cb(Result::SUCCESS, time);
+ return Void();
+}
+
+Return<Result> TimeFilter::close() {
+ ALOGV("%s", __FUNCTION__);
+
+ return Result::SUCCESS;
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace tuner
+} // namespace tv
+} // namespace hardware
+} // namespace android
\ No newline at end of file
diff --git a/tv/tuner/1.0/default/TimeFilter.h b/tv/tuner/1.0/default/TimeFilter.h
new file mode 100644
index 0000000..7131df8
--- /dev/null
+++ b/tv/tuner/1.0/default/TimeFilter.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_HARDWARE_TV_TUNER_V1_0_TIMEFILTER_H_
+#define ANDROID_HARDWARE_TV_TUNER_V1_0_TIMEFILTER_H_
+
+#include <android/hardware/tv/tuner/1.0/ITimeFilter.h>
+#include "Demux.h"
+
+using namespace std;
+
+namespace android {
+namespace hardware {
+namespace tv {
+namespace tuner {
+namespace V1_0 {
+namespace implementation {
+
+using ::android::hardware::tv::tuner::V1_0::IDemux;
+using ::android::hardware::tv::tuner::V1_0::IFilterCallback;
+using ::android::hardware::tv::tuner::V1_0::Result;
+
+using FilterMQ = MessageQueue<uint8_t, kSynchronizedReadWrite>;
+
+class Demux;
+
+class TimeFilter : public ITimeFilter {
+ public:
+ TimeFilter();
+
+ TimeFilter(sp<Demux> demux);
+
+ ~TimeFilter();
+
+ virtual Return<Result> setTimeStamp(uint64_t timeStamp) override;
+
+ virtual Return<Result> clearTimeStamp() override;
+
+ virtual Return<void> getTimeStamp(getTimeStamp_cb _hidl_cb) override;
+
+ virtual Return<void> getSourceTime(getSourceTime_cb _hidl_cb) override;
+
+ virtual Return<Result> close() override;
+
+ private:
+ sp<Demux> mDemux;
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace tuner
+} // namespace tv
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_TV_TUNER_V1_0_TIMEFILTER_H_
\ No newline at end of file
diff --git a/tv/tuner/1.0/types.hal b/tv/tuner/1.0/types.hal
index 890c1ed..fa00a6e 100644
--- a/tv/tuner/1.0/types.hal
+++ b/tv/tuner/1.0/types.hal
@@ -17,6 +17,7 @@
package android.hardware.tv.tuner@1.0;
import android.hidl.safe_union@1.0;
+import android.hidl.safe_union@1.0::Monostate;
@export
enum Result : int32_t {
@@ -41,9 +42,13 @@
enum FrontendType : uint32_t {
UNDEFINED = 0,
ANALOG,
- /* Advanced Television Systems Committee (ATSC) Standard A/72. */
+ /**
+ * Advanced Television Systems Committee (ATSC) Standard A/72.
+ */
ATSC,
- /* Advanced Television Systems Committee (ATSC 3.0) Standard A/300. */
+ /**
+ * Advanced Television Systems Committee (ATSC 3.0) Standard A/300.
+ */
ATSC3,
/**
* Digital Video Broadcasting - Cable
@@ -62,15 +67,18 @@
* ETSI EN 302 755 V1.4.1.
*/
DVBT,
- /* Integrated Services Digital Broadcasting-Satellite (ISDB-S)
+ /**
+ * Integrated Services Digital Broadcasting-Satellite (ISDB-S)
* ARIB STD-B20 is technical document of ISDB-S.
*/
ISDBS,
- /* Integrated Services Digital Broadcasting-Satellite (ISDB-S)
+ /**
+ * Integrated Services Digital Broadcasting-Satellite (ISDB-S)
* ARIB STD-B44 is technical document of ISDB-S3.
*/
ISDBS3,
- /* Integrated Services Digital Broadcasting-Terrestrial (ISDB-T or SBTVD)
+ /**
+ * Integrated Services Digital Broadcasting-Terrestrial (ISDB-T or SBTVD)
* ABNT NBR 15603 is technical document of ISDB-T.
*/
ISDBT,
@@ -82,79 +90,153 @@
*/
@export
enum FrontendInnerFec : uint64_t {
- /* Not defined */
+ /**
+ * Not defined
+ */
FEC_UNDEFINED = 0,
- /* hardware is able to detect and set FEC automatically */
+ /**
+ * hardware is able to detect and set FEC automatically
+ */
AUTO = 1 << 0,
- /* 1/2 conv. code rate */
+ /**
+ * 1/2 conv. code rate
+ */
FEC_1_2 = 1 << 1,
- /* 1/3 conv. code rate */
+ /**
+ * 1/3 conv. code rate
+ */
FEC_1_3 = 1 << 2,
- /* 1/4 conv. code rate */
+ /**
+ * 1/4 conv. code rate
+ */
FEC_1_4 = 1 << 3,
- /* 1/5 conv. code rate */
+ /**
+ * 1/5 conv. code rate
+ */
FEC_1_5 = 1 << 4,
- /* 2/3 conv. code rate */
+ /**
+ * 2/3 conv. code rate
+ */
FEC_2_3 = 1 << 5,
- /* 2/5 conv. code rate */
+ /**
+ * 2/5 conv. code rate
+ */
FEC_2_5 = 1 << 6,
- /* 2/9 conv. code rate */
+ /**
+ * 2/9 conv. code rate
+ */
FEC_2_9 = 1 << 7,
- /* 3/4 conv. code rate */
+ /**
+ * 3/4 conv. code rate
+ */
FEC_3_4 = 1 << 8,
- /* 3/5 conv. code rate */
+ /**
+ * 3/5 conv. code rate
+ */
FEC_3_5 = 1 << 9,
- /* 4/5 conv. code rate */
+ /**
+ * 4/5 conv. code rate
+ */
FEC_4_5 = 1 << 10,
- /* 4/15 conv. code rate */
+ /**
+ * 4/15 conv. code rate
+ */
FEC_4_15 = 1 << 11,
- /* 5/6 conv. code rate */
+ /**
+ * 5/6 conv. code rate
+ */
FEC_5_6 = 1 << 12,
- /* 5/9 conv. code rate */
+ /**
+ * 5/9 conv. code rate
+ */
FEC_5_9 = 1 << 13,
- /* 6/7 conv. code rate */
+ /**
+ * 6/7 conv. code rate
+ */
FEC_6_7 = 1 << 14,
- /* 7/8 conv. code rate */
+ /**
+ * 7/8 conv. code rate
+ */
FEC_7_8 = 1 << 15,
- /* 7/9 conv. code rate */
+ /**
+ * 7/9 conv. code rate
+ */
FEC_7_9 = 1 << 16,
- /* 7/15 conv. code rate */
+ /**
+ * 7/15 conv. code rate
+ */
FEC_7_15 = 1 << 17,
- /* 8/9 conv. code rate */
+ /**
+ * 8/9 conv. code rate
+ */
FEC_8_9 = 1 << 18,
- /* 8/15 conv. code rate */
+ /**
+ * 8/15 conv. code rate
+ */
FEC_8_15 = 1 << 19,
- /* 9/10 conv. code rate */
+ /**
+ * 9/10 conv. code rate
+ */
FEC_9_10 = 1 << 20,
- /* 9/20 conv. code rate */
+ /**
+ * 9/20 conv. code rate
+ */
FEC_9_20 = 1 << 21,
- /* 11/15 conv. code rate */
+ /**
+ * 11/15 conv. code rate
+ */
FEC_11_15 = 1 << 22,
- /* 11/20 conv. code rate */
+ /**
+ * 11/20 conv. code rate
+ */
FEC_11_20 = 1 << 23,
- /* 11/45 conv. code rate */
+ /**
+ * 11/45 conv. code rate
+ */
FEC_11_45 = 1 << 24,
- /* 13/18 conv. code rate */
+ /**
+ * 13/18 conv. code rate
+ */
FEC_13_18 = 1 << 25,
- /* 13/45 conv. code rate */
+ /**
+ * 13/45 conv. code rate
+ */
FEC_13_45 = 1 << 26,
- /* 14/45 conv. code rate */
+ /**
+ * 14/45 conv. code rate
+ */
FEC_14_45 = 1 << 27,
- /* 23/36 conv. code rate */
+ /**
+ * 23/36 conv. code rate
+ */
FEC_23_36 = 1 << 28,
- /* 25/36 conv. code rate */
+ /**
+ * 25/36 conv. code rate
+ */
FEC_25_36 = 1 << 29,
- /* 26/45 conv. code rate */
+ /**
+ * 26/45 conv. code rate
+ */
FEC_26_45 = 1 << 30,
- /* 28/45 conv. code rate */
+ /**
+ * 28/45 conv. code rate
+ */
FEC_28_45 = 1 << 31,
- /* 29/45 conv. code rate */
+ /**
+ * 29/45 conv. code rate
+ */
FEC_29_45 = 1 << 32,
- /* 31/45 conv. code rate */
+ /**
+ * 31/45 conv. code rate
+ */
FEC_31_45 = 1 << 33,
- /* 32/45 conv. code rate */
+ /**
+ * 32/45 conv. code rate
+ */
FEC_32_45 = 1 << 34,
- /* 77/90 conv. code rate */
+ /**
+ * 77/90 conv. code rate
+ */
FEC_77_90 = 1 << 35,
};
@@ -164,9 +246,11 @@
@export
enum FrontendAtscModulation : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set modulation automatically */
- AUTO = 1 << 0,
- MOD_8VSB = 1 << 2,
+ /**
+ * hardware is able to detect and set modulation automatically
+ */
+ AUTO = 1 << 0,
+ MOD_8VSB = 1 << 2,
MOD_16VSB = 1 << 3,
};
@@ -174,8 +258,11 @@
* Signal Settings for an ATSC Frontend.
*/
struct FrontendAtscSettings {
- /** Signal frequency in Hertz */
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
+
FrontendAtscModulation modulation;
};
@@ -183,7 +270,9 @@
* Capabilities for ATSC Frontend.
*/
struct FrontendAtscCapabilities {
- /** Modulation capability */
+ /**
+ * Modulation capability
+ */
bitfield<FrontendAtscModulation> modulationCap;
};
@@ -193,12 +282,14 @@
@export
enum FrontendAtsc3Modulation : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set modulation automatically */
- AUTO = 1 << 0,
- MOD_QPSK = 1 << 1,
- MOD_16QAM = 1 << 2,
- MOD_64QAM = 1 << 3,
- MOD_256QAM = 1 << 4,
+ /**
+ * hardware is able to detect and set modulation automatically
+ */
+ AUTO = 1 << 0,
+ MOD_QPSK = 1 << 1,
+ MOD_16QAM = 1 << 2,
+ MOD_64QAM = 1 << 3,
+ MOD_256QAM = 1 << 4,
MOD_1024QAM = 1 << 5,
MOD_4096QAM = 1 << 6,
};
@@ -209,7 +300,9 @@
@export
enum FrontendAtsc3Bandwidth : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set bandwidth automatically */
+ /**
+ * hardware is able to detect and set bandwidth automatically
+ */
AUTO = 1 << 0,
BANDWIDTH_6MHZ = 1 << 1,
BANDWIDTH_7MHZ = 1 << 2,
@@ -222,10 +315,12 @@
@export
enum FrontendAtsc3TimeInterleaveMode : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set TimeInterleaveMode automatically */
+ /**
+ * hardware is able to detect and set TimeInterleaveMode automatically
+ */
AUTO = 1 << 0,
- CTI = 1 << 1,
- HTI = 1 << 2,
+ CTI = 1 << 1,
+ HTI = 1 << 2,
};
/**
@@ -234,20 +329,22 @@
@export
enum FrontendAtsc3CodeRate : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Coderate automatically */
- AUTO = 1 << 0,
- CODERATE_2_15 = 1 << 1,
- CODERATE_3_15 = 1 << 2,
- CODERATE_4_15 = 1 << 3,
- CODERATE_5_15 = 1 << 4,
- CODERATE_6_15 = 1 << 5,
- CODERATE_7_15 = 1 << 6,
- CODERATE_8_15 = 1 << 7,
- CODERATE_9_15 = 1 << 8,
- CODERATE_10_15 = 1 << 9,
- CODERATE_11_15 = 1 << 10,
- CODERATE_12_15 = 1 << 11,
- CODERATE_13_15 = 1 << 12,
+ /**
+ * hardware is able to detect and set Coderate automatically
+ */
+ AUTO = 1 << 0,
+ CODERATE_2_15 = 1 << 1,
+ CODERATE_3_15 = 1 << 2,
+ CODERATE_4_15 = 1 << 3,
+ CODERATE_5_15 = 1 << 4,
+ CODERATE_6_15 = 1 << 5,
+ CODERATE_7_15 = 1 << 6,
+ CODERATE_8_15 = 1 << 7,
+ CODERATE_9_15 = 1 << 8,
+ CODERATE_10_15 = 1 << 9,
+ CODERATE_11_15 = 1 << 10,
+ CODERATE_12_15 = 1 << 11,
+ CODERATE_13_15 = 1 << 12,
};
/**
@@ -256,14 +353,16 @@
@export
enum FrontendAtsc3Fec : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set FEC automatically */
- AUTO = 1 << 0,
+ /**
+ * hardware is able to detect and set FEC automatically
+ */
+ AUTO = 1 << 0,
BCH_LDPC_16K = 1 << 1,
BCH_LDPC_64K = 1 << 2,
CRC_LDPC_16K = 1 << 3,
CRC_LDPC_64K = 1 << 4,
- LDPC_16K = 1 << 5,
- LDPC_64K = 1 << 6,
+ LDPC_16K = 1 << 5,
+ LDPC_64K = 1 << 6,
};
/**
@@ -271,12 +370,18 @@
*/
@export
enum FrontendAtsc3DemodOutputFormat : uint8_t {
- /** Dummy. Scan uses this. */
+ /**
+ * Dummy. Scan uses this.
+ */
UNDEFINED = 0,
- /** ALP format. Typically used in US region. */
+ /**
+ * ALP format. Typically used in US region.
+ */
ATSC3_LINKLAYER_PACKET = 1 << 0,
- /** BaseBand packet format. Typically used in Korea region. */
- BASEBAND_PACKET = 1 << 1,
+ /**
+ * BaseBand packet format. Typically used in Korea region.
+ */
+ BASEBAND_PACKET = 1 << 1,
};
/**
@@ -284,9 +389,13 @@
*/
struct FrontendAtsc3PlpSettings {
uint8_t plpId;
+
FrontendAtsc3Modulation modulation;
+
FrontendAtsc3TimeInterleaveMode interleaveMode;
+
FrontendAtsc3CodeRate codeRate;
+
FrontendAtsc3Fec fec;
};
@@ -294,11 +403,18 @@
* Signal Settings for an ATSC3 Frontend.
*/
struct FrontendAtsc3Settings {
- /** Signal frequency in Hertz */
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
- /** Bandwidth of tuning band. */
+
+ /**
+ * Bandwidth of tuning band.
+ */
FrontendAtsc3Bandwidth bandwidth;
+
FrontendAtsc3DemodOutputFormat demodOutputFormat;
+
vec<FrontendAtsc3PlpSettings> plpSettings;
};
@@ -306,17 +422,34 @@
* Capabilities for ATSC3 Frontend.
*/
struct FrontendAtsc3Capabilities {
- /** Bandwidth capability */
+ /**
+ * Bandwidth capability
+ */
bitfield<FrontendAtsc3Bandwidth> bandwidthCap;
- /** Modulation capability */
+
+ /**
+ * Modulation capability
+ */
bitfield<FrontendAtsc3Modulation> modulationCap;
- /** TimeInterleaveMode capability */
+
+ /**
+ * TimeInterleaveMode capability
+ */
bitfield<FrontendAtsc3TimeInterleaveMode> timeInterleaveModeCap;
- /** CodeRate capability */
+
+ /**
+ * CodeRate capability
+ */
bitfield<FrontendAtsc3CodeRate> codeRateCap;
- /** FEC capability */
+
+ /**
+ * FEC capability
+ */
bitfield<FrontendAtsc3Fec> fecCap;
- /** Demodulator Output Format capability */
+
+ /**
+ * Demodulator Output Format capability
+ */
bitfield<FrontendAtsc3DemodOutputFormat> demodOutputFormatCap;
};
@@ -326,7 +459,9 @@
@export
enum FrontendDvbsModulation : int32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Modulation automatically */
+ /**
+ * hardware is able to detect and set Modulation automatically
+ */
AUTO = 1 << 0,
MOD_QPSK = 1 << 1,
MOD_8PSK = 1 << 2,
@@ -340,7 +475,9 @@
MOD_64APSK = 1 << 10,
MOD_128APSK = 1 << 11,
MOD_256APSK = 1 << 12,
- /** Reserved for Proprietary modulation */
+ /**
+ * Reserved for Proprietary modulation
+ */
MOD_RESERVED = 1 << 13,
};
@@ -374,10 +511,17 @@
*/
struct FrontendDvbsCodeRate {
FrontendInnerFec fec;
+
bool isLinear;
- /* true if enable short frame */
+
+ /**
+ * true if enable short frame
+ */
bool isShortFrames;
- /* bits number in 1000 symbol. 0 if use the default. */
+
+ /**
+ * bits number in 1000 symbol. 0 if use the default.
+ */
uint32_t bitsPer1000Symbol;
};
@@ -396,15 +540,26 @@
* Signal Settings for an DVBS Frontend.
*/
struct FrontendDvbsSettings {
- /** Signal frequency in Hertz */
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
+
FrontendDvbsModulation modulation;
+
FrontendDvbsCodeRate coderate;
- /** Symbols per second */
+
+ /**
+ * Symbols per second
+ */
uint32_t symbolRate;
+
FrontendDvbsRolloff rolloff;
+
FrontendDvbsPilot pilot;
+
uint32_t inputStreamId;
+
FrontendDvbsStandard standard;
};
@@ -413,8 +568,10 @@
*/
struct FrontendDvbsCapabilities {
bitfield<FrontendDvbsModulation> modulationCap;
+
bitfield<FrontendInnerFec> innerfecCap;
- bitfield<FrontendDvbsStandard> standard;
+
+ bitfield<FrontendDvbsStandard> standard;
};
/**
@@ -423,7 +580,9 @@
@export
enum FrontendDvbcModulation : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Modulation automatically */
+ /**
+ * hardware is able to detect and set Modulation automatically
+ */
AUTO = 1 << 0,
MOD_16QAM = 1 << 1,
MOD_32QAM = 1 << 2,
@@ -467,14 +626,24 @@
* Signal Settings for an DVBC Frontend.
*/
struct FrontendDvbcSettings {
- /** Signal frequency in Hertz */
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
+
FrontendDvbcModulation modulation;
+
FrontendInnerFec fec;
- /** Symbols per second */
+
+ /**
+ * Symbols per second
+ */
uint32_t symbolRate;
+
FrontendDvbcOuterFec outerFec;
+
FrontendDvbcAnnex annex;
+
FrontendDvbcSpectralInversion spectralInversion;
};
@@ -483,7 +652,9 @@
*/
struct FrontendDvbcCapabilities {
bitfield<FrontendDvbcModulation> modulationCap;
+
bitfield<FrontendInnerFec> fecCap;
+
bitfield<FrontendDvbcAnnex> annexCap;
};
@@ -493,7 +664,9 @@
@export
enum FrontendDvbtBandwidth : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Bandwidth automatically */
+ /**
+ * hardware is able to detect and set Bandwidth automatically
+ */
AUTO = 1 << 0,
BANDWIDTH_8MHZ = 1 << 1,
BANDWIDTH_7MHZ = 1 << 2,
@@ -509,7 +682,9 @@
@export
enum FrontendDvbtConstellation : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Constellation automatically */
+ /**
+ * hardware is able to detect and set Constellation automatically
+ */
AUTO = 1 << 0,
CONSTELLATION_QPSK = 1 << 1,
CONSTELLATION_16QAM = 1 << 2,
@@ -523,7 +698,9 @@
@export
enum FrontendDvbtHierarchy : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Hierarchy automatically */
+ /**
+ * hardware is able to detect and set Hierarchy automatically
+ */
AUTO = 1 << 0,
HIERARCHY_NON_NATIVE = 1 << 1,
HIERARCHY_1_NATIVE = 1 << 2,
@@ -541,7 +718,9 @@
@export
enum FrontendDvbtCoderate : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Hierarchy automatically */
+ /**
+ * hardware is able to detect and set Hierarchy automatically
+ */
AUTO = 1 << 0,
CODERATE_1_2 = 1 << 1,
CODERATE_2_3 = 1 << 2,
@@ -560,7 +739,9 @@
@export
enum FrontendDvbtGuardInterval : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Guard Interval automatically */
+ /**
+ * hardware is able to detect and set Guard Interval automatically
+ */
AUTO = 1 << 0,
INTERVAL_1_32 = 1 << 1,
INTERVAL_1_16 = 1 << 2,
@@ -577,7 +758,9 @@
@export
enum FrontendDvbtTransmissionMode : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Transmission Mode automatically */
+ /**
+ * hardware is able to detect and set Transmission Mode automatically
+ */
AUTO = 1 << 0,
MODE_2K = 1 << 1,
MODE_8K = 1 << 2,
@@ -607,27 +790,50 @@
};
/**
- * Signal Setting for DVBT Frontend.
+ * Signal Settings for DVBT Frontend.
*/
struct FrontendDvbtSettings {
- /** Signal frequency in Hertz */
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
+
FrontendDvbtTransmissionMode transmissionMode;
+
FrontendDvbtBandwidth bandwidth;
+
FrontendDvbtConstellation constellation;
+
FrontendDvbtHierarchy hierarchy;
- /** Code Rate for High Priority level */
+
+ /**
+ * Code Rate for High Priority level
+ */
FrontendDvbtCoderate hpCoderate;
- /** Code Rate for Low Priority level */
+
+ /**
+ * Code Rate for Low Priority level
+ */
FrontendDvbtCoderate lpCoderate;
+
FrontendDvbtGuardInterval guardInterval;
+
bool isHighPriority;
+
FrontendDvbtStandard standard;
+
bool isMiso;
+
FrontendDvbtPlpMode plpMode;
- /** Physical Layer Pipe (PLP) Id */
+
+ /**
+ * Physical Layer Pipe (PLP) Id
+ */
uint8_t plpId;
- /** Group Id for Physical Layer Pipe (PLP) */
+
+ /**
+ * Group Id for Physical Layer Pipe (PLP)
+ */
uint8_t plpGroupId;
};
@@ -636,12 +842,19 @@
*/
struct FrontendDvbtCapabilities {
bitfield<FrontendDvbtTransmissionMode> transmissionModeCap;
+
bitfield<FrontendDvbtBandwidth> bandwidthCap;
+
bitfield<FrontendDvbtConstellation> constellationCap;
+
bitfield<FrontendDvbtCoderate> coderateCap;
+
bitfield<FrontendDvbtHierarchy> hierarchyCap;
+
bitfield<FrontendDvbtGuardInterval> guardIntervalCap;
+
bool isT2Supported;
+
bool isMisoSupported;
};
@@ -660,11 +873,13 @@
@export
enum FrontendIsdbsModulation : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Modulation automatically */
- AUTO = 1 << 0,
- MOD_BPSK = 1 << 1,
- MOD_QPSK = 1 << 2,
- MOD_TC8PSK = 1 << 3,
+ /**
+ * hardware is able to detect and set Modulation automatically
+ */
+ AUTO = 1 << 0,
+ MOD_BPSK = 1 << 1,
+ MOD_QPSK = 1 << 2,
+ MOD_TC8PSK = 1 << 3,
};
/**
@@ -673,13 +888,15 @@
@export
enum FrontendIsdbsCoderate : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Code Rate automatically */
- AUTO = 1 << 0,
- CODERATE_1_2 = 1 << 1,
- CODERATE_2_3 = 1 << 2,
- CODERATE_3_4 = 1 << 3,
- CODERATE_5_6 = 1 << 4,
- CODERATE_7_8 = 1 << 5,
+ /**
+ * hardware is able to detect and set Code Rate automatically
+ */
+ AUTO = 1 << 0,
+ CODERATE_1_2 = 1 << 1,
+ CODERATE_2_3 = 1 << 2,
+ CODERATE_3_4 = 1 << 3,
+ CODERATE_5_6 = 1 << 4,
+ CODERATE_7_8 = 1 << 5,
};
/**
@@ -692,17 +909,27 @@
};
/**
- * Signal Setting for ISDBS Frontend.
+ * Signal Settings for ISDBS Frontend.
*/
struct FrontendIsdbsSettings {
- /** Signal frequency in Hertz */
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
+
uint16_t streamId;
+
FrontendIsdbsStreamIdType streamIdType;
+
FrontendIsdbsModulation modulation;
+
FrontendIsdbsCoderate coderate;
- /** Symbols per second */
+
+ /**
+ * Symbols per second
+ */
uint32_t symbolRate;
+
FrontendIsdbsRolloff rolloff;
};
@@ -711,6 +938,7 @@
*/
struct FrontendIsdbsCapabilities {
bitfield<FrontendIsdbsModulation> modulationCap;
+
bitfield<FrontendIsdbsCoderate> coderateCap;
};
@@ -729,13 +957,15 @@
@export
enum FrontendIsdbs3Modulation : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Modulation automatically */
- AUTO = 1 << 5,
- MOD_BPSK = 1 << 1,
- MOD_QPSK = 1 << 2,
- MOD_8PSK = 1 << 3,
- MOD_16APSK = 1 << 4,
- MOD_32APSK = 1 << 5,
+ /**
+ * hardware is able to detect and set Modulation automatically
+ */
+ AUTO = 1 << 5,
+ MOD_BPSK = 1 << 1,
+ MOD_QPSK = 1 << 2,
+ MOD_8PSK = 1 << 3,
+ MOD_16APSK = 1 << 4,
+ MOD_32APSK = 1 << 5,
};
/**
@@ -744,33 +974,45 @@
@export
enum FrontendIsdbs3Coderate : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Code Rate automatically */
- AUTO = 1 << 0,
- CODERATE_1_3 = 1 << 1,
- CODERATE_2_5 = 1 << 2,
- CODERATE_1_2 = 1 << 3,
- CODERATE_3_5 = 1 << 4,
- CODERATE_2_3 = 1 << 5,
- CODERATE_3_4 = 1 << 6,
- CODERATE_7_9 = 1 << 7,
- CODERATE_4_5 = 1 << 8,
- CODERATE_5_6 = 1 << 9,
- CODERATE_7_8 = 1 << 10,
- CODERATE_9_10 = 1 << 11,
+ /**
+ * hardware is able to detect and set Code Rate automatically
+ */
+ AUTO = 1 << 0,
+ CODERATE_1_3 = 1 << 1,
+ CODERATE_2_5 = 1 << 2,
+ CODERATE_1_2 = 1 << 3,
+ CODERATE_3_5 = 1 << 4,
+ CODERATE_2_3 = 1 << 5,
+ CODERATE_3_4 = 1 << 6,
+ CODERATE_7_9 = 1 << 7,
+ CODERATE_4_5 = 1 << 8,
+ CODERATE_5_6 = 1 << 9,
+ CODERATE_7_8 = 1 << 10,
+ CODERATE_9_10 = 1 << 11,
};
/**
- * Signal Setting for ISDBS3 Frontend.
+ * Signal Settings for ISDBS3 Frontend.
*/
struct FrontendIsdbs3Settings {
- /** Signal frequency in Hertz */
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
+
uint16_t streamId;
+
FrontendIsdbsStreamIdType streamIdType;
+
FrontendIsdbs3Modulation modulation;
+
FrontendIsdbs3Coderate coderate;
- /** Symbols per second */
+
+ /**
+ * Symbols per second
+ */
uint32_t symbolRate;
+
FrontendIsdbs3Rolloff rolloff;
};
@@ -779,6 +1021,7 @@
*/
struct FrontendIsdbs3Capabilities {
bitfield<FrontendIsdbs3Modulation> modulationCap;
+
bitfield<FrontendIsdbs3Coderate> coderateCap;
};
@@ -788,7 +1031,9 @@
@export
enum FrontendIsdbtMode : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Mode automatically */
+ /**
+ * hardware is able to detect and set Mode automatically
+ */
AUTO = 1 << 0,
MODE_1 = 1 << 1,
MODE_2 = 1 << 2,
@@ -801,7 +1046,9 @@
@export
enum FrontendIsdbtBandwidth : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Bandwidth automatically */
+ /**
+ * hardware is able to detect and set Bandwidth automatically
+ */
AUTO = 1 << 0,
BANDWIDTH_8MHZ = 1 << 1,
BANDWIDTH_7MHZ = 1 << 2,
@@ -814,7 +1061,9 @@
@export
enum FrontendIsdbtModulation : uint32_t {
UNDEFINED = 0,
- /** hardware is able to detect and set Modulation automatically */
+ /**
+ * hardware is able to detect and set Modulation automatically
+ */
AUTO = 1 << 0,
MOD_DQPSK = 1 << 1,
MOD_QPSK = 1 << 2,
@@ -822,23 +1071,29 @@
MOD_64QAM = 1 << 4,
};
-/** Code Rate for ISDBT. */
typedef FrontendDvbtCoderate FrontendIsdbtCoderate;
-/** Guard Interval for ISDBT. */
typedef FrontendDvbtGuardInterval FrontendIsdbtGuardInterval;
/**
- * Signal Setting for ISDBT Frontend.
+ * Signal Settings for ISDBT Frontend.
*/
struct FrontendIsdbtSettings {
- /** Signal frequency in Hertz */
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
+
FrontendIsdbtModulation modulation;
+
FrontendIsdbtBandwidth bandwidth;
+
FrontendIsdbtMode mode;
+
FrontendIsdbtCoderate coderate;
+
FrontendIsdbtGuardInterval guardInterval;
+
uint32_t serviceAreaId;
};
@@ -847,9 +1102,13 @@
*/
struct FrontendIsdbtCapabilities {
bitfield<FrontendIsdbtMode> modeCap;
+
bitfield<FrontendIsdbtBandwidth> bandwidthCap;
+
bitfield<FrontendIsdbtModulation> constellationCap;
+
bitfield<FrontendIsdbtCoderate> coderateCap;
+
bitfield<FrontendIsdbtGuardInterval> guardIntervalCap;
};
@@ -872,7 +1131,7 @@
UNDEFINED = 0,
BG = 1 << 0,
BG_A2 = 1 << 1,
- BG_NICAM = 1 << 2,
+ BG_NICAM = 1 << 2,
I = 1 << 3,
DK = 1 << 4,
DK1 = 1 << 5,
@@ -890,12 +1149,16 @@
};
/**
- * Signal Setting for Analog Frontend.
+ * Signal Settings for Analog Frontend.
*/
struct FrontendAnalogSettings {
- /** Signal frequency in Hertz */
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
+
FrontendAnalogType type;
+
FrontendAnalogSifStandard sifStandard;
};
@@ -904,21 +1167,30 @@
*/
struct FrontendAnalogCapabilities {
bitfield<FrontendAnalogType> typeCap;
+
bitfield<FrontendAnalogSifStandard> sifStandardCap;
};
/**
- * Signal Setting for Frontend.
+ * Signal Settings for Frontend.
*/
safe_union FrontendSettings {
FrontendAnalogSettings analog;
+
FrontendAtscSettings atsc;
+
FrontendAtsc3Settings atsc3;
+
FrontendDvbsSettings dvbs;
+
FrontendDvbcSettings dvbc;
+
FrontendDvbtSettings dvbt;
+
FrontendIsdbsSettings isdbs;
+
FrontendIsdbs3Settings isdbs3;
+
FrontendIsdbtSettings isdbt;
};
@@ -935,25 +1207,45 @@
* Scan Message Type for Frontend.
*/
enum FrontendScanMessageType : uint32_t {
- /** Scan locked the signal. */
+ /**
+ * Scan locked the signal.
+ */
LOCKED,
- /** Scan stopped. */
+ /**
+ * Scan stopped.
+ */
END,
- /** Scan progress report. */
+ /**
+ * Scan progress report.
+ */
PROGRESS_PERCENT,
- /** Locked frequency report. */
+ /**
+ * Locked frequency report.
+ */
FREQUENCY,
- /** Locked symbol rate. */
+ /**
+ * Locked symbol rate.
+ */
SYMBOL_RATE,
- /** Locked Plp Ids for DVBT2 frontend. */
+ /**
+ * Locked Plp Ids for DVBT2 frontend.
+ */
PLP_IDS,
- /** Locked group Ids for DVBT2 frontend. */
+ /**
+ * Locked group Ids for DVBT2 frontend.
+ */
GROUP_IDS,
- /** Stream Ids. */
+ /**
+ * Stream Ids.
+ */
INPUT_STREAM_IDS,
- /** Locked signal standard. */
+ /**
+ * Locked signal standard.
+ */
STANDARD,
- /** PLP status in a tuned frequency band for ATSC3 frontend. */
+ /**
+ * PLP status in a tuned frequency band for ATSC3 frontend.
+ */
ATSC3_PLP_INFO,
};
@@ -962,6 +1254,7 @@
*/
struct FrontendScanAtsc3PlpInfo {
uint8_t plpId;
+
bool bLlsFlag;
};
@@ -970,21 +1263,39 @@
*/
safe_union FrontendScanMessage {
bool isLocked;
+
bool isEnd;
- /** scan progress percent (0..100) */
+
+ /**
+ * scan progress percent (0..100)
+ */
uint8_t progressPercent;
- /** Signal frequency in Hertz */
+
+ /**
+ * Signal frequency in Hertz
+ */
uint32_t frequency;
- /** Symbols per second */
+
+ /**
+ * Symbols per second
+ */
uint32_t symbolRate;
+
vec<uint8_t> plpIds;
+
vec<uint8_t> groupIds;
+
vec<uint16_t> inputStreamIds;
+
safe_union standard {
FrontendDvbsStandard sStd;
+
FrontendDvbtStandard tStd;
} std;
- /** A list of PLP status in a tuned frequency band for ATSC3 frontend. */
+
+ /**
+ * A list of PLP status in a tuned frequency band for ATSC3 frontend.
+ */
vec<FrontendScanAtsc3PlpInfo> atsc3PlpInfos;
};
@@ -1008,22 +1319,6 @@
* event.
*/
LOST_LOCK,
- /**
- * If frontend detect that incoming Diseqc message is overflow.
- */
- DISEQC_RX_OVERFLOW,
- /**
- * If frontend detect that outgoing Diseqc message isn't delivered on time.
- */
- DISEQC_RX_TIMEOUT,
- /**
- * If frontend detect that the incoming Diseqc message has parity error.
- */
- DISEQC_RX_PARITY_ERROR,
- /**
- * If frontend detect that the LNB is overload.
- */
- LNB_OVERLOAD,
};
/**
@@ -1031,60 +1326,106 @@
*/
@export
enum FrontendStatusType : uint32_t {
- /** Lock status for Demod. */
+ /**
+ * Lock status for Demod.
+ */
DEMOD_LOCK,
- /** Signal to Noise Ratio. */
+ /**
+ * Signal to Noise Ratio.
+ */
SNR,
- /** Bit Error Ratio. */
+ /**
+ * Bit Error Ratio.
+ */
BER,
- /** Packages Error Ratio. */
+ /**
+ * Packages Error Ratio.
+ */
PER,
- /** Bit Error Ratio before FEC. */
+ /**
+ * Bit Error Ratio before FEC.
+ */
PRE_BER,
- /*
+ /**
* Signal Quality (0..100). Good data over total data in percent can be
* used as a way to present Signal Quality.
*/
SIGNAL_QUALITY,
- /** Signal Strength. */
+ /**
+ * Signal Strength.
+ */
SIGNAL_STRENGTH,
- /** Symbol Rate. */
+ /**
+ * Symbol Rate.
+ */
SYMBOL_RATE,
- /** Forward Error Correction Type. */
+ /**
+ * Forward Error Correction Type.
+ */
FEC,
- /** Modulation Type. */
+ /**
+ * Modulation Type.
+ */
MODULATION,
- /** Spectral Inversion Type. */
+ /**
+ * Spectral Inversion Type.
+ */
SPECTRAL,
- /** LNB Voltage. */
+ /**
+ * LNB Voltage.
+ */
LNB_VOLTAGE,
- /** Physical Layer Pipe ID. */
+ /**
+ * Physical Layer Pipe ID.
+ */
PLP_ID,
- /** Status for Emergency Warning Broadcasting System. */
+ /**
+ * Status for Emergency Warning Broadcasting System.
+ */
EWBS,
- /** Automatic Gain Control. */
+ /**
+ * Automatic Gain Control.
+ */
AGC,
- /** Low Noise Amplifier. */
+ /**
+ * Low Noise Amplifier.
+ */
LNA,
- /** Lock status for stream. */
- STREAM_LOCK,
- /** Error status by layer. */
+ /**
+ * Error status by layer.
+ */
LAYER_ERROR,
- /** CN value by VBER. */
+ /**
+ * CN value by VBER.
+ */
VBER_CN,
- /** CN value by LBER. */
+ /**
+ * CN value by LBER.
+ */
LBER_CN,
- /** CN value by XER. */
+ /**
+ * CN value by XER.
+ */
XER_CN,
- /** Moduration Error Ratio. */
+ /**
+ * Moduration Error Ratio.
+ */
MER,
- /** Difference between tuning frequency and actual locked frequency. */
+ /**
+ * Difference between tuning frequency and actual locked frequency.
+ */
FREQ_OFFSET,
- /* Hierarchy for DVBT. */
+ /**
+ * Hierarchy for DVBT.
+ */
HIERARCHY,
- /** Lock status for RF. */
+ /**
+ * Lock status for RF.
+ */
RF_LOCK,
- /** PLP information in a frequency band for ATSC3.0 frontend. */
+ /**
+ * PLP information in a frequency band for ATSC3.0 frontend.
+ */
ATSC3_PLP_INFO,
};
@@ -1092,23 +1433,34 @@
* Status for each tuning PLPs
*/
struct FrontendStatusAtsc3PlpInfo {
- /** PLP Id value. */
+ /**
+ * PLP Id value.
+ */
uint8_t plpId;
- /** Demod Lock/Unlock status of this particular PLP. */
+
+ /**
+ * Demod Lock/Unlock status of this particular PLP.
+ */
bool isLocked;
- /** Uncorrectable Error Counts (UEC) of this particular PLP since last tune operation. */
+
+ /**
+ * Uncorrectable Error Counts (UEC) of this particular PLP since last tune operation.
+ */
uint32_t uec;
};
-
/**
* Modulation Type for Frontend's status.
*/
safe_union FrontendModulationStatus {
FrontendDvbcModulation dvbc;
+
FrontendDvbsModulation dvbs;
+
FrontendIsdbsModulation isdbs;
+
FrontendIsdbs3Modulation isdbs3;
+
FrontendIsdbtModulation isdbt;
};
@@ -1116,46 +1468,99 @@
* The status for Frontend.
*/
safe_union FrontendStatus {
- /** Lock status for Demod in True/False. */
+ /**
+ * Lock status for Demod in True/False.
+ */
bool isDemodLocked;
- /** SNR value measured by 0.001 dB. */
+
+ /**
+ * SNR value measured by 0.001 dB.
+ */
int32_t snr;
- /** The number of error bit per 1 billion bits. */
+
+ /**
+ * The number of error bit per 1 billion bits.
+ */
uint32_t ber;
- /** The number of error package per 1 billion packages. */
+
+ /**
+ * The number of error package per 1 billion packages.
+ */
uint32_t per;
- /** The number of error bit per 1 billion bits before FEC. */
+
+ /**
+ * The number of error bit per 1 billion bits before FEC.
+ */
uint32_t preBer;
- /** Signal Quality in percent. */
+
+ /**
+ * Signal Quality in percent.
+ */
uint32_t signalQuality;
- /** Signal Strength measured by 0.001 dBm. */
+
+ /**
+ * Signal Strength measured by 0.001 dBm.
+ */
int32_t signalStrength;
- /** Symbols per second */
+
+ /**
+ * Symbols per second
+ */
uint32_t symbolRate;
+
FrontendInnerFec innerFec;
+
FrontendModulationStatus modulation;
+
FrontendDvbcSpectralInversion inversion;
- FrontendLnbVoltage lnbVoltage;
+
+ LnbVoltage lnbVoltage;
+
uint8_t plpId;
+
bool isEWBS;
- /** AGC value is normalized from 0 to 255. */
+
+ /**
+ * AGC value is normalized from 0 to 255.
+ */
uint8_t agc;
+
bool isLnaOn;
- bool isStreamLock;
+
vec<bool> isLayerError;
- /** CN value by VBER measured by 0.001 dB */
+
+ /**
+ * CN value by VBER measured by 0.001 dB
+ */
int32_t vberCn;
- /** CN value by LBER measured by 0.001 dB */
+
+ /**
+ * CN value by LBER measured by 0.001 dB
+ */
int32_t lberCn;
- /** CN value by XER measured by 0.001 dB */
+
+ /**
+ * CN value by XER measured by 0.001 dB
+ */
int32_t xerCn;
- /** MER value measured by 0.001 dB */
+
+ /**
+ * MER value measured by 0.001 dB
+ */
int32_t mer;
- /** Frequency difference in Hertz. */
+
+ /**
+ * Frequency difference in Hertz.
+ */
int32_t freqOffset;
+
FrontendDvbtHierarchy hierarchy;
+
bool isRfLocked;
- /** A list of PLP status for tuned PLPs for ATSC3 frontend. */
+
+ /**
+ * A list of PLP status for tuned PLPs for ATSC3 frontend.
+ */
vec<FrontendStatusAtsc3PlpInfo> plpInfo;
};
@@ -1164,32 +1569,60 @@
*/
struct FrontendInfo {
FrontendType type;
- /** Frequency in Hertz */
+
+ /**
+ * Frequency in Hertz
+ */
uint32_t minFrequency;
- /** Frequency in Hertz */
+
+ /**
+ * Frequency in Hertz
+ */
uint32_t maxFrequency;
- /** Minimum symbols per second */
+
+ /**
+ * Minimum symbols per second
+ */
uint32_t minSymbolRate;
- /** Maximum symbols per second */
+
+ /**
+ * Maximum symbols per second
+ */
uint32_t maxSymbolRate;
- /** Range in Hertz */
+
+ /**
+ * Range in Hertz
+ */
uint32_t acquireRange;
- /*
+
+ /**
* Frontends are assigned with the same exclusiveGroupId if they can't
* function at same time. For instance, they share same hardware module.
*/
uint32_t exclusiveGroupId;
- /** A list of supported status types which client can inquiry */
+
+ /**
+ * A list of supported status types which client can inquiry
+ */
vec<FrontendStatusType> statusCaps;
+
safe_union FrontendCapabilities {
FrontendAnalogCapabilities analogCaps;
+
FrontendAtscCapabilities atscCaps;
+
FrontendAtsc3Capabilities atsc3Caps;
+
FrontendDvbsCapabilities dvbsCaps;
+
FrontendDvbcCapabilities dvbcCaps;
+
FrontendDvbtCapabilities dvbtCaps;
+
FrontendIsdbsCapabilities isdbsCaps;
+
FrontendIsdbs3Capabilities isdbs3Caps;
+
FrontendIsdbtCapabilities isdbtCaps;
} frontendCaps;
};
@@ -1204,7 +1637,7 @@
* Power Voltage Type for LNB.
*/
@export
-enum FrontendLnbVoltage : uint32_t {
+enum LnbVoltage : uint32_t {
NONE,
VOLTAGE_5V,
VOLTAGE_11V,
@@ -1220,7 +1653,7 @@
* Tone Type for LNB.
*/
@export
-enum FrontendLnbTone : int32_t {
+enum LnbTone : int32_t {
NONE,
CONTINUOUS,
};
@@ -1229,41 +1662,92 @@
* The Position of LNB.
*/
@export
-enum FrontendLnbPosition : int32_t {
+enum LnbPosition : int32_t {
UNDEFINED,
POSITION_A,
POSITION_B,
};
+/**
+ * Lnb Event Type.
+ */
+@export
+enum LnbEventType : uint32_t {
+ DISEQC_RX_OVERFLOW,
+ /**
+ * If LNB detect that outgoing Diseqc message isn't delivered on time.
+ */
+ DISEQC_RX_TIMEOUT,
+ /**
+ * If LNB detect that the incoming Diseqc message has parity error.
+ */
+ DISEQC_RX_PARITY_ERROR,
+ /**
+ * If LNB detect that the LNB is overload.
+ */
+ LNB_OVERLOAD,
+};
+
/* Demux ID is used to associate with a hardware demux resource. */
typedef uint32_t DemuxId;
-/* Filter ID is used to associate with a hardware filter resource. */
-typedef uint32_t DemuxFilterId;
-
/**
- * Filter Type according to ISO/IEC 13818-1
+ * Filter Main Type specifies the protocol that the filter use to extract data
+ * from input stream.
*/
@export
-enum DemuxFilterType : uint32_t {
+enum DemuxFilterMainType : uint32_t {
/**
- * A filter to filter section data out from input stream.
+ * Transport Stream according to ISO/IEC 13818-1.
+ */
+ TS = 1 << 0,
+ /**
+ * MPEG Media Transport Protocol according to ISO/IEC 23008-1.
+ */
+ MMTP = 1 << 1,
+ /**
+ * Internet Protocol.
+ */
+ IP = 1 << 2,
+ /**
+ * Type Length Value according to ITU-R BT.1869.
+ */
+ TLV = 1 << 3,
+ /**
+ * ATSC Link-Layer Protocol according to A/330 ATSC3.0.
+ */
+ ALP = 1 << 4,
+};
+
+/**
+ * TS Filter Type according to ISO/IEC 13818-1
+ */
+@export
+enum DemuxTsFilterType : uint32_t {
+ UNDEFINED,
+ /**
+ * A filter to filter Section data out from input stream, and queue the
+ * data to the filter's FMQ (Fast Message Queue).
*/
SECTION,
/**
- * A filter to filter PES data out from input stream.
+ * A filter to filter Packetized Elementary Stream data out from input
+ * stream, and queue the data to the filter's FMQ.
*/
PES,
/**
- * A filter to filter TS payload out from input stream.
+ * A filter to filter a Transport Stream out from input stream, and queue
+ * the data to the filter's FMQ.
*/
TS,
/**
- * A filter to filter Audio Metadata out from input stream.
+ * A filter to filter Audio data out from input stream, and send Audio's
+ * Metadata to client through onFilterEvent.
*/
AUDIO,
/**
- * A filter to filter Video Metadata out from input stream.
+ * A filter to filter Video data out from input stream, and send Video's
+ * Metadata to client through onFilterEvent.
*/
VIDEO,
/**
@@ -1271,20 +1755,172 @@
*/
PCR,
/**
- * A filter to filter data directly to output buffer for record.
+ * A filter to filter data out from input stream, and queue the data to the
+ * buffer of the record.
*/
RECORD,
};
+/**
+ * MMTP Filter Type according to ISO/IEC 23008-1
+ */
+@export
+enum DemuxMmtpFilterType : uint32_t {
+ UNDEFINED,
+ /**
+ * A filter to filter signaling data out from input stream, and queue the
+ * data to the filter's FMQ (Fast Message Queue).
+ */
+ SECTION,
+ /**
+ * A filter to filter MFU (Media fragment unit) out from input stream, and
+ * queue the data to the filter's FMQ.
+ */
+ PES,
+ /**
+ * A filter to filter a MMTP stream out from input stream, and queue the
+ * data to the filter's FMQ.
+ */
+ MMTP,
+ /**
+ * A filter to filter Audio data out from input stream, and send Audio's
+ * Metadata to client through onFilterEvent.
+ */
+ AUDIO,
+ /**
+ * A filter to filter Video data out from input stream, and send Video's
+ * Metadata to client through onFilterEvent.
+ */
+ VIDEO,
+ /**
+ * A filter to filter data out from input stream, and queue the data to the
+ * buffer of the record.
+ */
+ RECORD,
+ /**
+ * A filter to filter application data out from input stream, and queue the
+ * data to the filter's FMQ.
+ */
+ DOWNLOAD,
+};
+
+/**
+ * IP Filter Type.
+ */
+@export
+enum DemuxIpFilterType : uint32_t {
+ UNDEFINED,
+ /**
+ * A filter to filter section data out from input stream, and queue the
+ * data to the filter's FMQ (Fast Message Queue).
+ */
+ SECTION,
+ /**
+ * A filter to set NTP (Network Time Procotol) channel from input stream.
+ */
+ NTP,
+ /**
+ * A filter to strip out IP message header and queue the data to the
+ * filter's FMQ.
+ */
+ IP_PAYLOAD,
+ /**
+ * A filter to filter a IP stream out from input stream. The output can be
+ * either upper stream of another filter or queued to the filter's FMQ.
+ */
+ IP,
+ /**
+ * A filter to strip out IP message header and be a data source of another
+ * filter.
+ */
+ PAYLOAD_THROUGH,
+};
+
+/**
+ * TLV Filter Type according to ITU-R BT.1869.
+ */
+@export
+enum DemuxTlvFilterType : uint32_t {
+ UNDEFINED,
+ /**
+ * A filter to filter signaling data out from input stream, and queue the
+ * data to the filter's FMQ (Fast Message Queue).
+ */
+ SECTION,
+ /**
+ * A filter to filter a TLV stream out from input stream. The output can be
+ * either upper stream of another filter or queued to the filter's FMQ.
+ */
+ TLV,
+ /**
+ * A filter to strip out TLV message header and be a data source of another
+ * filter.
+ */
+ PAYLOAD_THROUGH,
+};
+
+/**
+ * ALP Filter Type according to A/330 ATSC3.0.
+ */
+@export
+enum DemuxAlpFilterType : uint32_t {
+ UNDEFINED,
+ /**
+ * A filter to filter signaling data out from input stream, and queue the
+ * data to the filter's FMQ (Fast Message Queue).
+ */
+ SECTION,
+ /**
+ * A filter to set PTP (Precision Time Protocol) channel from input stream.
+ */
+ PTP,
+ /**
+ * A filter to strip out ALP message header and be a data source of another
+ * filter.
+ */
+ PAYLOAD_THROUGH,
+};
+
+/**
+ * Demux Filter Type.
+ */
+struct DemuxFilterType {
+ DemuxFilterMainType mainType;
+
+ safe_union DemuxFilterSubType {
+ DemuxTsFilterType tsFilterType;
+
+ DemuxMmtpFilterType mmtpFilterType;
+
+ DemuxIpFilterType ipFilterType;
+
+ DemuxTlvFilterType tlvFilterType;
+
+ DemuxAlpFilterType alpFilterType;
+ } subType;
+};
+
/* Packet ID is used to specify packets in transport stream. */
typedef uint16_t DemuxTpid;
+/* Packet ID is used to specify packets in MMTP */
+typedef uint16_t DemuxMmtpPid;
+
+/**
+ * Demux Packet ID.
+ */
+safe_union DemuxPid {
+ DemuxTpid tPid;
+
+ DemuxMmtpPid mmtpPid;
+};
+
@export
enum Constant : uint16_t {
/**
* An invalid packet ID in transport stream according to ISO/IEC 13818-1.
*/
- INVALID_TPID = 0xFFFF,
+ INVALID_TS_PID = 0xFFFF,
/**
* An invalid Stream ID.
*/
@@ -1304,7 +1940,7 @@
* The available data amount in the filter buffer is at low level which is
* set to 25 percent by default.
*/
- LOW_WATER = 1 << 1,
+ LOW_WATER = 1 << 1,
/**
* The available data amount in the filter buffer is at high level which is
* set to 75 percent by default.
@@ -1314,18 +1950,122 @@
* The data in the filter buffer is full and newly filtered data is being
* discarded.
*/
- OVERFLOW = 1 << 3,
+ OVERFLOW = 1 << 3,
};
/**
- * Bits Setting for Section Filter.
+ * Indexes can be tagged through TS (Transport Stream) header.
+ */
+@export
+enum DemuxTsIndex : uint32_t {
+ FIRST_PACKET = 1 << 0,
+ PAYLOAD_UNIT_START_INDICATOR = 1 << 1,
+ CHANGE_TO_NOT_SCRAMBLED = 1 << 2,
+ CHANGE_TO_EVEN_SCRAMBLED = 1 << 3,
+ CHANGE_TO_ODD_SCRAMBLED = 1 << 4,
+ DISCONTINUITY_INDICATOR = 1 << 5,
+ RANDOM_ACCESS_INDICATOR = 1 << 6,
+ PRIORITY_INDICATOR = 1 << 7,
+ PCR_FLAG = 1 << 8,
+ OPCR_FLAG = 1 << 9,
+ SPLICING_POINT_FLAG = 1 << 10,
+ PRIVATE_DATA = 1 << 11,
+ ADAPTATION_EXTENSION_FLAG = 1 << 12,
+};
+
+/**
+ * Indexes can be tagged by Start Code in PES (Packetized Elementary Stream)
+ * according to ISO/IEC 13818-1.
+ */
+@export
+enum DemuxScIndex : uint32_t {
+ /**
+ * Start Code is for a new I Frame
+ */
+ I_FRAME = 1 << 0,
+ /**
+ * Start Code is for a new P Frame
+ */
+ P_FRAME = 1 << 1,
+ /**
+ * Start Code is for a new B Frame
+ */
+ B_FRAME = 1 << 2,
+ /**
+ * Start Code is for a new Sequence
+ */
+ SEQUENCE = 1 << 3,
+};
+
+/**
+ * Indexes can be tagged by NAL unit group in HEVC
+ * according to ISO/IEC 23008-2.
+ */
+@export
+enum DemuxScHevcIndex : uint32_t {
+ SPS = 1 << 0,
+ AUD = 1 << 1,
+ SLICE_CE_BLA_W_LP = 1 << 2,
+ SLICE_BLA_W_RADL = 1 << 3,
+ SLICE_BLA_N_LP = 1 << 4,
+ SLICE_IDR_W_RADL = 1 << 5,
+ SLICE_IDR_N_LP = 1 << 6,
+ SLICE_TRAIL_CRA = 1 << 7,
+};
+
+/**
+ * Index type to be used in the filter for record
+ */
+@export
+enum DemuxRecordIndexType : uint32_t {
+ /**
+ * Don't use index
+ */
+ NONE,
+ /**
+ * Use TS index
+ */
+ TS,
+ /**
+ * Use Start Code index
+ */
+ SC,
+ /**
+ * Use Start Code index for HEVC
+ */
+ SC_HEVC,
+};
+
+/**
+ * Filter Settings for Record data.
+ */
+struct DemuxFilterRecordSettings {
+ DemuxRecordIndexType indexType;
+
+ safe_union IndexMask {
+ bitfield<DemuxTsIndex> tsIndexMask;
+
+ bitfield<DemuxScIndex> scIndexMask;
+
+ bitfield<DemuxScHevcIndex> scHevcIndexMask;
+ } indexMask;
+};
+
+/**
+ * Bits Settings for Section Filter.
*/
struct DemuxFilterSectionBits {
- /* The bytes are configured for Section Filter */
+ /**
+ * The bytes are configured for Section Filter
+ */
vec<uint8_t> filter;
- /* Active bits in the configured bytes to be used for filtering */
+
+ /**
+ * Active bits in the configured bytes to be used for filtering
+ */
vec<uint8_t> mask;
- /*
+
+ /**
* Do positive match at the bit position of the configured bytes when the
* bit at same position of the mode is 0.
* Do negative match at the bit position of the configured bytes when the
@@ -1338,45 +2078,56 @@
* Filter Settings for Section data according to ISO/IEC 13818-1.
*/
struct DemuxFilterSectionSettings {
- DemuxTpid tpid;
- DemuxFilterSectionBits bits;
- /* Table ID for Section Filter */
- uint16_t tableId;
- /* Version number for Section Filter */
- uint16_t version;
- /* true if the filter checks CRC and discards data with wrong CRC */
+ safe_union Condition {
+ DemuxFilterSectionBits sectionBits;
+
+ struct TableInfo {
+ /**
+ * Table ID for Section Filter
+ */
+ uint16_t tableId;
+
+ /**
+ * Version number for Section Filter
+ */
+ uint16_t version;
+ } tableInfo;
+ } condition;
+
+ /**
+ * true if the filter checks CRC and discards data with wrong CRC
+ */
bool isCheckCrc;
- /* true if the filter repeats the data with the same version */
+
+ /**
+ * true if the filter repeats the data with the same version
+ */
bool isRepeat;
- /* true if the filter output raw data */
+
+ /**
+ * true if the filter send onFilterStatus instead of onFilterEvent.
+ */
bool isRaw;
};
-/* Stream ID is used to specify one elementary stream */
typedef uint16_t DemuxStreamId;
/**
* Filter Settings for a PES Data.
*/
struct DemuxFilterPesDataSettings {
- DemuxTpid tpid;
DemuxStreamId streamId;
- /* true if the filter output raw data */
+
+ /**
+ * true if the filter send onFilterStatus instead of onFilterEvent.
+ */
bool isRaw;
};
/**
- * Filter Settings for a TS Data.
+ * Filter Settings for a Video and Audio.
*/
-struct DemuxFilterTsSettings {
- DemuxTpid tpid;
-};
-
-/**
- * Filter Settings for a Audio.
- */
-struct DemuxFilterAudioSettings {
- DemuxTpid tpid;
+struct DemuxFilterAvSettings {
/**
* true if the filter output goes to decoder directly in pass through mode.
*/
@@ -1384,107 +2135,181 @@
};
/**
- * Filter Settings for a Video.
+ * Filter Settings for a Download.
*/
-struct DemuxFilterVideoSettings {
+struct DemuxFilterDownloadSettings {
+ uint32_t downloadId;
+};
+
+/**
+ * IP Settings for a IP filter.
+ */
+struct DemuxIpAddress {
+ safe_union SrcIpAddress {
+ uint8_t[4] v4;
+
+ uint8_t[16] v6;
+ } srcIpAddress;
+
+ safe_union DstIpAddress {
+ uint8_t[4] v4;
+
+ uint8_t[16] v6;
+ } dstIpAddress;
+
+ uint16_t srcPort;
+
+ uint16_t dstPort;
+};
+
+/**
+ * Filter Settings for a TS filter.
+ */
+struct DemuxTsFilterSettings {
DemuxTpid tpid;
+
+ safe_union FilterSettings {
+ /**
+ * Not additional parameters. it's used by PCR, TS subtype filters.
+ */
+ Monostate noinit;
+
+ DemuxFilterSectionSettings section;
+
+ DemuxFilterAvSettings av;
+
+ DemuxFilterPesDataSettings pesData;
+
+ DemuxFilterRecordSettings record;
+ } filterSettings;
+};
+
+/**
+ * Filter Settings for a MMTP filter.
+ */
+struct DemuxMmtpFilterSettings {
+ DemuxMmtpPid mmtpPid;
+
+ safe_union FilterSettings {
+ /**
+ * Not additional parameters. it's used by MMTP subtype filters.
+ */
+ Monostate noinit;
+
+ DemuxFilterSectionSettings section;
+
+ DemuxFilterAvSettings av;
+
+ DemuxFilterPesDataSettings pesData;
+
+ DemuxFilterRecordSettings record;
+
+ DemuxFilterDownloadSettings download;
+ } filterSettings;
+};
+
+/**
+ * Filter Settings for a IP filter.
+ */
+struct DemuxIpFilterSettings {
+ DemuxIpAddress ipAddr;
+
+ safe_union FilterSettings {
+ /**
+ * Not additional parameters. it's used by NTP, IP_PAYLOAD,
+ * PAYLOAD_THROUGH subtype filters.
+ */
+ Monostate noinit;
+
+ DemuxFilterSectionSettings section;
+
+ DemuxFilterPesDataSettings pesData;
+
+ /**
+ * true if the data from IP subtype go to next filter directly
+ */
+ bool bPassthrough;
+ } filterSettings;
+};
+
+/**
+ * Filter Settings for a TLV filter.
+ */
+struct DemuxTlvFilterSettings {
+ uint8_t packetType;
+
/**
- * true if the filter output goes to decoder directly in pass through mode.
+ * true if the filtered data is commpressed ip packet
*/
- bool isPassthrough;
+ bool bIsCompressedIpPacket;
+
+ safe_union FilterSettings {
+ /**
+ * Not additional parameters. it's used by PAYLOAD_THROUGH subtype
+ * filters.
+ */
+ Monostate noinit;
+
+ DemuxFilterSectionSettings section;
+
+ /**
+ * true if the data from TLV subtype go to next filter directly
+ */
+ bool bPassthrough;
+ } filterSettings;
};
/**
- * Filter Settings for a PCR (Program Clock Reference).
- */
-struct DemuxFilterPcrSettings {
- DemuxTpid tpid;
-};
-
-/**
- * Indexes can be tagged through TS (Transport Stream) header.
+ * ALP Length Type
*/
@export
-enum DemuxTsIndex : uint32_t {
- FIRST_PACKET = 1 << 0,
- PAYLOAD_UNIT_START_INDICATOR = 1 << 1,
- CHANGE_TO_NOT_SCRAMBLED = 1 << 2,
- CHANGE_TO_EVEN_SCRAMBLED = 1 << 3,
- CHANGE_TO_ODD_SCRAMBLED = 1 << 4,
- DISCONTINUITY_INDICATOR = 1 << 5,
- RANDOM_ACCESS_INDICATOR = 1 << 6,
- PRIORITY_INDICATOR = 1 << 7,
- PCR_FLAG = 1 << 8,
- OPCR_FLAG = 1 << 9,
- SPLICING_POINT_FLAG = 1 << 10,
- PRIVATE_DATA = 1 << 11,
- ADAPTATION_EXTENSION_FLAG = 1 << 12,
+enum DemuxAlpLengthType : uint8_t {
+ UNDEFINED = 0,
+ /**
+ * Length does NOT include additional header. Used in US region.
+ */
+ WITHOUT_ADDITIONAL_HEADER,
+ /**
+ * Length includes additional header. Used in Korea region.
+ */
+ WITH_ADDITIONAL_HEADER,
};
/**
- * A mask of TS indexes
- *
- * It's a combination of TS indexes.
+ * Filter Settings for a ALP filter.
*/
-typedef bitfield<DemuxTsIndex> DemuxTsIndexMask;
+struct DemuxAlpFilterSettings {
+ /**
+ * 0: IpV4, 2:Compressed Ip, 4:Signaling.
+ */
+ uint8_t packetType;
-/**
- * Indexes can be tagged by Start Code in PES (Packetized Elementary Stream)
- * according to ISO/IEC 13818-1.
- */
-@export
-enum DemuxScIndex : uint32_t {
- /* Start Code is for a new I Frame */
- I_FRAME = 1 << 0,
- /* Start Code is for a new P Frame */
- P_FRAME = 1 << 1,
- /* Start Code is for a new B Frame */
- B_FRAME = 1 << 2,
- /* Start Code is for a new Sequence */
- SEQUENCE = 1 << 3,
-};
+ DemuxAlpLengthType lengthType;
-/**
- * A mask of Start Code Indexes
- *
- * It's a combination of Start Code Indexes.
- */
-typedef bitfield<DemuxScIndex> DemuxScIndexMask;
+ safe_union FilterSettings {
+ /**
+ * Not additional parameters. it's used by PTP, PAYLOAD_THROUGH subtype
+ * filters.
+ */
+ Monostate noinit;
-/* Index type to be used in the filter for record */
-@export
-enum DemuxRecordIndexType : uint32_t {
- /* Don't use index */
- NONE,
- /* Use TS index */
- TS,
- /* Use Start Code index */
- SC,
-};
-
-/**
- * Filter Settings for Record data.
- */
-struct DemuxFilterRecordSettings {
- DemuxTpid tpid;
- DemuxRecordIndexType indexType;
- safe_union IndexMask {
- DemuxTsIndexMask tsIndexMask;
- DemuxScIndexMask scIndexMask;
- } indexMask;
+ DemuxFilterSectionSettings section;
+ } filterSettings;
};
/**
* Filter Settings.
*/
safe_union DemuxFilterSettings {
- DemuxFilterSectionSettings section;
- DemuxFilterPesDataSettings pesData;
- DemuxFilterTsSettings ts;
- DemuxFilterAudioSettings audio;
- DemuxFilterVideoSettings video;
- DemuxFilterPcrSettings pcr;
- DemuxFilterRecordSettings record;
+ DemuxTsFilterSettings ts;
+
+ DemuxMmtpFilterSettings mmtp;
+
+ DemuxIpFilterSettings ip;
+
+ DemuxTlvFilterSettings tlv;
+
+ DemuxAlpFilterSettings alp;
};
/**
@@ -1493,38 +2318,106 @@
*/
@export
enum DemuxQueueNotifyBits : uint32_t {
- /* client writes data and notify HAL the data is ready. */
+ /**
+ * client writes data and notify HAL the data is ready.
+ */
DATA_READY = 1 << 0,
- /* client reads data and notify HAL the data is consumed. */
- DATA_CONSUMED = 1 << 1
+ /**
+ * client reads data and notify HAL the data is consumed.
+ */
+ DATA_CONSUMED = 1 << 1,
};
/**
* Filter Event for Section Filter.
*/
struct DemuxFilterSectionEvent {
- /* Table ID of filtered data */
+ /**
+ * Table ID of filtered data
+ */
uint16_t tableId;
- /* Version number of filtered data */
+
+ /**
+ * Version number of filtered data
+ */
uint16_t version;
- /* Section number of filtered data */
+
+ /**
+ * Section number of filtered data
+ */
uint16_t sectionNum;
- /* Data size in bytes of filtered data */
+
+ /**
+ * Data size in bytes of filtered data
+ */
uint16_t dataLength;
};
/**
+ * Extra Meta Data from AD (Audio Descriptor) according to
+ * ETSI TS 101 154 V2.1.1.
+ */
+struct AudioExtraMetaData {
+ uint8_t adFade;
+
+ uint8_t adPan;
+
+ uint8_t versionTextTag;
+
+ uint8_t adGainCenter;
+
+ uint8_t adGainFront;
+
+ uint8_t adGainSurround;
+};
+
+/**
* Filter Event for Audio or Video Filter.
*/
struct DemuxFilterMediaEvent {
- /* Presentation Time Stamp for audio or video frame. It based on 90KHz has
+ DemuxStreamId streamId;
+
+ /**
+ * true if PTS is present in PES header.
+ */
+ bool isPtsPresent;
+
+ /**
+ * Presentation Time Stamp for audio or video frame. It based on 90KHz has
* the same format as PTS (Presentation Time Stamp).
*/
uint64_t pts;
- /* Data size in bytes of audio or video frame */
- uint16_t dataLength;
- /* A handle associated to the memory where audio or video data stays. */
- handle secureMemory;
+
+ /**
+ * Data size in bytes of audio or video frame
+ */
+ uint32_t dataLength;
+
+ /**
+ * A handle associated to the memory where audio or video data stays.
+ */
+ handle avMemory;
+
+ /**
+ * True if the avMemory is in secure area, and isn't mappable.
+ */
+ bool isSecureMemory;
+
+ /**
+ * MPU sequence number of filtered data (only for MMTP)
+ */
+ uint32_t mpuSequenceNumber;
+
+ bool isPesPrivateData;
+
+ safe_union ExtraMetaData {
+ /**
+ * Not additional parameters. it's used for video.
+ */
+ Monostate noinit;
+
+ AudioExtraMetaData audio;
+ } extraMetaData;
};
/**
@@ -1532,176 +2425,309 @@
*/
struct DemuxFilterPesEvent {
DemuxStreamId streamId;
- /* Data size in bytes of PES data */
+
+ /**
+ * Data size in bytes of PES data
+ */
+ uint16_t dataLength;
+
+ /**
+ * MPU sequence number of filtered data (only for MMTP)
+ */
+ uint32_t mpuSequenceNumber;
+};
+
+/**
+ * Filter Event for TS Record data.
+ */
+struct DemuxFilterTsRecordEvent {
+ DemuxPid pid;
+
+ /**
+ * Indexes of record output
+ */
+ safe_union IndexMask {
+ bitfield<DemuxTsIndex> tsIndexMask;
+
+ bitfield<DemuxScIndex> scIndexMask;
+
+ bitfield<DemuxScHevcIndex> scHevcIndexMask;
+ } indexMask;
+
+ /**
+ * Byte number from beginning of the filter's output
+ */
+ uint64_t byteNumber;
+};
+
+/**
+ * Filter Event for MMTP Record data.
+ */
+struct DemuxFilterMmtpRecordEvent {
+ bitfield<DemuxScHevcIndex> scHevcIndexMask;
+
+ /**
+ * Byte number from beginning of the filter's output
+ */
+ uint64_t byteNumber;
+};
+
+/**
+ * Filter Event for Download data.
+ */
+struct DemuxFilterDownloadEvent {
+ uint32_t itemId;
+
+ /**
+ * MPU sequence number of filtered data (only for MMTP)
+ */
+ uint32_t mpuSequenceNumber;
+
+ uint32_t itemFragmentIndex;
+
+ uint32_t lastItemFragmentIndex;
+
+ /**
+ * Data size in bytes of filtered data
+ */
uint16_t dataLength;
};
/**
- * Filter Event for Record data.
+ * Filter Event for IP payload data.
*/
-struct DemuxFilterRecordEvent {
- DemuxTpid tpid;
- /* Indexes of record output */
- safe_union IndexMask {
- DemuxTsIndexMask tsIndexMask;
- DemuxScIndexMask scIndexMask;
- } indexMask;
- /* Packet number from beginning of the filter's output */
- uint64_t packetNum;
+struct DemuxFilterIpPayloadEvent {
+ /**
+ * Data size in bytes of IP data
+ */
+ uint16_t dataLength;
};
/**
* Filter Event.
*/
struct DemuxFilterEvent {
- DemuxFilterId filterId;
- DemuxFilterType filterType;
safe_union Event {
DemuxFilterSectionEvent section;
+
DemuxFilterMediaEvent media;
+
DemuxFilterPesEvent pes;
- DemuxFilterRecordEvent ts;
+
+ DemuxFilterTsRecordEvent tsRecord;
+
+ DemuxFilterMmtpRecordEvent mmtpRecord;
+
+ DemuxFilterDownloadEvent download;
+
+ DemuxFilterIpPayloadEvent ipPayload;
};
- /* An array of events */
+
+ /**
+ * An array of events
+ */
vec<Event> events;
};
-/**
- * A hardware resource ID to be used for audio and video hardware sync.
- */
typedef uint32_t AvSyncHwId;
-/**
- * A token to be used to link descrambler and key slot. It's opaque to
- * framework and apps.
- */
typedef vec<uint8_t> TunerKeyToken;
/**
* A data format in demux's output or input according to ISO/IEC 13818-1.
*/
@export
-enum DemuxDataFormat : uint32_t {
- /* Data is Transport Stream. */
+enum DataFormat : uint32_t {
+ /**
+ * Data is Transport Stream.
+ */
TS,
- /* Data is Packetized Elementary Stream. */
+ /**
+ * Data is Packetized Elementary Stream.
+ */
PES,
- /* Data is Elementary Stream. */
+ /**
+ * Data is Elementary Stream.
+ */
ES,
- /* Data is TLV (type-length-value) Stream for JP SHV */
+ /**
+ * Data is TLV (type-length-value) Stream for JP SHV
+ */
SHV_TLV,
};
-/**
- * A status of the demux's output.
- */
-typedef DemuxFilterStatus DemuxOutputStatus;
+typedef DemuxFilterStatus RecordStatus;
/**
- * The Settings for the demux's output.
+ * The Settings for the record in DVR.
*/
-struct DemuxOutputSettings {
+struct RecordSettings {
/**
* Register for interested status events so that the HAL can send these
* status events back to client.
*/
- bitfield<DemuxOutputStatus> statusMask;
+ bitfield<RecordStatus> statusMask;
+
/**
- * Unconsumed data size in bytes in the output. The HAL uses it to trigger
- * DemuxOutputStatus::LOW_WATER.
+ * Unconsumed data size in bytes in the record. The HAL uses it to trigger
+ * OutputStatus::LOW_WATER.
*/
uint32_t lowThreshold;
+
/**
- * Unconsumed data size in bytes in the output. The HAL uses it to trigger
- * DemuxOutputStatus::High_WATER.
+ * Unconsumed data size in bytes in the record. The HAL uses it to trigger
+ * OutputStatus::High_WATER.
*/
uint32_t highThreshold;
+
/**
- * The data format in the output.
+ * The data format in the record.
*/
- DemuxDataFormat dataFormat;
+ DataFormat dataFormat;
+
/**
- * The packet size in bytes in the output.
+ * The packet size in bytes in the record.
*/
uint8_t packetSize;
};
/**
- * A status of the demux's input.
+ * A status of the playback in DVR.
*/
@export
-enum DemuxInputStatus : uint32_t {
+enum PlaybackStatus : uint32_t {
/**
- * The space of the demux's input is empty.
+ * The space of the demux's playback is empty.
*/
- SPACE_EMPTY = 1 << 0,
+ SPACE_EMPTY = 1 << 0,
/**
- * The spece of the demux's input is almost empty.
+ * The spece of the demux's playback is almost empty.
*/
SPACE_ALMOST_EMPTY = 1 << 1,
/**
- * The space of the demux's input is almost full.
+ * The space of the demux's playback is almost full.
*/
- SPACE_ALMOST_FULL = 1 << 2,
+ SPACE_ALMOST_FULL = 1 << 2,
/**
- * The space of the demux's input is full.
+ * The space of the demux's playback is full.
*/
- SPACE_FULL = 1 << 3,
+ SPACE_FULL = 1 << 3,
};
/**
- * The Settings for the demux's input.
+ * The Setting for the playback in DVR.
*/
-@export
-struct DemuxInputSettings {
+struct PlaybackSettings {
/**
* Register for interested status events so that the HAL can send these
* status events back to client.
*/
- bitfield<DemuxInputStatus> statusMask;
+ bitfield<PlaybackStatus> statusMask;
+
/**
- * Unused space size in bytes in the input. The HAL uses it to trigger
- * DemuxInputStatus::SPACE_ALMOST_EMPTY.
+ * Unused space size in bytes in the playback. The HAL uses it to trigger
+ * InputStatus::SPACE_ALMOST_EMPTY.
*/
uint32_t lowThreshold;
+
/**
- * Unused space size in bytes in the input. The HAL uses it to trigger
- * DemuxInputStatus::SPACE_ALMOST_FULL.
+ * Unused space size in bytes in the playback. The HAL uses it to trigger
+ * InputStatus::SPACE_ALMOST_FULL.
*/
uint32_t highThreshold;
+
/**
- * The data format in the input.
+ * The data format in the playback.
*/
- DemuxDataFormat dataFormat;
+ DataFormat dataFormat;
+
/**
- * The packet size in bytes in the input.
+ * The packet size in bytes in the playback.
*/
uint8_t packetSize;
};
/**
+ * The type of DVR.
+ */
+@export
+enum DvrType : uint8_t {
+ RECORD,
+ PLAYBACK,
+};
+
+/**
+ * The Setting for DVR.
+ */
+safe_union DvrSettings {
+ RecordSettings record;
+
+ PlaybackSettings playback;
+};
+
+/**
* Capabilities for Demux.
*/
-@export
struct DemuxCapabilities {
- /* The number of Demux to be supported. */
+ /**
+ * The number of Demux to be supported.
+ */
uint32_t numDemux;
- /* The number of Input to be supported. */
- uint32_t numInput;
- /* The number of Output to be supported. */
- uint32_t numOutput;
- /* The number of TS Filter to be supported. */
+
+ /**
+ * The number of record to be supported.
+ */
+ uint32_t numRecord;
+
+ /**
+ * The number of playback to be supported.
+ */
+ uint32_t numPlayback;
+
+ /**
+ * The number of TS Filter to be supported.
+ */
uint32_t numTsFilter;
- /* The number of Section Filter to be supported. */
+
+ /**
+ * The number of Section Filter to be supported.
+ */
uint32_t numSectionFilter;
- /* The number of Audio Filter to be supported. */
+
+ /**
+ * The number of Audio Filter to be supported.
+ */
uint32_t numAudioFilter;
- /* The number of Video Filter to be supported. */
+
+ /**
+ * The number of Video Filter to be supported.
+ */
uint32_t numVideoFilter;
- /* The number of PES Filter to be supported. */
+
+ /**
+ * The number of PES Filter to be supported.
+ */
uint32_t numPesFilter;
- /* The number of PCR Filter to be supported. */
+
+ /**
+ * The number of PCR Filter to be supported.
+ */
uint32_t numPcrFilter;
- /* The maximum number of bytes is supported in the mask of Section Filter. */
+
+ /**
+ * The maximum number of bytes is supported in the mask of Section Filter.
+ */
uint32_t numBytesInSectionFilter;
+
+ bitfield<DemuxFilterMainType> filterCaps;
+
+ /**
+ * The array has same elements as DemuxFilterMainType. linkCaps[i] presents
+ * filter's capability as soource for the ith type in DemuxFilterMainType.
+ * The jth bit of linkCaps[i] is 1 if the output of ith type filter can be
+ * data source for the filter type j.
+ */
+ vec<bitfield<DemuxFilterMainType>> linkCaps;
+
+ bool bTimeFilter;
};
diff --git a/tv/tuner/1.0/vts/functional/VtsHalTvTunerV1_0TargetTest.cpp b/tv/tuner/1.0/vts/functional/VtsHalTvTunerV1_0TargetTest.cpp
index 7936185..c666226 100644
--- a/tv/tuner/1.0/vts/functional/VtsHalTvTunerV1_0TargetTest.cpp
+++ b/tv/tuner/1.0/vts/functional/VtsHalTvTunerV1_0TargetTest.cpp
@@ -20,8 +20,11 @@
#include <VtsHalHidlTargetTestEnvBase.h>
#include <android-base/logging.h>
#include <android/hardware/tv/tuner/1.0/IDemux.h>
-#include <android/hardware/tv/tuner/1.0/IDemuxCallback.h>
#include <android/hardware/tv/tuner/1.0/IDescrambler.h>
+#include <android/hardware/tv/tuner/1.0/IDvr.h>
+#include <android/hardware/tv/tuner/1.0/IDvrCallback.h>
+#include <android/hardware/tv/tuner/1.0/IFilter.h>
+#include <android/hardware/tv/tuner/1.0/IFilterCallback.h>
#include <android/hardware/tv/tuner/1.0/IFrontend.h>
#include <android/hardware/tv/tuner/1.0/IFrontendCallback.h>
#include <android/hardware/tv/tuner/1.0/ITuner.h>
@@ -57,8 +60,9 @@
using android::hardware::MQDescriptorSync;
using android::hardware::Return;
using android::hardware::Void;
-using android::hardware::tv::tuner::V1_0::DemuxDataFormat;
+using android::hardware::tv::tuner::V1_0::DataFormat;
using android::hardware::tv::tuner::V1_0::DemuxFilterEvent;
+using android::hardware::tv::tuner::V1_0::DemuxFilterMainType;
using android::hardware::tv::tuner::V1_0::DemuxFilterPesDataSettings;
using android::hardware::tv::tuner::V1_0::DemuxFilterPesEvent;
using android::hardware::tv::tuner::V1_0::DemuxFilterSectionEvent;
@@ -66,10 +70,11 @@
using android::hardware::tv::tuner::V1_0::DemuxFilterSettings;
using android::hardware::tv::tuner::V1_0::DemuxFilterStatus;
using android::hardware::tv::tuner::V1_0::DemuxFilterType;
-using android::hardware::tv::tuner::V1_0::DemuxInputSettings;
-using android::hardware::tv::tuner::V1_0::DemuxInputStatus;
-using android::hardware::tv::tuner::V1_0::DemuxOutputStatus;
using android::hardware::tv::tuner::V1_0::DemuxQueueNotifyBits;
+using android::hardware::tv::tuner::V1_0::DemuxTsFilterSettings;
+using android::hardware::tv::tuner::V1_0::DemuxTsFilterType;
+using android::hardware::tv::tuner::V1_0::DvrSettings;
+using android::hardware::tv::tuner::V1_0::DvrType;
using android::hardware::tv::tuner::V1_0::FrontendAtscModulation;
using android::hardware::tv::tuner::V1_0::FrontendAtscSettings;
using android::hardware::tv::tuner::V1_0::FrontendDvbtSettings;
@@ -80,11 +85,17 @@
using android::hardware::tv::tuner::V1_0::FrontendScanMessageType;
using android::hardware::tv::tuner::V1_0::FrontendSettings;
using android::hardware::tv::tuner::V1_0::IDemux;
-using android::hardware::tv::tuner::V1_0::IDemuxCallback;
using android::hardware::tv::tuner::V1_0::IDescrambler;
+using android::hardware::tv::tuner::V1_0::IDvr;
+using android::hardware::tv::tuner::V1_0::IDvrCallback;
+using android::hardware::tv::tuner::V1_0::IFilter;
+using android::hardware::tv::tuner::V1_0::IFilterCallback;
using android::hardware::tv::tuner::V1_0::IFrontend;
using android::hardware::tv::tuner::V1_0::IFrontendCallback;
using android::hardware::tv::tuner::V1_0::ITuner;
+using android::hardware::tv::tuner::V1_0::PlaybackSettings;
+using android::hardware::tv::tuner::V1_0::PlaybackStatus;
+using android::hardware::tv::tuner::V1_0::RecordStatus;
using android::hardware::tv::tuner::V1_0::Result;
namespace {
@@ -131,17 +142,28 @@
0x73, 0x63, 0x65, 0x6e, 0x65,
};
-const uint16_t FMQ_SIZE_4K = 0x1000;
+// const uint16_t FMQ_SIZE_4K = 0x1000;
const uint32_t FMQ_SIZE_1M = 0x100000;
+const uint32_t FMQ_SIZE_16M = 0x1000000;
struct FilterConf {
DemuxFilterType type;
DemuxFilterSettings setting;
};
-struct InputConf {
+enum FilterEventType : uint8_t {
+ UNDEFINED,
+ SECTION,
+ MEDIA,
+ PES,
+ RECORD,
+ MMTPRECORD,
+ DOWNLOAD,
+};
+
+struct PlaybackConf {
string inputDataFile;
- DemuxInputSettings setting;
+ PlaybackSettings setting;
};
class FrontendCallback : public IFrontendCallback {
@@ -154,14 +176,6 @@
return Void();
}
- virtual Return<void> onDiseqcMessage(const hidl_vec<uint8_t>& diseqcMessage) override {
- android::Mutex::Autolock autoLock(mMsgLock);
- mDiseqcMessageReceived = true;
- mEventMessage = diseqcMessage;
- mMsgCondition.signal();
- return Void();
- }
-
virtual Return<void> onScanMessage(FrontendScanMessageType /* type */,
const FrontendScanMessage& /* message */) override {
android::Mutex::Autolock autoLock(mMsgLock);
@@ -211,14 +225,14 @@
}
}
-class DemuxCallback : public IDemuxCallback {
+class FilterCallback : public IFilterCallback {
public:
virtual Return<void> onFilterEvent(const DemuxFilterEvent& filterEvent) override {
android::Mutex::Autolock autoLock(mMsgLock);
// Temprarily we treat the first coming back filter data on the matching pid a success
// once all of the MQ are cleared, means we got all the expected output
- mFilterIdToEvent[filterEvent.filterId] = filterEvent;
- readFilterEventData(filterEvent.filterId);
+ mFilterIdToEvent = filterEvent;
+ readFilterEventData();
mPidFilterOutputCount++;
// mFilterIdToMQ.erase(filterEvent.filterId);
@@ -227,96 +241,50 @@
return Void();
}
- virtual Return<void> onFilterStatus(uint32_t /*filterId*/,
- const DemuxFilterStatus /*status*/) override {
+ virtual Return<void> onFilterStatus(const DemuxFilterStatus /*status*/) override {
return Void();
}
- virtual Return<void> onOutputStatus(DemuxOutputStatus /*status*/) override { return Void(); }
+ void setFilterId(uint32_t filterId) { mFilterId = filterId; }
+ void setFilterEventType(FilterEventType type) { mFilterEventType = type; }
- virtual Return<void> onInputStatus(DemuxInputStatus status) override {
- // android::Mutex::Autolock autoLock(mMsgLock);
- ALOGW("[vts] input status %d", status);
- switch (status) {
- case DemuxInputStatus::SPACE_EMPTY:
- case DemuxInputStatus::SPACE_ALMOST_EMPTY:
- ALOGW("[vts] keep inputing %d", status);
- mKeepWritingInputFMQ = true;
- break;
- case DemuxInputStatus::SPACE_ALMOST_FULL:
- case DemuxInputStatus::SPACE_FULL:
- ALOGW("[vts] stop inputing %d", status);
- mKeepWritingInputFMQ = false;
- break;
- }
- return Void();
- }
-
- void testOnFilterEvent(uint32_t filterId);
void testFilterDataOutput();
- void stopInputThread();
- void startPlaybackInputThread(InputConf inputConf, MQDesc& inputMQDescriptor);
void startFilterEventThread(DemuxFilterEvent event);
- static void* __threadLoopInput(void* threadArgs);
static void* __threadLoopFilter(void* threadArgs);
- void inputThreadLoop(InputConf* inputConf, bool* keepWritingInputFMQ);
void filterThreadLoop(DemuxFilterEvent& event);
- void updateFilterMQ(uint32_t filterId, MQDesc& filterMQDescriptor);
- void updateGoldenOutputMap(uint32_t filterId, string goldenOutputFile);
- bool readFilterEventData(uint32_t filterId);
+ void updateFilterMQ(MQDesc& filterMQDescriptor);
+ void updateGoldenOutputMap(string goldenOutputFile);
+ bool readFilterEventData();
private:
- struct InputThreadArgs {
- DemuxCallback* user;
- InputConf* inputConf;
- bool* keepWritingInputFMQ;
- };
struct FilterThreadArgs {
- DemuxCallback* user;
+ FilterCallback* user;
DemuxFilterEvent event;
};
uint16_t mDataLength = 0;
std::vector<uint8_t> mDataOutputBuffer;
- bool mFilterEventReceived;
- std::map<uint32_t, string> mFilterIdToGoldenOutput;
+ string mFilterIdToGoldenOutput;
- std::map<uint32_t, std::unique_ptr<FilterMQ>> mFilterIdToMQ;
- std::unique_ptr<FilterMQ> mInputMQ;
- std::map<uint32_t, EventFlag*> mFilterIdToMQEventFlag;
- std::map<uint32_t, DemuxFilterEvent> mFilterIdToEvent;
- EventFlag* mInputMQEventFlag;
+ uint32_t mFilterId;
+ FilterEventType mFilterEventType;
+ std::unique_ptr<FilterMQ> mFilterIdToMQ;
+ EventFlag* mFilterIdToMQEventFlag;
+ DemuxFilterEvent mFilterIdToEvent;
android::Mutex mMsgLock;
android::Mutex mFilterOutputLock;
- android::Mutex mInputThreadLock;
android::Condition mMsgCondition;
android::Condition mFilterOutputCondition;
- bool mKeepWritingInputFMQ = true;
- bool mInputThreadRunning;
- pthread_t mInputThread;
pthread_t mFilterThread;
int mPidFilterOutputCount = 0;
};
-void DemuxCallback::startPlaybackInputThread(InputConf inputConf, MQDesc& inputMQDescriptor) {
- mInputMQ = std::make_unique<FilterMQ>(inputMQDescriptor, true /* resetPointers */);
- EXPECT_TRUE(mInputMQ);
- struct InputThreadArgs* threadArgs =
- (struct InputThreadArgs*)malloc(sizeof(struct InputThreadArgs));
- threadArgs->user = this;
- threadArgs->inputConf = &inputConf;
- threadArgs->keepWritingInputFMQ = &mKeepWritingInputFMQ;
-
- pthread_create(&mInputThread, NULL, __threadLoopInput, (void*)threadArgs);
- pthread_setname_np(mInputThread, "test_playback_input_loop");
-}
-
-void DemuxCallback::startFilterEventThread(DemuxFilterEvent event) {
+void FilterCallback::startFilterEventThread(DemuxFilterEvent event) {
struct FilterThreadArgs* threadArgs =
(struct FilterThreadArgs*)malloc(sizeof(struct FilterThreadArgs));
threadArgs->user = this;
@@ -326,7 +294,7 @@
pthread_setname_np(mFilterThread, "test_playback_input_loop");
}
-void DemuxCallback::testFilterDataOutput() {
+void FilterCallback::testFilterDataOutput() {
android::Mutex::Autolock autoLock(mMsgLock);
while (mPidFilterOutputCount < 1) {
if (-ETIMEDOUT == mMsgCondition.waitRelative(mMsgLock, WAIT_TIMEOUT)) {
@@ -338,95 +306,25 @@
ALOGW("[vts] pass and stop");
}
-void DemuxCallback::stopInputThread() {
- mInputThreadRunning = false;
- mKeepWritingInputFMQ = false;
-
- android::Mutex::Autolock autoLock(mInputThreadLock);
+void FilterCallback::updateFilterMQ(MQDesc& filterMQDescriptor) {
+ mFilterIdToMQ = std::make_unique<FilterMQ>(filterMQDescriptor, true /* resetPointers */);
+ EXPECT_TRUE(mFilterIdToMQ);
+ EXPECT_TRUE(EventFlag::createEventFlag(mFilterIdToMQ->getEventFlagWord(),
+ &mFilterIdToMQEventFlag) == android::OK);
}
-void DemuxCallback::updateFilterMQ(uint32_t filterId, MQDesc& filterMQDescriptor) {
- mFilterIdToMQ[filterId] =
- std::make_unique<FilterMQ>(filterMQDescriptor, true /* resetPointers */);
- EXPECT_TRUE(mFilterIdToMQ[filterId]);
- EXPECT_TRUE(EventFlag::createEventFlag(mFilterIdToMQ[filterId]->getEventFlagWord(),
- &mFilterIdToMQEventFlag[filterId]) == android::OK);
+void FilterCallback::updateGoldenOutputMap(string goldenOutputFile) {
+ mFilterIdToGoldenOutput = goldenOutputFile;
}
-void DemuxCallback::updateGoldenOutputMap(uint32_t filterId, string goldenOutputFile) {
- mFilterIdToGoldenOutput[filterId] = goldenOutputFile;
-}
-
-void* DemuxCallback::__threadLoopInput(void* threadArgs) {
- DemuxCallback* const self =
- static_cast<DemuxCallback*>(((struct InputThreadArgs*)threadArgs)->user);
- self->inputThreadLoop(((struct InputThreadArgs*)threadArgs)->inputConf,
- ((struct InputThreadArgs*)threadArgs)->keepWritingInputFMQ);
- return 0;
-}
-
-void DemuxCallback::inputThreadLoop(InputConf* inputConf, bool* keepWritingInputFMQ) {
- android::Mutex::Autolock autoLock(mInputThreadLock);
- mInputThreadRunning = true;
-
- // Create the EventFlag that is used to signal the HAL impl that data have been
- // written into the Input FMQ
- EventFlag* inputMQEventFlag;
- EXPECT_TRUE(EventFlag::createEventFlag(mInputMQ->getEventFlagWord(), &inputMQEventFlag) ==
- android::OK);
-
- // open the stream and get its length
- std::ifstream inputData(inputConf->inputDataFile, std::ifstream::binary);
- int writeSize = inputConf->setting.packetSize * 6;
- char* buffer = new char[writeSize];
- ALOGW("[vts] input thread loop start %s", inputConf->inputDataFile.c_str());
- if (!inputData.is_open()) {
- mInputThreadRunning = false;
- ALOGW("[vts] Error %s", strerror(errno));
- }
-
- while (mInputThreadRunning) {
- // move the stream pointer for packet size * 6 every read until the end
- while (*keepWritingInputFMQ) {
- inputData.read(buffer, writeSize);
- if (!inputData) {
- int leftSize = inputData.gcount();
- if (leftSize == 0) {
- mInputThreadRunning = false;
- break;
- }
- inputData.clear();
- inputData.read(buffer, leftSize);
- // Write the left over of the input data and quit the thread
- if (leftSize > 0) {
- EXPECT_TRUE(mInputMQ->write((unsigned char*)&buffer[0], leftSize));
- inputMQEventFlag->wake(static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_READY));
- }
- mInputThreadRunning = false;
- break;
- }
- // Write input FMQ and notify the Tuner Implementation
- EXPECT_TRUE(mInputMQ->write((unsigned char*)&buffer[0], writeSize));
- inputMQEventFlag->wake(static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_READY));
- inputData.seekg(writeSize, inputData.cur);
- sleep(1);
- }
- }
-
- ALOGW("[vts] Input thread end.");
-
- delete[] buffer;
- inputData.close();
-}
-
-void* DemuxCallback::__threadLoopFilter(void* threadArgs) {
- DemuxCallback* const self =
- static_cast<DemuxCallback*>(((struct FilterThreadArgs*)threadArgs)->user);
+void* FilterCallback::__threadLoopFilter(void* threadArgs) {
+ FilterCallback* const self =
+ static_cast<FilterCallback*>(((struct FilterThreadArgs*)threadArgs)->user);
self->filterThreadLoop(((struct FilterThreadArgs*)threadArgs)->event);
return 0;
}
-void DemuxCallback::filterThreadLoop(DemuxFilterEvent& /* event */) {
+void FilterCallback::filterThreadLoop(DemuxFilterEvent& /* event */) {
android::Mutex::Autolock autoLock(mFilterOutputLock);
// Read from mFilterIdToMQ[event.filterId] per event and filter type
@@ -439,30 +337,184 @@
// end thread
}
-bool DemuxCallback::readFilterEventData(uint32_t filterId) {
+bool FilterCallback::readFilterEventData() {
bool result = false;
- DemuxFilterEvent filterEvent = mFilterIdToEvent[filterId];
- ALOGW("[vts] reading from filter FMQ %d", filterId);
+ DemuxFilterEvent filterEvent = mFilterIdToEvent;
+ ALOGW("[vts] reading from filter FMQ %d", mFilterId);
// todo separate filter handlers
for (int i = 0; i < filterEvent.events.size(); i++) {
- DemuxFilterPesEvent event = filterEvent.events[i].pes();
- mDataLength = event.dataLength;
+ switch (mFilterEventType) {
+ case FilterEventType::SECTION:
+ mDataLength = filterEvent.events[i].section().dataLength;
+ break;
+ case FilterEventType::PES:
+ mDataLength = filterEvent.events[i].pes().dataLength;
+ break;
+ case FilterEventType::MEDIA:
+ break;
+ case FilterEventType::RECORD:
+ break;
+ case FilterEventType::MMTPRECORD:
+ break;
+ case FilterEventType::DOWNLOAD:
+ break;
+ default:
+ break;
+ }
// EXPECT_TRUE(mDataLength == goldenDataOutputBuffer.size()) << "buffer size does not
// match";
mDataOutputBuffer.resize(mDataLength);
- result = mFilterIdToMQ[filterId]->read(mDataOutputBuffer.data(), mDataLength);
+ result = mFilterIdToMQ->read(mDataOutputBuffer.data(), mDataLength);
EXPECT_TRUE(result) << "can't read from Filter MQ";
/*for (int i = 0; i < mDataLength; i++) {
EXPECT_TRUE(goldenDataOutputBuffer[i] == mDataOutputBuffer[i]) << "data does not match";
}*/
}
- mFilterIdToMQEventFlag[filterId]->wake(
- static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_CONSUMED));
+ mFilterIdToMQEventFlag->wake(static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_CONSUMED));
return result;
}
+class DvrCallback : public IDvrCallback {
+ public:
+ virtual Return<void> onRecordStatus(RecordStatus /*status*/) override { return Void(); }
+
+ virtual Return<void> onPlaybackStatus(PlaybackStatus status) override {
+ // android::Mutex::Autolock autoLock(mMsgLock);
+ ALOGW("[vts] playback status %d", status);
+ switch (status) {
+ case PlaybackStatus::SPACE_EMPTY:
+ case PlaybackStatus::SPACE_ALMOST_EMPTY:
+ ALOGW("[vts] keep playback inputing %d", status);
+ mKeepWritingPlaybackFMQ = true;
+ break;
+ case PlaybackStatus::SPACE_ALMOST_FULL:
+ case PlaybackStatus::SPACE_FULL:
+ ALOGW("[vts] stop playback inputing %d", status);
+ mKeepWritingPlaybackFMQ = false;
+ break;
+ }
+ return Void();
+ }
+
+ void testFilterDataOutput();
+ void stopPlaybackThread();
+
+ void startPlaybackInputThread(PlaybackConf playbackConf, MQDesc& playbackMQDescriptor);
+ static void* __threadLoopPlayback(void* threadArgs);
+ void playbackThreadLoop(PlaybackConf* playbackConf, bool* keepWritingPlaybackFMQ);
+
+ private:
+ struct PlaybackThreadArgs {
+ DvrCallback* user;
+ PlaybackConf* playbackConf;
+ bool* keepWritingPlaybackFMQ;
+ };
+ uint16_t mDataLength = 0;
+ std::vector<uint8_t> mDataOutputBuffer;
+
+ std::map<uint32_t, std::unique_ptr<FilterMQ>> mFilterIdToMQ;
+ std::unique_ptr<FilterMQ> mPlaybackMQ;
+ std::map<uint32_t, EventFlag*> mFilterIdToMQEventFlag;
+ std::map<uint32_t, DemuxFilterEvent> mFilterIdToEvent;
+ EventFlag* mPlaybackMQEventFlag;
+
+ android::Mutex mMsgLock;
+ android::Mutex mPlaybackThreadLock;
+ android::Condition mMsgCondition;
+
+ bool mKeepWritingPlaybackFMQ = true;
+ bool mPlaybackThreadRunning;
+ pthread_t mPlaybackThread;
+
+ int mPidFilterOutputCount = 0;
+};
+
+void DvrCallback::startPlaybackInputThread(PlaybackConf playbackConf,
+ MQDesc& playbackMQDescriptor) {
+ mPlaybackMQ = std::make_unique<FilterMQ>(playbackMQDescriptor, true /* resetPointers */);
+ EXPECT_TRUE(mPlaybackMQ);
+ struct PlaybackThreadArgs* threadArgs =
+ (struct PlaybackThreadArgs*)malloc(sizeof(struct PlaybackThreadArgs));
+ threadArgs->user = this;
+ threadArgs->playbackConf = &playbackConf;
+ threadArgs->keepWritingPlaybackFMQ = &mKeepWritingPlaybackFMQ;
+
+ pthread_create(&mPlaybackThread, NULL, __threadLoopPlayback, (void*)threadArgs);
+ pthread_setname_np(mPlaybackThread, "test_playback_input_loop");
+}
+
+void DvrCallback::stopPlaybackThread() {
+ mPlaybackThreadRunning = false;
+ mKeepWritingPlaybackFMQ = false;
+
+ android::Mutex::Autolock autoLock(mPlaybackThreadLock);
+}
+
+void* DvrCallback::__threadLoopPlayback(void* threadArgs) {
+ DvrCallback* const self =
+ static_cast<DvrCallback*>(((struct PlaybackThreadArgs*)threadArgs)->user);
+ self->playbackThreadLoop(((struct PlaybackThreadArgs*)threadArgs)->playbackConf,
+ ((struct PlaybackThreadArgs*)threadArgs)->keepWritingPlaybackFMQ);
+ return 0;
+}
+
+void DvrCallback::playbackThreadLoop(PlaybackConf* playbackConf, bool* keepWritingPlaybackFMQ) {
+ android::Mutex::Autolock autoLock(mPlaybackThreadLock);
+ mPlaybackThreadRunning = true;
+
+ // Create the EventFlag that is used to signal the HAL impl that data have been
+ // written into the Playback FMQ
+ EventFlag* playbackMQEventFlag;
+ EXPECT_TRUE(EventFlag::createEventFlag(mPlaybackMQ->getEventFlagWord(), &playbackMQEventFlag) ==
+ android::OK);
+
+ // open the stream and get its length
+ std::ifstream inputData(playbackConf->inputDataFile, std::ifstream::binary);
+ int writeSize = playbackConf->setting.packetSize * 6;
+ char* buffer = new char[writeSize];
+ ALOGW("[vts] playback thread loop start %s", playbackConf->inputDataFile.c_str());
+ if (!inputData.is_open()) {
+ mPlaybackThreadRunning = false;
+ ALOGW("[vts] Error %s", strerror(errno));
+ }
+
+ while (mPlaybackThreadRunning) {
+ // move the stream pointer for packet size * 6 every read until the end
+ while (*keepWritingPlaybackFMQ) {
+ inputData.read(buffer, writeSize);
+ if (!inputData) {
+ int leftSize = inputData.gcount();
+ if (leftSize == 0) {
+ mPlaybackThreadRunning = false;
+ break;
+ }
+ inputData.clear();
+ inputData.read(buffer, leftSize);
+ // Write the left over of the input data and quit the thread
+ if (leftSize > 0) {
+ EXPECT_TRUE(mPlaybackMQ->write((unsigned char*)&buffer[0], leftSize));
+ playbackMQEventFlag->wake(
+ static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_READY));
+ }
+ mPlaybackThreadRunning = false;
+ break;
+ }
+ // Write input FMQ and notify the Tuner Implementation
+ EXPECT_TRUE(mPlaybackMQ->write((unsigned char*)&buffer[0], writeSize));
+ playbackMQEventFlag->wake(static_cast<uint32_t>(DemuxQueueNotifyBits::DATA_READY));
+ inputData.seekg(writeSize, inputData.cur);
+ sleep(1);
+ }
+ }
+
+ ALOGW("[vts] Playback thread end.");
+
+ delete[] buffer;
+ inputData.close();
+}
+
// Test environment for Tuner HIDL HAL.
class TunerHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
public:
@@ -494,16 +546,21 @@
sp<FrontendCallback> mFrontendCallback;
sp<IDescrambler> mDescrambler;
sp<IDemux> mDemux;
- sp<DemuxCallback> mDemuxCallback;
+ sp<IDvr> mDvr;
+ sp<IFilter> mFilter;
+ std::map<uint32_t, sp<IFilter>> mFilters;
+ std::map<uint32_t, sp<FilterCallback>> mFilterCallbacks;
+ sp<FilterCallback> mFilterCallback;
+ sp<DvrCallback> mDvrCallback;
MQDesc mFilterMQDescriptor;
- MQDesc mInputMQDescriptor;
+ MQDesc mPlaybackMQDescriptor;
vector<uint32_t> mUsedFilterIds;
uint32_t mDemuxId;
uint32_t mFilterId;
- pthread_t mInputThread;
- bool mInputThreadRunning;
+ pthread_t mPlaybackshread;
+ bool mPlaybackThreadRunning;
::testing::AssertionResult createFrontend(int32_t frontendId);
::testing::AssertionResult tuneFrontend(int32_t frontendId);
@@ -512,16 +569,16 @@
::testing::AssertionResult createDemux();
::testing::AssertionResult createDemuxWithFrontend(int32_t frontendId,
FrontendSettings settings);
- ::testing::AssertionResult getInputMQDescriptor();
- ::testing::AssertionResult addInputToDemux(DemuxInputSettings setting);
+ ::testing::AssertionResult getPlaybackMQDescriptor();
+ ::testing::AssertionResult addPlaybackToDemux(PlaybackSettings setting);
::testing::AssertionResult addFilterToDemux(DemuxFilterType type, DemuxFilterSettings setting);
- ::testing::AssertionResult getFilterMQDescriptor(const uint32_t filterId);
+ ::testing::AssertionResult getFilterMQDescriptor();
::testing::AssertionResult closeDemux();
::testing::AssertionResult createDescrambler();
::testing::AssertionResult closeDescrambler();
::testing::AssertionResult playbackDataFlowTest(vector<FilterConf> filterConf,
- InputConf inputConf,
+ PlaybackConf playbackConf,
vector<string> goldenOutputFiles);
::testing::AssertionResult broadcastDataFlowTest(vector<FilterConf> filterConf,
vector<string> goldenOutputFiles);
@@ -665,39 +722,43 @@
return ::testing::AssertionResult(status == Result::SUCCESS);
}
-::testing::AssertionResult TunerHidlTest::addInputToDemux(DemuxInputSettings setting) {
+::testing::AssertionResult TunerHidlTest::addPlaybackToDemux(PlaybackSettings setting) {
Result status;
if (!mDemux && createDemux() == ::testing::AssertionFailure()) {
return ::testing::AssertionFailure();
}
- // Create demux callback
- if (!mDemuxCallback) {
- mDemuxCallback = new DemuxCallback();
- }
+ // Create dvr callback
+ mDvrCallback = new DvrCallback();
// Add playback input to the local demux
- status = mDemux->addInput(FMQ_SIZE_1M, mDemuxCallback);
+ mDemux->openDvr(DvrType::PLAYBACK, FMQ_SIZE_1M, mDvrCallback,
+ [&](Result result, const sp<IDvr>& dvr) {
+ mDvr = dvr;
+ status = result;
+ });
if (status != Result::SUCCESS) {
return ::testing::AssertionFailure();
}
- status = mDemux->configureInput(setting);
+ DvrSettings dvrSetting;
+ dvrSetting.playback(setting);
+ status = mDvr->configure(dvrSetting);
return ::testing::AssertionResult(status == Result::SUCCESS);
}
-::testing::AssertionResult TunerHidlTest::getInputMQDescriptor() {
+::testing::AssertionResult TunerHidlTest::getPlaybackMQDescriptor() {
Result status;
- if (!mDemux && createDemux() == ::testing::AssertionFailure()) {
+ if ((!mDemux && createDemux() == ::testing::AssertionFailure()) || !mDvr) {
return ::testing::AssertionFailure();
}
- mDemux->getInputQueueDesc([&](Result result, const MQDesc& inputMQDesc) {
- mInputMQDescriptor = inputMQDesc;
+ mDvr->getQueueDesc([&](Result result, const MQDesc& dvrMQDesc) {
+ mPlaybackMQDescriptor = dvrMQDesc;
status = result;
});
@@ -713,13 +774,20 @@
}
// Create demux callback
- if (!mDemuxCallback) {
- mDemuxCallback = new DemuxCallback();
- }
+ mFilterCallback = new FilterCallback();
// Add filter to the local demux
- mDemux->addFilter(type, FMQ_SIZE_4K, mDemuxCallback, [&](Result result, uint32_t filterId) {
- // TODO use a map to save all the filter id and FMQ
+ mDemux->openFilter(type, FMQ_SIZE_16M, mFilterCallback,
+ [&](Result result, const sp<IFilter>& filter) {
+ mFilter = filter;
+ status = result;
+ });
+
+ if (status != Result::SUCCESS) {
+ return ::testing::AssertionFailure();
+ }
+
+ mFilter->getId([&](Result result, uint32_t filterId) {
mFilterId = filterId;
status = result;
});
@@ -728,20 +796,64 @@
return ::testing::AssertionFailure();
}
+ mFilterCallback->setFilterId(mFilterId);
+
+ FilterEventType eventType = FilterEventType::UNDEFINED;
+ switch (type.mainType) {
+ case DemuxFilterMainType::TS:
+ switch (type.subType.tsFilterType()) {
+ case DemuxTsFilterType::UNDEFINED:
+ break;
+ case DemuxTsFilterType::SECTION:
+ eventType = FilterEventType::SECTION;
+ break;
+ case DemuxTsFilterType::PES:
+ eventType = FilterEventType::PES;
+ break;
+ case DemuxTsFilterType::TS:
+ break;
+ case DemuxTsFilterType::AUDIO:
+ case DemuxTsFilterType::VIDEO:
+ eventType = FilterEventType::MEDIA;
+ break;
+ case DemuxTsFilterType::PCR:
+ break;
+ case DemuxTsFilterType::RECORD:
+ eventType = FilterEventType::RECORD;
+ break;
+ }
+ break;
+ case DemuxFilterMainType::MMTP:
+ /*mmtpSettings*/
+ break;
+ case DemuxFilterMainType::IP:
+ /*ipSettings*/
+ break;
+ case DemuxFilterMainType::TLV:
+ /*tlvSettings*/
+ break;
+ case DemuxFilterMainType::ALP:
+ /*alpSettings*/
+ break;
+ default:
+ break;
+ }
+ mFilterCallback->setFilterEventType(eventType);
+
// Configure the filter
- status = mDemux->configureFilter(mFilterId, setting);
+ status = mFilter->configure(setting);
return ::testing::AssertionResult(status == Result::SUCCESS);
}
-::testing::AssertionResult TunerHidlTest::getFilterMQDescriptor(const uint32_t filterId) {
+::testing::AssertionResult TunerHidlTest::getFilterMQDescriptor() {
Result status;
- if (!mDemux) {
+ if (!mDemux || !mFilter) {
return ::testing::AssertionFailure();
}
- mDemux->getFilterQueueDesc(filterId, [&](Result result, const MQDesc& filterMQDesc) {
+ mFilter->getQueueDesc([&](Result result, const MQDesc& filterMQDesc) {
mFilterMQDescriptor = filterMQDesc;
status = result;
});
@@ -750,7 +862,8 @@
}
::testing::AssertionResult TunerHidlTest::playbackDataFlowTest(
- vector<FilterConf> filterConf, InputConf inputConf, vector<string> /*goldenOutputFiles*/) {
+ vector<FilterConf> filterConf, PlaybackConf playbackConf,
+ vector<string> /*goldenOutputFiles*/) {
Result status;
int filterIdsSize;
// Filter Configuration Module
@@ -758,45 +871,58 @@
if (addFilterToDemux(filterConf[i].type, filterConf[i].setting) ==
::testing::AssertionFailure() ||
// TODO use a map to save the FMQs/EvenFlags and pass to callback
- getFilterMQDescriptor(mFilterId) == ::testing::AssertionFailure()) {
+ getFilterMQDescriptor() == ::testing::AssertionFailure()) {
return ::testing::AssertionFailure();
}
filterIdsSize = mUsedFilterIds.size();
mUsedFilterIds.resize(filterIdsSize + 1);
mUsedFilterIds[filterIdsSize] = mFilterId;
- mDemuxCallback->updateFilterMQ(mFilterId, mFilterMQDescriptor);
- // mDemuxCallback->updateGoldenOutputMap(mFilterId, goldenOutputFiles[i]);
- status = mDemux->startFilter(mFilterId);
+ mFilters[mFilterId] = mFilter;
+ mFilterCallbacks[mFilterId] = mFilterCallback;
+ mFilterCallback->updateFilterMQ(mFilterMQDescriptor);
+ // mDemuxCallback->updateGoldenOutputMap(goldenOutputFiles[i]);
+ status = mFilter->start();
if (status != Result::SUCCESS) {
return ::testing::AssertionFailure();
}
}
// Playback Input Module
- DemuxInputSettings inputSetting = inputConf.setting;
- if (addInputToDemux(inputSetting) == ::testing::AssertionFailure() ||
- getInputMQDescriptor() == ::testing::AssertionFailure()) {
+ PlaybackSettings playbackSetting = playbackConf.setting;
+ if (addPlaybackToDemux(playbackSetting) == ::testing::AssertionFailure() ||
+ getPlaybackMQDescriptor() == ::testing::AssertionFailure()) {
return ::testing::AssertionFailure();
}
- mDemuxCallback->startPlaybackInputThread(inputConf, mInputMQDescriptor);
- status = mDemux->startInput();
+ for (int i = 0; i <= filterIdsSize; i++) {
+ if (mDvr->attachFilter(mFilters[mUsedFilterIds[i]]) != Result::SUCCESS) {
+ return ::testing::AssertionFailure();
+ }
+ }
+ mDvrCallback->startPlaybackInputThread(playbackConf, mPlaybackMQDescriptor);
+ status = mDvr->start();
if (status != Result::SUCCESS) {
return ::testing::AssertionFailure();
}
// Data Verify Module
- mDemuxCallback->testFilterDataOutput();
- mDemuxCallback->stopInputThread();
+ std::map<uint32_t, sp<FilterCallback>>::iterator it;
+ for (it = mFilterCallbacks.begin(); it != mFilterCallbacks.end(); it++) {
+ it->second->testFilterDataOutput();
+ }
+ mDvrCallback->stopPlaybackThread();
// Clean Up Module
for (int i = 0; i <= filterIdsSize; i++) {
- if (mDemux->stopFilter(mUsedFilterIds[i]) != Result::SUCCESS) {
+ if (mFilters[mUsedFilterIds[i]]->stop() != Result::SUCCESS) {
return ::testing::AssertionFailure();
}
}
- if (mDemux->stopInput() != Result::SUCCESS) {
+ if (mDvr->stop() != Result::SUCCESS) {
return ::testing::AssertionFailure();
}
+ mUsedFilterIds.clear();
+ mFilterCallbacks.clear();
+ mFilters.clear();
return closeDemux();
}
@@ -831,31 +957,39 @@
if (addFilterToDemux(filterConf[i].type, filterConf[i].setting) ==
::testing::AssertionFailure() ||
// TODO use a map to save the FMQs/EvenFlags and pass to callback
- getFilterMQDescriptor(mFilterId) == ::testing::AssertionFailure()) {
+ getFilterMQDescriptor() == ::testing::AssertionFailure()) {
return ::testing::AssertionFailure();
}
filterIdsSize = mUsedFilterIds.size();
mUsedFilterIds.resize(filterIdsSize + 1);
mUsedFilterIds[filterIdsSize] = mFilterId;
- mDemuxCallback->updateFilterMQ(mFilterId, mFilterMQDescriptor);
- status = mDemux->startFilter(mFilterId);
+ mFilters[mFilterId] = mFilter;
+ mFilterCallbacks[mFilterId] = mFilterCallback;
+ mFilterCallback->updateFilterMQ(mFilterMQDescriptor);
+ status = mFilter->start();
if (status != Result::SUCCESS) {
return ::testing::AssertionFailure();
}
}
// Data Verify Module
- mDemuxCallback->testFilterDataOutput();
+ std::map<uint32_t, sp<FilterCallback>>::iterator it;
+ for (it = mFilterCallbacks.begin(); it != mFilterCallbacks.end(); it++) {
+ it->second->testFilterDataOutput();
+ }
// Clean Up Module
for (int i = 0; i <= filterIdsSize; i++) {
- if (mDemux->stopFilter(mUsedFilterIds[i]) != Result::SUCCESS) {
+ if (mFilters[mUsedFilterIds[i]]->stop() != Result::SUCCESS) {
return ::testing::AssertionFailure();
}
}
if (mFrontend->stopTune() != Result::SUCCESS) {
return ::testing::AssertionFailure();
}
+ mUsedFilterIds.clear();
+ mFilterCallbacks.clear();
+ mFilters.clear();
return closeDemux();
}
@@ -992,7 +1126,7 @@
/*
* DATA FLOW TESTS
*/
-TEST_F(TunerHidlTest, PlaybackDataFlowWithPesFilterTest) {
+TEST_F(TunerHidlTest, PlaybackDataFlowWithSectionFilterTest) {
description("Feed ts data from playback and configure pes filter to get output");
// todo modulize the filter conf parser
@@ -1000,32 +1134,39 @@
filterConf.resize(1);
DemuxFilterSettings filterSetting;
- DemuxFilterPesDataSettings pesFilterSetting{
+ DemuxTsFilterSettings tsFilterSetting{
.tpid = 18,
};
- filterSetting.pesData(pesFilterSetting);
- FilterConf pesFilterConf{
- .type = DemuxFilterType::PES,
+ DemuxFilterSectionSettings sectionFilterSetting;
+ tsFilterSetting.filterSettings.section(sectionFilterSetting);
+ filterSetting.ts(tsFilterSetting);
+
+ DemuxFilterType type{
+ .mainType = DemuxFilterMainType::TS,
+ };
+ type.subType.tsFilterType(DemuxTsFilterType::SECTION);
+ FilterConf sectionFilterConf{
+ .type = type,
.setting = filterSetting,
};
- filterConf[0] = pesFilterConf;
+ filterConf[0] = sectionFilterConf;
- DemuxInputSettings inputSetting{
+ PlaybackSettings playbackSetting{
.statusMask = 0xf,
.lowThreshold = 0x1000,
.highThreshold = 0x07fff,
- .dataFormat = DemuxDataFormat::TS,
+ .dataFormat = DataFormat::TS,
.packetSize = 188,
};
- InputConf inputConf{
+ PlaybackConf playbackConf{
.inputDataFile = "/vendor/etc/test1.ts",
- .setting = inputSetting,
+ .setting = playbackSetting,
};
vector<string> goldenOutputFiles;
- ASSERT_TRUE(playbackDataFlowTest(filterConf, inputConf, goldenOutputFiles));
+ ASSERT_TRUE(playbackDataFlowTest(filterConf, playbackConf, goldenOutputFiles));
}
TEST_F(TunerHidlTest, BroadcastDataFlowWithPesFilterTest) {
@@ -1036,12 +1177,19 @@
filterConf.resize(1);
DemuxFilterSettings filterSetting;
- DemuxFilterPesDataSettings pesFilterSetting{
- .tpid = 18,
+ DemuxTsFilterSettings tsFilterSetting{
+ .tpid = 119,
};
- filterSetting.pesData(pesFilterSetting);
+ DemuxFilterPesDataSettings pesFilterSetting;
+ tsFilterSetting.filterSettings.pesData(pesFilterSetting);
+ filterSetting.ts(tsFilterSetting);
+
+ DemuxFilterType type{
+ .mainType = DemuxFilterMainType::TS,
+ };
+ type.subType.tsFilterType(DemuxTsFilterType::PES);
FilterConf pesFilterConf{
- .type = DemuxFilterType::PES,
+ .type = type,
.setting = filterSetting,
};
filterConf[0] = pesFilterConf;
diff --git a/vr/1.0/vts/functional/Android.bp b/vr/1.0/vts/functional/Android.bp
index 958cce7..bd0336c 100644
--- a/vr/1.0/vts/functional/Android.bp
+++ b/vr/1.0/vts/functional/Android.bp
@@ -19,5 +19,5 @@
defaults: ["VtsHalTargetTestDefaults"],
srcs: ["VtsHalVrV1_0TargetTest.cpp"],
static_libs: ["android.hardware.vr@1.0"],
- test_suites: ["general-tests"],
+ test_suites: ["general-tests", "vts-core"],
}
diff --git a/vr/1.0/vts/functional/VtsHalVrV1_0TargetTest.cpp b/vr/1.0/vts/functional/VtsHalVrV1_0TargetTest.cpp
index b165613..c08e5ca 100644
--- a/vr/1.0/vts/functional/VtsHalVrV1_0TargetTest.cpp
+++ b/vr/1.0/vts/functional/VtsHalVrV1_0TargetTest.cpp
@@ -15,11 +15,12 @@
*/
#define LOG_TAG "vr_hidl_hal_test"
-#include <VtsHalHidlTargetTestBase.h>
-#include <VtsHalHidlTargetTestEnvBase.h>
#include <android-base/logging.h>
#include <android/hardware/vr/1.0/IVr.h>
+#include <gtest/gtest.h>
#include <hardware/vr.h>
+#include <hidl/GtestPrinter.h>
+#include <hidl/ServiceManagement.h>
#include <log/log.h>
using ::android::hardware::vr::V1_0::IVr;
@@ -27,24 +28,11 @@
using ::android::hardware::Void;
using ::android::sp;
-// Test environment for Vr HIDL HAL.
-class VrHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
- public:
- // get the test environment singleton
- static VrHidlEnvironment* Instance() {
- static VrHidlEnvironment* instance = new VrHidlEnvironment;
- return instance;
- }
-
- virtual void registerTestServices() override { registerTestService<IVr>(); }
-};
-
// The main test class for VR HIDL HAL.
-class VrHidlTest : public ::testing::VtsHalHidlTargetTestBase {
+class VrHidlTest : public ::testing::TestWithParam<std::string> {
public:
void SetUp() override {
- vr = ::testing::VtsHalHidlTargetTestBase::getService<IVr>(
- VrHidlEnvironment::Instance()->getServiceName<IVr>());
+ vr = IVr::getService(GetParam());
ASSERT_NE(vr, nullptr);
}
@@ -54,19 +42,19 @@
};
// Sanity check that Vr::init does not crash.
-TEST_F(VrHidlTest, Init) {
+TEST_P(VrHidlTest, Init) {
EXPECT_TRUE(vr->init().isOk());
}
// Sanity check Vr::setVrMode is able to enable and disable VR mode.
-TEST_F(VrHidlTest, SetVrMode) {
+TEST_P(VrHidlTest, SetVrMode) {
EXPECT_TRUE(vr->init().isOk());
EXPECT_TRUE(vr->setVrMode(true).isOk());
EXPECT_TRUE(vr->setVrMode(false).isOk());
}
// Sanity check that Vr::init and Vr::setVrMode can be used in any order.
-TEST_F(VrHidlTest, ReInit) {
+TEST_P(VrHidlTest, ReInit) {
EXPECT_TRUE(vr->init().isOk());
EXPECT_TRUE(vr->setVrMode(true).isOk());
EXPECT_TRUE(vr->init().isOk());
@@ -75,11 +63,8 @@
EXPECT_TRUE(vr->setVrMode(false).isOk());
}
-int main(int argc, char **argv) {
- ::testing::AddGlobalTestEnvironment(VrHidlEnvironment::Instance());
- ::testing::InitGoogleTest(&argc, argv);
- VrHidlEnvironment::Instance()->init(&argc, argv);
- int status = RUN_ALL_TESTS();
- ALOGI("Test result = %d", status);
- return status;
-}
+INSTANTIATE_TEST_SUITE_P(
+ PerInstance, VrHidlTest,
+ testing::ValuesIn(android::hardware::getAllHalInstanceNames(IVr::descriptor)),
+ android::hardware::PrintInstanceNameToString);
+
diff --git a/wifi/offload/1.0/vts/functional/Android.bp b/wifi/offload/1.0/vts/functional/Android.bp
index de15aa7..965c946 100644
--- a/wifi/offload/1.0/vts/functional/Android.bp
+++ b/wifi/offload/1.0/vts/functional/Android.bp
@@ -19,5 +19,5 @@
defaults: ["VtsHalTargetTestDefaults"],
srcs: ["VtsHalWifiOffloadV1_0TargetTest.cpp"],
static_libs: ["android.hardware.wifi.offload@1.0"],
- test_suites: ["general-tests"],
+ test_suites: ["general-tests", "vts-core"],
}
diff --git a/wifi/offload/1.0/vts/functional/VtsHalWifiOffloadV1_0TargetTest.cpp b/wifi/offload/1.0/vts/functional/VtsHalWifiOffloadV1_0TargetTest.cpp
index dbe4e74..83d834c 100644
--- a/wifi/offload/1.0/vts/functional/VtsHalWifiOffloadV1_0TargetTest.cpp
+++ b/wifi/offload/1.0/vts/functional/VtsHalWifiOffloadV1_0TargetTest.cpp
@@ -20,10 +20,11 @@
#include <android/hardware/wifi/offload/1.0/IOffload.h>
#include <android/hardware/wifi/offload/1.0/IOffloadCallback.h>
#include <android/hardware/wifi/offload/1.0/types.h>
+#include <gtest/gtest.h>
+#include <hidl/GtestPrinter.h>
+#include <hidl/ServiceManagement.h>
#include <VtsHalHidlTargetCallbackBase.h>
-#include <VtsHalHidlTargetTestBase.h>
-#include <VtsHalHidlTargetTestEnvBase.h>
#include <vector>
@@ -69,33 +70,11 @@
OffloadStatus error_code_;
};
-// Test environment for Weaver HIDL HAL.
-class WifiOffloadHidlEnvironment
- : public ::testing::VtsHalHidlTargetTestEnvBase {
- public:
- // get the test environment singleton
- static WifiOffloadHidlEnvironment* Instance() {
- static WifiOffloadHidlEnvironment* instance =
- new WifiOffloadHidlEnvironment;
- return instance;
- }
-
- virtual void registerTestServices() override {
- registerTestService<IOffload>();
- }
-
- private:
- WifiOffloadHidlEnvironment() {}
-};
-
// The main test class for WifiOffload HIDL HAL.
-class WifiOffloadHidlTest : public ::testing::VtsHalHidlTargetTestBase {
+class WifiOffloadHidlTest : public ::testing::TestWithParam<std::string> {
public:
virtual void SetUp() override {
- wifi_offload_ =
- ::testing::VtsHalHidlTargetTestBase::getService<IOffload>(
- WifiOffloadHidlEnvironment::Instance()
- ->getServiceName<IOffload>());
+ wifi_offload_ = IOffload::getService(GetParam());
ASSERT_NE(wifi_offload_, nullptr);
wifi_offload_cb_ = new OffloadCallback();
@@ -136,7 +115,7 @@
/*
* Verify that setEventCallback method returns without errors
*/
-TEST_F(WifiOffloadHidlTest, setEventCallback) {
+TEST_P(WifiOffloadHidlTest, setEventCallback) {
auto returnObject = wifi_offload_->setEventCallback(wifi_offload_cb_);
ASSERT_EQ(true, returnObject.isOk());
}
@@ -144,7 +123,7 @@
/*
* Verify that subscribeScanResults method returns without errors
*/
-TEST_F(WifiOffloadHidlTest, subscribeScanResults) {
+TEST_P(WifiOffloadHidlTest, subscribeScanResults) {
const auto& result = HIDL_INVOKE(wifi_offload_, subscribeScanResults, 0);
ASSERT_EQ(OffloadStatusCode::OK, result.code);
}
@@ -152,7 +131,7 @@
/*
* Verify that unsubscribeScanResults method returns without errors
*/
-TEST_F(WifiOffloadHidlTest, unsubscribeScanResults) {
+TEST_P(WifiOffloadHidlTest, unsubscribeScanResults) {
auto returnObject = wifi_offload_->unsubscribeScanResults();
ASSERT_EQ(true, returnObject.isOk());
}
@@ -160,7 +139,7 @@
/*
* Verify that configureScans method returns without errors
*/
-TEST_F(WifiOffloadHidlTest, configureScans) {
+TEST_P(WifiOffloadHidlTest, configureScans) {
ScanParam* pScanParam = new ScanParam();
std::vector<uint32_t> frequencyList = {kFrequency1, kFrequency2};
pScanParam->disconnectedModeScanIntervalMs =
@@ -192,7 +171,7 @@
/*
* Verify that getScanStats returns without any errors
*/
-TEST_F(WifiOffloadHidlTest, getScanStats) {
+TEST_P(WifiOffloadHidlTest, getScanStats) {
const auto& result = HIDL_INVOKE(wifi_offload_, getScanStats);
OffloadStatus status = result.first;
ASSERT_EQ(OffloadStatusCode::OK, status.code);
@@ -201,7 +180,7 @@
/*
* Verify that onScanResult callback is invoked
*/
-TEST_F(WifiOffloadHidlTest, getScanResults) {
+TEST_P(WifiOffloadHidlTest, getScanResults) {
wifi_offload_->setEventCallback(wifi_offload_cb_);
std::vector<ScanResult> scan_results;
std::vector<uint8_t> ssid(kSsid1, kSsid1 + sizeof(kSsid1));
@@ -223,7 +202,7 @@
/*
* Verify that onError callback is invoked
*/
-TEST_F(WifiOffloadHidlTest, getError) {
+TEST_P(WifiOffloadHidlTest, getError) {
wifi_offload_->setEventCallback(wifi_offload_cb_);
OffloadStatus status = {OffloadStatusCode::ERROR, ""};
wifi_offload_cb_->onError(status);
@@ -231,12 +210,8 @@
ASSERT_EQ(true, res.no_timeout);
}
-int main(int argc, char** argv) {
- ::testing::AddGlobalTestEnvironment(WifiOffloadHidlEnvironment::Instance());
- ::testing::InitGoogleTest(&argc, argv);
- WifiOffloadHidlEnvironment::Instance()->init(&argc, argv);
- int status = RUN_ALL_TESTS();
- LOG(INFO) << "Test result = " << status;
-
- return status;
-}
+INSTANTIATE_TEST_SUITE_P(
+ PerInstance, WifiOffloadHidlTest,
+ testing::ValuesIn(
+ android::hardware::getAllHalInstanceNames(IOffload::descriptor)),
+ android::hardware::PrintInstanceNameToString);
\ No newline at end of file
diff --git a/wifi/offload/1.0/vts/functional/hidl_call_util.h b/wifi/offload/1.0/vts/functional/hidl_call_util.h
index f3ca517..99868e8 100644
--- a/wifi/offload/1.0/vts/functional/hidl_call_util.h
+++ b/wifi/offload/1.0/vts/functional/hidl_call_util.h
@@ -21,8 +21,6 @@
#include <type_traits>
#include <utility>
-#include <VtsHalHidlTargetTestBase.h>
-
namespace {
namespace detail {
template <typename>