diff --git a/qcom/opensource/agm/Android.mk b/qcom/opensource/agm/Android.mk deleted file mode 100755 index 3d1f1919..00000000 --- a/qcom/opensource/agm/Android.mk +++ /dev/null @@ -1,3 +0,0 @@ -ifneq ($(AUDIO_USE_STUB_HAL), true) - include $(call all-subdir-makefiles) -endif diff --git a/qcom/opensource/agm/NOTICE b/qcom/opensource/agm/NOTICE deleted file mode 100755 index 0d751151..00000000 --- a/qcom/opensource/agm/NOTICE +++ /dev/null @@ -1,180 +0,0 @@ -Copyright (c) 2019, The Linux Foundation. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of The Linux Foundation nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -___________________________________________________________ -service/inc/agm_list.h: -Copyright (C) 2008-2013 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. - -plugins/tinyalsa/test/agmcap.c and plugins/tinyalsa/test/agmplay.c: - -Copyright 2011, The Android Open Source Project - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of The Android Open Source Project nor the names of - its contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -DAMAGE. -_________________________________________________ -plugins/tinyalsa/test/agmcompressplay.c: - -This file is provided under a dual BSD/LGPLv2.1 license. This code is used under the BSD license. - -BSD LICENSE - -tinyplay command line player for compress audio offload in alsa -Copyright (c) 2011-2012, Intel Corporation -All rights reserved. - -Author: Vinod Koul - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation -and/or other materials provided with the distribution. -Neither the name of Intel Corporation nor the names of its contributors -may be used to endorse or promote products derived from this software -without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - -LGPL LICENSE - -tinyplay command line player for compress audio offload in alsa -Copyright (c) 2011-2012, Intel Corporation. - -This program is free software; you can redistribute it and/or modify it -under the terms and conditions of the GNU Lesser General Public License, -version 2.1, as published by the Free Software Foundation. - -This program is distributed in the hope it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with this program; if not, write to -the Free Software Foundation, Inc., -51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. -_________________________________________________ -plugins/tinyalsa/test/agmcompresscap.c: -This file is provided under a dual BSD/LGPLv2.1 license. This code is used under the BSD license. - -BSD LICENSE - -crecord command line recorder for compress audio record in alsa -Copyright (c) 2011-2012, Intel Corporation -Copyright (c) 2013-2014, Wolfson Microelectronic Ltd. -All rights reserved. - -Author: Vinod Koul -Author: Charles Keepax - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation -and/or other materials provided with the distribution. -Neither the name of Intel Corporation nor the names of its contributors -may be used to endorse or promote products derived from this software -without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - -LGPL LICENSE - -crecord command line recorder for compress audio record in alsa -Copyright (c) 2011-2012, Intel Corporation -Copyright (c) 2013-2014, Wolfson Microelectronic Ltd. - -This program is free software; you can redistribute it and/or modify it -under the terms and conditions of the GNU Lesser General Public License, -version 2.1, as published by the Free Software Foundation. - -This program is distributed in the hope it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with this program; if not, write to -the Free Software Foundation, Inc., -51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. diff --git a/qcom/opensource/agm/README.md b/qcom/opensource/agm/README.md deleted file mode 100755 index 3e19e3f2..00000000 --- a/qcom/opensource/agm/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# agm -Audio Graph Manager diff --git a/qcom/opensource/agm/ipc/Android.mk b/qcom/opensource/agm/ipc/Android.mk deleted file mode 100755 index 62a31c2a..00000000 --- a/qcom/opensource/agm/ipc/Android.mk +++ /dev/null @@ -1,8 +0,0 @@ -LOCAL_PATH := $(call my-dir) -MY_LOCAL_PATH := $(call my-dir) -ifeq ($(AUDIO_FEATURE_AGM_USES_SW_BINDER), true) -include $(call all-makefiles-under, $(LOCAL_PATH)/SwBinders) -else - -include $(MY_LOCAL_PATH)/aidl/Android.mk -endif diff --git a/qcom/opensource/agm/ipc/DBus/agm_client/Makefile.am b/qcom/opensource/agm/ipc/DBus/agm_client/Makefile.am deleted file mode 100755 index ebca7ecb..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_client/Makefile.am +++ /dev/null @@ -1,17 +0,0 @@ -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = agmclient.pc -EXTRA_DIST = $(pkgconfig_DATA) - -AM_CPPFLAGS = -Wno-narrowing -AM_CPPFLAGS += -I ${WORKSPACE}/vendor/qcom/opensource/agm/service/inc -AM_CPPFLAGS += -D__unused=__attribute__\(\(__unused__\)\) -AM_CPPFLAGS += $(GLIB_CFLAGS) -Dstrlcpy=g_strlcpy -Dstrlcat=g_strlcat -include glib.h -AM_CPPFLAGS += $(GIO_CFLAGS) - -agmclient_sources = ${top_srcdir}/src/agm_client_wrapper_dbus.cpp - -lib_LTLIBRARIES = libagmclientwrapper.la -libagmclientwrapper_la_SOURCES = $(agmclient_sources) -libagmclientwrapper_la_CPPFLAGS := $(AM_CPPFLAGS) $(DBUS_CFLAGS) -libagmclientwrapper_la_LIBADD = -lglib-2.0 -lgobject-2.0 -lgio-2.0 -lar_osal -libagmclientwrapper_la_LDFLAGS = -ldl -shared -avoid-version -lpthread -lrt $(DBUS_LIBS) diff --git a/qcom/opensource/agm/ipc/DBus/agm_client/agmclient.pc.in b/qcom/opensource/agm/ipc/DBus/agm_client/agmclient.pc.in deleted file mode 100755 index b8f76a4e..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_client/agmclient.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: agmclient -Description: agmclient library -Version: @VERSION@ -Libs: -L${libdir} -Cflags: -I${includedir}/agm_client/ diff --git a/qcom/opensource/agm/ipc/DBus/agm_client/configure.ac b/qcom/opensource/agm/ipc/DBus/agm_client/configure.ac deleted file mode 100755 index ed601cd3..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_client/configure.ac +++ /dev/null @@ -1,61 +0,0 @@ -# -*- Autoconf -*- -# configure.ac -- Autoconf script for halinterface -# - -# Process this file with autoconf to produce a configure script. - -# Requires autoconf tool later than 2.61 -AC_PREREQ([2.69]) -# Initialize the hal-interface package version 1.0.0 -AC_INIT(halinterface,1.0.0) -# Does not strictly follow GNU Coding standards -AM_INIT_AUTOMAKE([foreign]) -# Disables auto rebuilding of configure, Makefile.ins -#AM_MAINTAINER_MODE -# defines some macros variable to be included by source -AC_CONFIG_HEADERS([config.h]) -# defines some macros variable to be included by source -AC_CONFIG_MACRO_DIR([m4]) - -# Checks for programs. -AC_PROG_CC - -AM_PROG_CC_C_O -AC_PROG_CXX -AC_PROG_LIBTOOL -AC_PROG_AWK -AC_PROG_CPP -AC_PROG_INSTALL -AC_PROG_LN_S -AC_PROG_MAKE_SET -PKG_PROG_PKG_CONFIG - -PKG_CHECK_MODULES([GIO], [gio-2.0]) -AC_SUBST([GIO_CFLAGS]) -AC_SUBST([GIO_LIBS]) - -AC_ARG_WITH([glib], - AC_HELP_STRING([--with-glib], - [enable glib, Build against glib. Use this when building for HLOS systems which use glib])) - -if (test "x${with_glib}" = "xyes"); then - PKG_CHECK_MODULES(GTHREAD, gthread-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GThread >= 2.16 is required)) - PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GLib >= 2.16 is required)) - GLIB_CFLAGS="$GLIB_CFLAGS $GTHREAD_CFLAGS" - GLIB_LIBS="$GLIB_LIBS $GTHREAD_LIBS" - - AC_SUBST(GLIB_CFLAGS) - AC_SUBST(GLIB_LIBS) -fi - -AM_CONDITIONAL(USE_GLIB, test "x${with_glib}" = "xyes") - -AC_CONFIG_FILES([ \ - Makefile\ - agmclient.pc - ]) - -AC_OUTPUT - diff --git a/qcom/opensource/agm/ipc/DBus/agm_client/src/agm_client_wrapper_dbus.cpp b/qcom/opensource/agm/ipc/DBus/agm_client/src/agm_client_wrapper_dbus.cpp deleted file mode 100755 index de438702..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_client/src/agm_client_wrapper_dbus.cpp +++ /dev/null @@ -1,2160 +0,0 @@ -/* -** Copyright (c) 2020, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -/* -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted (subject to the limitations in the -** disclaimer below) provided that the following conditions are met: -** -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** -** * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE -** GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT -** HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -** IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -** IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "agm_client_wrapper" - -#include -#include -#include -#include "utils.h" - -#define AGM_OBJECT_PATH "/org/qti/agm" -#define AGM_MODULE_IFACE "org.Qti.Agm" -#define AGM_SESSION_IFACE "org.Qti.Agm.Session" -#define AGM_DBUS_CONNECTION "org.Qti.AgmService" -#define AGM_MAX_G_OBJ_PATH 128 -#define AGM_DBUS_ASYNC_CALL_TIMEOUT_MS 1000 - -typedef struct { - GDBusConnection *conn; - GDBusProxy *proxy; - char g_obj_path[AGM_MAX_G_OBJ_PATH]; - GHashTable *ses_hash_table; -} agm_client_module_data; - -typedef struct { - GDBusConnection *conn; - GDBusProxy *proxy; - char *obj_path; - uint32_t session_id; - GThread *thread_loop; - GMainLoop *loop; - GList *callbacks; - GMainLoop *ses_loop; - GThread *ses_thread_loop; - guint sub_id; - GMutex mutex; - GCond cond; - void *buf; - uint32_t buf_size; -} agm_client_session_data; - -typedef struct { - uint32_t session_id; - void *client_data; - agm_event_cb cb; - uint32_t evt_type; - guint sub_id_callback_event; -} agm_callback_data; - -static agm_client_module_data *mdata = NULL; - -static GDBusConnection *get_dbus_connection() { - GError *error = NULL; - GDBusConnection *conn = NULL; - conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error); - - if (conn == NULL) { - AGM_LOGE("%s: Error in getting dbus connection: %s", __func__, - error->message); - return NULL; - } - - return conn; -} - -static GDBusProxy *get_proxy_object(GDBusConnection *connection, - GDBusProxyFlags flags, - const gchar *name, - const gchar *object_path, - const gchar *interface_name) { - GError *error = NULL; - GDBusProxy *proxy; - - AGM_LOGD("%s\n", __func__); - - proxy = g_dbus_proxy_new_sync(connection, - flags, - NULL, - name, - object_path, - interface_name, - NULL, - &error); - - if (proxy == NULL) - AGM_LOGE("%s: Error in getting dbus proxy: %s", __func__, - error->message); - return proxy; -} - -static int initialize_module_data() { - int rc = 0; - - mdata = (agm_client_module_data *) - g_malloc0(sizeof(agm_client_module_data)); - mdata->conn = get_dbus_connection(); - - if (mdata->conn == NULL) { - AGM_LOGE("%s: Error in getting dbus connection", __func__); - rc = -EINVAL; - free(mdata); - mdata = NULL; - return rc; - } - - mdata->proxy = get_proxy_object(mdata->conn, - G_DBUS_PROXY_FLAGS_NONE, - AGM_DBUS_CONNECTION, - AGM_OBJECT_PATH, - AGM_MODULE_IFACE); - if (mdata->proxy == NULL) { - AGM_LOGE("%s: Couldn't get proxy object\n", __func__); - rc = -EINVAL; - free(mdata); - mdata = NULL; - return rc; - } - - g_snprintf(mdata->g_obj_path, AGM_MAX_G_OBJ_PATH, - "%s", AGM_OBJECT_PATH); - - mdata->ses_hash_table = g_hash_table_new(g_direct_hash, g_direct_equal); - return rc; -} - -static void on_emit_signal_callback(GDBusConnection *conn, - const gchar *sender_name, - const gchar *object_path, - const gchar *interface_name, - const gchar *signal_name, - GVariant *parameters, - gpointer data) { - agm_callback_data *cb_data = (agm_callback_data *)data; - GVariant *array_v; - GVariantIter arg_i; - struct agm_event_cb_params event_params; - struct agm_event_cb_params *event_params_l; - gsize element_size = sizeof(guchar); - gsize n_elements = 0; - gconstpointer value; - - AGM_LOGD("%s\n", __func__); - - g_variant_iter_init(&arg_i, parameters); - g_variant_iter_next(&arg_i, "u", &event_params.source_module_id); - g_variant_iter_next(&arg_i, "u", &event_params.event_id); - g_variant_iter_next(&arg_i, "u", &event_params.event_payload_size); - event_params_l = (struct agm_event_cb_params*) calloc(1, - (sizeof(struct agm_event_cb_params) + - event_params.event_payload_size)); - array_v = g_variant_iter_next_value(&arg_i); - value = g_variant_get_fixed_array(array_v, &n_elements, element_size); - memcpy(&event_params_l->event_payload[0], value, n_elements); - g_variant_unref(array_v); - - event_params_l->source_module_id = event_params.source_module_id; - event_params_l->event_id = event_params.event_id; - event_params_l->event_payload_size = event_params.event_payload_size; - - cb_data->cb(cb_data->session_id, event_params_l, cb_data->client_data); -} - -static void on_emit_ses_signal_callback(GDBusConnection *conn, - const gchar *sender_name, - const gchar *object_path, - const gchar *interface_name, - const gchar *signal_name, - GVariant *parameters, - gpointer data) { - - agm_client_session_data *ses_data = NULL; - GVariantIter arg_i; - GVariant *array_v; - gconstpointer value; - gsize n_elements; - gsize element_size = sizeof(guchar); - uint32_t dir = 0; - uint32_t status = 0; - uint32_t session_id = 0; - - g_variant_iter_init(&arg_i, parameters); - g_variant_iter_next(&arg_i, "u", &dir); - g_variant_iter_next(&arg_i, "u", &status); - g_variant_iter_next(&arg_i, "u", &session_id); - - if ((ses_data = (agm_client_session_data *) - g_hash_table_lookup(mdata->ses_hash_table, - GINT_TO_POINTER(session_id))) == NULL) { - AGM_LOGE("%s: Invalid session id received\n", __func__); - } - - AGM_LOGD("Waking up session threads read/write = %d thread sts:%u, sid:%d\n", - dir, status, session_id); - - if(!dir){ - array_v = g_variant_iter_next_value(&arg_i); - value = g_variant_get_fixed_array(array_v, &n_elements, element_size); - AGM_LOGD("%s:n_elements %d, element_size %d, %p\n", __func__, - n_elements, element_size, ses_data->buf); - if (n_elements <= ses_data->buf_size) { - memcpy(ses_data->buf, value, n_elements); - ses_data->buf_size = n_elements; - } else { - AGM_LOGE("Insufficient bytes size to copy bytes read\n"); - } - g_variant_unref(array_v); - } - - g_mutex_lock(&ses_data->mutex); - g_cond_signal(&ses_data->cond); - g_mutex_unlock(&ses_data->mutex); -} - -static void free_callbacks(agm_client_session_data *ses_data) { - GList *node; - agm_callback_data *cb_data; - g_assert(mdata != NULL); - - for (node = ses_data->callbacks; node != NULL; node = node->next) { - if (node->data != NULL) { - cb_data = (agm_callback_data *)node->data; - g_dbus_connection_signal_unsubscribe(mdata->conn, - cb_data->sub_id_callback_event); - free(node->data); - node->data = NULL; - } - } - - g_list_free(ses_data->callbacks); -} - -static int subscribe_ses_callback_event(agm_client_session_data *ses_data, - bool subscribe) { - GVariant *result; - GError *error = NULL; - gint ret = 0; - GHashTableIter iter; - gpointer key, value; - GList *node = NULL; - agm_callback_data *node_data = NULL; - - g_assert(mdata != NULL); - - if (subscribe) { - AGM_LOGD("Subscribing to session events\n"); - ses_data->sub_id = g_dbus_connection_signal_subscribe( - mdata->conn, - NULL, - AGM_SESSION_IFACE, - "AgmSesEventCb", - ses_data->obj_path, - NULL, - G_DBUS_SIGNAL_FLAGS_NONE, - on_emit_ses_signal_callback, - ses_data, - NULL); - - } else { - AGM_LOGD("Unsubscribing to session events\n"); - g_dbus_connection_signal_unsubscribe(mdata->conn, ses_data->sub_id); - } - - return 0; -} - -static int subscribe_callback_event(agm_client_session_data *ses_data, - bool subscribe, - agm_callback_data *cb_data) { - GVariant *result; - GError *error = NULL; - gint ret = 0; - GHashTableIter iter; - gpointer key, value; - GList *node = NULL; - agm_callback_data *node_data = NULL; - - AGM_LOGD("%s\n", __func__); - g_assert(mdata != NULL); - g_assert(cb_data != NULL); - - if (subscribe) { - cb_data->sub_id_callback_event = g_dbus_connection_signal_subscribe( - mdata->conn, - NULL, - AGM_SESSION_IFACE, - "AgmEventCb", - ses_data->obj_path, - NULL, - G_DBUS_SIGNAL_FLAGS_NONE, - on_emit_signal_callback, - cb_data, - NULL); - - ses_data->callbacks = g_list_prepend(ses_data->callbacks, cb_data); - } else { - for (node = ses_data->callbacks; node != NULL; node = node->next) { - node_data = (agm_callback_data *)node->data; - if (node_data != NULL) { - if (node_data->session_id == cb_data->session_id && - node_data->evt_type == cb_data->evt_type && - node_data->sub_id_callback_event == - cb_data->sub_id_callback_event) { - g_dbus_connection_signal_unsubscribe(mdata->conn, - cb_data->sub_id_callback_event); - ses_data->callbacks = g_list_remove( - ses_data->callbacks, - node_data); - free(node_data); - node_data = NULL; - break; - } - } - } - } - - return 0; -} - -static void *signal_threadloop(void *cookie) { - agm_client_session_data *ses_data = (agm_client_session_data *)cookie; - - AGM_LOGD("Enter %s %p\n", __func__, ses_data); - if (!ses_data) { - AGM_LOGE("Invalid thread params"); - goto exit; - } - - ses_data->loop = g_main_loop_new(NULL, FALSE); - AGM_LOGD("initiate main loop run for callbacks"); - g_main_loop_run(ses_data->loop); - - AGM_LOGD("out of main loop\n"); - g_main_loop_unref(ses_data->loop); - -exit: - return NULL; -} - -static void *ses_signal_threadloop(void *cookie) { - agm_client_session_data *ses_data = (agm_client_session_data *)cookie; - - AGM_LOGD("Enter %s %p\n", __func__, ses_data); - if (!ses_data) { - AGM_LOGE("Invalid thread params"); - goto exit; - } - - ses_data->ses_loop = g_main_loop_new(NULL, FALSE); - AGM_LOGE("initiate ses main loop run for callbacks"); - g_main_loop_run(ses_data->ses_loop); - - AGM_LOGE("out of ses main loop\n"); - g_main_loop_unref(ses_data->ses_loop); - -exit: - return NULL; -} - - -static int agm_session_deregister_cb(uint32_t session_id, - enum event_type evt_type, - void *client_data) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - agm_client_session_data *ses_data = NULL; - char *obj_path = NULL; - agm_callback_data *cb_data; - GList *node = NULL; - uint64_t data; - - AGM_LOGD("%s\n", __func__); - - data = (uint64_t)client_data; - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(evt_type); - value_3 = g_variant_new_uint64(data); - - argument = g_variant_new("(@u@u@t)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionDeRegisterCb", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionDeRegisterCb: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - if ((ses_data = (agm_client_session_data *) - g_hash_table_lookup(mdata->ses_hash_table, - GINT_TO_POINTER(session_id))) == NULL) { - ses_data = (agm_client_session_data *) - g_malloc0(sizeof(agm_client_session_data)); - - g_variant_get(result, "(o)", &ses_data->obj_path); - ses_data->conn = mdata->conn; - - ses_data->proxy = g_dbus_proxy_new_sync(ses_data->conn, - G_DBUS_PROXY_FLAGS_NONE, - NULL, - AGM_DBUS_CONNECTION, - ses_data->obj_path, - AGM_SESSION_IFACE, - NULL, - &error); - - if (ses_data->proxy == NULL) { - AGM_LOGE("%s: Error in getting dbus proxy: %s", __func__, - error->message); - rc = -EINVAL; - free(ses_data); - ses_data = NULL; - g_error_free(error); - goto exit; - } - - ses_data->session_id = session_id; - /* add session to sessions hash table */ - g_hash_table_insert(mdata->ses_hash_table, - GINT_TO_POINTER - (ses_data->session_id), - ses_data); - } - - cb_data = (agm_callback_data *)malloc(sizeof(agm_callback_data)); - cb_data->client_data = client_data; - cb_data->session_id = session_id; - cb_data->cb = NULL; - - if (subscribe_callback_event(ses_data, false, cb_data)) { - AGM_LOGE("Unable to subscribe for callback event\n"); - g_error_free(error); - g_free(ses_data); - g_free(cb_data); - rc = -EINVAL; - } - - g_free(cb_data); - cb_data = NULL; - g_variant_unref(result); - -exit: - return rc; -} - -int agm_session_register_cb(uint32_t session_id, - agm_event_cb cb, - enum event_type evt_type, - void *client_data) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - agm_client_session_data *ses_data = NULL; - char *obj_path = NULL; - agm_callback_data *cb_data; - gchar thread_name[16] = ""; - uint64_t data; - - AGM_LOGD("%s\n", __func__); - - if (cb == NULL) - return agm_session_deregister_cb(session_id, evt_type, client_data); - - data = (uint64_t)client_data; - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(evt_type); - value_3 = g_variant_new_uint64(data); - - argument = g_variant_new("(@u@u@t)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionRegisterCb", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionRegisterCb: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - if ((ses_data = (agm_client_session_data *) - g_hash_table_lookup(mdata->ses_hash_table, - GINT_TO_POINTER(session_id))) == NULL) { - ses_data = (agm_client_session_data *) - g_malloc0(sizeof(agm_client_session_data)); - - g_variant_get(result, "(o)", &ses_data->obj_path); - ses_data->conn = mdata->conn; - - ses_data->proxy = g_dbus_proxy_new_sync(ses_data->conn, - G_DBUS_PROXY_FLAGS_NONE, - NULL, - AGM_DBUS_CONNECTION, - ses_data->obj_path, - AGM_SESSION_IFACE, - NULL, - &error); - - if (ses_data->proxy == NULL) { - AGM_LOGE("%s: Error in getting dbus proxy: %s", __func__, - error->message); - rc = -EINVAL; - free(ses_data); - ses_data = NULL; - g_error_free(error); - goto exit; - } - - ses_data->session_id = session_id; - snprintf(thread_name, sizeof(thread_name), "agm_loop_%d", session_id); - AGM_LOGD("%s:create thread %s\n", __func__, thread_name); - ses_data->thread_loop = g_thread_try_new(thread_name, signal_threadloop, - ses_data, &error); - if (!ses_data->thread_loop) { - rc = -EINVAL; - AGM_LOGE("Could not create thread %s, error %s\n", thread_name, - error->message); - g_error_free(error); - g_free(ses_data); - goto exit; - } - /* add session to sessions hash table */ - g_hash_table_insert(mdata->ses_hash_table, - GINT_TO_POINTER(ses_data->session_id), - ses_data); - } - - cb_data = (agm_callback_data *)malloc(sizeof(agm_callback_data)); - cb_data->client_data = client_data; - cb_data->session_id = session_id; - cb_data->cb = cb; - cb_data->evt_type = evt_type; - - if (subscribe_callback_event(ses_data, true, cb_data)) { - AGM_LOGE("Unable to subscribe for callback event\n"); - g_error_free(error); - g_free(ses_data); - g_free(cb_data); - rc = -EINVAL; - } - - g_variant_unref(result); - -exit: - return rc; -} - -int agm_session_register_for_events(uint32_t session_id, - struct agm_event_reg_cfg *evt_reg_cfg) { - GVariant *value_1, *value_2, *value_arr, *argument; - GVariantBuilder builder_1; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - g_assert(evt_reg_cfg != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(session_id); - g_variant_builder_init(&builder_1, G_VARIANT_TYPE("(uuuyay)")); - g_variant_builder_add(&builder_1, - "u", - (guint32)evt_reg_cfg->module_instance_id); - g_variant_builder_add(&builder_1, - "u", - (guint32)evt_reg_cfg->event_id); - g_variant_builder_add(&builder_1, - "u", - (guint32)evt_reg_cfg->event_config_payload_size); - g_variant_builder_add(&builder_1, "y", (guint32)evt_reg_cfg->is_register); - - value_arr = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)&evt_reg_cfg->event_config_payload[0], - evt_reg_cfg->event_config_payload_size, - sizeof(guchar)); - g_variant_builder_add_value(&builder_1, value_arr); - value_2 = g_variant_builder_end(&builder_1); - - argument = g_variant_new("(@u@(uuuyay))", value_1, value_2); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionRegisterForEvents", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionRegisterForEvents: %s\n", - __func__, error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_session_aif_set_cal(uint32_t session_id, - uint32_t aif_id, - struct agm_cal_config *cal_config) { - GVariant *value_1, *value_2, *value_3, *value_4; - GVariant *argument, *argument_2; - GVariantBuilder builder_1; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - gint i = 0; - - AGM_LOGD("%s :", __func__); - g_assert(cal_config != NULL); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(aif_id); - value_3 = g_variant_new_uint32(cal_config->num_ckvs); - value_4 = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)cal_config->kv, - cal_config->num_ckvs* - sizeof(struct agm_key_value), - sizeof(gchar)); - - argument = g_variant_new("(@u@u@u@ay)", value_1, value_2, value_3, value_4); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionAifSetCal", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionAifSetCal: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_session_aif_set_params(uint32_t session_id, - uint32_t aif_id, - void* payload, - size_t size) { - GVariant *value_1, *value_2, *value_3, *value_4, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - g_assert(payload != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(aif_id); - value_3 = g_variant_new_uint32(size); - value_4 = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)payload, - size, - sizeof(gchar)); - - argument = g_variant_new("(@u@u@u@ay)", value_1, value_2, value_3, value_4); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionAifSetParams", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionAifSetParams: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_session_aif_get_tag_module_info_size(uint32_t session_id, - uint32_t aif_id, - size_t *size) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - AGM_LOGD("%s\n", __func__); - - g_assert(size != NULL); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(aif_id); - value_3 = g_variant_new_uint32(*size); - - argument = g_variant_new("(@u@u@u)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionAifGetTagModuleInfoSize", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionAifGetTagModuleInfo: %s\n", - __func__, error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_get(result, "(u)", size); - g_variant_unref(result); - return rc; -} - -int agm_session_aif_get_tag_module_info(uint32_t session_id, - uint32_t aif_id, - void *payload, - size_t *size) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GVariant *val_arr = NULL; - GError *error = NULL; - gsize n_elements = 0; - gsize element_size = sizeof(guchar); - GVariant *array_v; - GVariantIter arg_i; - gconstpointer value; - int rc = 0; - - AGM_LOGD("%s\n", __func__); - - if (payload == NULL) - return agm_session_aif_get_tag_module_info_size(session_id, - aif_id, - size); - - g_assert(size != NULL); - g_assert(payload != NULL); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(aif_id); - value_3 = g_variant_new_uint32(*size); - - argument = g_variant_new("(@u@u@u)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionAifGetTagModuleInfo", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionAifGetTagModuleInfo: %s\n", - __func__, error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_iter_init(&arg_i, result); - g_variant_iter_next(&arg_i, "u", size); - array_v = g_variant_iter_next_value(&arg_i); - value = g_variant_get_fixed_array(array_v, &n_elements, element_size); - memcpy(payload, value, n_elements); - g_variant_unref(array_v); - g_variant_unref(result); - return rc; -} - -int agm_session_aif_connect(uint32_t session_id, - uint32_t aif_id, - bool state) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(aif_id); - value_3 = g_variant_new_boolean(state); - - argument = g_variant_new("(@u@u@b)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionAifConnect", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionAifConnect: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_session_set_ec_ref(uint32_t capture_session_id, - uint32_t aif_id, - bool state) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(capture_session_id); - value_2 = g_variant_new_uint32(aif_id); - value_3 = g_variant_new_boolean(state); - - argument = g_variant_new("(@u@u@b)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionSetEcRef", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionSetEcRef: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_session_get_params(uint32_t session_id, void* payload, size_t size) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *val_arr = NULL, *result = NULL; - GError *error = NULL; - gconstpointer value; - gsize n_elements; - gsize element_size = sizeof(guchar); - int rc = 0; - - g_assert(payload != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(size); - value_3 = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)payload, - size, - sizeof(gchar)); - - argument = g_variant_new("(@u@u@ay)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionGetParams", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionGetParams: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - val_arr = g_variant_get_child_value(result, 0); - value = g_variant_get_fixed_array(val_arr, &n_elements, element_size); - if (n_elements <= size) { - memcpy(payload, value, n_elements); - } else { - AGM_LOGE("Insufficient bytes size to copy bytes read\n"); - return -ENOMEM; - } - - g_variant_unref(val_arr); - g_variant_unref(result); - return rc; -} - -int agm_session_set_params(uint32_t session_id, void* payload, size_t size) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - g_assert(payload != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(size); - value_3 = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)payload, - size, - sizeof(gchar)); - - argument = g_variant_new("(@u@u@ay)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionSetParams", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionSetParams: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -static int agm_get_aif_info_list_size(size_t *num_aif_info) { - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - AGM_LOGD("%s\n", __func__); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmGetAifInfoListSize", - NULL, - G_DBUS_CALL_FLAGS_NONE, - G_MAXINT, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmGetAifInfoListSize: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_get(result, "(u)", num_aif_info); - g_variant_unref(result); - return rc; -} - -int agm_get_aif_info_list(struct aif_info *aif_list, size_t *num_aif_info) { - GVariant *value_1 = NULL, *argument = NULL; - GVariant *result = NULL, *array_v, *struct_v; - GError *error = NULL; - GVariantIter arg_i, struct_i, array_i; - int rc = 0, i = 0; - const char *name = NULL; - - g_assert(num_aif_info != NULL); - AGM_LOGD("%s\n", __func__); - - if (*num_aif_info == 0) { - return agm_get_aif_info_list_size(num_aif_info); - } else { - g_assert(aif_list != NULL); - value_1 = g_variant_new_uint32(*num_aif_info); - - argument = g_variant_new("(@u)", value_1); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmGetAifInfoList", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmGetAifInfoList: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - } - - g_variant_iter_init(&arg_i, result); - array_v = g_variant_iter_next_value(&arg_i); - g_variant_iter_init(&array_i, array_v); - for (i = 0; i < *num_aif_info; i++) { - struct_v = g_variant_iter_next_value(&array_i); - g_variant_iter_init(&struct_i, struct_v); - g_variant_iter_next(&struct_i, "u", &aif_list[i].dir); - g_variant_iter_next(&struct_i, "s", &name); - strlcpy(aif_list[i].aif_name, name, (strlen(name) +1)); - g_variant_unref(struct_v); - } - g_variant_unref(array_v); - g_variant_unref(result); - - return rc; -} -int agm_session_get_buf_info(uint32_t session_id, struct agm_buf_info *buf_info, - uint32_t flag) -{ - GVariant *value_1 = NULL, *value_2 = NULL, *struct_v = NULL, *argument = NULL; - GVariant *val_arr = NULL, *result = NULL; - GVariantIter arg_i, struct_i; - GError *error = NULL; - gconstpointer value; - gsize n_elements; - gsize element_size = sizeof(guchar); - int rc = 0; - - AGM_LOGD("%s\n", __func__); - - if(!buf_info) { - AGM_LOGE("%s: buf_info is NULL\n", __func__); - return -EINVAL; - } - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(flag); - - argument = g_variant_new("(@u@u)", value_1, value_2); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionGetBufInfo", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionGetBufInfo: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_iter_init(&arg_i, result); - struct_v = g_variant_iter_next_value(&arg_i); - g_variant_iter_init(&struct_i, struct_v); - g_variant_iter_next(&struct_i, "i", &buf_info->data_buf_fd); - g_variant_iter_next(&struct_i, "i", &buf_info->data_buf_size); - g_variant_iter_next(&struct_i, "i", &buf_info->pos_buf_fd); - g_variant_iter_next(&struct_i, "i", &buf_info->pos_buf_size); - g_variant_unref(result); - return rc; -} - -int agm_aif_set_params(uint32_t aif_id, void* payload, - size_t size) { - GVariant *value_1 = NULL, *value_2 = NULL, *value_3 = NULL, *argument = NULL; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - g_assert(payload != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(aif_id); - value_2 = g_variant_new_uint32(size); - value_3 = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)payload, - size, - sizeof(gchar)); - - argument = g_variant_new("(@u@u@ay)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmAifSetParams", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmAifSetParams: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_set_params_with_tag(uint32_t session_id, - uint32_t aif_id, - struct agm_tag_config *tag_config) { - GVariant *value_1, *value_2, *value_3, *value_4, *value_5; - GVariant *argument, *argument_2; - GVariantBuilder builder_1; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - gint i = 0; - - g_assert(tag_config != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(aif_id); - value_3 = g_variant_new_uint32(tag_config->tag); - value_4 = g_variant_new_uint32(tag_config->num_tkvs); - - g_variant_builder_init(&builder_1, G_VARIANT_TYPE("a(uu)")); - for (i = 0; i < tag_config->num_tkvs; i++) { - g_variant_builder_open(&builder_1, G_VARIANT_TYPE("(uu)")); - g_variant_builder_add(&builder_1, "u", (guint32)tag_config->kv[i].key); - g_variant_builder_add(&builder_1, "u", - (guint32)tag_config->kv[i].value); - g_variant_builder_close(&builder_1); - } - - value_5 = g_variant_builder_end(&builder_1); - - argument_2 = g_variant_new("(@u@u@a(uu))", value_3, value_4, value_5); - - argument = g_variant_new("(@u@u@(uua(uu)))", value_1, value_2, argument_2); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSetParamsWithTag", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSetParamsWithTag: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_session_set_loopback(uint32_t capture_session_id, - uint32_t playback_session_id, - bool state) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(capture_session_id); - value_2 = g_variant_new_uint32(playback_session_id); - value_3 = g_variant_new_boolean(state); - - argument = g_variant_new("(@u@u@b)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionSetLoopback", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionSetLoopback: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_session_set_metadata(uint32_t session_id, - uint32_t size, uint8_t *metadata) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - g_assert(metadata != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(size); - value_3 = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)metadata, - size, - sizeof(gchar)); - - argument = g_variant_new("(@u@u@ay)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionSetMetadata", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionSetMetadata: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_session_aif_set_metadata(uint32_t session_id, - uint32_t aif_id, - uint32_t size, uint8_t *metadata) { - GVariant *value_1, *value_2, *value_3, *value_4, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - g_assert(metadata != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(aif_id); - value_3 = g_variant_new_uint32(size); - value_4 = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)metadata, - size, - sizeof(gchar)); - - argument = g_variant_new("(@u@u@u@ay)", value_1, value_2, value_3, value_4); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionAifSetMetadata", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionAifSetMetadata: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_aif_set_metadata(uint32_t aif_id, - uint32_t size, uint8_t *metadata) { - GVariant *value_1, *value_2, *value_3, *argument; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - g_assert(metadata != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(aif_id); - value_2 = g_variant_new_uint32(size); - value_3 = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)metadata, - size, - sizeof(gchar)); - - argument = g_variant_new("(@u@u@ay)", value_1, value_2, value_3); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmAifSetMetadata", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmAifSetMetadata: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_aif_set_media_config(uint32_t aif_id, - struct agm_media_config *media_config) { - GVariant *value_1, *value_2, *argument; - GVariantBuilder builder_1; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - g_assert(media_config != NULL); - AGM_LOGD("%s\n", __func__); - - value_1 = g_variant_new_uint32(aif_id); - - g_variant_builder_init(&builder_1, G_VARIANT_TYPE("(uuiu)")); - g_variant_builder_add(&builder_1, "u", (guint32)media_config->rate); - g_variant_builder_add(&builder_1, "u", (guint32)media_config->channels); - g_variant_builder_add(&builder_1, "i", (gint32)media_config->format); - g_variant_builder_add(&builder_1, "u", (guint32)media_config->data_format); - value_2 = g_variant_builder_end(&builder_1); - - argument = g_variant_new("(@u@(uuiu))", value_1, value_2); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmAifSetMediaConfig", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmAifSetMediaConfig: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_unref(result); - return rc; -} - -int agm_get_buffer_timestamp(uint32_t session_id, uint64_t *timestamp) { - GVariant *argument = NULL; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - AGM_LOGD("%s\n", __func__); - - argument = g_variant_new("(@u)", g_variant_new_uint32(session_id)); - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmGetBufferTimestamp", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmGetBufferTimestamp: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - return rc; - } - - g_variant_get(result, "(t)", timestamp); - g_variant_unref(result); - return rc; -} - -size_t agm_get_hw_processed_buff_cnt(uint64_t handle, enum direction dir) { - GVariant *argument = NULL; - GVariant *result = NULL; - GError *error = NULL; - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - size_t bufCount; - int rc = 0; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - - AGM_LOGD("%s\n", __func__); - - argument = g_variant_new("(@u)", g_variant_new_uint32(dir)); - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmGetHwProcessedBufCount", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmGetHwProcessedBufCount: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - g_variant_get(result, "(i)", &bufCount); - g_variant_unref(result); - return bufCount; -} - -int agm_get_session_time(uint64_t handle, uint64_t *timestamp) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result; - GError *error = NULL; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - g_assert(timestamp != NULL); - - AGM_LOGD("%s\n", __func__); - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionGetTime", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionGetTime: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - g_variant_get(result, "(t)", timestamp); - g_variant_unref(result); - return 0; -} - -int agm_session_eos(uint64_t handle) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result; - GError *error = NULL; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - - AGM_LOGD("%s\n", __func__); - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionEos", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionEos: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - g_variant_unref(result); - return 0; -} - -int agm_session_set_config(uint64_t handle, - struct agm_session_config *session_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result = NULL, *arr = NULL, *argument = NULL, *value_1, *value_2; - GError *error = NULL; - GVariantBuilder builder_1; - - g_assert(ses_data != NULL); - g_assert(session_config != NULL); - g_assert(media_config != NULL); - g_assert(buffer_config != NULL); - g_assert(ses_data->proxy != NULL); - - AGM_LOGD("%s\n", __func__); - - g_variant_builder_init(&builder_1, G_VARIANT_TYPE("(uuu)")); - g_variant_builder_add(&builder_1, "u", (guint32)media_config->rate); - g_variant_builder_add(&builder_1, "u", (guint32)media_config->channels); - g_variant_builder_add(&builder_1, "u", (guint32)media_config->format); - value_1 = g_variant_builder_end(&builder_1); - - g_variant_builder_init(&builder_1, G_VARIANT_TYPE("(uu)")); - g_variant_builder_add(&builder_1, "u", (guint32)buffer_config->count); - g_variant_builder_add(&builder_1, "u", (guint32)buffer_config->size); - value_2 = g_variant_builder_end(&builder_1); - - arr = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)session_config, - sizeof(struct agm_session_config), - sizeof(guchar)); - - argument = g_variant_new("(@(uuu)@(uu)@ay)", - value_1, - value_2, - arr); - - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionSetConfig", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionSetConfig: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - g_variant_unref(result); - return 0; -} - -int agm_session_write(uint64_t handle, void *buf, size_t *byte_count) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result = NULL, *arr = NULL, *argument = NULL; - GError *error = NULL; - gint64 start_time, end_time; - int ret = 0; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - AGM_LOGD("%s\n", __func__); - - arr = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, - (gconstpointer)buf, - *byte_count, - sizeof(guchar)); - argument = g_variant_new("(@u@ay)", g_variant_new_uint32(*byte_count), arr); - - g_mutex_lock(&ses_data->mutex); - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionWrite", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionWrite: %s\n", __func__, - error->message); - g_error_free(error); - g_mutex_unlock(&ses_data->mutex); - return -EINVAL; - } - - start_time = g_get_monotonic_time(); - end_time = start_time + (AGM_DBUS_ASYNC_CALL_TIMEOUT_MS * G_TIME_SPAN_MILLISECOND); - g_cond_wait_until(&ses_data->cond, &ses_data->mutex, end_time); - if (g_get_monotonic_time() >= end_time){ - AGM_LOGE("%s: -ETIMEDOUT %d\n", __func__, g_get_monotonic_time()); - } - - g_mutex_unlock(&ses_data->mutex); - g_variant_get(result, "(u)", byte_count); - g_variant_unref(result); - return ret; -} - -int agm_session_read(uint64_t handle, void *buf, size_t *byte_count) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result = NULL, *val_arr = NULL, *argument = NULL; - GError *error = NULL; - GVariantIter arg_i; - gconstpointer value; - gsize n_elements; - gsize element_size = sizeof(guchar); - gint64 start_time, end_time; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - AGM_LOGD("%s\n", __func__); - - argument = g_variant_new("(@u)", g_variant_new_uint32(*byte_count)); - ses_data->buf_size = *byte_count; - ses_data->buf = buf; - - g_mutex_lock(&ses_data->mutex); - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionRead", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionRead: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - start_time = g_get_monotonic_time(); - end_time = start_time + (AGM_DBUS_ASYNC_CALL_TIMEOUT_MS * G_TIME_SPAN_MILLISECOND); - g_cond_wait_until(&ses_data->cond, &ses_data->mutex, end_time); - if (g_get_monotonic_time() >= end_time){ - AGM_LOGE("%s: -ETIMEDOUT %d\n", __func__, g_get_monotonic_time()); - } - *byte_count = ses_data->buf_size; - - g_mutex_unlock(&ses_data->mutex); - g_variant_unref(result); - return 0; -} - -int agm_session_resume(uint64_t handle) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result = NULL; - GError *error = NULL; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - AGM_LOGD("%s\n", __func__); - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionResume", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionResume: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - g_variant_unref(result); - return 0; -} - -int agm_session_pause(uint64_t handle) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result = NULL; - GError *error = NULL; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - AGM_LOGD("%s\n", __func__); - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionPause", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionPause: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - g_variant_unref(result); - return 0; -} - -int agm_session_stop(uint64_t handle) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result = NULL; - GError *error = NULL; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - AGM_LOGD("%s\n", __func__); - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionStop", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionStop: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - g_variant_unref(result); - return 0; -} - -int agm_session_start(uint64_t handle) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result = NULL; - GError *error = NULL; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - AGM_LOGD("%s\n", __func__); - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionStart", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionStart: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - g_variant_unref(result); - return 0; -} - -int agm_session_prepare(uint64_t handle) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result = NULL; - GError *error = NULL; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - AGM_LOGD("%s\n", __func__); - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionPrepare", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionPrepare: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - g_variant_unref(result); - return 0; -} - -int agm_session_close(uint64_t handle) { - agm_client_session_data *ses_data = (agm_client_session_data *) handle; - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - - g_assert(ses_data != NULL); - g_assert(ses_data->proxy != NULL); - AGM_LOGD("%s\n", __func__); - - result = g_dbus_proxy_call_sync(ses_data->proxy, - "AgmSessionClose", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionClose: %s\n", __func__, - error->message); - g_error_free(error); - return -EINVAL; - } - - free_callbacks(ses_data); - - if (ses_data->thread_loop) { - AGM_LOGE("%s:Quitting loop", __func__); - g_main_loop_quit(ses_data->loop); - g_thread_join(ses_data->thread_loop); - ses_data->thread_loop = NULL; - } - - subscribe_ses_callback_event(ses_data, false); - g_cond_clear(&ses_data->cond); - g_mutex_clear(&ses_data->mutex); - - if (ses_data->ses_thread_loop) { - AGM_LOGE("Quitting ses thread loop"); - g_main_loop_quit(ses_data->ses_loop); - g_thread_join(ses_data->ses_thread_loop); - ses_data->ses_thread_loop = NULL; - } - - g_hash_table_remove(mdata->ses_hash_table, - GINT_TO_POINTER(ses_data->session_id)); - g_free(ses_data->obj_path); - - if (ses_data->proxy != NULL) { - g_object_unref(ses_data->proxy); - ses_data->proxy = NULL; - } - - g_free(ses_data); - g_variant_unref(result); - return 0; -} - -int agm_session_open(uint32_t session_id, enum agm_session_mode sess_mode, uint64_t *handle) { - - GVariant *value_1 = NULL, *value_2 = NULL, *argument = NULL; - - GVariant *result = NULL; - GError *error = NULL; - int rc = 0; - agm_client_session_data *ses_data = NULL; - agm_callback_data *cb_data; - gchar thread_name[16] = ""; - - g_assert(handle != NULL); - AGM_LOGD("%s\n", __func__); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - return rc; - } - - value_1 = g_variant_new_uint32(session_id); - value_2 = g_variant_new_uint32(sess_mode); - - argument = g_variant_new("(@u@u)", value_1, value_2); - - - result = g_dbus_proxy_call_sync(mdata->proxy, - "AgmSessionOpen", - argument, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - - if (result == NULL) { - AGM_LOGE("%s: Error invoking AgmSessionOpen: %s\n", __func__, - error->message); - g_error_free(error); - rc = -EINVAL; - goto exit; - } - - - if ((ses_data = (agm_client_session_data *)g_hash_table_lookup( - mdata->ses_hash_table, - GINT_TO_POINTER(session_id))) == NULL) { - ses_data = (agm_client_session_data *) - g_malloc0(sizeof(agm_client_session_data)); - - g_variant_get(result, "(o)", &ses_data->obj_path); - ses_data->conn = mdata->conn; - *handle = (uint64_t)ses_data; - - ses_data->proxy = g_dbus_proxy_new_sync(ses_data->conn, - G_DBUS_PROXY_FLAGS_NONE, - NULL, - AGM_DBUS_CONNECTION, - ses_data->obj_path, - AGM_SESSION_IFACE, - NULL, - &error); - - if (ses_data->proxy == NULL) { - AGM_LOGE("%s: Error in getting dbus proxy: %s", __func__, - error->message); - rc = -EINVAL; - g_error_free(error); - goto exit; - } - - ses_data->session_id = session_id; - /* add session to sessions hash table */ - g_hash_table_insert(mdata->ses_hash_table, - GINT_TO_POINTER(ses_data->session_id), - ses_data); - g_variant_unref(result); - } else { - *handle = (uint64_t)ses_data; - } - - g_mutex_init(&ses_data->mutex); - g_cond_init(&ses_data->cond); - snprintf(thread_name, sizeof(thread_name), "ses_loop_%d", session_id); - AGM_LOGD("create thread %s\n", thread_name); - ses_data->ses_thread_loop = g_thread_try_new(thread_name, ses_signal_threadloop, ses_data, &error); - if (!ses_data->ses_thread_loop) { - rc = -EINVAL; - AGM_LOGE("Could not create thread %s, error %s\n", thread_name, - error->message); - g_error_free(error); - g_free(ses_data); - goto exit; - } - - if (subscribe_ses_callback_event(ses_data, true)) { - AGM_LOGE("Unable to subscribe for ses callback event\n"); - g_error_free(error); - g_free(ses_data); - rc = -EINVAL; - } - - return rc; - -exit: - if (ses_data != NULL) - g_free(ses_data); - return rc; -} - -int agm_init() { - GError *error = NULL; - int rc = 0; - - AGM_LOGD("%s\n", __func__); - - if (mdata == NULL) { - if ((rc = initialize_module_data()) != 0) - goto exit; - } - - return rc; - -exit: - if (mdata) - g_free(mdata); - return rc; -} - -int agm_deinit() { -} diff --git a/qcom/opensource/agm/ipc/DBus/agm_server/Makefile.am b/qcom/opensource/agm/ipc/DBus/agm_server/Makefile.am deleted file mode 100755 index f61c0c58..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_server/Makefile.am +++ /dev/null @@ -1,31 +0,0 @@ -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = agmserver.pc -EXTRA_DIST = $(pkgconfig_DATA) - -h_sources = ${top_srcdir}/inc/agm-dbus-utils.h \ - ${top_srcdir}/inc/agm_server_wrapper_dbus.h - -AM_CPPFLAGS = -Wno-narrowing -AM_CPPFLAGS += -I ${top_srcdir}/inc -AM_CPPFLAGS += -I ${WORKSPACE}/vendor/qcom/opensource/agm/service/inc -AM_CPPFLAGS += -D__unused=__attribute__\(\(__unused__\)\) -AM_CPPFLAGS += $(GLIB_CFLAGS) -Dstrlcpy=g_strlcpy -Dstrlcat=g_strlcat -include glib.h - -library_include_HEADERS = $(h_sources) -library_includedir = $(includedir)/agm - -agmserver_sources = ${top_srcdir}/src/agm-dbus-utils.cpp \ - ${top_srcdir}/src/agm_server_wrapper_dbus.cpp - -lib_LTLIBRARIES = libagmserverwrapper.la -libagmserverwrapper_la_SOURCES = $(agmserver_sources) -libagmserverwrapper_la_CPPFLAGS := $(AM_CPPFLAGS) $(DBUS_CFLAGS) -libagmserverwrapper_la_LIBADD = -lagm -laudio_log_utils -lar_osal -libagmserverwrapper_la_LDFLAGS = -ldl -shared -avoid-version -lpthread -lar_osal $(DBUS_LIBS) - -bin_PROGRAMS := agm_server - -agm_server_SOURCES := ./src/agm-server-daemon.cpp -agm_server_la_CPPFLAGS := $(AM_CPPFLAGS) -agm_server_LDADD = libagmserverwrapper.la -laudio_log_utils -lar_osal -llog $(GLIB_LIBS) -agm_server_la_LDFLAGS = -ldl -shared -avoid-version diff --git a/qcom/opensource/agm/ipc/DBus/agm_server/agmserver.pc.in b/qcom/opensource/agm/ipc/DBus/agm_server/agmserver.pc.in deleted file mode 100755 index 5d5d01c2..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_server/agmserver.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: agmserver -Description: agmserver library -Version: @VERSION@ -Libs: -L${libdir} -lagmserver -Cflags: -I${includedir}/mm-audio/qti-agm-server diff --git a/qcom/opensource/agm/ipc/DBus/agm_server/configure.ac b/qcom/opensource/agm/ipc/DBus/agm_server/configure.ac deleted file mode 100755 index 61aa384a..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_server/configure.ac +++ /dev/null @@ -1,79 +0,0 @@ -# -*- Autoconf -*- -# configure.ac -- Autoconf script for halinterface -# - -# Process this file with autoconf to produce a configure script. - -# Requires autoconf tool later than 2.61 -AC_PREREQ([2.69]) -# Initialize the hal-interface package version 1.0.0 -AC_INIT(halinterface,1.0.0) -# Does not strictly follow GNU Coding standards -AM_INIT_AUTOMAKE([foreign]) -# Disables auto rebuilding of configure, Makefile.ins -#AM_MAINTAINER_MODE -# defines some macros variable to be included by source -AC_CONFIG_HEADERS([config.h]) -# defines some macros variable to be included by source -AC_CONFIG_MACRO_DIR([m4]) - -# Checks for programs. -AC_PROG_CC -AM_PROG_CC_C_O -AC_PROG_CXX -AC_PROG_LIBTOOL -AC_PROG_AWK -AC_PROG_CPP -AC_PROG_INSTALL -AC_PROG_LN_S -AC_PROG_MAKE_SET -PKG_PROG_PKG_CONFIG - -AC_ARG_WITH([glib], - AC_HELP_STRING([--with-glib], - [enable glib, Build against glib. Use this when building for HLOS systems which use glib])) - -if (test "x${with_glib}" = "xyes"); then - PKG_CHECK_MODULES(GTHREAD, gthread-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GThread >= 2.16 is required)) - PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GLib >= 2.16 is required)) - GLIB_CFLAGS="$GLIB_CFLAGS $GTHREAD_CFLAGS" - GLIB_LIBS="$GLIB_LIBS $GTHREAD_LIBS" - - AC_SUBST(GLIB_CFLAGS) - AC_SUBST(GLIB_LIBS) -fi - -AM_CONDITIONAL(USE_GLIB, test "x${with_glib}" = "xyes") - -AC_ARG_ENABLE([dbus], - AS_HELP_STRING([--disable-dbus],[Disable optional D-Bus support])) - -AS_IF([test "x$enable_dbus" != "xno"], - [PKG_CHECK_MODULES(DBUS, [ dbus-1 >= 1.4.12 ], HAVE_DBUS=1, HAVE_DBUS=0)], - HAVE_DBUS=0) - -AS_IF([test "x$enable_dbus" = "xyes" && test "x$HAVE_DBUS" = "x0"], - [AC_MSG_ERROR([*** D-Bus not available or too old version])]) - -AS_IF([test "x$HAVE_DBUS" = "x1"], - [ - save_CFLAGS="$CFLAGS"; CFLAGS="$CFLAGS $DBUS_CFLAGS" - save_LIBS="$LIBS"; LIBS="$LIBS $DBUS_LIBS" - AC_CHECK_FUNCS(dbus_watch_get_unix_fd) - CFLAGS="$save_CFLAGS" - LIBS="$save_LIBS" - ]) - -AC_SUBST(HAVE_DBUS) -AM_CONDITIONAL([HAVE_DBUS], [test "x$HAVE_DBUS" = x1]) -AS_IF([test "x$HAVE_DBUS" = "x1"], AC_DEFINE([HAVE_DBUS], 1, [Have D-Bus.])) - -AC_CONFIG_FILES([ \ - Makefile \ - agmserver.pc - ]) - -AC_OUTPUT - diff --git a/qcom/opensource/agm/ipc/DBus/agm_server/inc/agm-dbus-utils.h b/qcom/opensource/agm/ipc/DBus/agm_server/inc/agm-dbus-utils.h deleted file mode 100755 index 376cf4e3..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_server/inc/agm-dbus-utils.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -** Copyright (c) 2020, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#include -#include -#include - -typedef void (*agm_dbus_receive_cb_t)(DBusConnection *conn, - DBusMessage *msg, - void *userdata); - -typedef struct { - const char *method_name; - const char *method_signature; - agm_dbus_receive_cb_t cb_func; -} agm_dbus_method; - -typedef struct { - const char *method_name; - const char *method_signature; -} agm_dbus_signal; - -typedef struct { - const char *name; - agm_dbus_method *methods; - int method_count; - agm_dbus_signal *signals; - int signal_count; -} agm_dbus_interface_info; - -typedef struct { - DBusConnection *conn; - guint watch_id; - int watch_fd; - DBusWatch *watch; -} agm_dbus_watch_data; - -typedef struct { - DBusConnection *conn; - guint timeout_id; - DBusTimeout *timeout; -} agm_dbus_timeout_data; - -typedef struct { - DBusConnection *conn; - GHashTable *objects; -} agm_dbus_connection; - -/* Creates a new agm_dbus_connection object and returns it */ -agm_dbus_connection *agm_dbus_new_connection(); - -/* Frees agm_dbus_connection object */ -void agm_dbus_connection_free(agm_dbus_connection *conn); - -/* Registers dbus interface with the object */ -int agm_dbus_add_interface(agm_dbus_connection *conn, - const char *dbus_obj_path, - agm_dbus_interface_info *interface_info, - void *userdata); - -/* Removes dbus interface from the object */ -int agm_dbus_remove_interface(agm_dbus_connection *conn, - const char *dbus_obj_path, - const char *interface); - -/* Sends error to dbus client */ -void agm_dbus_send_error(agm_dbus_connection *conn, - DBusMessage *msg, - char *dbus_error, - char *error); - -/* Sends a signal to dbus client */ -void agm_dbus_send_signal(agm_dbus_connection *conn, DBusMessage *msg); - -/* Sets the watch and timeout functions of a DBusConnection to integrate the - connection. Returns 0 on success */ -int agm_setup_dbus_with_main_loop(agm_dbus_connection *conn); diff --git a/qcom/opensource/agm/ipc/DBus/agm_server/inc/agm_server_wrapper_dbus.h b/qcom/opensource/agm/ipc/DBus/agm_server/inc/agm_server_wrapper_dbus.h deleted file mode 100755 index 78520fba..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_server/inc/agm_server_wrapper_dbus.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -** Copyright (c) 2020, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -int ipc_agm_init(); -void ipc_agm_deinit(); diff --git a/qcom/opensource/agm/ipc/DBus/agm_server/src/agm-dbus-utils.cpp b/qcom/opensource/agm/ipc/DBus/agm_server/src/agm-dbus-utils.cpp deleted file mode 100755 index 359b5a4d..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_server/src/agm-dbus-utils.cpp +++ /dev/null @@ -1,677 +0,0 @@ -/* -** Copyright (c) 2020, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -/* -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted (subject to the limitations in the -** disclaimer below) provided that the following conditions are met: -** -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** -** * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE -** GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT -** HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -** IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -** IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "agm_dbus_utils" - -#include -#include -#include - -#include "agm-dbus-utils.h" -#include "utils.h" - -#define DISPATCH_TIMEOUT 0 - -typedef struct { - const char *name; - GHashTable *methods; /* Key -> method_name Value -> agm_dbus_method */ - GHashTable *signals; /* Key -> method_name Value -> agm_dbus_signal */ - void *userdata; -} agm_dbus_interface; - -typedef struct { - const char *obj_path; - GHashTable *interfaces; /* Key -> interface name Value -> agm_dbus_interface */ -} agm_dbus_object; - -static DBusHandlerResult server_message_handler(DBusConnection *connection, - DBusMessage *message, - void *userdata) { - DBusHandlerResult result; - DBusMessage *reply = NULL; - DBusError err; - agm_dbus_connection *conn = (agm_dbus_connection *)userdata; - const char *dbus_obj_path = NULL; - const char *dbus_interface = NULL; - const char *dbus_method = NULL; - agm_dbus_object *object = NULL; - agm_dbus_interface *interface = NULL; - agm_dbus_method *method = NULL; - - if (dbus_message_get_type(message) != DBUS_MESSAGE_TYPE_METHOD_CALL) - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - - dbus_interface = dbus_message_get_interface(message); - dbus_method = dbus_message_get_member(message); - dbus_obj_path = dbus_message_get_path(message); - - if ((object = (agm_dbus_object *)g_hash_table_lookup - (conn->objects, dbus_obj_path)) == NULL) { - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } else { - if ((interface = (agm_dbus_interface *) - g_hash_table_lookup(object->interfaces, dbus_interface)) == NULL) { - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } else { - if ((method = (agm_dbus_method *) - g_hash_table_lookup(interface->methods, dbus_method)) == NULL) { - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } else { - method->cb_func(connection, message, interface->userdata); - return DBUS_HANDLER_RESULT_HANDLED; - } - } - } -} - -static DBusObjectPathVTable vtable = { - .unregister_function = NULL, - .message_function = server_message_handler, - .dbus_internal_pad1 = NULL, - .dbus_internal_pad2 = NULL, - .dbus_internal_pad3 = NULL, - .dbus_internal_pad4 = NULL -}; - -static void agm_handle_dispatch_status(DBusConnection *conn, - DBusDispatchStatus status, - void *userdata) { - if (status == DBUS_DISPATCH_DATA_REMAINS) { - while (dbus_connection_get_dispatch_status(conn) == - DBUS_DISPATCH_DATA_REMAINS) - dbus_connection_dispatch(conn); - } -} - -static void dispatch_status(DBusConnection *conn, - DBusDispatchStatus status, - void *userdata) -{ - if (!dbus_connection_get_is_connected(conn)) - return; - - agm_handle_dispatch_status(conn, status, userdata); -} - -static void agm_free_dbus_watch_data(void *userdata) { - agm_dbus_watch_data *watch_data = (agm_dbus_watch_data *)userdata; - - if (watch_data == NULL) { - AGM_LOGD("%s: Watch data is NULL\n", __func__); - return; - } - - if (watch_data->watch_id > 0) { - g_source_remove(watch_data->watch_id); - watch_data->watch_id = 0; - } - - if (watch_data->conn) - dbus_connection_unref(watch_data->conn); - - if (watch_data) - free(watch_data); -} - -static void agm_remove_dbus_watch_cb(DBusWatch *watch, void *userdata) { - if (dbus_watch_get_enabled(watch)) - return; - - /* Triggers agm_free_dbus_watch_data which is set in agm_add_dbus_watch_cb*/ - dbus_watch_set_data(watch, NULL, NULL); -} - -static gboolean agm_cond_watch_cb(GIOChannel *channel, - GIOCondition io_condition, - gpointer userdata) { - agm_dbus_watch_data *watch_data = (agm_dbus_watch_data *)userdata; - unsigned int flags = 0; - - flags |= (io_condition & G_IO_IN ? DBUS_WATCH_READABLE : 0) | - (io_condition & G_IO_OUT ? DBUS_WATCH_WRITABLE : 0) | - (io_condition & G_IO_HUP ? DBUS_WATCH_HANGUP : 0) | - (io_condition & G_IO_ERR ? DBUS_WATCH_ERROR : 0); - - /* Notifies the D-Bus library when a previously-added watch is ready for - reading or writing or has an exception */ - if (dbus_watch_handle(watch_data->watch, flags) == false) - AGM_LOGE("dbus_watch_handle() failed\n"); - - agm_handle_dispatch_status(watch_data->conn, - dbus_connection_get_dispatch_status(watch_data->conn), - (void *)userdata); - return true; -} - -static dbus_bool_t agm_add_dbus_watch_cb(DBusWatch *watch, void *userdata) { - agm_dbus_connection *conn = (agm_dbus_connection *) userdata; - agm_dbus_watch_data *watch_data = NULL; - dbus_bool_t status; - GIOChannel *channel; - int watch_fd; - unsigned int watch_flags; - GIOCondition io_condition; - - if (conn->conn == NULL) { - AGM_LOGE("%s: Connection is NULL\n", __func__); - return -1; - } - - status = dbus_watch_get_enabled(watch); - - if (!status) - return true; - - watch_data = (agm_dbus_watch_data *)calloc(1, sizeof(agm_dbus_watch_data)); - - if (watch_data == NULL) { - AGM_LOGE("%s: Couldn't allocate memory for watch_data\n", __func__); - return false; - } - - /* Gets unix file descriptor for DBusWatch object we want to watch */ - watch_data->watch_fd = dbus_watch_get_unix_fd(watch); - /* Creates a new GIOChannel given a file descriptor */ - channel = g_io_channel_unix_new(watch_data->watch_fd); - watch_data->watch = watch; - watch_data->conn = dbus_connection_ref(conn->conn); - - /* Sets data which can be retrieved with dbus_watch_get_data() */ - dbus_watch_set_data(watch_data->watch, watch_data, agm_free_dbus_watch_data); - /* Dbus flags indicating the conditions to be monitored on the dbus watch */ - watch_flags = dbus_watch_get_flags(watch_data->watch); - - if (watch_flags & DBUS_WATCH_READABLE) { - io_condition = G_IO_IN; - io_condition = (GIOCondition)(io_condition | (G_IO_HUP | G_IO_ERR)); - } else if (watch_flags & DBUS_WATCH_WRITABLE) { - io_condition = G_IO_OUT; - io_condition = (GIOCondition) (io_condition | (G_IO_HUP | G_IO_ERR)); - } else { - io_condition = (GIOCondition) (G_IO_HUP | G_IO_ERR); - } - - /* Adds IOChannel to default main loop and calls the provided function - whenever condition is satisfied */ - watch_data->watch_id = g_io_add_watch_full(channel, - G_PRIORITY_DEFAULT, - io_condition, - agm_cond_watch_cb, - watch_data, - agm_free_dbus_watch_data); - g_io_channel_unref(channel); - return true; -} - -static void agm_toggle_dbus_watch_cb(DBusWatch *watch, void *userdata) { - if (dbus_watch_get_enabled(watch)) - agm_add_dbus_watch_cb(watch, userdata); - else - agm_remove_dbus_watch_cb(watch, userdata); -} - -static void agm_free_dbus_timeout_data(void *userdata) { - agm_dbus_timeout_data *timeout_data = (agm_dbus_timeout_data *)userdata; - - if (timeout_data == NULL) { - AGM_LOGE("%s: Timeout data is NULL\n", __func__); - return; - } - - if (timeout_data->timeout_id > 0) { - /* Removes the source with the given ID from the default main context.*/ - g_source_remove(timeout_data->timeout_id); - timeout_data->timeout_id = 0; - } - - dbus_connection_unref(timeout_data->conn); - free(timeout_data); -} - -static gboolean agm_timeout_dispatch_cb(gpointer userdata) { - agm_dbus_timeout_data *timeout_data = (agm_dbus_timeout_data *)userdata; - - timeout_data->timeout_id = 0; - - /* if not enabled should not be polled by the main loop */ - if (!dbus_timeout_get_enabled(timeout_data->timeout)) - return FALSE; - - dbus_timeout_handle(timeout_data->timeout); - - return FALSE; -} - -static void agm_remove_dbus_timeout_cb(DBusTimeout *timeout, void *userdata) { - /* This will trigger agm_free_dbus_timeout_data() */ - dbus_timeout_set_data(timeout, NULL, NULL); -} - -static dbus_bool_t agm_add_dbus_timeout_cb(DBusTimeout *timeout, - void *userdata) { - int interval; - agm_dbus_connection *conn = (agm_dbus_connection *) userdata; - agm_dbus_timeout_data *timeout_data = NULL; - dbus_bool_t status; - - if (conn->conn == NULL) { - AGM_LOGE("%s: Connection is NULL\n", __func__); - return -1; - } - - status = dbus_timeout_get_enabled(timeout); - - if (!status) - return true; - - timeout_data = (agm_dbus_timeout_data *) - calloc(1, sizeof(agm_dbus_timeout_data)); - - if (timeout_data == NULL) { - AGM_LOGE("%s: Couldn't allocate memory for timeout_data\n", __func__); - return false; - } - - interval = dbus_timeout_get_interval(timeout); - timeout_data->conn = dbus_connection_ref(conn->conn); - timeout_data->timeout = timeout; - - /* Sets data which can be retrieved with dbus_timeout_get_data() */ - dbus_timeout_set_data(timeout_data->timeout, - timeout_data, - agm_free_dbus_timeout_data); - /* Sets a function to be called at regular intervals - with the given priority */ - timeout_data->timeout_id = g_timeout_add_full(G_PRIORITY_DEFAULT, - interval, - agm_timeout_dispatch_cb, - timeout_data, - agm_free_dbus_timeout_data); - - return true; -} - -static void agm_toggle_dbus_timeout_cb(DBusTimeout *timeout, void *userdata) { - if (dbus_timeout_get_enabled(timeout)) - agm_add_dbus_timeout_cb(timeout, userdata); - else - agm_remove_dbus_timeout_cb(timeout, userdata); -} - -int agm_setup_dbus_with_main_loop(agm_dbus_connection *conn) { - if (conn == NULL) { - AGM_LOGE("%s: Connection object is NULL\n", __func__); - return -1; - } - - if (!dbus_connection_set_watch_functions(conn->conn, - agm_add_dbus_watch_cb, - agm_remove_dbus_watch_cb, - agm_toggle_dbus_watch_cb, - conn, - NULL)) { - AGM_LOGE("%s: dbus_connection_set_watch_functions failed\n", __func__); - return -1; - } - - if (!dbus_connection_set_timeout_functions(conn->conn, - agm_add_dbus_timeout_cb, - agm_remove_dbus_timeout_cb, - agm_toggle_dbus_timeout_cb, - conn, - NULL)) { - AGM_LOGE("%s: dbus_connection_set_timeout_functions failed\n", __func__); - return -1; - } - - dbus_connection_set_dispatch_status_function(conn->conn, - agm_handle_dispatch_status, - conn, - NULL); - - return 0; -} - -static void unregister_object(agm_dbus_connection *conn, - agm_dbus_object *object) { - dbus_connection_unregister_object_path(conn->conn, object->obj_path); -} - -void agm_dbus_send_signal(agm_dbus_connection *conn, DBusMessage *signal_msg) { - DBusMessage *signal_copy; - - signal_copy = dbus_message_copy(signal_msg); - dbus_connection_send(conn->conn, signal_copy, NULL); - dbus_message_unref(signal_copy); -} - -void agm_dbus_send_error(agm_dbus_connection *conn, - DBusMessage *msg, - char *dbus_error, - char *error) { - DBusMessage *reply = NULL; - - reply = dbus_message_new_error(msg, dbus_error, error); - dbus_connection_send(conn->conn, reply, NULL); - dbus_message_unref(reply); - return; -} - -void agm_free_signal(gpointer data) { - agm_dbus_signal *signal = (agm_dbus_signal *)data; - - if(signal == NULL) - return; - - free(signal); - signal = NULL; -} - -void agm_free_method(gpointer data) { - agm_dbus_method *method = (agm_dbus_method *)data; - - if(method == NULL) - return; - - free(method); - method = NULL; -} - - -void agm_free_interface(gpointer data) { - agm_dbus_interface *interface = (agm_dbus_interface *)data; - - if(interface == NULL) - return; - - g_hash_table_remove_all(interface->methods); - g_hash_table_unref(interface->methods); - - g_hash_table_remove_all(interface->signals); - g_hash_table_unref(interface->signals); - - free(interface); - interface = NULL; -} - -void agm_free_object(gpointer data) { - agm_dbus_object *object = (agm_dbus_object *)data; - - if(object == NULL) - return; - - g_hash_table_remove_all(object->interfaces); - g_hash_table_unref(object->interfaces); - - free(object); - object = NULL; -} - -int agm_dbus_remove_interface(agm_dbus_connection *conn, - const char *dbus_obj_path, - const char *interface_path) { - agm_dbus_object *object = NULL; - agm_dbus_interface *interface = NULL; - - if (conn == NULL || dbus_obj_path == NULL || interface_path == NULL) - return -1; - - if ((object = (agm_dbus_object *) - g_hash_table_lookup(conn->objects, dbus_obj_path)) == NULL) - return -1; - - if ((interface = (agm_dbus_interface *) - g_hash_table_lookup(object->interfaces, interface_path)) == NULL) - return -1; - - g_hash_table_remove(object->interfaces,interface_path); - interface = NULL; - - if (g_hash_table_size(object->interfaces) == 0) { - unregister_object(conn, object); - g_hash_table_remove(conn->objects, (void *)object->obj_path); - object = NULL; - } - - return 0; -} - -int agm_dbus_add_interface(agm_dbus_connection *conn, - const char *dbus_obj_path, - agm_dbus_interface_info *interface_info, - void *userdata) { - DBusError err; - int i = 0; - agm_dbus_object *object = NULL; - agm_dbus_interface *interface = NULL; - agm_dbus_method *method = NULL; - agm_dbus_signal *signal = NULL; - - if ((conn == NULL) || conn->conn == NULL || conn->objects == NULL) { - AGM_LOGE("Connection not initialized\n"); - return -EINVAL; - } - - if (dbus_obj_path == NULL) { - AGM_LOGE("Invalid object path\n"); - return -EINVAL; - } - - if (interface_info == NULL) { - AGM_LOGE("Invalid interface\n"); - return -EINVAL; - } - - dbus_error_init(&err); - - if ((object = (agm_dbus_object *) - g_hash_table_lookup(conn->objects, dbus_obj_path)) == NULL) { - object = (agm_dbus_object *)malloc(sizeof(agm_dbus_object)); - object->obj_path = dbus_obj_path; - object->interfaces = g_hash_table_new_full(g_str_hash, - g_str_equal, - NULL, - agm_free_interface); - - interface = (agm_dbus_interface *)malloc(sizeof(agm_dbus_interface)); - interface->name = interface_info->name; - interface->methods = g_hash_table_new_full(g_str_hash, - g_str_equal, - NULL, - agm_free_method); - - for (i = 0; i < interface_info->method_count; i++) { - method = (agm_dbus_method *)malloc(sizeof(agm_dbus_method)); - method->method_name = interface_info->methods[i].method_name; - method->method_signature = - interface_info->methods[i].method_signature; - method->cb_func = interface_info->methods[i].cb_func; - g_hash_table_insert(interface->methods, - g_strdup(method->method_name), - method); - } - - interface->signals = g_hash_table_new_full(g_str_hash, - g_str_equal, - NULL, - agm_free_signal); - for (i = 0; i < interface_info->signal_count; i++) { - signal = (agm_dbus_signal *)malloc(sizeof(agm_dbus_signal)); - signal->method_name = interface_info->signals[i].method_name; - signal->method_signature = - interface_info->signals[i].method_signature; - g_hash_table_insert(interface->signals, - g_strdup(signal->method_name), - signal); - } - - interface->userdata = userdata; - g_hash_table_insert(object->interfaces, - g_strdup(interface->name), - interface); - - g_hash_table_insert(conn->objects, g_strdup(object->obj_path), object); - if (!dbus_connection_register_object_path(conn->conn, - dbus_obj_path, - &vtable, - conn)) { - AGM_LOGE("Failed to register a object path for agm\n"); - dbus_error_free(&err); - return -EINVAL; - } - AGM_LOGE("Registered object %s", dbus_obj_path); - } else { - if ((interface = (agm_dbus_interface *) - g_hash_table_lookup(object->interfaces, - interface_info->name)) == NULL) { - interface = (agm_dbus_interface *) - malloc(sizeof(agm_dbus_interface)); - interface->name = interface_info->name; - interface->signals = NULL; - interface->methods = NULL; - if (interface_info->methods != NULL) { - interface->methods = g_hash_table_new_full(g_str_hash, - g_str_equal, - NULL, - agm_free_method); - - for (i = 0; i < interface_info->method_count; i++) { - method = (agm_dbus_method *)malloc(sizeof(agm_dbus_method)); - method->method_name = - interface_info->methods[i].method_name; - method->method_signature = - interface_info->methods[i].method_signature; - method->cb_func = interface_info->methods[i].cb_func; - g_hash_table_insert(interface->methods, - g_strdup(method->method_name), - method); - } - } - - if (interface_info->signals != NULL) { - interface->signals = g_hash_table_new_full(g_str_hash, - g_str_equal, - NULL, - agm_free_signal); - for (i = 0; i < interface_info->signal_count; i++) { - signal = (agm_dbus_signal *)malloc(sizeof(agm_dbus_signal)); - signal->method_name = - interface_info->signals[i].method_name; - signal->method_signature = - interface_info->signals[i].method_signature; - g_hash_table_insert(interface->signals, - g_strdup(signal->method_name), - signal); - } - } - - interface->userdata = userdata; - g_hash_table_insert(object->interfaces, - g_strdup(interface->name), - interface); - } - } - - dbus_error_free(&err); - return 0; -} - -void agm_dbus_connection_free(agm_dbus_connection *conn) { - if (conn == NULL) { - AGM_LOGE("Connection is NULL\n"); - return; - } - - g_hash_table_remove_all(conn->objects); - g_hash_table_unref(conn->objects); - - free(conn); - conn = NULL; -} - -agm_dbus_connection *agm_dbus_new_connection() { - int rc = 0; - DBusError err; - agm_dbus_connection *conn = NULL; - - conn = (agm_dbus_connection *)malloc(sizeof(agm_dbus_connection)); - conn->objects = NULL; - - dbus_error_init(&err); - conn->conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err); - - if (conn->conn == NULL) { - AGM_LOGE("Failed to request name on bus: %s\n", err.message); - free(conn); - dbus_error_free(&err); - return NULL; - } - - conn->objects = g_hash_table_new_full(g_str_hash, - g_str_equal, - NULL, - agm_free_object); - dbus_error_free(&err); - return conn; -} diff --git a/qcom/opensource/agm/ipc/DBus/agm_server/src/agm-server-daemon.cpp b/qcom/opensource/agm/ipc/DBus/agm_server/src/agm-server-daemon.cpp deleted file mode 100755 index daf5fcd6..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_server/src/agm-server-daemon.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* -** Copyright (c) 2020, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -/* -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted (subject to the limitations in the -** disclaimer below) provided that the following conditions are met: -** -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** -** * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE -** GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT -** HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -** IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -** IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "agm_server_daemon" - -#include -#include -#include - -#include "agm_server_wrapper_dbus.h" -#include - -GMainLoop *mainloop = NULL; - -void signal_handler(int sig) { - switch (sig) { - case SIGINT: - case SIGTERM: - case SIGABRT: - case SIGQUIT: - case SIGKILL: - default: - AGM_LOGE("Terminating signal received\n"); - ipc_agm_deinit(); - g_main_loop_quit(mainloop); - break; - } -} - -int main() { - int rc = 0; - mainloop = g_main_loop_new(NULL, false); - - rc = ipc_agm_init(); - if (rc != 0) { - AGM_LOGE("AGM init failed\n"); - return rc; - } - - AGM_LOGD("agm init done\n"); - - signal(SIGINT, signal_handler); - signal(SIGTERM, signal_handler); - signal(SIGQUIT, signal_handler); - signal(SIGKILL, signal_handler); - signal(SIGABRT, signal_handler); - - g_main_loop_run(mainloop); - return 0; -} diff --git a/qcom/opensource/agm/ipc/DBus/agm_server/src/agm_server_wrapper_dbus.cpp b/qcom/opensource/agm/ipc/DBus/agm_server/src/agm_server_wrapper_dbus.cpp deleted file mode 100755 index 2f36701a..00000000 --- a/qcom/opensource/agm/ipc/DBus/agm_server/src/agm_server_wrapper_dbus.cpp +++ /dev/null @@ -1,2613 +0,0 @@ -/* -** Copyright (c) 2020, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -/* -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted (subject to the limitations in the -** disclaimer below) provided that the following conditions are met: -** -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** -** * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE -** GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT -** HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -** IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -** IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "agm_server_wrapper_dbus" - -#include -#include -#include -#include -#include -#include -#include "agm-dbus-utils.h" -#include "agm_server_wrapper_dbus.h" - -#include "utils.h" - -#define AGM_OBJECT_PATH "/org/qti/agm" -#define AGM_MODULE_IFACE "org.Qti.Agm" -#define AGM_SESSION_IFACE "org.Qti.Agm.Session" -#define AGM_DBUS_CONNECTION "org.Qti.AgmService" - -using namespace std; - -/* Module Level data */ -typedef struct { - /* Dbus path where agm module listens for connections */ - char *dbus_obj_path; - /* Dbus connection */ - agm_dbus_connection *conn; - /* Hashmap containing all sessions info */ - GHashTable *sessions; -} agm_module_dbus_data; - -/* Session specific data */ -typedef struct { - /* Session id */ - uint32_t session_id; - /* Session handle */ - uint64_t handle; - /* Dbus path for session specific APIs */ - char *dbus_obj_path; - /* List which maintains all the callbacks associated with a session id. - Used to de-register callbacks when client dies abruptly */ - GList *callbacks; - - char buf[16392]; - uint32_t buf_size; - int thread_state; - pthread_mutex_t lock; - pthread_cond_t cond; - pthread_t ses_tid; - char eventType[50]; -} agm_session_data; - -typedef struct { - uint32_t session_id; - uint32_t event_type; - uint64_t client_data; -} agm_callback_data; - -static agm_module_dbus_data *mdata = NULL; - -enum AgmModuleMethods { - AgmAifSetMediaConfig, - AgmAifSetMetadata, - AgmSessionAifSetMetadata, - AgmSessionSetMetadata, - AgmSessionSetLoopback, - AgmSetParamsWithTag, - AgmGetAifInfoListSize, - AgmGetAifInfoList, - AgmSessionSetParams, - AgmSessionRegisterForEvents, - AgmSessionRegisterCb, - AgmSessionDeRegisterCb, - AgmSessionSetEcRef, - AgmSessionAifConnect, - AgmSessionAifGetTagModuleInfo, - AgmSessionAifGetTagModuleInfoSize, - AgmSessionAifSetParams, - AgmAifSetParams, - AgmSessionAifSetCal, - AgmSessionGetParams, - AgmSessionGetBufInfo, - AgmGetBufferTimestamp, - AgmSessionOpen, - AgmDbusModuleMethodMax -}; - -enum AgmSessionMethods { - AgmSessionClose, - AgmSessionPrepare, - AgmSessionStart, - AgmSessionStop, - AgmSessionPause, - AgmSessionResume, - AgmSessionRead, - AgmSessionWrite, - AgmSessionSetConfig, - AgmSessionEos, - AgmSessionGetTime, - AgmGetHwProcessedBufCount, - AgmDbusSessionMethodMax -}; - -enum AgmEventSignals { - AgmEventCb, - AgmSesEventCb, - AgmSignalMax -}; - -enum { - SES_THREAD_IDLE, - SES_THREAD_READ_QUEUED, - SES_THREAD_WRITE_QUEUED, - SES_THREAD_EXIT, -}; - -static void ipc_agm_audio_intf_set_metadata(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_audio_intf_set_media_config(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_audio_inf_set_metadata(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_set_metadata(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_set_loopback(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_set_params_with_tag(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_get_aif_info_list_size(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_get_aif_info_list(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_set_params(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_register_for_events(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_set_ec_ref(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_audio_inf_connect(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_aif_get_tag_module_info(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_aif_get_tag_module_info_size(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_aif_set_params(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_aif_set_params(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_aif_set_cal(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_get_params(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_get_buf_info(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_open(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_close(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_prepare(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_start(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_stop(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_pause(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_resume(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_read(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_write(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_set_config(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_eos(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_get_session_time(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_get_hw_processed_buff_cnt(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_get_buffer_timestamp(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_register_cb(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ipc_agm_session_deregister_cb(DBusConnection *conn, - DBusMessage *msg, - void *userdata); -static void ses_write_done(agm_session_data *ses_data, uint32_t status); -static void ses_read_done(agm_session_data *ses_data, uint32_t status); - -static agm_dbus_method agm_dbus_module_methods[AgmDbusModuleMethodMax] = { - {"AgmAifSetMediaConfig", "u(uuiu)", ipc_agm_audio_intf_set_media_config}, - {"AgmAifSetMetadata", "uuay", ipc_agm_audio_intf_set_metadata}, - {"AgmSessionAifSetMetadata", "uuuay", - ipc_agm_session_audio_inf_set_metadata}, - {"AgmSessionSetMetadata", "uuay", ipc_agm_session_set_metadata}, - {"AgmSessionSetLoopback", "uub", ipc_agm_session_set_loopback}, - {"AgmSetParamsWithTag", "uu(uua(uu))", ipc_agm_set_params_with_tag}, - {"AgmGetAifInfoListSize", "", ipc_agm_get_aif_info_list_size}, - {"AgmGetAifInfoList", "u", ipc_agm_get_aif_info_list}, - {"AgmSessionSetParams", "uuay", ipc_agm_session_set_params}, - {"AgmSessionRegisterForEvents", "u(uuuyay)", - ipc_agm_session_register_for_events}, - {"AgmSessionRegisterCb", "uut", ipc_agm_session_register_cb}, - {"AgmSessionDeRegisterCb", "uut", ipc_agm_session_deregister_cb}, - {"AgmSessionSetEcRef", "uub", ipc_agm_session_set_ec_ref}, - {"AgmSessionAifConnect", "uub", ipc_agm_session_audio_inf_connect}, - {"AgmSessionAifGetTagModuleInfo", "uuu", - ipc_agm_session_aif_get_tag_module_info}, - {"AgmSessionAifGetTagModuleInfoSize", "uuu", - ipc_agm_session_aif_get_tag_module_info_size}, - {"AgmSessionAifSetParams", "uuuay", ipc_agm_session_aif_set_params}, - {"AgmAifSetParams", "uuay", ipc_agm_aif_set_params}, - {"AgmSessionAifSetCal", "uuuay", ipc_agm_session_aif_set_cal}, - {"AgmSessionGetParams", "uuay", ipc_agm_session_get_params}, - {"AgmSessionGetBufInfo", "uu", ipc_agm_session_get_buf_info}, - {"AgmGetBufferTimestamp", "u", ipc_agm_get_buffer_timestamp}, - {"AgmSessionOpen", "uu", ipc_agm_session_open} -}; - -static agm_dbus_method agm_dbus_session_methods[AgmDbusSessionMethodMax] = { - {"AgmSessionClose", "", ipc_agm_session_close}, - {"AgmSessionPrepare", "", ipc_agm_session_prepare}, - {"AgmSessionStart", "", ipc_agm_session_start}, - {"AgmSessionStop", "", ipc_agm_session_stop}, - {"AgmSessionPause", "", ipc_agm_session_pause}, - {"AgmSessionResume", "", ipc_agm_session_resume}, - {"AgmSessionRead", "u", ipc_agm_session_read}, - {"AgmSessionWrite", "uay", ipc_agm_session_write}, - {"AgmSessionSetConfig", "(uuu)(uu)ay", ipc_agm_session_set_config}, - {"AgmSessionEos", "", ipc_agm_session_eos}, - {"AgmSessionGetTime", "", ipc_agm_get_session_time}, - {"AgmGetHwProcessedBufCount", "u", ipc_agm_get_hw_processed_buff_cnt} -}; - -static agm_dbus_signal event_callback[AgmSignalMax] = { - {"AgmEventCb", "uuuay"}, - {"AgmSesEventCb", "uuuay"} -}; - -agm_dbus_interface_info module_interface_info = { - .name=AGM_MODULE_IFACE, - .methods=agm_dbus_module_methods, - .method_count=AgmDbusModuleMethodMax, - .signals=NULL, - .signal_count=0 -}; - -agm_dbus_interface_info session_interface_info = { - .name=AGM_SESSION_IFACE, - .methods=agm_dbus_session_methods, - .method_count=AgmDbusSessionMethodMax, - .signals=event_callback, - .signal_count=AgmSignalMax -}; - -static void* async_thread_func(void *userdata) { - agm_session_data *ses_data = (agm_session_data *)userdata; - int ret = 0; - - AGM_LOGD("%s:Starting Async Thread\n", __func__); - - pthread_mutex_lock(&ses_data->lock); - if (strcmp(ses_data->eventType, "Wait") == 0) { - while (ses_data->thread_state != SES_THREAD_EXIT) { - ret = pthread_cond_wait(&ses_data->cond, &ses_data->lock); - AGM_LOGV("%s:returned value from wait:%d\n", __func__, ret); - - if(ses_data->thread_state == SES_THREAD_EXIT){ - AGM_LOGE("%s:thread_state is: SES_THREAD_EXIT\n", __func__); - break; - } - - if (ses_data->thread_state == SES_THREAD_WRITE_QUEUED) { - pthread_mutex_unlock(&ses_data->lock); - - if (agm_session_write(ses_data->handle, ses_data->buf, (size_t *) &ses_data->buf_size)) { - AGM_LOGE("%s:agm_session_write failed\n", __func__); - ret = -1; - } - pthread_mutex_lock(&ses_data->lock); - ses_write_done(ses_data, ret); - ses_data->thread_state = SES_THREAD_IDLE; - } - - if (ses_data->thread_state == SES_THREAD_READ_QUEUED) { - pthread_mutex_unlock(&ses_data->lock); - if (agm_session_read(ses_data->handle, ses_data->buf, (size_t *) &ses_data->buf_size)) { - AGM_LOGE("agm_session_read failed"); - ret = -1; - } - pthread_mutex_lock(&ses_data->lock); - ses_read_done(ses_data, ret); - ses_data->thread_state = SES_THREAD_IDLE; - } - } - - } - if (strcmp(ses_data->eventType, "Signal") == 0) { - AGM_LOGV("%s:Signal Event\n", __func__); - pthread_cond_signal(&ses_data->cond); - } - - pthread_mutex_unlock(&ses_data->lock); - AGM_LOGV("Exiting asycn thread for session id = %d\n", ses_data->session_id); - return NULL; -} - -static DBusHandlerResult disconnection_filter_cb(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - agm_session_data *ses_data = (agm_session_data *) userdata; - GList *node = NULL; - agm_callback_data *cb_data = NULL; - - if (conn == NULL) { - AGM_LOGE("%s:Connection is NULL", __func__); - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - if (msg == NULL) { - AGM_LOGE("%s:msg is NULL", __func__); - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - if (userdata == NULL) { - AGM_LOGE("%s:Userdata is NULL ", __func__); - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - if (dbus_message_is_signal(msg, - "org.freedesktop.DBus.Local", - "Disconnected")) { - /* connection died close the session for which callback got triggered */ - AGM_LOGE("%s:connection died for session %d", __func__, ses_data->session_id); - - for (node = ses_data->callbacks; node != NULL; node = node->next) { - cb_data = (agm_callback_data *)node->data; - if (agm_session_register_cb(cb_data->session_id, - NULL, - (enum event_type)cb_data->event_type, - (void *)ses_data) != 0) - AGM_LOGE("%s:Deregistering callback failed.", __func__); - free(node->data); - node->data = NULL; - } - - g_list_free(ses_data->callbacks); - - dbus_connection_remove_filter(conn, disconnection_filter_cb, ses_data); - - if (agm_session_close(ses_data->handle) != 0) { - AGM_LOGE("%s:agm_session_close failed.", __func__); - agm_dbus_send_error(mdata->conn, - msg, - DBUS_ERROR_FAILED, - "agm_session_close failed."); - } - - if (agm_dbus_remove_interface(mdata->conn, - ses_data->dbus_obj_path, - session_interface_info.name) != 0) { - AGM_LOGE("%s:Unable to remove interface", __func__); - agm_dbus_send_error(mdata->conn, - msg, - DBUS_ERROR_FAILED, - "agm_session_close failed."); - } - - g_hash_table_remove(mdata->sessions, - GUINT_TO_POINTER(ses_data->session_id)); - } - - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; -} - -void agm_free_session(gpointer c_data) { - agm_session_data *data = (agm_session_data *)data; - - if(data == NULL) - return; - - if (data->dbus_obj_path != NULL) { - if (agm_dbus_remove_interface(mdata->conn, - data->dbus_obj_path, - session_interface_info.name)) - AGM_LOGE("Unable to remove interface."); - free(data->dbus_obj_path); - data->dbus_obj_path = NULL; - } - - free(data); - data = NULL; -} - -static agm_session_data * get_session_data(agm_module_dbus_data *mdata, - uint32_t session_id) { - agm_session_data *ses_data = NULL; - stringstream ss; - size_t obj_length = 0; - - AGM_LOGV("%s:Enter", __func__); - - if (mdata == NULL) - return NULL; - - if ((ses_data = (agm_session_data *) - g_hash_table_lookup(mdata->sessions, - GUINT_TO_POINTER(session_id))) == NULL) { - ses_data = (agm_session_data *)malloc(sizeof(agm_session_data)); - ses_data->session_id = session_id; - ss << ses_data->session_id; - obj_length = sizeof(char)*(strlen(AGM_OBJECT_PATH)) + - strlen("/session_") + - ss.str().length() + 1; - ses_data->dbus_obj_path = (char *)malloc(obj_length); - snprintf(ses_data->dbus_obj_path, - obj_length, - "%s%s%d", - AGM_OBJECT_PATH, - "/session_", - session_id); - ses_data->callbacks = NULL; - - if (agm_dbus_add_interface(mdata->conn, - ses_data->dbus_obj_path, - &session_interface_info, - ses_data)) { - free(ses_data->dbus_obj_path); - ses_data->dbus_obj_path = NULL; - free(ses_data); - ses_data = NULL; - return NULL; - } - - g_hash_table_insert(mdata->sessions, - GUINT_TO_POINTER(session_id), - ses_data); - } - AGM_LOGV("%s:Exit", __func__); - return ses_data; -} - -static void agmevent_cb(uint32_t session_id, - struct agm_event_cb_params *event_params, - void *client_data) { - DBusMessage *message = NULL; - DBusMessageIter arg_i, array_i; - dbus_uint32_t i, j; - void *buf = NULL; - agm_session_data *ses_data = (agm_session_data *)client_data; - - AGM_LOGE("%s: Received event for session %d", __func__, session_id); - - buf = malloc(event_params->event_payload_size); - memcpy(buf, event_params->event_payload, event_params->event_payload_size); - - message = dbus_message_new_signal(ses_data->dbus_obj_path, - session_interface_info.name, - event_callback[AgmEventCb].method_name); - - dbus_message_iter_init_append(message, &arg_i); - dbus_message_iter_append_basic(&arg_i, - DBUS_TYPE_UINT32, - &event_params->source_module_id); - dbus_message_iter_append_basic(&arg_i, - DBUS_TYPE_UINT32, - &event_params->event_id); - dbus_message_iter_append_basic(&arg_i, - DBUS_TYPE_UINT32, - &event_params->event_payload_size); - dbus_message_iter_open_container(&arg_i, - DBUS_TYPE_ARRAY, - "y", - &array_i); - dbus_message_iter_append_fixed_array(&array_i, - DBUS_TYPE_BYTE, - &buf, - event_params->event_payload_size); - dbus_message_iter_close_container(&arg_i, &array_i); - agm_dbus_send_signal(mdata->conn, message); - dbus_message_unref(message); - free(buf); - buf = NULL; -} - -static void ses_write_done(agm_session_data *ses_data, uint32_t status) { - DBusMessage *message = NULL; - DBusMessageIter arg_i, array_i; - uint32_t dir = 1; - - AGM_LOGD("%s: Received write done event for session %d, status:%d", __func__, - ses_data->session_id, status); - - message = dbus_message_new_signal(ses_data->dbus_obj_path, - session_interface_info.name, - event_callback[AgmSesEventCb].method_name); - - dbus_message_iter_init_append(message, &arg_i); - dbus_message_iter_append_basic(&arg_i, DBUS_TYPE_UINT32, &dir); - dbus_message_iter_append_basic(&arg_i, DBUS_TYPE_UINT32, &status); - dbus_message_iter_append_basic(&arg_i, DBUS_TYPE_UINT32, &ses_data->session_id); - dbus_message_iter_open_container(&arg_i, - DBUS_TYPE_ARRAY, - "y", - &array_i); - dbus_message_iter_close_container(&arg_i, &array_i); - - agm_dbus_send_signal(mdata->conn, message); - dbus_message_unref(message); - AGM_LOGD("%s:Exit", __func__); - return; -} - -static void ses_read_done(agm_session_data *ses_data, uint32_t status) { - DBusMessage *message = NULL; - DBusMessageIter arg_i, array_i; - uint32_t dir = 0; - void *arr = ses_data->buf; - - AGM_LOGD("%s: Received read done event for session %d, status:%d", __func__, - ses_data->session_id, status); - - message = dbus_message_new_signal(ses_data->dbus_obj_path, - session_interface_info.name, - event_callback[AgmSesEventCb].method_name); - - dbus_message_iter_init_append(message, &arg_i); - dbus_message_iter_append_basic(&arg_i, DBUS_TYPE_UINT32, &dir); - dbus_message_iter_append_basic(&arg_i, DBUS_TYPE_UINT32, &status); - dbus_message_iter_append_basic(&arg_i, DBUS_TYPE_UINT32, &ses_data->session_id); - dbus_message_iter_open_container(&arg_i, - DBUS_TYPE_ARRAY, - "y", - &array_i); - dbus_message_iter_append_fixed_array(&array_i, - DBUS_TYPE_BYTE, - &arr, - ses_data->buf_size); - dbus_message_iter_close_container(&arg_i, &array_i); - - agm_dbus_send_signal(mdata->conn, message); - dbus_message_unref(message); - AGM_LOGD("%s:Exit", __func__); - return; -} - -static void ipc_agm_session_deregister_cb(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - uint32_t session_id; - uint32_t evt_type; - agm_session_data *ses_data = NULL; - agm_module_dbus_data *mdata = (agm_module_dbus_data *)userdata; - uint64_t client_data; - GList *node = NULL; - agm_callback_data *cb_data = NULL; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, - msg, DBUS_ERROR_FAILED, "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_deregister_cb has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_deregister_cb has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uut")) { - AGM_LOGE("Invalid signature for ipc_agm_session_deregister_cb."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_deregister_cb."); - return; - } - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &evt_type); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &client_data); - - ses_data = get_session_data(mdata, session_id); - - if (agm_session_register_cb(session_id, NULL, - (enum event_type)evt_type, - (void *)ses_data) != 0) { - AGM_LOGE("agm_session_register_cb failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Failed to de-register callback. agm_session_register_cb failed."); - agm_free_session(ses_data); - return; - } - - cb_data = (agm_callback_data *)malloc(sizeof(agm_callback_data)); - cb_data->session_id = session_id; - cb_data->event_type = evt_type; - cb_data->client_data = client_data; - node = g_list_find(ses_data->callbacks, cb_data); - if (node != NULL) { - ses_data->callbacks = g_list_remove(ses_data->callbacks, cb_data); - free(node->data); - node->data = NULL; - } - free(cb_data); - cb_data = NULL; - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &arg_i); - dbus_message_iter_append_basic(&arg_i, - DBUS_TYPE_OBJECT_PATH, - &ses_data->dbus_obj_path); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_register_cb(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - uint32_t session_id; - uint32_t evt_type; - agm_session_data *ses_data = NULL; - agm_module_dbus_data *mdata = (agm_module_dbus_data *)userdata; - uint64_t client_data; - agm_callback_data *cb_data = NULL; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_register_cb has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_register_cb has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uut")) { - AGM_LOGE("Invalid signature for ipc_agm_session_register_cb."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_register_cb."); - return; - } - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &evt_type); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &client_data); - - ses_data = get_session_data(mdata, session_id); - - if (agm_session_register_cb(session_id, - agmevent_cb, - (enum event_type)evt_type, - (void *)ses_data) != 0) { - AGM_LOGE("agm_session_register_cb failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_register_cb failed."); - agm_free_session(ses_data); - return; - } - - cb_data = (agm_callback_data *)malloc(sizeof(agm_callback_data)); - cb_data->session_id = session_id; - cb_data->event_type = evt_type; - cb_data->client_data = client_data; - ses_data->callbacks = g_list_prepend(ses_data->callbacks, cb_data); - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &arg_i); - dbus_message_iter_append_basic(&arg_i, DBUS_TYPE_OBJECT_PATH, - &ses_data->dbus_obj_path); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - - -static void ipc_agm_session_register_for_events(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, struct_i, struct_ii, array_i; - struct agm_tag_config tag_config; - uint32_t session_id; - uint32_t i = 0; - uint8_t *value = NULL; - uint8_t **addr_value = &value; - int arg_type; - int n_elements = 0; - struct agm_event_reg_cfg *evt_reg_cfg; - uint32_t module_instance_id; - uint32_t event_id; - uint32_t event_config_payload_size; - uint8_t is_register; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_register_for_events has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_register_for_events has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "u(uuuyay)")) { - AGM_LOGE("Invalid signature for ipc_agm_session_register_for_events."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_register_for_events."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &struct_i); - dbus_message_iter_get_basic(&struct_i, &module_instance_id); - dbus_message_iter_next(&struct_i); - dbus_message_iter_get_basic(&struct_i, &event_id); - dbus_message_iter_next(&struct_i); - dbus_message_iter_get_basic(&struct_i, &event_config_payload_size); - dbus_message_iter_next(&struct_i); - dbus_message_iter_get_basic(&struct_i, &is_register); - dbus_message_iter_next(&struct_i); - dbus_message_iter_recurse(&struct_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - evt_reg_cfg = (struct agm_event_reg_cfg *) - calloc (1,(sizeof(struct agm_event_reg_cfg) + - (event_config_payload_size)*sizeof(uint8_t))); - evt_reg_cfg->module_instance_id = module_instance_id; - evt_reg_cfg->event_id = event_id; - evt_reg_cfg->event_config_payload_size = event_config_payload_size; - evt_reg_cfg->is_register = is_register; - memcpy(&evt_reg_cfg->event_config_payload[0], value, n_elements); - - - if (agm_session_register_for_events(session_id, evt_reg_cfg) != 0) { - AGM_LOGE("agm_session_register_for_events failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_register_for_events failed."); - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_get_params(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i; - DBusMessageIter r_arg, r_array_i; - uint32_t session_id, size; - void *payload = NULL; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_get_params has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_get_params has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuay")) { - AGM_LOGE("Invalid signature for ipc_agm_session_get_params."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_get_params."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &size); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - payload = (void *)malloc(n_elements*sizeof(char)); - memcpy(payload, value, n_elements); - - if (agm_session_get_params(session_id, (void *)payload, size) != 0) { - AGM_LOGE("agm_session_get_params failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_get_params failed."); - free(payload); - payload = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_open_container(&r_arg, DBUS_TYPE_ARRAY, "y", &r_array_i); - dbus_message_iter_append_fixed_array(&r_array_i, DBUS_TYPE_BYTE, &payload, - size); - dbus_message_iter_close_container(&r_arg, &r_array_i); - dbus_connection_send(conn, reply, NULL); - free(payload); - payload = NULL; - dbus_message_unref(reply); -} - -static void ipc_agm_session_get_buf_info(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i; - DBusMessageIter r_arg, struct_i; - uint32_t session_id, flag; - struct agm_buf_info *buf_info; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_get_buf_info has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_get_buf_info has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uu")) { - AGM_LOGE("Invalid signature for ipc_agm_session_get_buf_info."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_get_buf_info."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &flag); - //dbus_message_iter_next(&arg_i); - buf_info = (agm_buf_info *) calloc(1,(sizeof(struct agm_buf_info))); - - if (agm_session_get_buf_info(session_id, buf_info, flag) != 0) { - AGM_LOGE("agm_session_get_buf_info failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_get_buf_info failed."); - free(buf_info); - buf_info = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_open_container(&r_arg, DBUS_TYPE_STRUCT, NULL, &struct_i); - dbus_message_iter_append_basic(&struct_i, DBUS_TYPE_INT32, &buf_info->data_buf_fd); - dbus_message_iter_append_basic(&struct_i, DBUS_TYPE_INT32, &buf_info->data_buf_size); - dbus_message_iter_append_basic(&struct_i, DBUS_TYPE_INT32, &buf_info->pos_buf_fd); - dbus_message_iter_append_basic(&struct_i, DBUS_TYPE_INT32, &buf_info->pos_buf_size); - dbus_message_iter_close_container(&r_arg, &struct_i); - dbus_connection_send(conn, reply, NULL); - free(buf_info); - buf_info = NULL; - dbus_message_unref(reply); -} - -static void ipc_agm_session_aif_set_cal(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i; - struct agm_cal_config *cal_config = NULL; - uint32_t session_id, aif_id, num_ckv; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - AGM_LOGD("%s:Enter\n", __func__); - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("%s:ipc_agm_session_aif_set_cal has no arguments\n", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_aif_set_cal has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuuay")) { - AGM_LOGE("%s:Invalid signature for ipc_agm_session_aif_set_cal.\n", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_aif_set_cal."); - return; - } - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &num_ckv); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - - cal_config = (struct agm_cal_config *) - calloc (1, sizeof(struct agm_cal_config) + - num_ckv * sizeof(struct agm_key_value)); - cal_config->num_ckvs = num_ckv; - memcpy(cal_config->kv, value, - cal_config->num_ckvs*sizeof(struct agm_key_value)); - - if (agm_session_aif_set_cal(session_id, aif_id, cal_config)) { - AGM_LOGE("%s:agm_session_aif_set_cal failed.\n", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_aif_set_cal failed."); - free(cal_config); - cal_config = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); - free(cal_config); - cal_config = NULL; - AGM_LOGD("%s:Exit\n", __func__); - return; -} - -static void ipc_agm_session_aif_set_params(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i, r_arg; - uint32_t session_id, aif_id, size; - void *buf = NULL; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_aif_set_params has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_aif_set_params has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuuay")) { - AGM_LOGE("Invalid signature for ipc_agm_session_aif_set_params."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_aif_set_params."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &size); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - buf = (void *)malloc(n_elements*sizeof(char)); - memcpy(buf, value, n_elements); - - if (agm_session_aif_set_params(session_id, aif_id, buf, size) != 0) { - AGM_LOGE("agm_session_aif_set_params failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_aif_set_params failed."); - free(buf); - buf = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - free(buf); - buf = NULL; - dbus_message_unref(reply); -} - -static void ipc_agm_aif_set_params(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i, r_arg; - uint32_t aif_id, size; - void *buf = NULL; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_aif_set_params has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_aif_set_params has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuay")) { - AGM_LOGE("Invalid signature for ipc_agm_aif_set_params."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_aif_set_params."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &size); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - buf = (void *)malloc(n_elements*sizeof(char)); - memcpy(buf, value, n_elements); - - if (agm_aif_set_params(aif_id, buf, size) != 0) { - AGM_LOGE("agmaif_set_params failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_aif_set_params failed."); - free(buf); - buf = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - free(buf); - buf = NULL; - dbus_message_unref(reply); -} - - -static void ipc_agm_session_aif_get_tag_module_info_size(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i, r_arg; - uint32_t session_id, aif_id; - size_t size=0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_aif_get_tag_module_info_size has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuu")) { - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_aif_get_tag_module_info_size."); - return; - } - - AGM_LOGV("%s : ", __func__); - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &size); - - if (agm_session_aif_get_tag_module_info(session_id, - aif_id, - NULL, - &size) != 0) { - AGM_LOGE("agm_session_aif_get_tag_module_info failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_aif_get_tag_module_info failed."); - return; - } - - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_append_basic(&r_arg, DBUS_TYPE_UINT32, &size); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_aif_get_tag_module_info(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i, r_arg, r_array_i; - uint32_t session_id, aif_id; - size_t size=0; - void *buf = NULL; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_aif_get_tag_module_info has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_aif_get_tag_module_info has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuu")) { - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_aif_get_tag_module_info."); - return; - } - - AGM_LOGV("%s : ", __func__); - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &size); - - buf = calloc(size, sizeof(uint8_t)); - - if (agm_session_aif_get_tag_module_info(session_id, - aif_id, - buf, - &size) != 0) { - AGM_LOGE("agm_session_aif_get_tag_module_info failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_aif_get_tag_module_info failed."); - free(buf); - buf = NULL; - return; - } - - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_append_basic(&r_arg, DBUS_TYPE_UINT32, &size); - dbus_message_iter_open_container(&r_arg, DBUS_TYPE_ARRAY, "y", &r_array_i); - dbus_message_iter_append_fixed_array(&r_array_i, DBUS_TYPE_BYTE, &buf, - size); - dbus_message_iter_close_container(&r_arg, &r_array_i); - dbus_connection_send(conn, reply, NULL); - free(buf); - buf = NULL; - dbus_message_unref(reply); -} - -static void ipc_agm_session_audio_inf_connect(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - uint32_t session_id, aif_id; - dbus_bool_t state; - AGM_LOGD("%s :Enter ", __func__); - - if (userdata == NULL) { - AGM_LOGE("%s :Invalid userdata", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("%s :ipc_agm_session_audio_inf_connect has no arguments", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_audio_inf_connect has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uub")) { - AGM_LOGE("%s :Invalid signature for ipc_agm_session_audio_inf_connect.", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_audio_inf_connect."); - return; - } - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &state); - - if (agm_session_aif_connect(session_id, aif_id, (bool)state) != 0) { - AGM_LOGE("%s :agm_session_aif_connect failed.", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_aif_connect failed."); - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_set_ec_ref(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - uint32_t capture_session_id, aif_id; - dbus_bool_t state; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_set_ec_ref has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_set_ec_ref has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uub")) { - AGM_LOGE("Invalid signature for ipc_agm_session_set_ec_ref."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_set_ec_ref."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &capture_session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &state); - - if (agm_session_set_ec_ref(capture_session_id, aif_id, (bool)state) != 0) { - AGM_LOGE("agm_session_set_ec_ref failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_set_ec_ref failed."); - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_set_params(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i; - uint32_t session_id, size; - void *payload = NULL; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_set_params has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_set_params has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuay")) { - AGM_LOGE("Invalid signature for ipc_agm_session_set_params."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_set_params."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &size); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - payload = (void *)malloc(n_elements*sizeof(char)); - memcpy(payload, value, n_elements); - - if (agm_session_set_params(session_id, (void *)payload, size) != 0) { - AGM_LOGE("agm_session_set_params failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_set_params failed."); - free(payload); - payload = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - free(payload); - payload = NULL; - dbus_message_unref(reply); -} - -static void ipc_agm_get_aif_info_list_size(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter r_arg; - agm_module_dbus_data *mdata = (agm_module_dbus_data *)userdata; - size_t num_aif_info = 0; - - if (agm_get_aif_info_list(NULL, &num_aif_info) != 0) { - AGM_LOGE("agm_get_aif_info_list failed"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_get_aif_info_list_size failed"); - return; - } - - AGM_LOGV("%s : ", __func__); - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_append_basic(&r_arg, DBUS_TYPE_UINT32, &num_aif_info); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_get_aif_info_list(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - DBusMessageIter r_arg, array_i, struct_i; - agm_module_dbus_data *mdata = (agm_module_dbus_data *)userdata; - size_t num_aif_info; - struct aif_info *aifinfo = NULL; - char *name; - int i = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_get_aif_info_list has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_get_aif_info_list has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "u")) { - AGM_LOGE("Invalid signature for ipc_agm_get_aif_info_list."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_get_aif_info_list."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &num_aif_info); - - aifinfo = (struct aif_info *)calloc(num_aif_info, sizeof(struct aif_info)); - - if (agm_get_aif_info_list(aifinfo, &num_aif_info)) { - AGM_LOGE("agm_get_aif_info_list failed"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_get_aif_info_list failed"); - free(aifinfo); - aifinfo = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_open_container(&r_arg, DBUS_TYPE_ARRAY, "(us)", &array_i); - for (i = 0; i < num_aif_info; i++) { - dbus_message_iter_open_container(&array_i, DBUS_TYPE_STRUCT, NULL, - &struct_i); - dbus_message_iter_append_basic(&struct_i, DBUS_TYPE_UINT32, - &aifinfo[i].dir); - name = aifinfo[i].aif_name; - dbus_message_iter_append_basic(&struct_i, DBUS_TYPE_STRING, &name); - dbus_message_iter_close_container(&array_i, &struct_i); - } - dbus_message_iter_close_container(&r_arg, &array_i); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); - free(aifinfo); - aifinfo = NULL; -} - -static void ipc_agm_set_params_with_tag(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, struct_i, struct_ii, array_i; - struct agm_tag_config *tag_config; - uint32_t tag; - uint32_t num_tkvs; - uint32_t session_id, aif_id; - uint32_t i = 0; - int arg_type; - size_t size_local = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_set_params_with_tag has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_set_params_with_tag has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uu(uua(uu))")) { - AGM_LOGE("Invalid signature for ipc_agm_set_params_with_tag."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_set_params_with_tag."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &struct_i); - dbus_message_iter_get_basic(&struct_i, &tag); - dbus_message_iter_next(&struct_i); - dbus_message_iter_get_basic(&struct_i, &num_tkvs); - dbus_message_iter_next(&struct_i); - size_local = (sizeof(struct agm_tag_config) + - (num_tkvs) * sizeof(agm_key_value)); - tag_config = (struct agm_tag_config *) calloc(1,size_local); - tag_config->tag = tag; - tag_config->num_tkvs = num_tkvs; - dbus_message_iter_recurse(&struct_i, &array_i); - while (((arg_type = dbus_message_iter_get_arg_type(&array_i)) - != DBUS_TYPE_INVALID) - && (i < tag_config->num_tkvs)) { - dbus_message_iter_recurse(&array_i, &struct_ii); - dbus_message_iter_get_basic(&struct_ii, &tag_config->kv[i].key); - dbus_message_iter_next(&struct_ii); - dbus_message_iter_get_basic(&struct_ii, &tag_config->kv[i].value); - dbus_message_iter_next(&array_i); - i++; - } - - if (agm_set_params_with_tag(session_id, aif_id, tag_config)) { - AGM_LOGE("agm_set_params_with_tag failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_set_params_with_tag failed."); - free(tag_config); - tag_config = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); - free(tag_config); - tag_config = NULL; -} - -static void ipc_agm_session_set_loopback(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - uint32_t capture_session_id, playback_session_id; - dbus_bool_t flag; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_set_loopback has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_set_loopback has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uub")) { - AGM_LOGE("Invalid signature for ipc_agm_session_set_loopback."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_set_loopback."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &capture_session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &playback_session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &flag); - - if (agm_session_set_loopback(capture_session_id, - playback_session_id, - (bool)flag) != 0) { - AGM_LOGE("agm_session_set_loopback failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_set_loopback failed."); - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_set_metadata(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i; - uint32_t session_id, size; - void *metadata; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_set_metadata has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_set_metadata has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuay")) { - AGM_LOGE("Invalid signature for ipc_agm_session_set_metadata."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_set_metadata."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &size); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - metadata = (void *)malloc(n_elements*sizeof(char)); - memcpy(metadata, value, n_elements); - - if (agm_session_set_metadata(session_id, size, (uint8_t *)metadata) != 0) { - AGM_LOGE("agm_session_set_metadata failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_set_metadata failed."); - free(metadata); - metadata = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - free(metadata); - metadata = NULL; - dbus_message_unref(reply); -} - -static void ipc_agm_session_audio_inf_set_metadata(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i; - uint32_t session_id, aif_id, size; - void *metadata; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_audio_inf_set_metadata has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_audio_inf_set_metadata has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuuay")) { - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_audio_inf_set_metadata."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &size); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - metadata = (void *)malloc(n_elements*sizeof(char)); - memcpy(metadata, value, n_elements); - - if (agm_session_aif_set_metadata(session_id, - aif_id, - size, - (uint8_t *)metadata) != 0) { - AGM_LOGE("agm_session_aif_set_metadata failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_aif_set_metadata failed."); - free(metadata); - metadata = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - free(metadata); - metadata = NULL; - dbus_message_unref(reply); -} - -static void ipc_agm_audio_intf_set_metadata(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i; - uint32_t aif_id, size; - void *metadata; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_audio_intf_set_metadata has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_audio_intf_set_metadata has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uuay")) { - AGM_LOGE("Invalid signature for ipc_agm_audio_intf_set_metadata."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_audio_intf_set_metadata."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &size); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - metadata = (void *)malloc(n_elements*sizeof(char)); - memcpy(metadata, value, n_elements); - - if (agm_aif_set_metadata(aif_id, size, (uint8_t *)metadata) != 0) { - AGM_LOGE("agm_aif_set_metadata failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_aif_set_metadata failed."); - free(metadata); - metadata = NULL; - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - free(metadata); - metadata = NULL; - dbus_message_unref(reply); -} - -static void ipc_agm_audio_intf_set_media_config(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, struct_i; - struct agm_media_config media_config; - uint32_t aif_id; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_audio_intf_set_media_config has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_audio_intf_set_media_config has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "u(uuiu)")) { - AGM_LOGE("Invalid signature for ipc_agm_audio_intf_set_media_config."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_audio_intf_set_media_config."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &aif_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &struct_i); - dbus_message_iter_get_basic(&struct_i, &media_config.rate); - dbus_message_iter_next(&struct_i); - dbus_message_iter_get_basic(&struct_i, &media_config.channels); - dbus_message_iter_next(&struct_i); - dbus_message_iter_get_basic(&struct_i, &media_config.format); - dbus_message_iter_next(&struct_i); - dbus_message_iter_get_basic(&struct_i, &media_config.data_format); - - if (agm_aif_set_media_config(aif_id, &media_config)) { - AGM_LOGE("agm_aif_set_media_config failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_aif_set_media_config failed."); - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_get_buffer_timestamp(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - DBusMessageIter r_arg, r_array_i; - uint64_t timestamp = 0; - uint32_t session_id; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_get_buffer_timestamp has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_get_buffer_timestamp has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "u")) { - AGM_LOGE("Invalid signature for ipc_agm_get_buffer_timestamp."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_get_buffer_timestamp."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &session_id); - - if (agm_get_buffer_timestamp(session_id, ×tamp)) { - AGM_LOGE("agm_get_buffer_timestamp failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_get_buffer_timestamp failed."); - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_append_basic(&r_arg, DBUS_TYPE_UINT64, ×tamp); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_get_hw_processed_buff_cnt(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - DBusMessageIter r_arg, r_array_i; - agm_session_data *ses_data = (agm_session_data *)userdata; - uint32_t direction; - size_t buf_count; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_get_hw_processed_buff_cnt has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_get_hw_processed_buff_cnt has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "u")) { - AGM_LOGE("Invalid signature for ipc_agm_get_hw_processed_buff_cnt."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_get_hw_processed_buff_cnt."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &direction); - - buf_count = agm_get_hw_processed_buff_cnt(ses_data->handle, - (enum direction)direction); - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_append_basic(&r_arg, DBUS_TYPE_INT32, &buf_count); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_get_session_time(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter r_arg; - agm_session_data *ses_data = (agm_session_data *)userdata; - uint64_t timestamp; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (agm_get_session_time(ses_data->handle, ×tamp)) { - AGM_LOGE("agm_get_session_time failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_get_session_time failed."); - return; - } - - AGM_LOGV("%s : ", __func__); - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_append_basic(&r_arg, DBUS_TYPE_UINT64, ×tamp); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_set_config(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i, struct_i, struct_ii; - agm_session_data *ses_data = (agm_session_data *)userdata; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - struct agm_session_config session_config; - struct agm_media_config media_config; - struct agm_buffer_config buffer_config; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_set_config has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_set_config has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "(uuu)(uu)ay")) { - AGM_LOGE("Invalid signature for ipc_agm_session_set_config."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_set_config."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_recurse(&arg_i, &struct_i); - dbus_message_iter_get_basic(&struct_i, &media_config.rate); - dbus_message_iter_next(&struct_i); - dbus_message_iter_get_basic(&struct_i, &media_config.channels); - dbus_message_iter_next(&struct_i); - dbus_message_iter_get_basic(&struct_i, &media_config.format); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &struct_ii); - dbus_message_iter_get_basic(&struct_ii, &buffer_config.count); - dbus_message_iter_next(&struct_ii); - dbus_message_iter_get_basic(&struct_ii, &buffer_config.size); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - memcpy(&session_config, value, n_elements); - - if (agm_session_set_config(ses_data->handle, - &session_config, - &media_config, - &buffer_config)) { - AGM_LOGE("agm_session_set_config failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_set_config failed."); - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_eos(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - agm_session_data *ses_data = (agm_session_data *)userdata; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (agm_session_eos(ses_data->handle)) { - AGM_LOGE("agm_session_eos failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_eos failed."); - return; - } - - AGM_LOGV("%s : ", __func__); - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_write(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - - DBusMessage *reply = NULL; - DBusMessageIter arg_i, array_i, r_arg; - agm_session_data *ses_data = (agm_session_data *)userdata; - uint32_t buf_size=0; - char *value = NULL; - char **addr_value = &value; - int n_elements = 0; - - AGM_LOGD("%s :Enter ", __func__); - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_write has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_write has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uay")) { - AGM_LOGE("Invalid signature for ipc_agm_session_write."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_write."); - return; - } - - dbus_message_iter_get_basic(&arg_i, &buf_size); - dbus_message_iter_next(&arg_i); - dbus_message_iter_recurse(&arg_i, &array_i); - dbus_message_iter_get_fixed_array(&array_i, addr_value, &n_elements); - - pthread_mutex_lock(&ses_data->lock); - ses_data->buf_size = buf_size; - if (ses_data->thread_state != SES_THREAD_IDLE) { - pthread_mutex_unlock(&ses_data->lock); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, "write via async failed"); - return; - } - memcpy(ses_data->buf, value, n_elements); - ses_data->thread_state = SES_THREAD_WRITE_QUEUED; - snprintf(ses_data->eventType, sizeof("Signal"), "%s", "Signal"); - pthread_mutex_unlock(&ses_data->lock); - async_thread_func(ses_data); - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &r_arg); - dbus_message_iter_append_basic(&r_arg, DBUS_TYPE_UINT32, &buf_size); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); - AGM_LOGD("%s :Exit ", __func__); - return; -} - -static void ipc_agm_session_read(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - DBusMessageIter r_arg, r_array_i; - size_t buf_size=0; - agm_session_data *ses_data = (agm_session_data *)userdata; - AGM_LOGD("%s :Enter ", __func__); - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_read has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_read has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "u")) { - AGM_LOGE("Invalid signature for ipc_agm_session_read."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_read."); - return; - } - - AGM_LOGV("%s : ", __func__); - - dbus_message_iter_get_basic(&arg_i, &buf_size); - - pthread_mutex_lock(&ses_data->lock); - ses_data->buf_size = buf_size; - if (ses_data->thread_state != SES_THREAD_IDLE) { - pthread_mutex_unlock(&ses_data->lock); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, "read via async failed"); - return; - } - ses_data->thread_state = SES_THREAD_READ_QUEUED; - snprintf(ses_data->eventType, sizeof("Signal"), "%s", "Signal"); - pthread_mutex_unlock(&ses_data->lock); - async_thread_func(ses_data); - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); - AGM_LOGD("%s :Exit ", __func__); - return; -} - -static void ipc_agm_session_resume(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - agm_session_data *ses_data = (agm_session_data *)userdata; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (agm_session_resume(ses_data->handle)) { - AGM_LOGE("agm_session_resume failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_resume failed."); - return; - } - - AGM_LOGV("%s : ", __func__); - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_pause(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - agm_session_data *ses_data = (agm_session_data *)userdata; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (agm_session_pause(ses_data->handle)) { - AGM_LOGE("agm_session_pause failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_pause failed."); - return; - } - - AGM_LOGV("%s : ", __func__); - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_stop(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - agm_session_data *ses_data = (agm_session_data *)userdata; - - AGM_LOGD("%s : Enter", __func__); - - if (userdata == NULL) { - AGM_LOGE("%s :Invalid userdata", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (agm_session_stop(ses_data->handle)) { - AGM_LOGE("%s :agm_session_stop failed.", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_stop failed."); - return; - } - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); - AGM_LOGD("%s : Exit", __func__); -} - -static void ipc_agm_session_start(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - agm_session_data *ses_data = (agm_session_data *)userdata; - - AGM_LOGD("%s:Enter\n", __func__); - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (agm_session_start(ses_data->handle)) { - AGM_LOGE("agm_session_start failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_start failed."); - return; - } - - AGM_LOGV("%s : ", __func__); - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); - AGM_LOGD("%s:Exit\n", __func__); -} - -static void ipc_agm_session_prepare(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - agm_session_data *ses_data = (agm_session_data *)userdata; - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (agm_session_prepare(ses_data->handle)) { - AGM_LOGE("agm_session_prepare failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_prepare failed."); - return; - } - - AGM_LOGV("%s : ", __func__); - - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); -} - -static void ipc_agm_session_close(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - DBusMessage *reply = NULL; - agm_session_data *ses_data = (agm_session_data *)userdata; - GList *node = NULL; - - AGM_LOGD("%s : Enter", __func__); - - if (userdata == NULL) { - AGM_LOGE("%s :Invalid userdata", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - dbus_connection_remove_filter(conn, disconnection_filter_cb, ses_data); - - ses_data->thread_state = SES_THREAD_EXIT; - pthread_cond_signal(&ses_data->cond); - pthread_join(ses_data->ses_tid, NULL); - pthread_cond_destroy(&ses_data->cond); - pthread_mutex_destroy(&ses_data->lock); - - if (agm_session_close(ses_data->handle)) { - AGM_LOGE("agm_session_close failed."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_close failed."); - return; - } - - for (node = ses_data->callbacks; node != NULL; node = node->next) { - if (node->data != NULL) { - free(node->data); - node->data = NULL; - } - } - - g_list_free(ses_data->callbacks); - - if (agm_dbus_remove_interface(mdata->conn, - ses_data->dbus_obj_path, - session_interface_info.name)) { - AGM_LOGE("%s :Failed to remove interface", __func__); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_close failed. Failed to remove interface."); - return; - } - - g_hash_table_remove(mdata->sessions, - GUINT_TO_POINTER(ses_data->session_id)); - reply = dbus_message_new_method_return(msg); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); - AGM_LOGD("%s : Exit", __func__); - return; -} - -static void ipc_agm_session_open(DBusConnection *conn, - DBusMessage *msg, - void *userdata) { - agm_module_dbus_data *mdata = (agm_module_dbus_data *)userdata; - DBusMessage *reply = NULL; - DBusMessageIter arg_i; - uint32_t session_id, sess_mode; - char *dbus_obj_path = NULL; - gchar thread_name[32] = ""; - int32_t ret; - agm_session_data *ses_data = NULL; - - AGM_LOGD("%s :Enter ", __func__); - - if (userdata == NULL) { - AGM_LOGE("Invalid userdata"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "userdata is NULL"); - return; - } - - if (!dbus_message_iter_init(msg, &arg_i)) { - AGM_LOGE("ipc_agm_session_open has no arguments"); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "ipc_agm_session_open has no arguments"); - return; - } - - if (strcmp(dbus_message_get_signature(msg), "uu")) { - AGM_LOGE("Invalid signature for ipc_agm_session_open."); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "Invalid signature for ipc_agm_session_open."); - return; - } - dbus_message_iter_get_basic(&arg_i, &session_id); - dbus_message_iter_next(&arg_i); - dbus_message_iter_get_basic(&arg_i, &sess_mode); - ses_data = get_session_data(mdata, session_id); - - if (agm_session_open(session_id, (enum agm_session_mode) sess_mode, &ses_data->handle)) { - agm_free_session(ses_data); - agm_dbus_send_error(mdata->conn, msg, DBUS_ERROR_FAILED, - "agm_session_open failed."); - return; - } - - ses_data->lock = PTHREAD_MUTEX_INITIALIZER; - ses_data->cond = PTHREAD_COND_INITIALIZER; - ses_data->thread_state = SES_THREAD_IDLE; - snprintf(ses_data->eventType, sizeof("Wait"), "%s", "Wait"); - AGM_LOGD("%s:Wait Event", __func__); - snprintf(thread_name, sizeof(thread_name), "agm_ses_async_thread_%d", session_id); - if (pthread_create(&ses_data->ses_tid, NULL, async_thread_func, ses_data)){ - AGM_LOGE("%s: agm session async thread creation failed", __func__); - } - AGM_LOGD("%s : agm session async thread creation success", __func__); - - if (!dbus_connection_add_filter(conn, - disconnection_filter_cb, - ses_data, - NULL)) - AGM_LOGE("Unable to add death notification filter"); - - reply = dbus_message_new_method_return(msg); - dbus_message_iter_init_append(reply, &arg_i); - dbus_message_iter_append_basic(&arg_i, - DBUS_TYPE_OBJECT_PATH, - &ses_data->dbus_obj_path); - dbus_connection_send(conn, reply, NULL); - dbus_message_unref(reply); - AGM_LOGD("%s :Exit ", __func__); - return; -} - -/* Initialize module data. Get dbus connection and register module interface - with the connection */ -int ipc_agm_init() { - DBusError err; - int rc = 0; - - AGM_LOGV("%s : ", __func__); - - mdata = (agm_module_dbus_data *)malloc(sizeof(agm_module_dbus_data)); - mdata->dbus_obj_path = - (char *)malloc(sizeof(char)*(strlen(AGM_OBJECT_PATH) + 1)); - memcpy(mdata->dbus_obj_path, AGM_OBJECT_PATH, strlen(AGM_OBJECT_PATH)+1); - - mdata->conn = agm_dbus_new_connection(); - - dbus_error_init(&err); - rc = dbus_bus_request_name(mdata->conn->conn, - AGM_DBUS_CONNECTION, - DBUS_NAME_FLAG_REPLACE_EXISTING, - &err); - - if (rc != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { - AGM_LOGE("Failed to request name on bus: %s", err.message); - agm_dbus_connection_free(mdata->conn); - free(mdata->dbus_obj_path); - mdata->dbus_obj_path = NULL; - free(mdata); - mdata = NULL; - rc = -EINVAL; - return rc; - } - - if (agm_setup_dbus_with_main_loop(mdata->conn)) { - AGM_LOGE("Failed to setup main loop"); - agm_dbus_connection_free(mdata->conn); - free(mdata->dbus_obj_path); - mdata->dbus_obj_path = NULL; - free(mdata); - mdata = NULL; - rc = -EINVAL; - return rc; - } - - if ((rc = agm_dbus_add_interface(mdata->conn, - mdata->dbus_obj_path, - &module_interface_info, - mdata)) != 0) { - AGM_LOGE("Failed to add interface"); - agm_dbus_connection_free(mdata->conn); - free(mdata->dbus_obj_path); - mdata->dbus_obj_path = NULL; - free(mdata); - mdata = NULL; - rc = -EINVAL; - return rc; - } - - mdata->sessions = g_hash_table_new_full(g_direct_hash, - g_direct_equal, - NULL, - agm_free_session); - - if ((rc = agm_init()) != 0) { - AGM_LOGE("agm initialization failed"); - agm_dbus_connection_free(mdata->conn); - free(mdata->dbus_obj_path); - mdata->dbus_obj_path = NULL; - free(mdata); - mdata = NULL; - return rc; - } - - dbus_error_free(&err); - return rc; -} - -void ipc_agm_deinit() { - AGM_LOGV("%s : ", __func__); - - if (mdata == NULL) { - AGM_LOGE("ipc_agm_deinit failed"); - g_hash_table_remove_all(mdata->sessions); - g_hash_table_unref(mdata->sessions); - } - - if (mdata->dbus_obj_path != NULL) { - if (agm_dbus_remove_interface(mdata->conn, - mdata->dbus_obj_path, - module_interface_info.name) != 0) - AGM_LOGE("Unable to remove interface"); - free(mdata->dbus_obj_path); - mdata->dbus_obj_path = NULL; - } - - agm_dbus_connection_free(mdata->conn); - free(mdata); - mdata = NULL; - - if (agm_deinit() != 0) - AGM_LOGE("agm deinitialization failed"); -} diff --git a/qcom/opensource/agm/ipc/README.md b/qcom/opensource/agm/ipc/README.md deleted file mode 100755 index fccba52d..00000000 --- a/qcom/opensource/agm/ipc/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# IPC -IPC Binders implememtations diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_client/Android.mk b/qcom/opensource/agm/ipc/SwBinders/agm_client/Android.mk deleted file mode 100755 index 35ca6673..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_client/Android.mk +++ /dev/null @@ -1,25 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) -LOCAL_MODULE := agmclient -LOCAL_SRC_FILES := agm_client_wrapper.cpp - -LOCAL_SHARED_LIBRARIES := \ - liblog \ - libcutils \ - libdl \ - libbinder \ - libutils \ - libagmproxy - -LOCAL_CFLAGS += -Wall - -ifeq ($(strip $(AUDIO_FEATURE_ENABLED_DYNAMIC_LOG)), true) -LOCAL_CFLAGS += -DDYNAMIC_LOG_ENABLED -LOCAL_C_INCLUDES += $(TOP)/external/expat/lib/expat.h -LOCAL_SHARED_LIBRARIES += libaudio_log_utils -LOCAL_SHARED_LIBRARIES += libexpat -LOCAL_HEADER_LIBRARIES += libaudiologutils_headers -endif - -include $(BUILD_EXECUTABLE) diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_client/Makefile.am b/qcom/opensource/agm/ipc/SwBinders/agm_client/Makefile.am deleted file mode 100755 index 621cb7af..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_client/Makefile.am +++ /dev/null @@ -1,9 +0,0 @@ - -AM_CPPFLAGS := -I $(top_srcdir) -I $(PKG_CONFIG_SYSROOT_DIR)/usr/include/agm/ -AM_CPPFLAGS += -DDYNAMIC_LOG_ENABLED -lib_LTLIBRARIES = libagmclientwrapper.la -libagmclientwrapper_ladir = $(libdir) -libagmclientwrapper_la_SOURCES = src/agm_client_wrapper.cpp -libagmclientwrapper_la_CPPFLAGS := $(AM_CPPFLAGS) -libagmclientwrapper_la_LDFLAGS = -lcutils -llog -ldl -lbinder -shared -avoid-version -lutils -lrt -libagmclientwrapper_la_LIBADD = -lagmproxy -laudio_log_utils diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_client/agmclient.pc.in b/qcom/opensource/agm/ipc/SwBinders/agm_client/agmclient.pc.in deleted file mode 100755 index 390eb48e..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_client/agmclient.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: agmclient -Description: agmclient library -Version: @VERSION@ -Libs: -L${libdir} -lagmproxy -Cflags: -I${includedir}/agm_client/ diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_client/configure.ac b/qcom/opensource/agm/ipc/SwBinders/agm_client/configure.ac deleted file mode 100755 index ac5f5f6f..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_client/configure.ac +++ /dev/null @@ -1,41 +0,0 @@ -# -*- Autoconf -*- -# configure.ac -- Autoconf script for halinterface -# - -# Process this file with autoconf to produce a configure script. - -# Requires autoconf tool later than 2.61 -AC_PREREQ([2.69]) -# Initialize the hal-interface package version 1.0.0 -AC_INIT(halinterface,1.0.0) -# Does not strictly follow GNU Coding standards -AM_INIT_AUTOMAKE([foreign]) -# Disables auto rebuilding of configure, Makefile.ins -#AM_MAINTAINER_MODE -# defines some macros variable to be included by source -AC_CONFIG_HEADERS([config.h]) -# defines some macros variable to be included by source -AC_CONFIG_MACRO_DIR([m4]) - -PKG_CHECK_MODULES([AGMSERVER], [agmserver]) -AC_SUBST([AGMSERVER_CFLAGS]) - -# Checks for programs. -AC_PROG_CC - -AM_PROG_CC_C_O -AC_PROG_CXX -AC_PROG_LIBTOOL -AC_PROG_AWK -AC_PROG_CPP -AC_PROG_INSTALL -AC_PROG_LN_S -AC_PROG_MAKE_SET -PKG_PROG_PKG_CONFIG - -AC_CONFIG_FILES([ \ - Makefile\ - agmclient.pc - ]) - -AC_OUTPUT diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_client/src/agm_client_wrapper.cpp b/qcom/opensource/agm/ipc/SwBinders/agm_client/src/agm_client_wrapper.cpp deleted file mode 100755 index e3c09960..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_client/src/agm_client_wrapper.cpp +++ /dev/null @@ -1,523 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2022, 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the - * disclaimer below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE - * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT - * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "agm_client_wrapper" - -#include -#include -#include -#include -#include -#include -#ifdef FEATURE_IPQ_OPENWRT -#include -#include -#else -#include -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "utils.h" -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_CLIENT_WRAPPER -#include -#endif - -using namespace android; - -sp Server_death_notifier = NULL; -sp agm_client = NULL; -bool agm_server_died = false; - - -android::sp get_agm_server() -{ - if (agm_client == 0) { - AGM_LOGD("Agm client initialized\n"); - android:: sp binder = - android::defaultServiceManager()->getService(android::String16("AgmService")); - agm_client = android::interface_cast(binder); - AGM_LOGV("got service handle\n"); - if (Server_death_notifier == NULL) { - Server_death_notifier = new server_death_notifier(); - binder->linkToDeath(Server_death_notifier); - AGM_LOGV("%s : server linked to death \n", __func__); - } - } - return agm_client; -} - -server_death_notifier::server_death_notifier() -{ - AGM_LOGV("%s\n", __func__); - sp proc(ProcessState::self()); - proc->startThreadPool(); -} - -void server_death_notifier::binderDied(const wp& who __attribute__((unused))) -{ - agm_server_died = true; - AGM_LOGE("Agm server died !! and I am notified\n"); - //add further functionality -} - -int agm_register_service_crash_callback(agm_service_crash_cb cb, uint64_t cookie) -{ - return 0; -} - -int agm_aif_set_media_config(uint32_t audio_intf, - struct agm_media_config *media_config) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_audio_intf_set_media_config(audio_intf, - media_config); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_set_config(uint64_t handle, - struct agm_session_config *session_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_set_config(handle, session_config, - media_config, buffer_config); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_init(){ - /*agm_init in IPC happens in context of the server*/ - return 0; -} - -int agm_deinit(){ - /*agm_deinit in IPC happens in context of the server*/ - return 0; -} - -int agm_aif_set_metadata(uint32_t audio_intf, uint32_t size, uint8_t *metadata){ - if(!agm_server_died) - { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_audio_intf_set_metadata(audio_intf, size, - metadata); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_set_metadata(uint32_t session_id, uint32_t size, - uint8_t *metadata){ - if(!agm_server_died) - { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_set_metadata(session_id, size, - metadata); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_aif_set_metadata(uint32_t session_id, uint32_t audio_intf, - uint32_t size, uint8_t *metadata){ - if(!agm_server_died) - { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_audio_inf_set_metadata(session_id, - audio_intf, size, metadata); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_close(uint64_t handle) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_close(handle); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_prepare(uint64_t handle) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_prepare(handle); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_start(uint64_t handle) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_start(handle); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_stop(uint64_t handle) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_stop(handle); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_pause(uint64_t handle) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_pause(handle); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_resume(uint64_t handle) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_resume(handle); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_open(uint32_t session_id, - enum agm_session_mode sess_mode, - uint64_t *handle) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_open(session_id, sess_mode, handle); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_aif_connect(uint32_t session_id, uint32_t audio_intf, - bool state) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_audio_inf_connect(session_id, - audio_intf, state); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_read(uint64_t handle, void *buf, size_t *byte_count) -{ - - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - if (!handle) - return -EINVAL; - - return agm_client->ipc_agm_session_read(handle, buf, byte_count); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_write(uint64_t handle, void *buf, size_t *byte_count) -{ - - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - if (!handle) - return -EINVAL; - - return agm_client->ipc_agm_session_write(handle, buf, byte_count); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - - -int agm_session_set_loopback(uint32_t capture_session_id, - uint32_t playback_session_id, bool state) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_set_loopback(capture_session_id, - playback_session_id, state); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -size_t agm_get_hw_processed_buff_cnt(uint64_t handle, enum direction dir) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_get_hw_processed_buff_cnt(handle, dir); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_get_aif_info_list(struct aif_info *aif_list, size_t *num_aif_info) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_get_aif_info_list(aif_list, num_aif_info); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_aif_get_tag_module_info(uint32_t session_id, uint32_t aif_id, - void *payload, size_t *size) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_aif_get_tag_module_info(session_id, - aif_id, payload, size); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_aif_set_params(uint32_t aif_id,void *payload, size_t size) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_aif_set_params(aif_id, - payload, size); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_aif_set_params(uint32_t session_id, uint32_t aif_id, - void *payload, size_t size) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_aif_set_params(session_id, aif_id, - payload, size); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_set_params(uint32_t session_id, void *payload, size_t size) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_set_params(session_id, payload, - size); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_set_params_with_tag(uint32_t session_id, uint32_t aif_id, - struct agm_tag_config *tag_config) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_set_params_with_tag(session_id, aif_id, - tag_config); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_register_for_events(uint32_t session_id, - struct agm_event_reg_cfg *evt_reg_cfg) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_register_for_events(session_id, - evt_reg_cfg); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} -int agm_session_register_cb(uint32_t session_id, agm_event_cb cb, - enum event_type event, void *client_data) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_register_cb(session_id, cb, event, - client_data); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_set_ec_ref(uint32_t capture_session_id, uint32_t aif_id, - bool state) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_set_ec_ref(capture_session_id, - aif_id, state); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_aif_set_cal(uint32_t session_id, uint32_t audio_intf, - struct agm_cal_config *cal_config) -{ - if (!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_aif_set_cal(session_id, audio_intf, - cal_config); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_eos(uint64_t handle) -{ - if(!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_eos(handle); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_get_session_time(uint64_t handle, uint64_t *timestamp) -{ - if(!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_get_session_time(handle, timestamp); - } - AGM_LOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_get_params(uint32_t session_id, void *payload, size_t size) -{ - if(!agm_server_died) - { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_get_params(session_id, payload, size); - } - ALOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_get_buffer_timestamp(uint32_t session_id, uint64_t *timestamp) -{ - if(!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_get_buffer_timestamp(session_id, timestamp); - } - ALOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_set_gapless_session_metadata(uint64_t handle, - enum agm_gapless_silence_type type, - uint32_t silence) -{ - if(!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_set_gapless_session_metadata(handle, type, - silence); - } - ALOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} - -int agm_session_get_buf_info(uint32_t session_id, struct agm_buf_info *buf_info, - uint32_t flag) -{ - if(!agm_server_died) { - android::sp agm_client = get_agm_server(); - return agm_client->ipc_agm_session_get_buf_info(session_id, buf_info, - flag); - } - ALOGE("%s: agm service is not running\n", __func__); - return -EAGAIN; -} diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/Android.mk b/qcom/opensource/agm/ipc/SwBinders/agm_server/Android.mk deleted file mode 100755 index a2511529..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/Android.mk +++ /dev/null @@ -1,43 +0,0 @@ -LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) - -LOCAL_CFLAGS += -Wall -LOCAL_SRC_FILES := ipc_proxy_server.cpp - -LOCAL_C_INCLUDES += $(LOCAL_PATH) -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH) - -LOCAL_SHARED_LIBRARIES := \ - liblog \ - libcutils \ - libdl \ - libbinder \ - libutils - -LOCAL_MODULE := libagmproxy -LOCAL_MODULE_TAGS := optional - -include $(BUILD_SHARED_LIBRARY) -include $(CLEAR_VARS) -LOCAL_MODULE := agmserver -LOCAL_SRC_FILES := \ - agm_server_daemon.cpp \ - agm_server_wrapper.cpp - -LOCAL_SHARED_LIBRARIES := \ - liblog \ - libcutils \ - libdl \ - libbinder \ - libutils \ - libagmproxy - -ifeq ($(strip $(AUDIO_FEATURE_ENABLED_DYNAMIC_LOG)), true) -LOCAL_CFLAGS += -DDYNAMIC_LOG_ENABLED -LOCAL_C_INCLUDES += $(TOP)/external/expat/lib/expat.h -LOCAL_SHARED_LIBRARIES += libaudio_log_utils -LOCAL_SHARED_LIBRARIES += libexpat -LOCAL_HEADER_LIBRARIES += libaudiologutils_headers -endif - -include $(BUILD_EXECUTABLE) diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/Makefile.am b/qcom/opensource/agm/ipc/SwBinders/agm_server/Makefile.am deleted file mode 100755 index 620ca0a0..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/Makefile.am +++ /dev/null @@ -1,36 +0,0 @@ -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = agmserver.pc -EXTRA_DIST = $(pkgconfig_DATA) - -h_sources = $(top_srcdir)/inc/ipc_interface.h -h_sources += $(top_srcdir)/inc/agm_death_notifier.h -h_sources += $(top_srcdir)/inc/agm_callback.h - -AM_CPPFLAGS := -I $(top_srcdir) -I $(PKG_CONFIG_SYSROOT_DIR)/usr/include/agm/\ - -I $(PKG_CONFIG_SYSROOT_DIR)/usr/include/qti-agm-service\ - -I ${top_srcdir}/inc - -AM_CPPFLAGS += -D__unused=__attribute__\(\(__unused__\)\) -AM_CPPFLAGS += -DDYNAMIC_LOG_ENABLED -library_include_HEADERS = $(h_sources) -library_includedir = $(includedir)/qti-agm-service/ - -lib_LTLIBRARIES = libagmserverwrapper.la -libagmserverwrapper_la_SOURCES = ${top_srcdir}/src/agm_death_notifier.cpp ${top_srcdir}/src/agm_server_wrapper.cpp ${top_srcdir}/src/agm_callback.cpp - -libagmserverwrapper_la_CPPFLAGS := $(AM_CPPFLAGS) -libagmserverwrapper_la_LIBADD = -lagm -laudio_log_utils -libagmserverwrapper_la_LDFLAGS = -lcutils -llog -ldl -lbinder -shared -avoid-version -lutils -lpthread - -lib_LTLIBRARIES += libagmproxy.la -libagmproxy_la_SOURCES = ${top_srcdir}/src/ipc_proxy_server.cpp -libagmproxy_la_CPPFLAGS := $(AM_CPPFLAGS) -libagmproxy_la_LIBADD = libagmserverwrapper.la -libagmproxy_la_LDFLAGS = -lcutils -llog -ldl -lbinder -shared -avoid-version -lutils -lpthread - -bin_PROGRAMS := agm_server -agm_server_SOURCES := ${top_srcdir}/src/agm_server_daemon.cpp - -agmserver_la_CPPFLAGS := $(AM_CPPFLAGS) -agm_server_LDADD := libagmproxy.la -laudio_log_utils -agmserver_la_LDFLAGS = -lcutils -llog -ldl -lbinder -shared -avoid-version -lutils diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/agmserver.pc.in b/qcom/opensource/agm/ipc/SwBinders/agm_server/agmserver.pc.in deleted file mode 100755 index 87c9c676..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/agmserver.pc.in +++ /dev/null @@ -1,8 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: agmserver -Description: agmserver library -Version: @VERSION@ diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/configure.ac b/qcom/opensource/agm/ipc/SwBinders/agm_server/configure.ac deleted file mode 100755 index f8c3ebd1..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/configure.ac +++ /dev/null @@ -1,37 +0,0 @@ -# -*- Autoconf -*- -# configure.ac -- Autoconf script for halinterface -# - -# Process this file with autoconf to produce a configure script. - -# Requires autoconf tool later than 2.61 -AC_PREREQ([2.69]) -# Initialize the hal-interface package version 1.0.0 -AC_INIT(halinterface,1.0.0) -# Does not strictly follow GNU Coding standards -AM_INIT_AUTOMAKE([foreign]) -# Disables auto rebuilding of configure, Makefile.ins -#AM_MAINTAINER_MODE -# defines some macros variable to be included by source -AC_CONFIG_HEADERS([config.h]) -# defines some macros variable to be included by source -AC_CONFIG_MACRO_DIR([m4]) - -# Checks for programs. -AC_PROG_CC -AM_PROG_CC_C_O -AC_PROG_CXX -AC_PROG_LIBTOOL -AC_PROG_AWK -AC_PROG_CPP -AC_PROG_INSTALL -AC_PROG_LN_S -AC_PROG_MAKE_SET -PKG_PROG_PKG_CONFIG - -AC_CONFIG_FILES([ \ - Makefile \ - agmserver.pc - ]) - -AC_OUTPUT diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/agm_callback.h b/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/agm_callback.h deleted file mode 100755 index 9370d809..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/agm_callback.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -using namespace android; - -class ICallback : public ::android::IInterface -{ - public: - DECLARE_META_INTERFACE(Callback); - virtual int event_cb (uint32_t session_id, - struct agm_event_cb_params *event_params, - void *client_data, agm_event_cb cb_func) = 0; -}; - - -class BnCallback : public ::android::BnInterface -{ -public: - BnCallback(){}; - ~BnCallback(){}; -private: - int32_t onTransact(uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags) override; - int event_cb (uint32_t session_id, - struct agm_event_cb_params *event_params, - void *client_data, agm_event_cb cb_func) override; -}; - -typedef struct { - struct listnode list; - uint32_t session_id; - sp cb_binder; - agm_event_cb cb_func; - void * client_data; -}clbk_data ; diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/agm_death_notifier.h b/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/agm_death_notifier.h deleted file mode 100755 index 0b95196f..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/agm_death_notifier.h +++ /dev/null @@ -1,101 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "utils.h" - -using namespace android; - -class IAGMClient : public ::android::IInterface -{ - public: - DECLARE_META_INTERFACE(AGMClient); -}; - -class DummyBnClient : public ::android::BnInterface -{ - public: - DummyBnClient(){ - AGM_LOGV("Constructor of DummyBnClient called\n"); - } - ~DummyBnClient(){ - AGM_LOGV("Destructor of DummyBnClient called\n"); - } - private: - int32_t onTransact(uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags) override; -}; - - -class server_death_notifier : public IBinder::DeathRecipient -{ - public: - server_death_notifier(); - // DeathRecipient - virtual void binderDied(const android::wp& who); -}; - -class client_death_notifier : public IBinder::DeathRecipient -{ - public: - client_death_notifier(); - // DeathRecipient - virtual void binderDied(const android::wp& who); -}; - -typedef struct { - struct listnode list; - uint64_t handle; - //bool rx; - } agm_client_session_handle; - -typedef struct { - struct listnode list; - sp binder; - pid_t pid; - sp Client_death_notifier; - struct listnode agm_client_hndl_list; -} client_info; - -client_info *get_client_handle_from_list(pid_t pid); -void agm_register_client(sp binder); -void agm_unregister_client(sp binder); -void agm_add_session_obj_handle(uint64_t handle); -void agm_remove_session_obj_handle(uint64_t handle); diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/agm_server_wrapper.h b/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/agm_server_wrapper.h deleted file mode 100755 index 172a6aad..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/agm_server_wrapper.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -** Copyright (c) 2019, 2021 The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the - * disclaimer below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE - * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT - * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - - -#ifndef __Agm_SERVER_H__ -#define __Agm_SERVER_H__ - -#include -#include -#include "ipc_interface.h" -#include "utils.h" - -class AgmService : public BnAgmService -{ - public: - AgmService() - { - AGM_LOGV("AGMService constructor\n"); - agm_initialized = ((agm_init() == 0)?true:false); - } - virtual int ipc_agm_init(); - virtual int ipc_agm_audio_intf_set_metadata(uint32_t audio_intf, - uint32_t size, uint8_t *metadata); - virtual int ipc_agm_session_set_metadata(uint32_t session_id, - uint32_t size, uint8_t *metadata); - virtual int ipc_agm_session_audio_inf_set_metadata(uint32_t session_id, - uint32_t audio_intf, uint32_t size, - uint8_t *metadata); - virtual int ipc_agm_session_close(uint64_t handle); - virtual int ipc_agm_audio_intf_set_media_config(uint32_t audio_intf, - struct agm_media_config *media_config); - virtual int ipc_agm_session_prepare(uint64_t handle); - virtual int ipc_agm_session_start(uint64_t handle); - virtual int ipc_agm_session_stop(uint64_t handle); - virtual int ipc_agm_session_pause(uint64_t handle); - virtual int ipc_agm_session_resume(uint64_t handle); - virtual int ipc_agm_session_open(uint32_t session_id, - enum agm_session_mode sess_mode, - uint64_t *handle); - virtual int ipc_agm_session_read(uint64_t handle, void *buff, - size_t *count); - virtual int ipc_agm_session_write(uint64_t handle, void *buff, - size_t *count); - virtual int ipc_agm_session_audio_inf_connect(uint32_t session_id, - uint32_t audio_intf, bool state); - virtual int ipc_agm_session_set_loopback(uint32_t capture_session_id, - uint32_t playback_session_id, bool state); - virtual size_t ipc_agm_get_hw_processed_buff_cnt(uint64_t handle, - enum direction dir); - virtual int ipc_agm_get_aif_info_list(struct aif_info *aif_list, - size_t *num_aif_info); - virtual int ipc_agm_session_aif_get_tag_module_info(uint32_t session_id, - uint32_t aif_id, void *payload, - size_t *size); - virtual int ipc_agm_get_params_from_acdb_tunnel(void *payload, - size_t *size); - virtual int ipc_agm_session_aif_set_params(uint32_t session_id, - uint32_t aif_id, void *payload, - size_t size); - virtual int ipc_agm_aif_set_params(uint32_t aif_id, - void* payload, size_t size); - virtual int ipc_agm_session_set_params(uint32_t session_id, - void *payload, size_t size); - virtual int ipc_agm_set_params_with_tag(uint32_t session_id, - uint32_t aif_id, - struct agm_tag_config *tag_config); - virtual int ipc_agm_session_register_for_events(uint32_t session_id, - struct agm_event_reg_cfg *evt_reg_cfg); - virtual int ipc_agm_session_register_cb(uint32_t session_id, - agm_event_cb cb, enum event_type event, - void *client_data) ; - virtual int ipc_agm_session_set_config( - uint64_t handle, - struct agm_session_config *session_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config); - virtual int ipc_agm_session_set_ec_ref(uint32_t capture_session_id, - uint32_t aif_id, bool state); - virtual int ipc_agm_session_aif_set_cal( - uint32_t session_id, - uint32_t audio_intf, - struct agm_cal_config *cal_config); - virtual int ipc_agm_session_eos(uint64_t handle); - virtual int ipc_agm_get_session_time(uint64_t handle, uint64_t *timestamp); - virtual int ipc_agm_session_get_params(uint32_t session_id, - void *payload, size_t size); - virtual int ipc_agm_get_buffer_timestamp(uint32_t session_id, uint64_t *timestamp); - virtual int ipc_agm_set_gapless_session_metadata(uint64_t handle, - enum agm_gapless_silence_type type, uint32_t silence); - virtual int ipc_agm_session_get_buf_info(uint32_t session_id, - struct agm_buf_info *buf_info, uint32_t flag); - ~AgmService() - { - AGM_LOGV("AGMService destructor"); - agm_deinit(); - } - - int is_agm_service_initialized() { - return agm_initialized; - } - private: - bool agm_initialized = false; -}; - -#endif diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/ipc_interface.h b/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/ipc_interface.h deleted file mode 100755 index 163a1e6c..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/inc/ipc_interface.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -** Copyright (c) 2019, 2021 The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the - * disclaimer below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE - * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT - * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#ifndef __AGM_SERVER_INTERFACE_H__ -#define __AGM_SERVER_INTERFACE_H__ - -#include -#include -#include -#include -#include -#include -typedef void shmem_handle_t; - -// can be shared by both server and client. - -class IAgmService: public ::android::IInterface -{ - public: - DECLARE_META_INTERFACE(AgmService); - - virtual int ipc_agm_init()= 0; - virtual int ipc_agm_audio_intf_set_metadata(uint32_t audio_intf, - uint32_t size, uint8_t *metadata)= 0; - virtual int ipc_agm_session_set_metadata(uint32_t session_id, - uint32_t size, uint8_t *metadata)= 0; - virtual int ipc_agm_session_audio_inf_set_metadata(uint32_t session_id, - uint32_t audio_intf, uint32_t size, - uint8_t *metadata)= 0; - virtual int ipc_agm_session_close(uint64_t handle)= 0; - virtual int ipc_agm_audio_intf_set_media_config(uint32_t audio_intf, - struct agm_media_config *media_config)= 0; - virtual int ipc_agm_session_prepare(uint64_t handle)= 0; - virtual int ipc_agm_session_start(uint64_t handle)= 0; - virtual int ipc_agm_session_stop(uint64_t handle)= 0; - virtual int ipc_agm_session_pause(uint64_t handle)= 0; - virtual int ipc_agm_session_resume(uint64_t handle)= 0; - virtual int ipc_agm_session_read(uint64_t handle, - void *buff, size_t *count)= 0; - virtual int ipc_agm_session_write(uint64_t handle, void *buff, - size_t *count)= 0; - virtual int ipc_agm_session_audio_inf_connect(uint32_t session_id, - uint32_t audio_intf, bool state) = 0; - virtual int ipc_agm_session_set_loopback(uint32_t capture_session_id, - uint32_t playback_session_id, - bool state) = 0; - virtual size_t ipc_agm_get_hw_processed_buff_cnt(uint64_t handle, - enum direction dir) = 0; - virtual int ipc_agm_get_aif_info_list(struct aif_info *aif_list, - size_t *num_aif_info) = 0; - virtual int ipc_agm_session_open(uint32_t session_id, - enum agm_session_mode sess_mode, - uint64_t *handle) = 0; - virtual int ipc_agm_session_register_for_events(uint32_t session_id, - struct agm_event_reg_cfg *evt_reg_cfg) = 0; - virtual int ipc_agm_session_register_cb(uint32_t session_id, - agm_event_cb cb, enum event_type event, - void *client_data) = 0; - virtual int ipc_agm_session_set_config( - uint64_t handle, - struct agm_session_config *session_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config) = 0; - virtual int ipc_agm_session_aif_get_tag_module_info(uint32_t session_id, - uint32_t aif_id, void *payload, - size_t *size) = 0; - virtual int ipc_agm_get_params_with_tag_from_acdb(void *payload, - size_t *size) = 0; - virtual int ipc_agm_session_aif_set_params(uint32_t session_id, - uint32_t aif_id, void *payload, - size_t size) = 0; - virtual int ipc_agm_aif_set_params(uint32_t aif_id, - void* payload, size_t size) = 0; - virtual int ipc_agm_session_set_params(uint32_t session_id, - void *payload, size_t size) = 0; - virtual int ipc_agm_set_params_with_tag(uint32_t session_id, - uint32_t aif_id, - struct agm_tag_config *tag_config) = 0; - virtual int ipc_agm_session_set_ec_ref(uint32_t capture_session_id, - uint32_t aif_id, bool state) = 0; - virtual int ipc_agm_session_aif_set_cal( - uint32_t session_id, - uint32_t audio_intf, - struct agm_cal_config *cal_config) = 0; - virtual int ipc_agm_session_eos(uint64_t handle)= 0; - virtual int ipc_agm_get_session_time(uint64_t handle, - uint64_t *timestamp)= 0; - virtual int ipc_agm_session_get_params(uint32_t session_id, - void *payload, size_t size) = 0; - virtual int ipc_agm_get_buffer_timestamp(uint32_t session_id, - uint64_t *timestamp)= 0; - virtual int ipc_agm_set_gapless_session_metadata(uint64_t handle, - enum agm_gapless_silence_type type, - uint32_t silence) = 0; - virtual int ipc_agm_session_get_buf_info(uint32_t session_id, - struct agm_buf_info *buf_info, uint32_t flag) = 0; -}; - -class BnAgmService : public ::android::BnInterface { - android::status_t onTransact(uint32_t code, - const android::Parcel& data, - android::Parcel* reply, uint32_t flags); -}; -#endif diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_callback.cpp b/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_callback.cpp deleted file mode 100755 index eb40116b..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_callback.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "agm_callback" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include "agm_callback.h" -#include "utils.h" - -#ifndef MIN -#define MIN(a,b) (((a)<(b))?(a):(b)) -#endif - -#ifndef memscpy -#define memscpy(dst, dst_size, src, bytes_to_copy) (void) \ - memcpy(dst, src, MIN(dst_size, bytes_to_copy)) -#endif - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_CALLBACK -#include -#endif - -using namespace android; - -const android::String16 ICallback::descriptor("ICallback"); -const android::String16& ICallback::getInterfaceDescriptor() const -{ - return ICallback::descriptor; -} - -class BpCallback: public ::android:: BpInterface -{ -public: - BpCallback(const sp& impl) : BpInterface(impl) - { - AGM_LOGD("BpCallback::BpCallback()\n"); - } - - int event_cb(uint32_t session_id, struct agm_event_cb_params *event_params, - void *client_data, agm_event_cb cb_func) - { - AGM_LOGV("%s %d\n", __func__, __LINE__); - android::Parcel data, reply; - data.writeInterfaceToken(ICallback::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(event_params->source_module_id); - data.writeUint32(event_params->event_id); - data.writeUint32(event_params->event_payload_size); - uint32_t param_size = event_params->event_payload_size; - android::Parcel::WritableBlob blob; - data.writeBlob(param_size, false, &blob); - memset(blob.data(), 0x0, param_size); - memscpy(blob.data(), param_size, event_params->event_payload, param_size); - blob.release(); - data.writeInt64((long)client_data); - data.write(&cb_func, sizeof(agm_event_cb *)); - return remote()->transact(event_params->event_id, data, &reply); - } -}; - -android::sp ICallback::asInterface - (const android::sp& obj) -{ - AGM_LOGD("ICallback::asInterface()\n"); - android::sp intr; - if (obj != NULL) { - intr = static_cast(obj->queryLocalInterface(ICallback::descriptor).get()); - AGM_LOGD("ICallback::asInterface() interface %s\n", - ((intr == 0)?"zero":"non zero")); - if (intr == NULL) - intr = new BpCallback(obj); - } - return intr; -} - -ICallback::ICallback() -{AGM_LOGD("ICallback::ICallback()\n"); } -ICallback::~ICallback() -{AGM_LOGD("ICallback::~ICallback()\n"); } - -int32_t BnCallback::onTransact(uint32_t code, - const Parcel& data, - Parcel* reply __unused, - uint32_t flags) -{ - AGM_LOGD("BnCallback::onTransact(%i) %i\n", code, flags); - data.checkInterface(this); - uint32_t session_id; - uint32_t source_module_id; - uint32_t event_id; - uint32_t event_payload_size; - void *client_data; - agm_event_cb cb_func; - struct agm_event_cb_params *event_params = NULL; - session_id = data.readUint32(); - source_module_id = data.readUint32(); - event_id = data.readUint32(); - event_payload_size = data.readUint32(); - event_params = (struct agm_event_cb_params *) calloc(1, - (sizeof(agm_event_cb_params) + event_payload_size)); - if (event_params == NULL) { - AGM_LOGE("%s: Cannot allocate memory for struct \ - agm_event_cb_params\n", __func__); - return -ENOMEM; - } - event_params->source_module_id = source_module_id; - event_params->event_id = (agm_event_id) event_id; - event_params->event_payload_size = event_payload_size; - android::Parcel::ReadableBlob blob; - uint32_t blob_size = event_payload_size ; - data.readBlob(blob_size, &blob); - memset(event_params->event_payload, 0x0, event_params->event_payload_size); - memscpy(event_params->event_payload, - event_params->event_payload_size , blob.data(), blob_size); - blob.release(); - client_data = (void *)data.readInt64(); - data.read(&cb_func, sizeof(agm_event_cb *)); - return event_cb(session_id, event_params, client_data, cb_func); -} - -int BnCallback::event_cb(uint32_t session_id, - struct agm_event_cb_params *event_params, - void *client_data, agm_event_cb cb_func) -{ - AGM_LOGD("Calling Client Registered Callback(%x)\n", cb_func); - cb_func(session_id, event_params, client_data); - return 0; -} diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_death_notifier.cpp b/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_death_notifier.cpp deleted file mode 100755 index ff4e784b..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_death_notifier.cpp +++ /dev/null @@ -1,277 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "agm_death_notifier" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ipc_interface.h" -#include "agm_death_notifier.h" -#include "utils.h" - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_DEATH_NOTIFIER -#include -#endif - -using namespace android; - -struct listnode g_client_list; -pthread_mutex_t g_client_list_lock; -bool g_client_list_init = false; -//initialize mutex - -client_death_notifier::client_death_notifier(void) -{ - AGM_LOGV("%s:%d\n", __func__, __LINE__); - sp proc(ProcessState::self()); - proc->startThreadPool(); -} -sp Client_death_notifier = NULL; - -client_info *get_client_handle_from_list(pid_t pid) -{ - struct listnode *node = NULL; - client_info *handle = NULL; - - pthread_mutex_lock(&g_client_list_lock); - list_for_each(node, &g_client_list) { - handle = node_to_item(node, client_info, list); - if (handle->pid == pid) { - AGM_LOGV("%s: Found handle %p\n", __func__, handle); - pthread_mutex_unlock(&g_client_list_lock); - return handle; - } - } - pthread_mutex_unlock(&g_client_list_lock); - return NULL; -} - -void agm_register_client(sp binder) -{ - client_info *client_handle = NULL; - pid_t pid = IPCThreadState::self()->getCallingPid(); - android::sp client_binder = - android::interface_cast(binder); - Client_death_notifier = new client_death_notifier(); - IInterface::asBinder(client_binder)->linkToDeath(Client_death_notifier); - AGM_LOGD("%s: Client registered and death notifier linked to AGM\n", - __func__); - if (g_client_list_init == false) { - pthread_mutex_init(&g_client_list_lock, - (const pthread_mutexattr_t *) NULL); - list_init(&g_client_list); - g_client_list_init = true; - } - client_handle = (client_info *)calloc(1, sizeof(client_info)); - if (client_handle == NULL) { - AGM_LOGE("%s: Cannot allocate memory for client handle\n", - __func__); - return; - } - pthread_mutex_lock(&g_client_list_lock); - client_handle->binder = client_binder; - client_handle->pid = pid; - client_handle->Client_death_notifier = Client_death_notifier; - list_add_tail(&g_client_list, &client_handle->list); - list_init(&client_handle->agm_client_hndl_list); - pthread_mutex_unlock(&g_client_list_lock); - -} - -void agm_add_session_obj_handle(uint64_t handle) -{ - client_info *client_handle = NULL; - agm_client_session_handle *hndl = NULL; - - client_handle = - get_client_handle_from_list(IPCThreadState::self()->getCallingPid()); - if (client_handle == NULL) { - AGM_LOGE("%s: Could not find client handle\n", __func__); - goto exit; - } - - pthread_mutex_lock(&g_client_list_lock); - hndl = (agm_client_session_handle *)calloc(1, - sizeof(agm_client_session_handle)); - if (hndl == NULL) { - AGM_LOGE("%s: Cannot allocate memory to store agm session handle\n", - __func__); - goto exit; - } - hndl->handle = handle; - list_add_tail(&client_handle->agm_client_hndl_list, &hndl->list); - -exit: - pthread_mutex_unlock(&g_client_list_lock); -} - -void agm_remove_session_obj_handle(uint64_t handle) -{ - client_info *client_handle = NULL; - struct listnode *node = NULL; - agm_client_session_handle *hndl = NULL; - struct listnode *tempnode = NULL; - - client_handle = - get_client_handle_from_list(IPCThreadState::self()->getCallingPid()); - if (client_handle == NULL) { - AGM_LOGE("%s: Could not find client handle\n", __func__); - return; - } - - pthread_mutex_lock(&g_client_list_lock); - list_for_each_safe(node, tempnode, &client_handle->agm_client_hndl_list) { - hndl = node_to_item(node, agm_client_session_handle, list); - if (hndl->handle == handle) { - AGM_LOGV("%s: Removed handle 0x%llx\n", __func__, handle); - list_remove(node); - free(hndl); - break; - } - } - pthread_mutex_unlock(&g_client_list_lock); -} - -void agm_unregister_client(sp binder) -{ - android::sp client_binder = - android::interface_cast(binder); - client_info *handle = NULL; - struct listnode *tempnode = NULL; - struct listnode *node = NULL; - - AGM_LOGV("%s: enter\n", __func__); - pthread_mutex_lock(&g_client_list_lock); - list_for_each_safe(node, tempnode, &g_client_list) { - handle = node_to_item(node, client_info, list); - if (handle->pid == IPCThreadState::self()->getCallingPid()) { - if (handle->Client_death_notifier != NULL) { - IInterface::asBinder(client_binder)->unlinkToDeath(handle->Client_death_notifier); - handle->Client_death_notifier.clear(); - AGM_LOGV("%s: unlink to death %d\n", __func__, handle->pid); - } - list_remove(node); - free(handle); - } - } - AGM_LOGV("%s: exit\n", __func__); - pthread_mutex_unlock(&g_client_list_lock); -} - -void client_death_notifier::binderDied(const wp& who) -{ - client_info *handle = NULL; - struct listnode *node = NULL; - struct listnode *tempnode = NULL; - agm_client_session_handle *hndl = NULL; - struct listnode *sess_node = NULL; - struct listnode *sess_tempnode = NULL; - - pthread_mutex_lock(&g_client_list_lock); - list_for_each_safe(node, tempnode, &g_client_list) { - handle = node_to_item(node, client_info, list); - if (IInterface::asBinder(handle->binder).get() == who.unsafe_get()) { - list_for_each_safe(sess_node, sess_tempnode, - &handle->agm_client_hndl_list) { - hndl = node_to_item(sess_node, agm_client_session_handle, list); - if (hndl->handle) { - agm_session_close(hndl->handle); - list_remove(sess_node); - free(hndl); - } - } - list_remove(node); - free(handle); - } - } - pthread_mutex_unlock(&g_client_list_lock); - AGM_LOGD("%s: exit\n", __func__); -} - -const android::String16 IAGMClient::descriptor("IAGMClient"); -const android::String16& IAGMClient::getInterfaceDescriptor() const { - return IAGMClient::descriptor; -} - -class BpClient: public ::android:: BpInterface -{ -public: - BpClient(const sp& impl) : BpInterface(impl) { - AGM_LOGD("BpClient::BpClient()\n"); - } -}; - -android::sp IAGMClient::asInterface - (const android::sp& obj) -{ - AGM_LOGV("IAGMClient::asInterface()\n"); - android::sp intr; - if (obj != NULL) { - intr = static_cast(obj->queryLocalInterface - (IAGMClient::descriptor).get()); - AGM_LOGD("IAGMClient::asInterface() interface %s\n", - ((intr == 0)?"zero":"non zero")); - if (intr == NULL) - intr = new BpClient(obj); - } - return intr; -} -IAGMClient :: IAGMClient() { AGM_LOGD("IAGMClient::IAGMClient()"); } -IAGMClient :: ~IAGMClient() { AGM_LOGD("IAGMClient::~IAGMClient()"); } - -int32_t DummyBnClient::onTransact(uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags) -{ - int status = 0; - AGM_LOGV("DummyBnClient::onTransact(%i) %i\n", code, flags); - //data.checkInterface(this); //Alternate option to check interface - CHECK_INTERFACE(IAGMClient, data, reply); - switch(code) { - default: - return BBinder::onTransact(code, data, reply, flags); - break; - } - return status; -} - diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_server_daemon.cpp b/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_server_daemon.cpp deleted file mode 100755 index eb2f0908..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_server_daemon.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "agm_server_daemon" - -#include -#include -#include -#include "ipc_interface.h" -#include "agm_server_wrapper.h" -#include -#include "utils.h" - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_SERVER_DAEMON -#include -#endif - - -static class AgmService *agmServiceInstance = new AgmService(); - -static void sigint_handler(int sig __unused) -{ - AGM_LOGD("AgmService received signal\n"); - agmServiceInstance->~AgmService(); - exit(0); -} - -int main() -{ - signal(SIGINT, sigint_handler); - android::defaultServiceManager()->addService(android::String16("AgmService"), - agmServiceInstance); - if (agmServiceInstance->is_agm_service_initialized()) { - AGM_LOGD("AgmService initialized \n"); - android::ProcessState::self()->startThreadPool(); - AGM_LOGD("AGM service is now ready\n"); - android::IPCThreadState::self()->joinThreadPool(); - AGM_LOGD("AGM service thread joined\n"); - return 0; - } else { - AGM_LOGD("AgmService initialization failed"); - return -1; - } -} diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_server_wrapper.cpp b/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_server_wrapper.cpp deleted file mode 100755 index 0fa77e75..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/agm_server_wrapper.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "agm_server_wrapper" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "utils.h" -#include "agm_server_wrapper.h" - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_SERVER_WRAPPER -#include -#endif -using namespace android; - -#if 0 -AgmService::AgmService() -{ - agm_initialized = !agm_init(); - AGM_LOGV("agm_initialized %d", agm_initialized); -} - -AgmService::~AgmService() -{ - agm_initialized = agm_deinit(); - AGM_LOGV("agm_initialized %d", agm_initialized); -} -#endif - -int AgmService::ipc_agm_session_read(uint64_t handle, void *buff, size_t *count){ - AGM_LOGV("%s called \n", __func__); - return agm_session_read(handle, buff, count); -}; - -int AgmService::ipc_agm_session_write(uint64_t handle, void *buff, size_t *count){ - AGM_LOGV("%s called \n", __func__); - return agm_session_write(handle, buff, count); -}; - -int AgmService::ipc_agm_init(){ - AGM_LOGV("%s called\n", __func__); - return 0; -}; - -int AgmService::ipc_agm_audio_intf_set_metadata(uint32_t audio_intf, - uint32_t size, uint8_t *metadata) -{ - AGM_LOGE("%s called\n", __func__); - return agm_aif_set_metadata(audio_intf, size, metadata); -}; - -int AgmService::ipc_agm_session_set_metadata(uint32_t session_id, - uint32_t size, uint8_t *metadata) -{ - AGM_LOGE("%s called\n", __func__); - return agm_session_set_metadata(session_id, size, metadata); -}; - -int AgmService::ipc_agm_session_audio_inf_set_metadata(uint32_t session_id, - uint32_t audio_intf, uint32_t size, - uint8_t *metadata) -{ - AGM_LOGE("%s called\n", __func__); - return agm_session_aif_set_metadata(session_id, audio_intf, size, metadata); -}; - -int AgmService::ipc_agm_session_close(uint64_t handle){ - ALOGV("%s called\n", __func__); - return agm_session_close(handle); -}; - -int AgmService::ipc_agm_session_prepare(uint64_t handle){ - ALOGV("%s called\n", __func__); - return agm_session_prepare(handle); -}; - -int AgmService::ipc_agm_session_start(uint64_t handle){ - ALOGV("%s called\n", __func__); - return agm_session_start(handle); -}; - -int AgmService::ipc_agm_session_stop(uint64_t handle){ - ALOGV("%s called\n", __func__); - return agm_session_stop(handle); -}; - -int AgmService::ipc_agm_session_pause(uint64_t handle){ - ALOGV("%s called\n", __func__); - return agm_session_pause(handle); -}; - -int AgmService::ipc_agm_session_resume(uint64_t handle){ - ALOGV("%s called\n", __func__); - return agm_session_resume(handle); -}; - -int AgmService::ipc_agm_session_set_loopback(uint32_t capture_session_id, - uint32_t playback_session_id, bool state) -{ - AGM_LOGV("%s called\n", __func__); - return agm_session_set_loopback(capture_session_id, playback_session_id, - state); -}; - -size_t AgmService::ipc_agm_get_hw_processed_buff_cnt(uint64_t handle, - enum direction dir) { - AGM_LOGV("%s called\n", __func__); - return agm_get_hw_processed_buff_cnt(handle, dir); -}; - -int AgmService::ipc_agm_get_aif_info_list(struct aif_info *aif_list, - size_t *num_aif_info) -{ - AGM_LOGV("%s called\n", __func__); - return agm_get_aif_info_list(aif_list, num_aif_info); -}; - -int AgmService::ipc_agm_session_aif_get_tag_module_info(uint32_t session_id, - uint32_t aif_id, void *payload, size_t *size) -{ - AGM_LOGV("%s called\n", __func__); - return agm_session_aif_get_tag_module_info(session_id, aif_id, - payload, size); -}; - -int AgmService::ipc_agm_aif_set_params(uint32_t aif_id, - void* payload, size_t size) -{ - AGM_LOGV("%s called\n", __func__); - return agm_aif_set_params(aif_id, payload, size); -} - -int AgmService::ipc_agm_session_aif_set_params(uint32_t session_id, - uint32_t aif_id, void *payload, size_t size) -{ - AGM_LOGV("%s called\n", __func__); - return agm_session_aif_set_params(session_id, aif_id, payload, size); -}; - -int AgmService::ipc_agm_session_set_params(uint32_t session_id, void *payload, - size_t size) -{ - AGM_LOGV("%s called\n", __func__); - return agm_session_set_params(session_id, payload, size); -}; - -int AgmService::ipc_agm_set_params_with_tag(uint32_t session_id, - uint32_t aif_id, - struct agm_tag_config *tag_config) -{ - AGM_LOGV("%s called\n", __func__); - return agm_set_params_with_tag(session_id, aif_id, tag_config); -}; - -int AgmService::ipc_agm_session_open(uint32_t session_id, - enum agm_session_mode sess_mode, - uint64_t *handle){ - AGM_LOGV("%s called\n", __func__); - return agm_session_open(session_id, sess_mode, handle); -}; - -int AgmService::ipc_agm_session_set_config(uint64_t handle, - struct agm_session_config *session_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config){ - AGM_LOGV("%s called\n", __func__); - return agm_session_set_config(handle, session_config, - media_config, buffer_config); -}; - - int AgmService::ipc_agm_session_audio_inf_connect(uint32_t session_id, - uint32_t audio_intf, bool state) -{ - AGM_LOGV("%s called\n", __func__); - return agm_session_aif_connect(session_id, audio_intf, state); - }; - -int AgmService::ipc_agm_audio_intf_set_media_config(uint32_t audio_intf, - struct agm_media_config *media_config) -{ - AGM_LOGV("%s called\n", __func__); - return agm_aif_set_media_config(audio_intf, media_config); -}; - -int AgmService::ipc_agm_session_register_for_events(uint32_t session_id, - struct agm_event_reg_cfg *evt_reg_cfg) -{ - AGM_LOGV("%s called\n", __func__); - return agm_session_register_for_events(session_id, evt_reg_cfg); -}; - -int AgmService::ipc_agm_session_register_cb(uint32_t session_id, - agm_event_cb cb, enum event_type event, - void *client_data) -{ - AGM_LOGV("%s called\n", __func__); - return agm_session_register_cb(session_id, cb, event, client_data); -}; - -int AgmService::ipc_agm_session_set_ec_ref(uint32_t capture_session_id, - uint32_t aif_id, bool state) -{ - AGM_LOGV("%s called\n", __func__); - return agm_session_set_ec_ref(capture_session_id, aif_id, state); -}; - -int AgmService::ipc_agm_session_aif_set_cal(uint32_t session_id, - uint32_t audio_intf, - struct agm_cal_config *cal_config) -{ - AGM_LOGV("%s called\n", __func__); - return agm_session_aif_set_cal(session_id, audio_intf, cal_config); -}; -int AgmService::ipc_agm_session_eos(uint64_t handle) { - AGM_LOGV("%s called\n", __func__); - return agm_session_eos(handle); -}; - -int AgmService::ipc_agm_get_session_time(uint64_t handle, uint64_t *timestamp) { - AGM_LOGV("%s called\n", __func__); - return agm_get_session_time(handle, timestamp); -}; - -int AgmService::ipc_agm_session_get_params(uint32_t session_id, void *payload, size_t size){ - AGM_LOGV("%s called\n", __func__); - return agm_session_get_params(session_id, payload, size); -}; - -int AgmService::ipc_agm_get_buffer_timestamp(uint32_t session_id, uint64_t *timestamp) { - ALOGV("%s called\n", __func__); - return agm_get_buffer_timestamp(session_id, timestamp); -}; - -int AgmService::ipc_agm_set_gapless_session_metadata(uint64_t handle, - enum agm_gapless_silence_type type, - uint32_t silence) { - ALOGV("%s called\n", __func__); - return agm_set_gapless_session_metadata(handle, type, silence); -}; - -int AgmService::ipc_agm_session_get_buf_info(uint32_t session_id, - struct agm_buf_info *buf_info, uint32_t flag) { - ALOGV("%s called\n", __func__); - return agm_session_get_buf_info(session_id, buf_info, flag); -}; diff --git a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/ipc_proxy_server.cpp b/qcom/opensource/agm/ipc/SwBinders/agm_server/src/ipc_proxy_server.cpp deleted file mode 100755 index c0b3572a..00000000 --- a/qcom/opensource/agm/ipc/SwBinders/agm_server/src/ipc_proxy_server.cpp +++ /dev/null @@ -1,1478 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the - * disclaimer below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE - * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT - * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "ipc_proxy" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ipc_interface.h" -#include "agm_death_notifier.h" -#include -#include "agm_server_wrapper.h" -#include "agm_callback.h" -#include "utils.h" - -#ifndef MIN -#define MIN(a,b) (((a)<(b))?(a):(b)) -#endif - -#define MAX_KVPAIR 48 - -#ifndef memscpy -#define memscpy(dst, dst_size, src, bytes_to_copy) (void) \ - memcpy(dst, src, MIN(dst_size, bytes_to_copy)) -#endif - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_IPC_PROXY_SERVER -#include -#endif - -struct listnode clbk_data_list; -pthread_mutex_t clbk_data_list_lock; -bool clbk_data_list_init = false; - -android::sp clt_binder; - -using namespace android; - -enum { - OPEN = ::android::IBinder::FIRST_CALL_TRANSACTION, - REG_CLIENT, - UNREG_CLIENT, - SET_MEDIA_CONFIG, - INIT, - AUDIO_INTF_SET_META, - SESSION_SET_META, - SESSION_AUDIO_INTF_SET_META, - SESSION_SET_CONFIG, - CLOSE, - PREPARE, - START, - STOP, - PAUSE, - RESUME, - CONNECT, - READ, - WRITE, - LOOPBACK, - GET_BUFF_CNT, - GET_AIF_LIST, - REG_EVENT, - REG_CB, - GET_TAG_MODULE_INFO, - SESSION_AIF_SET_PARAMS, - SESSION_SET_PARAMS, - SET_PARAMS_WITH_TAG, - SET_ECREF, - SET_CALIBRATION, - EOS, - GET_SESSION_TIME, - GET_PARAMS, - BUF_TSTAMP, - AIF_SET_PARAMS, - SET_GAPLESS_SESSION_METADATA, - GET_BUF_INFO, -}; - -class BpAgmService : public ::android::BpInterface -{ - public: - BpAgmService(const android::sp& impl) : BpInterface(impl) - { - AGM_LOGV("BpAgmService() called\n"); - android::Parcel data, reply; - - sp binder = new DummyBnClient(); - android::ProcessState::self()->startThreadPool(); - clt_binder = interface_cast(binder); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeStrongBinder(IInterface::asBinder(clt_binder)); - remote()->transact(REG_CLIENT, data, &reply); - AGM_LOGD("calling REG_CLIENT from BpAgmService\n"); - } - - ~BpAgmService() - { - android:: Parcel data, reply; - - AGM_LOGV("~BpAgmservice() destructor called\n"); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeStrongBinder(IInterface::asBinder(clt_binder)); - remote()->transact(UNREG_CLIENT, data, &reply); - AGM_LOGD("calling UNREG_CLIENT from BpAgmService\n"); - } - - virtual int ipc_agm_audio_intf_set_media_config(uint32_t audio_intf, - struct agm_media_config *media_config) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(audio_intf); - uint32_t param_size = sizeof(agm_media_config); - data.writeUint32(param_size); - data.writeBlob(param_size, false, &blob); - memset(blob.data(), 0x0, param_size); - memscpy(blob.data(), param_size, media_config, param_size); - remote()->transact(SET_MEDIA_CONFIG, data, &reply); - blob.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_session_set_config(uint64_t handle, - struct agm_session_config *session_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob1, blob2, blob3; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - uint32_t session_param_size = sizeof(agm_session_config); - data.writeUint32(session_param_size); - data.writeBlob(session_param_size, false, &blob1); - memset(blob1.data(), 0x0, session_param_size); - memscpy(blob1.data(), session_param_size, session_config, - session_param_size); - uint32_t media_param_size = sizeof(agm_media_config); - data.writeUint32(media_param_size); - data.writeBlob(media_param_size, false, &blob2); - memset(blob2.data(), 0x0, media_param_size); - memscpy(blob2.data(), media_param_size, media_config, - media_param_size); - uint32_t buffer_param_size = sizeof(agm_buffer_config); - data.writeUint32(buffer_param_size); - data.writeBlob(buffer_param_size, false, &blob3); - memset(blob3.data(), 0x0, buffer_param_size); - memscpy(blob3.data(), buffer_param_size, buffer_config, - buffer_param_size); - remote()->transact(SESSION_SET_CONFIG, data, &reply); - blob1.release(); - blob2.release(); - blob3.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_init() - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - remote()->transact(INIT, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_set_loopback(uint32_t capture_session_id, - uint32_t playback_session_id, bool state) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(capture_session_id); - data.writeUint32(playback_session_id); - data.write(&state, sizeof(bool)); - remote()->transact(LOOPBACK, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_audio_intf_set_metadata(uint32_t audio_intf, - uint32_t size, uint8_t *metadata) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(audio_intf); - data.writeUint32(size); - data.writeBlob(size, false, &blob); - memset(blob.data(), 0x0, size); - memcpy(blob.data(), metadata, size); - remote()->transact(AUDIO_INTF_SET_META, data, &reply); - blob.release(); - - return reply.readInt32(); - } - - virtual int32_t ipc_agm_session_set_metadata(uint32_t session_id, - uint32_t size, uint8_t *metadata) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(size); - data.writeBlob(size, false, &blob); - memset(blob.data(), 0x0, size); - memcpy(blob.data(), metadata, size); - remote()->transact(SESSION_SET_META, data, &reply); - blob.release(); - - return reply.readInt32(); - } - - virtual int32_t ipc_agm_session_audio_inf_set_metadata( - uint32_t session_id, uint32_t audio_intf, - uint32_t size, uint8_t *metadata) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(audio_intf); - data.writeUint32(size); - data.writeBlob(size, false, &blob); - memset(blob.data(), 0x0, size); - memcpy(blob.data(), metadata, size); - remote()->transact(SESSION_AUDIO_INTF_SET_META, data, &reply); - blob.release(); - - return reply.readInt32(); - } - - virtual int ipc_agm_session_open(uint32_t session_id, - enum agm_session_mode sess_mode, - uint64_t *handle) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(sess_mode); - remote()->transact(OPEN, data, &reply); - *handle = (uint64_t)reply.readInt64(); - return reply.readInt32(); - } - - virtual int ipc_agm_session_close(uint64_t handle) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - remote()->transact(CLOSE, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_prepare(uint64_t handle) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - remote()->transact(PREPARE, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_start(uint64_t handle) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - remote()->transact(START, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_stop(uint64_t handle) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - remote()->transact(STOP, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_pause(uint64_t handle) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - remote()->transact(PAUSE, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_resume(uint64_t handle) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - remote()->transact(RESUME, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_audio_inf_connect(uint32_t session_id, - uint32_t audio_intf, bool state) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(audio_intf); - data.write(&state, sizeof(bool)); - remote()->transact(CONNECT, data, &reply); - return reply.readInt32(); - } - - virtual size_t ipc_agm_get_hw_processed_buff_cnt(uint64_t handle, - enum direction dir) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - data.writeUint32(dir); - remote()->transact(GET_BUFF_CNT, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_read(uint64_t session_handle, void *buff, - size_t *count) - { - int rc = 0; - android::Parcel data, reply; - android::Parcel::ReadableBlob blob; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)session_handle); - data.writeUint32(*count); - remote()->transact(READ, data, &reply); - rc = reply.readInt32(); - if (rc != 0) { - AGM_LOGE("read failed error out %d\n", rc); - goto fail_read; - } - *count = reply.readUint32(); - reply.readBlob(*count, &blob); - memset(buff, 0x0, *count); - memcpy(buff, blob.data(), *count); - fail_read: - return rc; - } - - virtual int ipc_agm_session_write(uint64_t session_handle, void *buff, - size_t *count) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)session_handle); - data.writeUint32(*count); - data.writeBlob(*count, false, &blob); - memset(blob.data(), 0x0, *count); - memcpy(blob.data(), buff, *count); - remote()->transact(WRITE, data, &reply); - *count = reply.readUint32(); - blob.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_get_aif_info_list(struct aif_info *aif_list, - size_t *num_aif_info) - { - android::Parcel data, reply; - int count = *num_aif_info; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - if (aif_list == NULL && count == 0) { - data.writeUint32(count); - data.writeInt64((long)aif_list); - remote()->transact(GET_AIF_LIST, data, &reply); - *num_aif_info = reply.readInt32(); - return reply.readInt32(); - } else if (aif_list != NULL && count != 0) { - android::Parcel::ReadableBlob aif_list_blob; - - uint32_t total_bytecnt = count * sizeof(struct aif_info); - data.writeUint32(count); - data.writeInt64((long)aif_list); - remote()->transact(GET_AIF_LIST, data, &reply); - reply.readBlob(total_bytecnt, &aif_list_blob); - memset(aif_list, 0x0, total_bytecnt); - memcpy(aif_list, aif_list_blob.data(), total_bytecnt); - aif_list_blob.release(); - return reply.readInt32(); - } - return -EINVAL; - } - - virtual int ipc_agm_session_register_for_events(uint32_t session_id, - struct agm_event_reg_cfg *evt_reg_cfg) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(evt_reg_cfg->module_instance_id); - data.writeUint32(evt_reg_cfg->event_id); - data.writeUint32(evt_reg_cfg->event_config_payload_size); - data.writeUint32(evt_reg_cfg->is_register); - uint32_t param_size = evt_reg_cfg->event_config_payload_size; - data.writeUint32(param_size); - data.writeBlob(param_size, false, &blob); - memset(blob.data(), 0x0, param_size); - memscpy(blob.data(), param_size, evt_reg_cfg->event_config_payload, - param_size); - remote()->transact(REG_EVENT, data, &reply); - blob.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_session_register_cb(uint32_t session_id, - agm_event_cb cb, enum event_type event, - void *client_data) - { - android::Parcel data, reply; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.write(&cb, sizeof(agm_event_cb *)); - data.writeUint32(event); - data.writeInt64((long)client_data); - sp binder = new BnCallback(); - android::ProcessState::self()->startThreadPool(); - sp clbk = interface_cast(binder); - data.writeStrongBinder(IInterface::asBinder(clbk)); - remote()->transact(REG_CB, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_aif_get_tag_module_info(uint32_t session_id, - uint32_t aif_id, void *payload, size_t *size) - { - android::Parcel data, reply; - int count = *size; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - if (payload != NULL && count != 0) { - android::Parcel::ReadableBlob tag_info_blob; - - data.writeUint32(count); - data.writeUint32(session_id); - data.writeUint32(aif_id); - remote()->transact(GET_TAG_MODULE_INFO, data, &reply); - count = (size_t) reply.readUint32(); - reply.readBlob(count, &tag_info_blob); - memcpy(payload, tag_info_blob.data(), count); - tag_info_blob.release(); - return reply.readInt32(); - } - return -EINVAL; - } - - virtual int ipc_agm_session_aif_set_params(uint32_t session_id, - uint32_t aif_id, void *payload, size_t count) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(aif_id); - data.writeUint32(count); - data.writeBlob(count, false, &blob); - memset(blob.data(), 0x0, count); - memcpy(blob.data(), payload, count); - remote()->transact(SESSION_AIF_SET_PARAMS, data, &reply); - blob.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_aif_set_params(uint32_t aif_id, - void *payload, size_t count) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(aif_id); - data.writeUint32(count); - data.writeBlob(count, false, &blob); - memset(blob.data(), 0x0, count); - memcpy(blob.data(), payload, count); - remote()->transact(AIF_SET_PARAMS, data, &reply); - blob.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_session_set_params(uint32_t session_id, - void *payload, size_t count) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(count); - data.writeBlob(count, false, &blob); - memset(blob.data(), 0x0, count); - memcpy(blob.data(), payload, count); - remote()->transact(SESSION_SET_PARAMS, data, &reply); - blob.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_set_params_with_tag(uint32_t session_id, - uint32_t aif_id, - struct agm_tag_config *tag_config) - { - android::Parcel data, reply; - android::Parcel::WritableBlob tkv_blob; - uint32_t kv_size = sizeof(agm_key_value); - uint32_t tkv_size = kv_size * (tag_config->num_tkvs); - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(aif_id); - data.writeUint32(tag_config->tag); - data.writeUint32(tag_config->num_tkvs); - data.writeBlob(tkv_size, false, &tkv_blob); - memset(tkv_blob.data(), 0x0, tkv_size); - memcpy(tkv_blob.data(), &tag_config->kv[0], tkv_size); - remote()->transact(SET_PARAMS_WITH_TAG, data, &reply); - tkv_blob.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_session_eos(uint64_t handle) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - remote()->transact(EOS, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_get_session_time(uint64_t handle, uint64_t *timestamp) - { - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - data.writeUint64(*timestamp); - remote()->transact(GET_SESSION_TIME, data, &reply); - *timestamp = reply.readUint64(); - return reply.readInt32(); - } - - virtual int ipc_agm_session_set_ec_ref(uint32_t capture_session_id, - uint32_t aif_id, bool state) -{ - android::Parcel data, reply; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(capture_session_id); - data.writeUint32(aif_id); - data.write(&state, sizeof(bool)); - remote()->transact(SET_ECREF, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_aif_set_cal(uint32_t session_id, - uint32_t audio_intf, - struct agm_cal_config *cal_config) { - android::Parcel data, reply; - android::Parcel::WritableBlob ckv_blob; - uint32_t kv_size = sizeof(agm_key_value); - uint32_t ckv_size = kv_size * (cal_config->num_ckvs); - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - AGM_LOGV("\n%s: CKV key %x value:%x\n", __func__, - (cal_config->kv[0].key),(cal_config->kv[0].value)); - data.writeUint32(session_id); - data.writeUint32(audio_intf); - data.writeUint32(cal_config->num_ckvs); - data.writeBlob(ckv_size, false, &ckv_blob); - memset(ckv_blob.data(), 0x0, ckv_size); - memcpy(ckv_blob.data(), cal_config->kv, ckv_size); - remote()->transact(SET_CALIBRATION, data, &reply); - ckv_blob.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_session_get_params(uint32_t session_id, - void *payload, size_t count) - { - android::Parcel data, reply; - android::Parcel::WritableBlob blob; - android::Parcel::ReadableBlob get_param_blob; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(count); - data.writeBlob(count, false, &blob); - memset(blob.data(), 0x0, count); - memcpy(blob.data(), payload, count); - - remote()->transact(GET_PARAMS, data, &reply); - - reply.readBlob(count, &get_param_blob); - memcpy(payload, get_param_blob.data(), count); - blob.release(); - get_param_blob.release(); - return reply.readInt32(); - } - - virtual int ipc_agm_get_buffer_timestamp(uint32_t session_id, uint64_t *timestamp) - { - android::Parcel data, reply; - ALOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - remote()->transact(BUF_TSTAMP, data, &reply); - *timestamp = reply.readUint64(); - return reply.readInt32(); - } - - virtual int ipc_agm_set_gapless_session_metadata(uint64_t handle, - enum agm_gapless_silence_type type, - uint32_t silence) - { - android::Parcel data, reply; - ALOGV("%s:%d\n", __func__, __LINE__); - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeInt64((long)handle); - data.writeUint32(type); - data.writeUint32(silence); - remote()->transact(SET_GAPLESS_SESSION_METADATA, data, &reply); - return reply.readInt32(); - } - - virtual int ipc_agm_session_get_buf_info(uint32_t session_id, - struct agm_buf_info *buf_info, uint32_t flag) - { - android::Parcel data, reply; - - data.writeInterfaceToken(IAgmService::getInterfaceDescriptor()); - data.writeUint32(session_id); - data.writeUint32(flag); - remote()->transact(GET_BUF_INFO, data, &reply); - if (flag & DATA_BUF) { - buf_info->data_buf_fd = dup(reply.readFileDescriptor()); - buf_info->data_buf_size = reply.readInt32(); - } - if (flag & POS_BUF) { - buf_info->pos_buf_fd = dup(reply.readFileDescriptor()); - buf_info->pos_buf_size = reply.readInt32(); - } - return reply.readInt32(); - } -}; - -void ipc_cb (uint32_t session_id, struct agm_event_cb_params *event_params, - void *client_data) -{ - struct listnode *node = NULL; - clbk_data *handle = NULL; - - pthread_mutex_lock(&clbk_data_list_lock); - list_for_each(node, &clbk_data_list) { - handle = node_to_item(node, clbk_data, list); - AGM_LOGV("%s: session_id %d, client_data %p\n", - __func__, handle->session_id, handle->client_data); - if (handle != NULL && handle->session_id == session_id && - handle->client_data == client_data) { - AGM_LOGV("%s: Found handle %p\n", __func__, handle); - break; - } - } - - if (handle!= NULL) { - sp cb_binder = handle->cb_binder; - if (cb_binder == NULL) { - AGM_LOGE("%s Invalid binder handle\n", __func__); - pthread_mutex_unlock(&clbk_data_list_lock); - return; - } - cb_binder->event_cb(session_id, event_params, - handle->client_data, handle->cb_func); - } - pthread_mutex_unlock(&clbk_data_list_lock); -} - - -IMPLEMENT_META_INTERFACE(AgmService, "AgmService"); - -android::status_t BnAgmService::onTransact(uint32_t code, - const android::Parcel& data, android::Parcel* reply, - uint32_t flags) -{ - AGM_LOGD("BnAgmService::onTransact(%i) %i\n", code, flags); - int rc = -EINVAL; - data.checkInterface(this); - - switch (code) { - case REG_CLIENT : { - sp binder = data.readStrongBinder(); - agm_register_client(binder); - break; } - - case UNREG_CLIENT : { - sp binder = data.readStrongBinder(); - agm_unregister_client(binder); - break; } - - case OPEN : { - uint32_t session_id; - enum agm_session_mode sess_mode; - uint64_t handle = 0; - session_id = data.readUint32(); - sess_mode = (enum agm_session_mode)data.readUint32(); - rc = ipc_agm_session_open(session_id, sess_mode, &handle); - if (handle != 0) - agm_add_session_obj_handle(handle);reply->writeInt64((long)handle); - reply->writeInt32(rc); - break; } - - case SESSION_SET_META : { - uint32_t session_id = 0; - size_t count = 0; - void *bn_payload; - android::Parcel::ReadableBlob blob; - - session_id = data.readUint32(); - count = (size_t) data.readUint32(); - data.readBlob(count, &blob); - - bn_payload = calloc(count, sizeof(uint8_t)); - if (!bn_payload) { - AGM_LOGE("calloc failed\n"); - rc = -ENOMEM; - goto fail_ses_set_meta; - } - - memcpy(bn_payload, blob.data(), count); - rc = ipc_agm_session_set_metadata(session_id, count, - (uint8_t *)bn_payload); - fail_ses_set_meta: - if (bn_payload) - free(bn_payload); - reply->writeInt32(rc); - break; - } - case SESSION_AUDIO_INTF_SET_META : { - uint32_t session_id, audio_intf = 0; - size_t count = 0; - void *bn_payload; - android::Parcel::ReadableBlob blob; - - session_id = data.readUint32(); - audio_intf = data.readUint32(); - count = (size_t) data.readUint32(); - data.readBlob(count, &blob); - - bn_payload = calloc(count, sizeof(uint8_t)); - if (!bn_payload) { - AGM_LOGE("calloc failed\n"); - rc = -ENOMEM; - goto fail_ses_aud_set_meta; - } - - memcpy(bn_payload, blob.data(), count); - rc = ipc_agm_session_audio_inf_set_metadata(session_id, audio_intf, - count, (uint8_t *)bn_payload); - fail_ses_aud_set_meta: - if (bn_payload) - free(bn_payload); - reply->writeInt32(rc); - break; - } - case INIT : { - rc = ipc_agm_init(); - reply->writeInt32(rc); - break; - } - - case GET_BUFF_CNT :{ - enum direction dir; - uint64_t handle = (uint64_t )data.readInt64(); - dir = (direction) data.readUint32(); - rc = (uint32_t)ipc_agm_get_hw_processed_buff_cnt(handle, dir); - reply->writeInt32(rc); - break; - } - - case AUDIO_INTF_SET_META : { - uint32_t audio_intf; - size_t count = 0; - void *bn_payload; - android::Parcel::ReadableBlob blob; - - audio_intf = data.readUint32(); - count = (size_t) data.readUint32(); - data.readBlob(count, &blob); - - bn_payload = calloc(count, sizeof(uint8_t)); - if (!bn_payload) { - AGM_LOGE("calloc failed\n"); - rc = -ENOMEM; - goto fail_audio_set_meta; - } - - memcpy(bn_payload, blob.data(), count); - rc = ipc_agm_audio_intf_set_metadata(audio_intf, count, - (uint8_t *)bn_payload); - - fail_audio_set_meta: - if (bn_payload) - free(bn_payload); - reply->writeInt32(rc); - break; - } - - case LOOPBACK : { - uint32_t capture_session_id; - uint32_t playback_session_id; - capture_session_id = data.readUint32(); - playback_session_id = data.readUint32(); - int state = data.readUint32(); - rc = ipc_agm_session_set_loopback(capture_session_id, - playback_session_id, state); - reply->writeInt32(rc); - break; } - - case CLOSE : { - uint64_t handle = (uint64_t )data.readInt64(); - rc = ipc_agm_session_close(handle); - agm_remove_session_obj_handle(handle); - reply->writeInt32(rc); - break; } - - case PREPARE : { - uint64_t handle = (uint64_t )data.readInt64(); - rc = ipc_agm_session_prepare(handle); - reply->writeInt32(rc); - break; } - - case START : { - uint64_t handle = (uint64_t )data.readInt64(); - rc = ipc_agm_session_start(handle); - reply->writeInt32(rc); - break; } - - case STOP : { - uint64_t handle = (uint64_t )data.readInt64(); - rc = ipc_agm_session_stop(handle); - reply->writeInt32(rc); - break; } - - case PAUSE : { - uint64_t handle = (uint64_t )data.readInt64(); - rc = ipc_agm_session_pause(handle); - reply->writeInt32(rc); - break; } - - case RESUME : { - uint64_t handle = (uint64_t )data.readInt64(); - rc = ipc_agm_session_resume(handle); - reply->writeInt32(rc); - break; } - - case CONNECT : { - uint32_t session_id; - uint32_t audio_intf; - - session_id = data.readUint32(); - audio_intf = data.readUint32(); - int state = data.readUint32(); - rc = ipc_agm_session_audio_inf_connect(session_id, audio_intf, state); - reply->writeInt32(rc); - break; } - - case SET_MEDIA_CONFIG : { - uint32_t audio_intf; - audio_intf = data.readUint32(); - struct agm_media_config media_config; - android::Parcel::ReadableBlob blob; - uint32_t blob_size; - data.readUint32(&blob_size); - data.readBlob(blob_size, &blob); - memset(&media_config, 0x0, sizeof(agm_media_config)); - memscpy(&media_config, sizeof(agm_media_config), blob.data(), - blob_size); - blob.release(); - rc = ipc_agm_audio_intf_set_media_config(audio_intf, &media_config); - reply->writeInt32(rc); - break; } - - case SESSION_SET_CONFIG : { - uint64_t handle = (uint64_t )data.readInt64(); - struct agm_session_config session_config; - struct agm_media_config media_config; - struct agm_buffer_config buffer_config; - android::Parcel::ReadableBlob blob; - uint32_t blob1_size, blob2_size, blob3_size; - - data.readUint32(&blob1_size); - data.readBlob(blob1_size, &blob); - memset(&session_config, 0x0, sizeof(agm_session_config)); - memscpy(&session_config, sizeof(agm_session_config), blob.data(), - blob1_size); - blob.release(); - data.readUint32(&blob2_size); - data.readBlob(blob2_size, &blob); - memset(&media_config, 0x0, sizeof(agm_media_config)); - memscpy(&media_config, sizeof(agm_media_config), blob.data(), - blob2_size); - blob.release(); - - data.readUint32(&blob3_size); - data.readBlob(blob3_size, &blob); - memset(&buffer_config, 0x0, sizeof(agm_buffer_config)); - memscpy(&buffer_config, sizeof(agm_buffer_config), blob.data(), - blob3_size); - blob.release(); - rc = ipc_agm_session_set_config(handle, &session_config, &media_config, - &buffer_config); - reply->writeInt32(rc); - break; } - - case READ : { - int32_t rc; - size_t byte_count; - uint64_t handle; - void *buf = NULL; - android::Parcel::WritableBlob blob; - handle = (uint64_t )data.readInt64(); - byte_count = data.readUint32(); - - buf = (void *)calloc(1, byte_count); - if (buf == NULL) { - AGM_LOGE("calloc failed\n"); - rc = -ENOMEM; - reply->writeInt32(rc); - goto free_buff; - } - - rc = ipc_agm_session_read(handle, buf, &byte_count); - reply->writeInt32(rc); - if (rc != 0) { - AGM_LOGE("session_read failed %d\n", rc); - goto free_buff; - } - reply->writeUint32(byte_count); - reply->writeBlob(byte_count, false, &blob); - memset(blob.data(), 0x0, byte_count); - memcpy(blob.data(), buf, byte_count); - - free_buff: - if (buf) - free(buf); - break; } - - case WRITE: { - uint32_t rc; - size_t byte_count; - void *buf; - uint64_t handle; - android::Parcel::ReadableBlob blob; - handle = (uint64_t )data.readInt64(); - byte_count = data.readUint32(); - - buf = calloc(1,byte_count); - if (buf == NULL) { - AGM_LOGE("calloc failed\n"); - rc = -ENOMEM; - goto fail_write; - } - data.readBlob(byte_count, &blob); - memcpy(buf, blob.data(), byte_count); - rc = ipc_agm_session_write(handle, buf, &byte_count); - reply->writeUint32(byte_count); - blob.release(); - - fail_write: - if (buf) - free(buf); - reply->writeInt32(rc); - break; } - - case GET_AIF_LIST: { - uint32_t rc, cp_val; - size_t count = 0; - struct aif_info *aif_list, *aif_list_bn; - android::Parcel::WritableBlob aif_list_blob; - - count = (size_t) data.readUint32(); - if (count == 0) { - aif_list = (struct aif_info*)data.readInt64(); - rc = ipc_agm_get_aif_info_list(aif_list, &count); - reply->writeInt32(count); - reply->writeInt32(rc); - } else if (count != 0){ - aif_list_bn = (struct aif_info*)calloc(count, - sizeof(struct aif_info)); - if (aif_list_bn == NULL) { - AGM_LOGE("calloc failed\n"); - return -ENOMEM; - } - rc = ipc_agm_get_aif_info_list(aif_list_bn, &count); - int total_bytecnt = count*sizeof(struct aif_info); - if(!rc) { - for (cp_val= 0; cp_val < count; cp_val++) - AGM_LOGV("aif_list %s:name:%s count:%d\n", __func__, - aif_list_bn[cp_val].aif_name, total_bytecnt); - } - reply->writeBlob(total_bytecnt, false, &aif_list_blob); - memset(aif_list_blob.data(), 0x0, total_bytecnt); - memcpy(aif_list_blob.data(), aif_list_bn, total_bytecnt); - aif_list_blob.release(); - reply->writeInt32(rc); - free(aif_list_bn); - } - break; } - - - case REG_EVENT : { - uint32_t session_id; - uint32_t module_instance_id; - uint32_t event_id; - uint32_t payload_size; - uint8_t is_register; - struct agm_event_reg_cfg *evt_reg_cfg = NULL; - android::Parcel::ReadableBlob blob; - uint32_t blob_size; - - session_id = data.readUint32(); - module_instance_id = data.readUint32(); - event_id = data.readUint32(); - payload_size = data.readUint32(); - is_register = (uint8_t) data.readUint32(); - evt_reg_cfg = (struct agm_event_reg_cfg*)calloc(1, - (sizeof(agm_event_reg_cfg)+payload_size)); - if (evt_reg_cfg == NULL) { - AGM_LOGE("calloc failed\n"); - return -ENOMEM; - } - evt_reg_cfg->module_instance_id = module_instance_id; - evt_reg_cfg->event_id = event_id; - evt_reg_cfg->event_config_payload_size = payload_size; - evt_reg_cfg->is_register = is_register; - data.readUint32(&blob_size); - data.readBlob(blob_size, &blob); - - memset(evt_reg_cfg->event_config_payload, 0x0, - evt_reg_cfg->event_config_payload_size); - memscpy(evt_reg_cfg->event_config_payload, - evt_reg_cfg->event_config_payload_size, - blob.data(), blob_size); - blob.release(); - rc = ipc_agm_session_register_for_events(session_id, evt_reg_cfg); - free(evt_reg_cfg); - reply->writeInt32(rc); - break; } - - case REG_CB : { - enum event_type evnt; - clbk_data *clbk_data_obj = NULL; - - if (clbk_data_list_init == false) { - pthread_mutex_init(&clbk_data_list_lock, - (const pthread_mutexattr_t *) NULL); - list_init(&clbk_data_list); - clbk_data_list_init = true; - } - - clbk_data_obj = (clbk_data *)calloc(1, sizeof(clbk_data)); - if (clbk_data_obj == NULL) { - AGM_LOGE("calloc failed\n"); - return -ENOMEM; - } - - pthread_mutex_lock(&clbk_data_list_lock); - clbk_data_obj->session_id = data.readUint32(); - data.read(&clbk_data_obj->cb_func, sizeof(agm_event_cb)); - evnt = (event_type) data.readUint32(); - clbk_data_obj->client_data = (void *)data.readInt64(); - sp binder = data.readStrongBinder(); - clbk_data_obj->cb_binder = interface_cast(binder); - if (clbk_data_obj->cb_func != NULL) { - list_add_tail(&clbk_data_list, &clbk_data_obj->list); - rc = ipc_agm_session_register_cb(clbk_data_obj->session_id, - &ipc_cb, evnt, clbk_data_obj->client_data); - } else { - clbk_data *clbk_data_obj_tmp = NULL; - struct listnode *node = NULL, *next = NULL; - list_for_each_safe(node, next, &clbk_data_list) { - clbk_data_obj_tmp = node_to_item(node, clbk_data, list); - if ((clbk_data_obj_tmp->session_id == clbk_data_obj->session_id) && - (clbk_data_obj_tmp->client_data == clbk_data_obj->client_data)) { - list_remove(&clbk_data_obj_tmp->list); - free(clbk_data_obj_tmp); - } - } - rc = ipc_agm_session_register_cb(clbk_data_obj->session_id, - NULL, evnt, clbk_data_obj->client_data); - free(clbk_data_obj); - } - - pthread_mutex_unlock(&clbk_data_list_lock); - reply->writeInt32(rc); - break ; } - - case GET_TAG_MODULE_INFO: { - uint32_t rc, pcm_idx, be_idx; - size_t count = 0; - void *bn_payload = NULL; - - count = (size_t) data.readUint32(); - pcm_idx = data.readUint32(); - be_idx = data.readUint32(); - if (count != 0){ - bn_payload = calloc(count, sizeof(uint8_t)); - if (bn_payload == NULL) { - AGM_LOGE("calloc failed\n"); - return -ENOMEM; - } - rc = ipc_agm_session_aif_get_tag_module_info(pcm_idx, be_idx, - bn_payload, &count); - android::Parcel::WritableBlob tag_info_blob; - reply->writeUint32(count); - reply->writeBlob(count, false, &tag_info_blob); - memcpy(tag_info_blob.data(), bn_payload, count); - tag_info_blob.release(); - free(bn_payload); - reply->writeInt32(rc); - } - break; } - - case SESSION_AIF_SET_PARAMS: { - uint32_t rc, pcm_idx, be_idx; - size_t count = 0; - android::Parcel::ReadableBlob blob; - void *bn_payload; - - pcm_idx = data.readUint32(); - be_idx = data.readUint32(); - count = (size_t) data.readUint32(); - data.readBlob(count, &blob); - - bn_payload = calloc(count, sizeof(uint8_t)); - if (!bn_payload) { - AGM_LOGE("calloc failed\n"); - reply->writeInt32(-ENOMEM); - return -ENOMEM; - } - - memcpy(bn_payload, blob.data(), count); - rc = ipc_agm_session_aif_set_params(pcm_idx, be_idx, bn_payload, count); - blob.release(); - free(bn_payload); - reply->writeInt32(rc); - break; } - - case AIF_SET_PARAMS: { - uint32_t rc, be_idx; - size_t count = 0; - android::Parcel::ReadableBlob blob; - void *bn_payload; - - be_idx = data.readUint32(); - count = (size_t) data.readUint32(); - data.readBlob(count, &blob); - - bn_payload = calloc(count, sizeof(uint8_t)); - if (!bn_payload) { - AGM_LOGE("calloc failed\n"); - reply->writeInt32(-ENOMEM); - return -ENOMEM; - } - - memcpy(bn_payload, blob.data(), count); - rc = ipc_agm_aif_set_params(be_idx, bn_payload, count); - blob.release(); - free(bn_payload); - reply->writeInt32(rc); - break; } - - case SESSION_SET_PARAMS: { - uint32_t rc, pcm_idx; - size_t count = 0; - void *bn_payload; - android::Parcel::ReadableBlob blob; - - pcm_idx = data.readUint32(); - count = (size_t) data.readUint32(); - data.readBlob(count, &blob); - - bn_payload = calloc(count, sizeof(uint8_t)); - if (!bn_payload) { - AGM_LOGE("calloc failed\n"); - rc = -ENOMEM; - goto session_set_param_fail; - } - - memcpy(bn_payload, blob.data(), count); - rc = ipc_agm_session_set_params(pcm_idx, bn_payload, count); - - free(bn_payload); - session_set_param_fail: - reply->writeInt32(rc); - break; } - - case SET_PARAMS_WITH_TAG: { - uint32_t rc, pcm_idx, be_idx; - struct agm_tag_config *atc = NULL; - uint32_t tag, num_tkv,tkv_blob_size = 0; - android::Parcel::ReadableBlob tkv_blob; - - pcm_idx = data.readUint32(); - be_idx = data.readUint32(); - tag = data.readUint32(); - num_tkv = data.readUint32(); - tkv_blob_size = num_tkv * (uint32_t)sizeof(struct agm_key_value); - AGM_LOGV("Bn:tkv.num_kvs = %d size %d\n", num_tkv, tkv_blob_size); - atc = (struct agm_tag_config*)calloc(1, sizeof(struct agm_tag_config) + - num_tkv * sizeof(agm_key_value)); - if (!atc) { - AGM_LOGE("calloc failed\n"); - rc = -ENOMEM; - goto set_param_with_tag_fail; - } - atc->num_tkvs = num_tkv; - atc->tag = tag; - data.readBlob(tkv_blob_size, &tkv_blob); - memcpy(&atc->kv[0], tkv_blob.data(), tkv_blob_size); - tkv_blob.release(); - rc = ipc_agm_set_params_with_tag (pcm_idx, be_idx, atc); - set_param_with_tag_fail: - reply->writeInt32(rc); - break; } - - case SET_ECREF : { - uint32_t cap_sess_id; - uint32_t aif_id; - - cap_sess_id = data.readUint32(); - aif_id = data.readUint32(); - int state = data.readUint32(); - rc = ipc_agm_session_set_ec_ref(cap_sess_id, aif_id, state); - reply->writeInt32(rc); - break; } - - case SET_CALIBRATION: { - uint32_t session_id, audio_intf = 0; - struct agm_cal_config *acc = NULL; - uint32_t num_ckv; - uint32_t ckv_blob_size = 0; - android::Parcel::ReadableBlob ckv_blob; - - session_id = data.readUint32(); - audio_intf = data.readUint32(); - num_ckv = data.readUint32(); - if (num_ckv > MAX_KVPAIR) { - AGM_LOGE("Num KVs %d more than expected: %d\n", num_ckv, MAX_KVPAIR); - rc = -EINVAL; - goto fail_ses_aud_set_cal_data; - } - ckv_blob_size = num_ckv * (uint32_t)sizeof(struct agm_key_value); - acc = (struct agm_cal_config *) calloc (1, sizeof(struct agm_cal_config) - + ckv_blob_size); - if (!acc) { - AGM_LOGE("calloc failed\n"); - rc = -ENOMEM; - goto fail_ses_aud_set_cal_data; - } - acc->num_ckvs = num_ckv; - data.readBlob(ckv_blob_size, &ckv_blob); - memcpy(acc->kv, ckv_blob.data(), ckv_blob_size); - ckv_blob.release(); - rc = ipc_agm_session_aif_set_cal(session_id, audio_intf, acc); - fail_ses_aud_set_cal_data: - if (acc) - free(acc); - reply->writeInt32(rc); - break; } - - case EOS : { - uint64_t handle = (uint64_t )data.readInt64(); - rc = ipc_agm_session_eos(handle); - reply->writeInt32(rc); - break; } - - case GET_SESSION_TIME : { - uint64_t handle = (uint64_t )data.readInt64(); - uint64_t ts = data.readUint64(); - rc = ipc_agm_get_session_time(handle, &ts); - reply->writeUint64(ts); - reply->writeInt32(rc); - break; } - - case GET_PARAMS: { - uint32_t rc, pcm_idx; - size_t count = 0; - void *bn_payload; - android::Parcel::ReadableBlob blob; - android::Parcel::WritableBlob get_param_blob; - - pcm_idx = data.readUint32(); - count = (size_t) data.readUint32(); - data.readBlob(count, &blob); - - bn_payload = calloc(count, sizeof(uint8_t)); - if (!bn_payload) { - AGM_LOGE("calloc failed\n"); - rc = -ENOMEM; - goto session_get_param_fail; - } - - memcpy(bn_payload, blob.data(), count); - rc = ipc_agm_session_get_params(pcm_idx, bn_payload, count); - - reply->writeBlob(count, false, &get_param_blob); - memcpy(get_param_blob.data(), bn_payload, count); - free(bn_payload); - session_get_param_fail: - reply->writeInt32(rc); - get_param_blob.release(); - blob.release(); - break; } - - case BUF_TSTAMP : { - uint32_t rc, pcm_idx; - uint64_t ts = 0; - - pcm_idx = data.readUint32(); - rc = ipc_agm_get_buffer_timestamp(pcm_idx, &ts); - reply->writeUint64(ts); - reply->writeInt32(rc); - break; } - - case SET_GAPLESS_SESSION_METADATA : { - uint64_t handle = (uint64_t )data.readInt64(); - agm_gapless_silence_type type = (agm_gapless_silence_type) data.readUint32(); - uint32_t silence = data.readUint32(); - rc = ipc_agm_set_gapless_session_metadata(handle, type, silence); - reply->writeInt32(rc); - break; } - - case GET_BUF_INFO : { - int rc; - uint32_t session_id, flag; - struct agm_buf_info buf_info; - - session_id = data.readUint32(); - flag = data.readUint32(); - rc = ipc_agm_session_get_buf_info(session_id, &buf_info, flag); - if (flag & DATA_BUF) { - reply->writeFileDescriptor(buf_info.data_buf_fd); - reply->writeInt32(buf_info.data_buf_size); - } - if (flag & POS_BUF) { - reply->writeFileDescriptor(buf_info.pos_buf_fd); - reply->writeInt32(buf_info.pos_buf_size); - } - reply->writeInt32(rc); - break; } - - default: - return BBinder::onTransact(code, data, reply, flags); - } -return 0; -} diff --git a/qcom/opensource/agm/ipc/aidl/Android.bp b/qcom/opensource/agm/ipc/aidl/Android.bp deleted file mode 100755 index 9e3fc7c9..00000000 --- a/qcom/opensource/agm/ipc/aidl/Android.bp +++ /dev/null @@ -1,30 +0,0 @@ -aidl_interface { - name: "vendor.qti.hardware.agm", - vendor: true, - srcs: ["vendor/qti/hardware/agm/*.aidl"], - stability: "vintf", - owner: "qti", - backend: { - cpp: { - enabled: false, - }, - java: { - sdk_version: "module_current", - }, - ndk: { - enabled: true, - }, - }, - - imports: [ - "android.hardware.common-V2", - ], - versions_with_info: [ - { - version: "1", - imports: ["android.hardware.common-V2"], - }, - ], - frozen: true, - -} diff --git a/qcom/opensource/agm/ipc/aidl/Android.mk b/qcom/opensource/agm/ipc/aidl/Android.mk deleted file mode 100755 index 5053e7d6..00000000 --- a/qcom/opensource/agm/ipc/aidl/Android.mk +++ /dev/null @@ -1 +0,0 @@ -include $(call all-subdir-makefiles) diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/.hash b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/.hash deleted file mode 100755 index 5b94ae6f..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/.hash +++ /dev/null @@ -1 +0,0 @@ -efa4ab1ccef17baa301d81deca852ddc0bbafbfb diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmBuff.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmBuff.aidl deleted file mode 100755 index 319e63a5..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmBuff.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmBuff { - long timestamp; - int flags; - int size; - int offset; - byte[] buffer; - byte[] metadata; - vendor.qti.hardware.agm.AgmExternAllocBuffInfo externalAllocInfo; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmBufferConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmBufferConfig.aidl deleted file mode 100755 index 2b2f9e79..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmBufferConfig.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmBufferConfig { - int count; - int size; - int maxMetadataSize; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmCalConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmCalConfig.aidl deleted file mode 100755 index bf77e489..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmCalConfig.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmCalConfig { - vendor.qti.hardware.agm.AgmKeyValue[] kv; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmDataMode.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmDataMode.aidl deleted file mode 100755 index 02e263b2..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmDataMode.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmDataMode { - AGM_DATA_INVALID, - AGM_DATA_BLOCKING, - AGM_DATA_NON_BLOCKING, - AGM_DATA_PUSH_PULL, - AGM_DATA_EXTERN_MEM, - AGM_DATA_MODE_MAX, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmDumpInfo.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmDumpInfo.aidl deleted file mode 100755 index 97f61915..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmDumpInfo.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmDumpInfo { - int signal; - int pid; - int uid; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventCallbackParameter.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventCallbackParameter.aidl deleted file mode 100755 index dbd516f4..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventCallbackParameter.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmEventCallbackParameter { - int sourceModuleId; - int eventId; - byte[] eventPayload; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventId.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventId.aidl deleted file mode 100755 index 22ec5e3c..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventId.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmEventId { - AGMEVENTEOSRENDERED = 0x0, - AGMEVENTREADDONE = 0x1, - AGMEVENTWRITEDONE = 0x2, - AGM_EVENT_EARLY_EOS = 0x08001126, - AGMEVENTIDMAX, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventReadWriteDonePayload.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventReadWriteDonePayload.aidl deleted file mode 100755 index c3b94290..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventReadWriteDonePayload.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmEventReadWriteDonePayload { - int tag; - int status; - int metadataStatus; - vendor.qti.hardware.agm.AgmBuff buffer; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventRegistrationConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventRegistrationConfig.aidl deleted file mode 100755 index 9e70cdbe..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmEventRegistrationConfig.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmEventRegistrationConfig { - int moduleInstanceId; - int eventId; - byte registerEvent; - byte[] eventConfigPayload; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmExternAllocBuffInfo.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmExternAllocBuffInfo.aidl deleted file mode 100755 index 7cf567e5..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmExternAllocBuffInfo.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmExternAllocBuffInfo { - android.hardware.common.NativeHandle allocHandle; - int allocatedSize; - int offset; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmGaplessSilenceType.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmGaplessSilenceType.aidl deleted file mode 100755 index d70360f9..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmGaplessSilenceType.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmGaplessSilenceType { - INITIAL_SILENCE, - TRAILING_SILENCE, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmGroupMediaConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmGroupMediaConfig.aidl deleted file mode 100755 index e34741cd..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmGroupMediaConfig.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmGroupMediaConfig { - int rate; - int channels; - vendor.qti.hardware.agm.AgmMediaFormat format; - int dataFormat; - int slotMask; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmKeyValue.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmKeyValue.aidl deleted file mode 100755 index de68e80d..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmKeyValue.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmKeyValue { - int key; - int value; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmMediaConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmMediaConfig.aidl deleted file mode 100755 index 5252c2f3..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmMediaConfig.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmMediaConfig { - int rate; - int channels; - vendor.qti.hardware.agm.AgmMediaFormat format; - int dataFormat; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmMediaFormat.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmMediaFormat.aidl deleted file mode 100755 index 294f4bd8..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmMediaFormat.aidl +++ /dev/null @@ -1,47 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmMediaFormat { - AGM_FORMAT_INVALID, - AGM_FORMAT_PCM_S8, - AGM_FORMAT_PCM_S16_LE, - AGM_FORMAT_PCM_S24_LE, - AGM_FORMAT_PCM_S24_3LE, - AGM_FORMAT_PCM_S32_LE, - AGM_FORMAT_MP3, - AGM_FORMAT_AAC, - AGM_FORMAT_FLAC, - AGM_FORMAT_ALAC, - AGM_FORMAT_APE, - AGM_FORMAT_WMASTD, - AGM_FORMAT_WMAPRO, - AGM_FORMAT_VORBIS, - AGM_FORMAT_AMR_NB, - AGM_FORMAT_AMR_WB, - AGM_FORMAT_AMR_WB_PLUS, - AGM_FORMAT_EVRC, - AGM_FORMAT_G711, - AGM_FORMAT_QCELP, - AGM_FORMAT_MAX, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmReadWriteEventCallbackParams.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmReadWriteEventCallbackParams.aidl deleted file mode 100755 index 91460174..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmReadWriteEventCallbackParams.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmReadWriteEventCallbackParams { - int sourceModuleId; - int eventId; - vendor.qti.hardware.agm.AgmEventReadWriteDonePayload payload; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionAacDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionAacDec.aidl deleted file mode 100755 index ede2db11..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionAacDec.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionAacDec { - int formatFlag; - int objectType; - int channels; - int sizeOfPCEBits; - int sampleRate; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionAacEnc.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionAacEnc.aidl deleted file mode 100755 index 7f17bace..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionAacEnc.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionAacEnc { - int bitRate; - int globalCutOffFrequency; - int mode; - int formatFlags; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionAlacDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionAlacDec.aidl deleted file mode 100755 index c00960e5..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionAlacDec.aidl +++ /dev/null @@ -1,38 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionAlacDec { - int frameLength; - byte compatibleVersion; - byte bitDepth; - byte pb; - byte mb; - byte kb; - byte channels; - int maxRun; - int maxFrameBytes; - int averageBitRate; - int sampleRate; - int channelLayoutTag; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionApeDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionApeDec.aidl deleted file mode 100755 index 5fab4686..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionApeDec.aidl +++ /dev/null @@ -1,36 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionApeDec { - int compatibleVersion; - int compressionLevel; - int formatFlags; - int blocksPerFrame; - int finalFrameBlocks; - int totalFrames; - int bitWidth; - int channels; - int sampleRate; - int seekTablePresent; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionCodec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionCodec.aidl deleted file mode 100755 index b034ce84..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionCodec.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -union AgmSessionCodec { - vendor.qti.hardware.agm.AgmSessionAacDec aacDecoder; - vendor.qti.hardware.agm.AgmSessionFlacDec flacDecoder; - vendor.qti.hardware.agm.AgmSessionAlacDec alacDecoder; - vendor.qti.hardware.agm.AgmSessionApeDec apeDecoder; - vendor.qti.hardware.agm.AgmSessionWmaDec wmaDecoder; - vendor.qti.hardware.agm.AgmSessionWmaproDec wmaproDecoder; - vendor.qti.hardware.agm.AgmSessionOpusDec opusDecoder; - vendor.qti.hardware.agm.AgmSessionAacEnc aacEncoder; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionConfig.aidl deleted file mode 100755 index 8ea743f6..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionConfig.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionConfig { - vendor.qti.hardware.agm.Direction direction; - vendor.qti.hardware.agm.AgmSessionMode sessionMode; - int startThreshold; - int stopThreshold; - @nullable vendor.qti.hardware.agm.AgmSessionCodec codec; - vendor.qti.hardware.agm.AgmDataMode dataMode; - int flags; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionFlacDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionFlacDec.aidl deleted file mode 100755 index 317d2293..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionFlacDec.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionFlacDec { - int channels; - int sampleSize; - int minBlockSize; - int maxBlockSize; - int sampleRate; - int minFrameSize; - int maxFrameSize; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionMode.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionMode.aidl deleted file mode 100755 index 4de8eecb..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionMode.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmSessionMode { - AGM_SESSION_DEFAULT, - AGM_SESSION_NO_HOST, - AGM_SESSION_NON_TUNNEL, - AGM_SESSION_NO_CONFIG, - AGM_SESSION_COMPRESS, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionOpusDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionOpusDec.aidl deleted file mode 100755 index 9d431c70..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionOpusDec.aidl +++ /dev/null @@ -1,38 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionOpusDec { - int bitStreamFormat; - int type; - byte version; - byte channels; - int preSkip; - long sampleRate; - int outputGain; - byte mappingFamily; - byte streamCount; - byte coupledCount; - byte[8] channelMap; - byte[3] reserved; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionWmaDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionWmaDec.aidl deleted file mode 100755 index e779f67b..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionWmaDec.aidl +++ /dev/null @@ -1,35 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionWmaDec { - int formatTag; - int channels; - int sampleRate; - int averageBytesPerSecond; - int blockAlign; - int bitsPerSample; - int channelMask; - int encoderOption; - int reserved; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionWmaproDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionWmaproDec.aidl deleted file mode 100755 index 03a22a8e..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmSessionWmaproDec.aidl +++ /dev/null @@ -1,36 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionWmaproDec { - int formatTag; - int channels; - int sampleRate; - int averageBytesPerSecond; - int blockAlign; - int bitsPerSample; - int channelMask; - int encoderOption; - int advancedEncoderOption; - int advancedEncoderOption2; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmTagConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmTagConfig.aidl deleted file mode 100755 index e9a88630..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AgmTagConfig.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmTagConfig { - int tag; - vendor.qti.hardware.agm.AgmKeyValue[] kv; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AifInfo.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AifInfo.aidl deleted file mode 100755 index f764940f..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/AifInfo.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AifInfo { - String aifName; - vendor.qti.hardware.agm.Direction direction; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/Direction.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/Direction.aidl deleted file mode 100755 index 4fff9447..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/Direction.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum Direction { - Rx = 1, - Tx, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/EventType.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/EventType.aidl deleted file mode 100755 index d03ba5b9..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/EventType.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum EventType { - AGM_EVENT_DATA_PATH = 1, - AGM_EVENT_MODULE, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/IAGM.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/IAGM.aidl deleted file mode 100755 index 46c41839..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/IAGM.aidl +++ /dev/null @@ -1,78 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -interface IAGM { - void ipc_agm_init(); - void ipc_agm_deinit(); - long ipc_agm_session_open(in int sessionId, in vendor.qti.hardware.agm.AgmSessionMode sessionMode); - void ipc_agm_session_start(in long handle); - void ipc_agm_session_stop(in long handle); - void ipc_agm_session_suspend(in long handle); - void ipc_agm_session_pause(in long handle); - void ipc_agm_session_resume(in long handle); - void ipc_agm_session_prepare(in long handle); - void ipc_agm_session_eos(in long handle); - void ipc_agm_session_flush(in long handle); - void ipc_agm_session_close(in long handle); - vendor.qti.hardware.agm.MmapBufInfo ipc_agm_session_get_buf_info(in int sessionId, in int flag); - byte[] ipc_agm_session_get_params(in int sessionId, in byte[] buffer); - byte[] ipc_agm_session_read(in long handle, in int count); - vendor.qti.hardware.agm.IAGM.AgmReadWithMetadataReturn ipc_agm_session_read_with_metadata(in long handle, in vendor.qti.hardware.agm.AgmBuff buffer, in int capturedSize); - void ipc_agm_session_register_callback(in vendor.qti.hardware.agm.IAGMCallback callback, in int sessionId, in int eventType, in boolean register, in long clientData); - void ipc_agm_session_register_for_events(in int sessionId, in vendor.qti.hardware.agm.AgmEventRegistrationConfig eventConfig); - void ipc_agm_session_set_config(in long handle, in vendor.qti.hardware.agm.AgmSessionConfig sessionConfig, in vendor.qti.hardware.agm.AgmMediaConfig mediaConfig, in vendor.qti.hardware.agm.AgmBufferConfig bufferConfig); - void ipc_agm_session_set_ec_ref(in int sessionId, in int aifId, in boolean state); - void ipc_agm_session_set_loopback(in int captureSessionId, in int playbackSessionId, in boolean state); - void ipc_agm_session_set_metadata(in int sessionId, in byte[] metadata); - void ipc_agm_session_set_non_tunnel_mode_config(in long handle, in vendor.qti.hardware.agm.AgmSessionConfig sessionConfig, in vendor.qti.hardware.agm.AgmMediaConfig inMediaConfig, in vendor.qti.hardware.agm.AgmMediaConfig outMediaConfig, in vendor.qti.hardware.agm.AgmBufferConfig inBufferConfig, in vendor.qti.hardware.agm.AgmBufferConfig outBufferConfig); - void ipc_agm_session_set_params(in int sessionId, in byte[] payload); - int ipc_agm_session_write(in long handle, in byte[] buff); - void ipc_agm_session_write_datapath_params(in int sessionId, in vendor.qti.hardware.agm.AgmBuff buff); - int ipc_agm_session_write_with_metadata(in long handle, in vendor.qti.hardware.agm.AgmBuff buff); - void ipc_agm_aif_group_set_media_config(in int groupId, in vendor.qti.hardware.agm.AgmGroupMediaConfig config); - void ipc_agm_aif_set_media_config(in int aifId, in vendor.qti.hardware.agm.AgmMediaConfig config); - void ipc_agm_aif_set_metadata(in int aifId, in byte[] metadata); - void ipc_agm_aif_set_params(in int aifId, in byte[] payload); - void ipc_agm_session_aif_connect(in int sessionId, in int aifId, in boolean state); - byte[] ipc_agm_session_aif_get_tag_module_info(in int sessionId, in int aifId, in int size); - void ipc_agm_session_aif_set_cal(in int sessionId, in int aifId, in vendor.qti.hardware.agm.AgmCalConfig calConfig); - void ipc_agm_session_aif_set_metadata(in int sessionId, in int aifId, in byte[] metadata); - void ipc_agm_session_aif_set_params(in int sessionId, in int aifId, in byte[] payload); - vendor.qti.hardware.agm.AifInfo[] ipc_agm_get_aif_info_list(in int numAifInfo); - long ipc_agm_get_buffer_timestamp(in int sessiondId); - vendor.qti.hardware.agm.AifInfo[] ipc_agm_get_group_aif_info_list(in int numberOfGroups); - void ipc_agm_get_hw_processed_buff_cnt(in long handle, in vendor.qti.hardware.agm.Direction direction); - byte[] ipc_agm_get_params_from_acdb_tunnel(in byte[] payload); - long ipc_agm_get_session_time(in long handle); - void ipc_agm_sessionid_flush(in int sessiondId); - void ipc_agm_set_gapless_session_metadata(in long handle, in vendor.qti.hardware.agm.AgmGaplessSilenceType type, in int silence); - void ipc_agm_set_params_to_acdb_tunnel(in byte[] payload); - void ipc_agm_set_params_with_tag(in int sessiondId, in int aifId, in vendor.qti.hardware.agm.AgmTagConfig tagConfig); - void ipc_agm_set_params_with_tag_to_acdb(in int sessiondId, in int aifId, in byte[] payload); - void ipc_agm_dump(in vendor.qti.hardware.agm.AgmDumpInfo dumpInfo); - parcelable AgmReadWithMetadataReturn { - vendor.qti.hardware.agm.AgmBuff buffer; - int capturesSize; - } -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/IAGMCallback.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/IAGMCallback.aidl deleted file mode 100755 index b2bd3c4e..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/IAGMCallback.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -interface IAGMCallback { - void eventCallback(in vendor.qti.hardware.agm.AgmEventCallbackParameter eventParam); - void eventCallbackReadWriteDone(in vendor.qti.hardware.agm.AgmReadWriteEventCallbackParams rwDonePayload); -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/MmapBufInfo.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/MmapBufInfo.aidl deleted file mode 100755 index 8b3b24f4..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/MmapBufInfo.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable MmapBufInfo { - android.hardware.common.NativeHandle dataFdHandle; - int dataSize; - android.hardware.common.NativeHandle positionFdHandle; - int posSize; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/Status.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/Status.aidl deleted file mode 100755 index ccbc6f35..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/1/vendor/qti/hardware/agm/Status.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum Status { - UNKNOWN = (-1) /* -1 */, - SUCCESS = 0, - IO_ERROR, - BUSY, - NO_SPACE, - INVALID_FD, - ADVERTISE_ERROR, - PROTOCOL_NOT_AVAILABLE, - NOT_SUPPORTED, - DOWN_WITH_SSR, - NOW_INPROGRESS, - ALREADY_INPROGRESS, - CANCELLED, - NOT_RECOVERABLE, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmBuff.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmBuff.aidl deleted file mode 100755 index 319e63a5..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmBuff.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmBuff { - long timestamp; - int flags; - int size; - int offset; - byte[] buffer; - byte[] metadata; - vendor.qti.hardware.agm.AgmExternAllocBuffInfo externalAllocInfo; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmBufferConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmBufferConfig.aidl deleted file mode 100755 index 2b2f9e79..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmBufferConfig.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmBufferConfig { - int count; - int size; - int maxMetadataSize; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmCalConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmCalConfig.aidl deleted file mode 100755 index bf77e489..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmCalConfig.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmCalConfig { - vendor.qti.hardware.agm.AgmKeyValue[] kv; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmDataMode.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmDataMode.aidl deleted file mode 100755 index 02e263b2..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmDataMode.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmDataMode { - AGM_DATA_INVALID, - AGM_DATA_BLOCKING, - AGM_DATA_NON_BLOCKING, - AGM_DATA_PUSH_PULL, - AGM_DATA_EXTERN_MEM, - AGM_DATA_MODE_MAX, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmDumpInfo.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmDumpInfo.aidl deleted file mode 100755 index 97f61915..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmDumpInfo.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmDumpInfo { - int signal; - int pid; - int uid; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventCallbackParameter.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventCallbackParameter.aidl deleted file mode 100755 index dbd516f4..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventCallbackParameter.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmEventCallbackParameter { - int sourceModuleId; - int eventId; - byte[] eventPayload; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventId.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventId.aidl deleted file mode 100755 index 22ec5e3c..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventId.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmEventId { - AGMEVENTEOSRENDERED = 0x0, - AGMEVENTREADDONE = 0x1, - AGMEVENTWRITEDONE = 0x2, - AGM_EVENT_EARLY_EOS = 0x08001126, - AGMEVENTIDMAX, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventReadWriteDonePayload.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventReadWriteDonePayload.aidl deleted file mode 100755 index c3b94290..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventReadWriteDonePayload.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmEventReadWriteDonePayload { - int tag; - int status; - int metadataStatus; - vendor.qti.hardware.agm.AgmBuff buffer; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventRegistrationConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventRegistrationConfig.aidl deleted file mode 100755 index 9e70cdbe..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmEventRegistrationConfig.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmEventRegistrationConfig { - int moduleInstanceId; - int eventId; - byte registerEvent; - byte[] eventConfigPayload; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmExternAllocBuffInfo.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmExternAllocBuffInfo.aidl deleted file mode 100755 index 7cf567e5..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmExternAllocBuffInfo.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmExternAllocBuffInfo { - android.hardware.common.NativeHandle allocHandle; - int allocatedSize; - int offset; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmGaplessSilenceType.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmGaplessSilenceType.aidl deleted file mode 100755 index d70360f9..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmGaplessSilenceType.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmGaplessSilenceType { - INITIAL_SILENCE, - TRAILING_SILENCE, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmGroupMediaConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmGroupMediaConfig.aidl deleted file mode 100755 index e34741cd..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmGroupMediaConfig.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmGroupMediaConfig { - int rate; - int channels; - vendor.qti.hardware.agm.AgmMediaFormat format; - int dataFormat; - int slotMask; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmKeyValue.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmKeyValue.aidl deleted file mode 100755 index de68e80d..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmKeyValue.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmKeyValue { - int key; - int value; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmMediaConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmMediaConfig.aidl deleted file mode 100755 index 5252c2f3..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmMediaConfig.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmMediaConfig { - int rate; - int channels; - vendor.qti.hardware.agm.AgmMediaFormat format; - int dataFormat; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmMediaFormat.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmMediaFormat.aidl deleted file mode 100755 index 294f4bd8..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmMediaFormat.aidl +++ /dev/null @@ -1,47 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmMediaFormat { - AGM_FORMAT_INVALID, - AGM_FORMAT_PCM_S8, - AGM_FORMAT_PCM_S16_LE, - AGM_FORMAT_PCM_S24_LE, - AGM_FORMAT_PCM_S24_3LE, - AGM_FORMAT_PCM_S32_LE, - AGM_FORMAT_MP3, - AGM_FORMAT_AAC, - AGM_FORMAT_FLAC, - AGM_FORMAT_ALAC, - AGM_FORMAT_APE, - AGM_FORMAT_WMASTD, - AGM_FORMAT_WMAPRO, - AGM_FORMAT_VORBIS, - AGM_FORMAT_AMR_NB, - AGM_FORMAT_AMR_WB, - AGM_FORMAT_AMR_WB_PLUS, - AGM_FORMAT_EVRC, - AGM_FORMAT_G711, - AGM_FORMAT_QCELP, - AGM_FORMAT_MAX, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmReadWriteEventCallbackParams.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmReadWriteEventCallbackParams.aidl deleted file mode 100755 index 91460174..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmReadWriteEventCallbackParams.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmReadWriteEventCallbackParams { - int sourceModuleId; - int eventId; - vendor.qti.hardware.agm.AgmEventReadWriteDonePayload payload; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionAacDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionAacDec.aidl deleted file mode 100755 index ede2db11..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionAacDec.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionAacDec { - int formatFlag; - int objectType; - int channels; - int sizeOfPCEBits; - int sampleRate; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionAacEnc.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionAacEnc.aidl deleted file mode 100755 index 7f17bace..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionAacEnc.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionAacEnc { - int bitRate; - int globalCutOffFrequency; - int mode; - int formatFlags; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionAlacDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionAlacDec.aidl deleted file mode 100755 index c00960e5..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionAlacDec.aidl +++ /dev/null @@ -1,38 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionAlacDec { - int frameLength; - byte compatibleVersion; - byte bitDepth; - byte pb; - byte mb; - byte kb; - byte channels; - int maxRun; - int maxFrameBytes; - int averageBitRate; - int sampleRate; - int channelLayoutTag; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionApeDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionApeDec.aidl deleted file mode 100755 index 5fab4686..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionApeDec.aidl +++ /dev/null @@ -1,36 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionApeDec { - int compatibleVersion; - int compressionLevel; - int formatFlags; - int blocksPerFrame; - int finalFrameBlocks; - int totalFrames; - int bitWidth; - int channels; - int sampleRate; - int seekTablePresent; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionCodec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionCodec.aidl deleted file mode 100755 index b034ce84..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionCodec.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -union AgmSessionCodec { - vendor.qti.hardware.agm.AgmSessionAacDec aacDecoder; - vendor.qti.hardware.agm.AgmSessionFlacDec flacDecoder; - vendor.qti.hardware.agm.AgmSessionAlacDec alacDecoder; - vendor.qti.hardware.agm.AgmSessionApeDec apeDecoder; - vendor.qti.hardware.agm.AgmSessionWmaDec wmaDecoder; - vendor.qti.hardware.agm.AgmSessionWmaproDec wmaproDecoder; - vendor.qti.hardware.agm.AgmSessionOpusDec opusDecoder; - vendor.qti.hardware.agm.AgmSessionAacEnc aacEncoder; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionConfig.aidl deleted file mode 100755 index 8ea743f6..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionConfig.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionConfig { - vendor.qti.hardware.agm.Direction direction; - vendor.qti.hardware.agm.AgmSessionMode sessionMode; - int startThreshold; - int stopThreshold; - @nullable vendor.qti.hardware.agm.AgmSessionCodec codec; - vendor.qti.hardware.agm.AgmDataMode dataMode; - int flags; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionFlacDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionFlacDec.aidl deleted file mode 100755 index 317d2293..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionFlacDec.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionFlacDec { - int channels; - int sampleSize; - int minBlockSize; - int maxBlockSize; - int sampleRate; - int minFrameSize; - int maxFrameSize; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionMode.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionMode.aidl deleted file mode 100755 index 4de8eecb..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionMode.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum AgmSessionMode { - AGM_SESSION_DEFAULT, - AGM_SESSION_NO_HOST, - AGM_SESSION_NON_TUNNEL, - AGM_SESSION_NO_CONFIG, - AGM_SESSION_COMPRESS, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionOpusDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionOpusDec.aidl deleted file mode 100755 index 9d431c70..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionOpusDec.aidl +++ /dev/null @@ -1,38 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionOpusDec { - int bitStreamFormat; - int type; - byte version; - byte channels; - int preSkip; - long sampleRate; - int outputGain; - byte mappingFamily; - byte streamCount; - byte coupledCount; - byte[8] channelMap; - byte[3] reserved; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionWmaDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionWmaDec.aidl deleted file mode 100755 index e779f67b..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionWmaDec.aidl +++ /dev/null @@ -1,35 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionWmaDec { - int formatTag; - int channels; - int sampleRate; - int averageBytesPerSecond; - int blockAlign; - int bitsPerSample; - int channelMask; - int encoderOption; - int reserved; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionWmaproDec.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionWmaproDec.aidl deleted file mode 100755 index 03a22a8e..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmSessionWmaproDec.aidl +++ /dev/null @@ -1,36 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmSessionWmaproDec { - int formatTag; - int channels; - int sampleRate; - int averageBytesPerSecond; - int blockAlign; - int bitsPerSample; - int channelMask; - int encoderOption; - int advancedEncoderOption; - int advancedEncoderOption2; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmTagConfig.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmTagConfig.aidl deleted file mode 100755 index e9a88630..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AgmTagConfig.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AgmTagConfig { - int tag; - vendor.qti.hardware.agm.AgmKeyValue[] kv; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AifInfo.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AifInfo.aidl deleted file mode 100755 index f764940f..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/AifInfo.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable AifInfo { - String aifName; - vendor.qti.hardware.agm.Direction direction; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/Direction.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/Direction.aidl deleted file mode 100755 index 4fff9447..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/Direction.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum Direction { - Rx = 1, - Tx, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/EventType.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/EventType.aidl deleted file mode 100755 index d03ba5b9..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/EventType.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum EventType { - AGM_EVENT_DATA_PATH = 1, - AGM_EVENT_MODULE, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/IAGM.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/IAGM.aidl deleted file mode 100755 index 46c41839..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/IAGM.aidl +++ /dev/null @@ -1,78 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -interface IAGM { - void ipc_agm_init(); - void ipc_agm_deinit(); - long ipc_agm_session_open(in int sessionId, in vendor.qti.hardware.agm.AgmSessionMode sessionMode); - void ipc_agm_session_start(in long handle); - void ipc_agm_session_stop(in long handle); - void ipc_agm_session_suspend(in long handle); - void ipc_agm_session_pause(in long handle); - void ipc_agm_session_resume(in long handle); - void ipc_agm_session_prepare(in long handle); - void ipc_agm_session_eos(in long handle); - void ipc_agm_session_flush(in long handle); - void ipc_agm_session_close(in long handle); - vendor.qti.hardware.agm.MmapBufInfo ipc_agm_session_get_buf_info(in int sessionId, in int flag); - byte[] ipc_agm_session_get_params(in int sessionId, in byte[] buffer); - byte[] ipc_agm_session_read(in long handle, in int count); - vendor.qti.hardware.agm.IAGM.AgmReadWithMetadataReturn ipc_agm_session_read_with_metadata(in long handle, in vendor.qti.hardware.agm.AgmBuff buffer, in int capturedSize); - void ipc_agm_session_register_callback(in vendor.qti.hardware.agm.IAGMCallback callback, in int sessionId, in int eventType, in boolean register, in long clientData); - void ipc_agm_session_register_for_events(in int sessionId, in vendor.qti.hardware.agm.AgmEventRegistrationConfig eventConfig); - void ipc_agm_session_set_config(in long handle, in vendor.qti.hardware.agm.AgmSessionConfig sessionConfig, in vendor.qti.hardware.agm.AgmMediaConfig mediaConfig, in vendor.qti.hardware.agm.AgmBufferConfig bufferConfig); - void ipc_agm_session_set_ec_ref(in int sessionId, in int aifId, in boolean state); - void ipc_agm_session_set_loopback(in int captureSessionId, in int playbackSessionId, in boolean state); - void ipc_agm_session_set_metadata(in int sessionId, in byte[] metadata); - void ipc_agm_session_set_non_tunnel_mode_config(in long handle, in vendor.qti.hardware.agm.AgmSessionConfig sessionConfig, in vendor.qti.hardware.agm.AgmMediaConfig inMediaConfig, in vendor.qti.hardware.agm.AgmMediaConfig outMediaConfig, in vendor.qti.hardware.agm.AgmBufferConfig inBufferConfig, in vendor.qti.hardware.agm.AgmBufferConfig outBufferConfig); - void ipc_agm_session_set_params(in int sessionId, in byte[] payload); - int ipc_agm_session_write(in long handle, in byte[] buff); - void ipc_agm_session_write_datapath_params(in int sessionId, in vendor.qti.hardware.agm.AgmBuff buff); - int ipc_agm_session_write_with_metadata(in long handle, in vendor.qti.hardware.agm.AgmBuff buff); - void ipc_agm_aif_group_set_media_config(in int groupId, in vendor.qti.hardware.agm.AgmGroupMediaConfig config); - void ipc_agm_aif_set_media_config(in int aifId, in vendor.qti.hardware.agm.AgmMediaConfig config); - void ipc_agm_aif_set_metadata(in int aifId, in byte[] metadata); - void ipc_agm_aif_set_params(in int aifId, in byte[] payload); - void ipc_agm_session_aif_connect(in int sessionId, in int aifId, in boolean state); - byte[] ipc_agm_session_aif_get_tag_module_info(in int sessionId, in int aifId, in int size); - void ipc_agm_session_aif_set_cal(in int sessionId, in int aifId, in vendor.qti.hardware.agm.AgmCalConfig calConfig); - void ipc_agm_session_aif_set_metadata(in int sessionId, in int aifId, in byte[] metadata); - void ipc_agm_session_aif_set_params(in int sessionId, in int aifId, in byte[] payload); - vendor.qti.hardware.agm.AifInfo[] ipc_agm_get_aif_info_list(in int numAifInfo); - long ipc_agm_get_buffer_timestamp(in int sessiondId); - vendor.qti.hardware.agm.AifInfo[] ipc_agm_get_group_aif_info_list(in int numberOfGroups); - void ipc_agm_get_hw_processed_buff_cnt(in long handle, in vendor.qti.hardware.agm.Direction direction); - byte[] ipc_agm_get_params_from_acdb_tunnel(in byte[] payload); - long ipc_agm_get_session_time(in long handle); - void ipc_agm_sessionid_flush(in int sessiondId); - void ipc_agm_set_gapless_session_metadata(in long handle, in vendor.qti.hardware.agm.AgmGaplessSilenceType type, in int silence); - void ipc_agm_set_params_to_acdb_tunnel(in byte[] payload); - void ipc_agm_set_params_with_tag(in int sessiondId, in int aifId, in vendor.qti.hardware.agm.AgmTagConfig tagConfig); - void ipc_agm_set_params_with_tag_to_acdb(in int sessiondId, in int aifId, in byte[] payload); - void ipc_agm_dump(in vendor.qti.hardware.agm.AgmDumpInfo dumpInfo); - parcelable AgmReadWithMetadataReturn { - vendor.qti.hardware.agm.AgmBuff buffer; - int capturesSize; - } -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/IAGMCallback.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/IAGMCallback.aidl deleted file mode 100755 index b2bd3c4e..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/IAGMCallback.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -interface IAGMCallback { - void eventCallback(in vendor.qti.hardware.agm.AgmEventCallbackParameter eventParam); - void eventCallbackReadWriteDone(in vendor.qti.hardware.agm.AgmReadWriteEventCallbackParams rwDonePayload); -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/MmapBufInfo.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/MmapBufInfo.aidl deleted file mode 100755 index 8b3b24f4..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/MmapBufInfo.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@VintfStability -parcelable MmapBufInfo { - android.hardware.common.NativeHandle dataFdHandle; - int dataSize; - android.hardware.common.NativeHandle positionFdHandle; - int posSize; -} diff --git a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/Status.aidl b/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/Status.aidl deleted file mode 100755 index ccbc6f35..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidl_api/vendor.qti.hardware.agm/current/vendor/qti/hardware/agm/Status.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.agm; -@Backing(type="int") @VintfStability -enum Status { - UNKNOWN = (-1) /* -1 */, - SUCCESS = 0, - IO_ERROR, - BUSY, - NO_SPACE, - INVALID_FD, - ADVERTISE_ERROR, - PROTOCOL_NOT_AVAILABLE, - NOT_SUPPORTED, - DOWN_WITH_SSR, - NOW_INPROGRESS, - ALREADY_INPROGRESS, - CANCELLED, - NOT_RECOVERABLE, -} diff --git a/qcom/opensource/agm/ipc/aidl/aidlconverter/Android.mk b/qcom/opensource/agm/ipc/aidl/aidlconverter/Android.mk deleted file mode 100755 index debedf02..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidlconverter/Android.mk +++ /dev/null @@ -1,31 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := libagmaidltypeconverter -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -v -Wall -Wextra -Wthread-safety -LOCAL_TIDY := true - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/inc -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/inc - -LOCAL_SRC_FILES := \ - src/AgmLegacyToAidl.cpp \ - src/AgmAidlToLegacy.cpp - -LOCAL_STATIC_LIBRARIES := libaidlcommonsupport - -LOCAL_SHARED_LIBRARIES := \ - liblog \ - libbinder_ndk \ - libbase \ - libcutils \ - libutils \ - libar-gsl \ - vendor.qti.hardware.agm-V1-ndk - -LOCAL_HEADER_LIBRARIES := libagm_headers - -include $(BUILD_STATIC_LIBRARY) diff --git a/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/AgmAidlToLegacy.h b/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/AgmAidlToLegacy.h deleted file mode 100755 index 0da960e7..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/AgmAidlToLegacy.h +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace aidl::vendor::qti::hardware::agm { - -struct AidlToLegacy { - /** - * @brief convertAgmMediaConfig converts AgmMediaConfig from AIDL to agm_media_config - * legacy type. Client needs to pass valid allocated memory of agm_media_config, - * who is also responsible for dellocating the memory. - * @param aidlConfig AgmMediaConfig media config in aidl types. - * @param legacyConfig agm_media_config type. - */ - static void convertAgmMediaConfig(const AgmMediaConfig &aidlConfig, - struct agm_media_config *legacyConfig); - - /** - * @brief convertAgmGroupMediaConfig converts AgmGroupMediaConfig from AIDL to - * agm_group_media_config - * legacy type. Client needs to pass valid allocated memory of agm_group_media_config, - * who is also responsible for dellocating the memory. - * @param aidlConfig AgmGroupMediaConfig media config in aidl types. - * @param legacyConfig agm_group_media_config type. - */ - static void convertAgmGroupMediaConfig(const AgmGroupMediaConfig &aidlConfig, - struct agm_group_media_config *legacyConfig); - - /** - * @brief convertAgmSessionConfig converts AgmSessionConfig from AIDL to agm_session_config - * legacy type. Client needs to pass valid allocated memory of agm_session_config, - * who is also responsible for dellocating the memory. - * @param aidlConfig AgmSessionConfig media config in AIDL types. - * @param legacyConfig agm_session_config type. - */ - static void convertAgmSessionConfig(const AgmSessionConfig &aidlConfig, - struct agm_session_config *legacyConfig); - - /** - * @brief convertAgmBufferConfig converts AgmBufferConfig from AIDL to agm_buffer_config - * legacy type. Client needs to pass valid allocated memory of agm_buffer_config, - * who is also responsible for dellocating the memory. - * @param aidlConfig AgmBufferConfig media config in AIDL types. - * @param legacyConfig agm_buffer_config type. - */ - static void convertAgmBufferConfig(const AgmBufferConfig &aidlConfig, - struct agm_buffer_config *legacyConfig); - - /** - * @brief convertAifInfoList converts AifInfo from AIDL to aif_info - * legacy type. Client needs to pass valid allocated memory of aif_info, - * who is also responsible for dellocating the memory. - * @param aidlAifList std::vector of AifInfo - * @param aif_list aif_info type. - */ - static void convertAifInfoList(const std::vector &aidlAifList, - struct aif_info *legacyAifList); - - /** - * @brief convertAgmEventRegistrationConfig converts AgmEventRegistrationConfig from AIDL to - * agm_event_reg_cfg - * legacy type. Client needs to pass valid allocated memory of agm_event_reg_cfg, - * who is also responsible for dellocating the memory. - * @param aidlEventRegistrationConfig AgmEventRegistrationConfig in AIDL - * @param legacyEventRegConfig agm_event_reg_cfg type. - */ - static void convertAgmEventRegistrationConfig( - const AgmEventRegistrationConfig &aidlEventRegistrationConfig, - struct agm_event_reg_cfg *legacyEventRegConfig); - - /** - * @brief convertCompressCodecInfo converts AgmSessionConfig from AIDL to agm_session_config - * legacy type. Client needs to pass valid allocated memory of agm_session_config, - * who is also responsible for dellocating the memory. - * @param aidlConfig AgmSessionConfig in AIDL - * @param legacyConfig agm_session_config type. - */ - static void convertCompressCodecInfo(const AgmSessionConfig &aidlConfig, - struct agm_session_config *legacyConfig); - /** - * @brief convertAacCompressDecoder converts AgmSessionAacDec from AIDL to agm_session_aac_dec - * Client needs to pass valid allocated memory of agm_session_config, - * who is also responsible for dellocating the memory. - * @param aidlDecoder codec is aac type based on getTag of AIDL type. - * @param legacyDecoder agm_session_aac_dec type. - */ - static void convertAacCompressDecoder(const AgmSessionAacDec &aidlDecoder, - struct agm_session_aac_dec *legacyDecoder); - - /** - * @brief convertFlacCompressDecoder converts AgmSessionFlacDec from AIDL to agm_session_flac_dec - * Client needs to pass valid allocated memory of agm_session_config, - * who is also responsible for dellocating the memory. - * @param aidlDecoder codec is Flac type based on getTag of AIDL union type. - * @param legacyDecoder agm_session_flac_dec type. - */ - static void convertFlacCompressDecoder(const AgmSessionFlacDec &aidlDecoder, - struct agm_session_flac_dec *legacyDecoder); - - /** - * @brief convertAlacCompressDecoder converts AgmSessionAlacDec from AIDL to agm_session_alac_dec - * Client needs to pass valid allocated memory of agm_session_config, - * who is also responsible for dellocating the memory. - * @param aidlDecoder codec is alac type based on getTag of AIDL union type. - * @param legacyDecoder agm_session_alac_dec type. - */ - static void convertAlacCompressDecoder(const AgmSessionAlacDec &aidlDecoder, - struct agm_session_alac_dec *legacyDecoder); - - /** - * @brief convertApeCompressDecoder converts AgmSessionApeDec from AIDL to agm_session_ape_dec - * Client needs to pass valid allocated memory of agm_session_ape_dec, - * who is also responsible for dellocating the memory. - * @param aidlDecoder codec is ape type based on getTag of AIDL union type. - * @param legacyDecoder agm_session_ape_dec type. - */ - static void convertApeCompressDecoder(const AgmSessionApeDec &aidlDecoder, - struct agm_session_ape_dec *legacyDecoder); - - /** - * @brief convertWmaProCompressDecoder converts AgmSessionWmaproDec from AIDL to - * agm_session_wmapro_dec - * Client needs to pass valid allocated memory of agm_session_wmapro_dec, - * who is also responsible for dellocating the memory. - * @param aidlDecoder codec is wmapro type based on getTag of AIDL union type. - * @param legacyDecoder agm_session_wmapro_dec type. - */ - static void convertWmaProCompressDecoder(const AgmSessionWmaproDec &aidlDecoder, - struct agm_session_wmapro_dec *legacyDecoder); - - /** - * @brief convertWmaStandardCompressDecoder converts AgmSessionCodec from AIDL to - * agm_session_wma_dec - * Client needs to pass valid allocated memory of agm_session_wma_dec, - * who is also responsible for dellocating the memory. - * @param aidlDecoder codec is wma type based on getTag of AIDL union type. - * @param legacyDecoder agm_session_wma_dec type. - */ - static void convertWmaStandardCompressDecoder(const AgmSessionWmaDec &aidlDecoder, - struct agm_session_wma_dec *legacyDecoder); - - /** - * @brief convertOpusCompressDecoder converts AgmSessionCodec from AIDL to - * agm_session_opus_dec - * Client needs to pass valid allocated memory of agm_session_opus_dec, - * who is also responsible for dellocating the memory. - * @param aidlDecoder codec is opus type based on getTag of AIDL union type. - * @param legacyDecoder agm_session_opus_dec type. - */ - static void convertOpusCompressDecoder(const AgmSessionOpusDec &aidlDecoder, - struct agm_session_opus_dec *legacyDecoder); - /** - * @brief convertAacCompressEncoder converts AgmSessionCodec from AIDL to agm_session_aac_enc - * Client needs to pass valid allocated memory of agm_session_aac_enc, - * who is also responsible for dellocating the memory. - * @param aidlEncoder codec is aac type encoder based on getTag of AIDL union type. - * @param legacyEncoder agm_session_aac_enc type. - */ - static void convertAacCompressEncoder(const AgmSessionAacEnc &aidlEncoder, - struct agm_session_aac_enc *legacyEncoder); - /** - * @brief getFdIntFromNativeHandle returns fd and associated ints based on - * AIDL NativeHandle. - * @param nativeHandle aidl NativeHandle - * @param doDup fd needs to be duped or not. - * @return pair of ints (fd, associated int) - */ - static std::pair getFdIntFromNativeHandle( - const aidl::android::hardware::common::NativeHandle &nativeHandle, bool doDup = true); - - /** - * @brief getFdFromNativeHandle returns dup'ed fd from nativehandle. - * @param nativeHandle aidl NativeHandle - * @return dup'ed fd - */ - static int getFdFromNativeHandle( - const aidl::android::hardware::common::NativeHandle &nativeHandle); - - /** - * @brief convertAgmBuffer converts AgmBuff from AIDL to agm_buff - * legacy type. Client needs to pass valid allocated memory of agm_buff, - * who is also responsible for dellocating the memory. - * @param aidlBuffer buffer in AgmBuff format. - * @param legacyAgmBuffer agm_buff type. - */ - static void convertAgmBuffer(const AgmBuff &aidlBuffer, struct agm_buff *legacyAgmBuffer); - - /** - * @brief convertMmapBufInfo converts MmapBufInfo from AIDL to agm_buf_info - * legacy type. Client needs to pass valid allocated memory of agm_buf_info, - * who is also responsible for dellocating the memory. - * @param aidlMmapBufferInfo buffer info in MmapBufInfo AIDL type. - * @param flags indicating whether a data or pos buffer - * @param legacyAgmBufferInfo agm_session_config type. - */ - static void convertMmapBufInfo(const MmapBufInfo &aidlMmapBufferInfo, - struct agm_buf_info *legacyAgmBufferInfo, uint32_t flag); - - /** - * @brief convertAgmCalConfig converts AgmCalConfig from AIDL to agm_cal_config - * legacy type. Client needs to pass valid allocated memory of agm_cal_config, - * who is also responsible for dellocating the memory. - * @param aidlCalConfig config in AgmCalConfig type. - * @param legacyAgmCalConfig agm_cal_config type. - */ - static void convertAgmCalConfig(const AgmCalConfig &aidlCalConfig, - struct agm_cal_config *legacyAgmCalConfig); - - /** - * @brief convertAgmTagConfig converts AgmTagConfig from AIDL to agm_tag_config - * legacy type. Client needs to pass valid allocated memory of agm_tag_config, - * who is also responsible for dellocating the memory. - * @param aidlCalConfig config in AgmTagConfig type. - * @param legacyAgmTagConfig agm_tag_config type. - */ - static void convertAgmTagConfig(const AgmTagConfig &aidlTagConfig, - struct agm_tag_config *legacyAgmTagConfig); -}; -} \ No newline at end of file diff --git a/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/AgmLegacyToAidl.h b/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/AgmLegacyToAidl.h deleted file mode 100755 index 3a6e8255..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/AgmLegacyToAidl.h +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace ::aidl::vendor::qti::hardware::agm; - -struct LegacyToAidl { - /** - * @brief convertAgmSessionConfigToAidl converts legacy agm_session_config to AIDL - * based AgmSessionConfig type. - * @param session_config agm_session_config in legacy types - * @param format agm_media_format to fetch session codec info for compress codecs. - * @return AgmSessionConfig AIDL object - */ - static AgmSessionConfig convertAgmSessionConfigToAidl(struct agm_session_config *sessionConfig, - agm_media_format format); - - /** - * @brief convertAgmMediaConfigToAidl converts legacy agm_media_config to AIDL - * based AgmMediaConfig type. - * @param media_config agm_media_config in legacy types - * @return AgmMediaConfig AIDL object - */ - static AgmMediaConfig convertAgmMediaConfigToAidl(struct agm_media_config *mediaConfig); - - /** - * @brief convertAgmBufferConfigToAidl converts legacy agm_buffer_config to AIDL - * based AgmBufferConfig type. - * @param buffer_config agm_buffer_config in legacy types - * @return AgmBufferConfig AIDL object - */ - static AgmBufferConfig convertAgmBufferConfigToAidl(struct agm_buffer_config *bufferConfig); - - /** - * @brief convertAgmGroupMediaConfigToAidl converts legacy agm_group_media_config to AIDL - * based AgmGroupMediaConfig type. - * @param media_config agm_group_media_config in legacy types - * @return AgmGroupMediaConfig AIDL object - */ - static AgmGroupMediaConfig convertAgmGroupMediaConfigToAidl( - struct agm_group_media_config *mediaConfig); - - /** - * @brief convertAgmTagConfigToAidl converts legacy agm_tag_config to AIDL - * based AgmTagConfig type. - * @param tag_config agm_tag_config in legacy types - * @return AgmTagConfig AIDL object - */ - static AgmTagConfig convertAgmTagConfigToAidl(struct agm_tag_config *tagConfig); - - /** - * @brief convertAgmCalConfigToAidl converts legacy agm_cal_config to AIDL - * based AgmCalConfig type. - * @param tag_config agm_cal_config in legacy types - * @return AgmCalConfig AIDL object - */ - static AgmCalConfig convertAgmCalConfigToAidl(struct agm_cal_config *calConfig); - - /** - * @brief convertAgmEventRegistrationConfigToAidl converts legacy agm_event_reg_cfg to AIDL - * based AgmEventRegistrationConfig type. - * @param evt_reg_cfg agm_event_reg_cfg in legacy types - * @return AgmEventRegistrationConfig AIDL object - */ - static AgmEventRegistrationConfig convertAgmEventRegistrationConfigToAidl( - agm_event_reg_cfg *eventRegConfig); - - /** - * @brief convertCompressCodecInfoToAidl converts legacy agm_session_config to AIDL - * based AgmSessionCodec type. - * @param session_config agm_session_config in legacy types - * @param format agm_media_format in legacy types - * @return AgmSessionCodec AIDL object - */ - static AgmSessionCodec convertCompressCodecInfoToAidl(struct agm_session_config *sessionConfig, - agm_media_format format); - - /** - * @brief convertCompressDecoderInfoToAidl converts legacy agm_session_codec to AIDL - * based AgmSessionCodec type. - * @param sessionCodec agm_session_codec in legacy types - * @param format agm_media_format in legacy types - * @return AgmSessionCodec AIDL object - */ - static AgmSessionCodec convertCompressDecoderInfoToAidl(union agm_session_codec *sessionCodec, - agm_media_format format); - - /** - * @brief convertCompressEncoderInfoToAidl converts legacy agm_session_codec to AIDL - * based AgmSessionCodec type. - * @param sessionCodec agm_session_codec in legacy types - * @param format agm_media_format in legacy types - * @return AgmSessionCodec AIDL object - */ - static AgmSessionCodec convertCompressEncoderInfoToAidl(union agm_session_codec *sessionCodec, - agm_media_format format); - - /** - * @brief convertAacCompressDecoderToAidl converts legacy agm_session_aac_dec to AIDL - * based AgmSessionAacDec type. - * @param legacyDecoder agm_session_aac_dec in legacy types - * @return AgmSessionAacDec AIDL object - */ - static AgmSessionAacDec convertAacCompressDecoderToAidl( - struct agm_session_aac_dec *legacyDecoder); - - /** - * @brief convertFlacCompressDecoderToAidl converts legacy agm_session_flac_dec to AIDL - * based AgmSessionFlacDec type. - * @param legacyDecoder agm_session_flac_dec in legacy types - * @return AgmSessionFlacDec AIDL object - */ - static AgmSessionFlacDec convertFlacCompressDecoderToAidl( - struct agm_session_flac_dec *legacyDecoder); - - /** - * @brief convertAlacCompressDecoderToAidl converts legacy agm_session_alac_dec to AIDL - * based AgmSessionAlacDec type. - * @param legacyDecoder agm_session_alac_dec in legacy types - * @return AgmSessionAlacDec AIDL object - */ - static AgmSessionAlacDec convertAlacCompressDecoderToAidl( - struct agm_session_alac_dec *legacyDecoder); - - /** - * @brief convertApeCompressDecoderToAidl converts legacy agm_session_ape_dec to AIDL - * based AgmSessionApeDec type. - * @param legacyDecoder agm_session_ape_dec in legacy types - * @return AgmSessionApeDec AIDL object - */ - static AgmSessionApeDec convertApeCompressDecoderToAidl( - struct agm_session_ape_dec *legacyDecoder); - - /** - * @brief convertWmaProCompressDecoderToAidl converts legacy agm_session_wmapro_dec to AIDL - * based AgmSessionWmaproDec type. - * @param legacyDecoder agm_session_wmapro_dec in legacy types - * @return AgmSessionWmaproDec AIDL object - */ - static AgmSessionWmaproDec convertWmaProCompressDecoderToAidl( - struct agm_session_wmapro_dec *legacyDecoder); - - /** - * @brief convertWmaStandardCompressDecoderToAidl converts legacy agm_session_config to AIDL - * based AgmSessionWmaDec type. - * @param legacyDecoder agm_session_config in legacy types - * @return AgmSessionWmaDec AIDL object - */ - static AgmSessionWmaDec convertWmaStandardCompressDecoderToAidl( - struct agm_session_wma_dec *legacyDecoder); - - - /** - * @brief convertOpusCompressDecoderToAidl converts legacy agm_session_config to AIDL - * based AgmSessionOpusDec type. - * @param legacyDecoder agm_session_config in legacy types - * @return AgmSessionOpusDec AIDL object - */ - static AgmSessionOpusDec convertOpusCompressDecoderToAidl( - struct agm_session_opus_dec *legacyDecoder); - - /** - * @brief convertAacCompressEncoderToAidl converts legacy agm_session_aac_enc to AIDL - * based AgmSessionAacEnc type. - * @param sessionConfig agm_session_aac_enc in legacy types - * @return AgmSessionAacEnc AIDL object - */ - static AgmSessionAacEnc convertAacCompressEncoderToAidl( - struct agm_session_aac_enc *legacyEncoder); - - /** - * @brief convertAgmEventCallbackParametersToAidl converts legacy agm_event_cb_params to AIDL - * based AgmEventCallbackParameter type. - * @param eventParams agm_event_cb_params in legacy types - * @return AgmEventCallbackParameter AIDL object - */ - static AgmEventCallbackParameter convertAgmEventCallbackParametersToAidl( - struct agm_event_cb_params *eventParams); - - /** - * @brief convertRawPayloadToVector converts legacy void * memory to std::vector - * so it can be used over AIDL. - * @param payload void * memory chunk - * @param size size of memory chunk passed, vector will be allocated according to this size - * @return std::vector copied from memory chunk - */ - static std::vector convertRawPayloadToVector(void *payload, size_t size); - - /** - * @brief convertAifInfoListToAidl converts legacy aif_info to AIDL - * based AifInfo type. - * @param agmLegacyAifInfoList aif_info in legacy types - * @param size size of aifInfo list - * @return vector of AifInfo based on legacy aif_info list - */ - static std::vector convertAifInfoListToAidl(struct aif_info *agmLegacyAifInfoList, - int size); - /* - * input buff is legacy agm buffer. - * @param externalMemory if nt mode use case - * @param copyBuffers for read usecases no need to copy the input buffers. - */ - - /** - * @brief convertAgmBufferToAidl converts legacy agm_buff to AIDL - * based AgmBuff type. - * @param buf agm_buff in legacy type. - * @param externalMemory set externalMemory to indicate non tunnel mode usecase. - * NonTunnel mode has metadata and fd infos. - * @param copyBuffers a boolean indicating whether buffers needs to be copied in returned - * AIDL types, for read usecases, AgmBuff does not need copyBuffers. - * @return AgmBuff converted from agm legacyBuffer - */ - static AgmBuff convertAgmBufferToAidl(struct agm_buff *buf, bool externalMemory = false, - bool copyBuffers = true); - - /** - * @brief getDupedFdFromAgmEventParams gets a dup'ed Fd from callback params. - * @param eventParams callback parameter of type agm_event_cb_params - * @return fd found in the callback. - */ - static int getDupedFdFromAgmEventParams(struct agm_event_cb_params *eventParams); - - /** - * @brief cleanUpMetadataMemory dellocates the memory of metadata field in agm_event_cb_params. - * This is used explicitly for callback associated with read_with_metadata API, as - * read_with_metadata API allocates a metadata which is used during callback on - * AGM_EVENT_READ_DONE - * callback. - * @param eventParams agm_event_cb_params in legacy types - * @return AgmSessionConfig AIDL object - */ - static void cleanUpMetadataMemory(struct agm_event_cb_params *eventParams); - - /** - * @brief convertAgmReadWriteEventCallbackParamsToAidl converts legacy agm_event_cb_params to - * AIDL - * based AgmReadWriteEventCallbackParams type. - * @param eventParams agm_event_cb_params in legacy types - * @param inputFd fd information sent during callback - * @return AgmReadWriteEventCallbackParams AIDL object - */ - static AgmReadWriteEventCallbackParams convertAgmReadWriteEventCallbackParamsToAidl( - struct agm_event_cb_params *eventParams, int inputFd); - - /** - * @brief convertMmapBufferInfoToAidl converts agm_buf_info agm_session_config to AIDL - * based MmapBufInfo type. - * @param legacyBufferInfo agm_buf_info in legacy types - * @param aidlBufferInfo MmapBufInfo AIDL pointer - * @param flags flags associated with agm_buf_info - */ - static void convertMmapBufferInfoToAidl(struct agm_buf_info *legacyBufferInfo, - MmapBufInfo *aidlBufferInfo, int flags); -}; diff --git a/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/BinderStatus.h b/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/BinderStatus.h deleted file mode 100755 index e6d747e8..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/BinderStatus.h +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include - -inline uint64_t convertAidlHandleToLegacy(int64_t aidlHandle) { - return (static_cast(aidlHandle)); -} - -inline int64_t convertLegacyHandleToAidlHandle(uint64_t handle) { - return (static_cast(handle)); -} - -/** -* @brief convertStatus_tToExceptionCode converts status_t based errorcode -* to Status (AIDL) type. This is used to preserve errors code across the -* AIDL layers. These Status types are used to throw AStatus_fromServiceSpecificErrorWithMessage -* @param errcode status_t error code. -* @return Status Aidl object corresponding to legacy error code. -*/ -static Status convertStatus_tToExceptionCode(int errcode) { - switch (errcode) { - case -EIO: - return Status::IO_ERROR; - case -EBUSY: - return Status::BUSY; - case -ENOSPC: - return Status::NO_SPACE; - case -EBADR: - return Status::INVALID_FD; - case -EADV: - return Status::ADVERTISE_ERROR; - case -ENOPROTOOPT: - return Status::PROTOCOL_NOT_AVAILABLE; - case -EOPNOTSUPP: - return Status::NOT_SUPPORTED; - case -ENETRESET: - return Status::DOWN_WITH_SSR; - case -EALREADY: - return Status::NOW_INPROGRESS; - case -EINPROGRESS: - return Status::ALREADY_INPROGRESS; - case -ECANCELED: - return Status::CANCELLED; - case -ENOTRECOVERABLE: - return Status::NOT_RECOVERABLE; - default: - return Status::UNKNOWN; - } -} - -/** -* @brief statusTFromExceptionCode converts Status(AIDL) based errorcode -* to legacy type. This is used to preserve errors code across the -* AIDL layers. This unmarshells the errorcode from exception received over -* AIDL, used along with statusTFromBinderStatus. -* @param exceptionCode exception in Status format. -* @return legacy error code -*/ -static int statusTFromExceptionCode(Status exceptionCode) { - switch (exceptionCode) { - case Status::SUCCESS: - return ::android::OK; - case Status::IO_ERROR: - return -EIO; - case Status::BUSY: - return -EBUSY; - case Status::NO_SPACE: - return -ENOSPC; - case Status::INVALID_FD: - return -EBADR; - case Status::ADVERTISE_ERROR: - return -EADV; - case Status::PROTOCOL_NOT_AVAILABLE: - return -ENOPROTOOPT; - case Status::NOT_SUPPORTED: - return -EOPNOTSUPP; - case Status::DOWN_WITH_SSR: - return -ENETRESET; - case Status::NOW_INPROGRESS: - return -EALREADY; - case Status::ALREADY_INPROGRESS: - return -EINPROGRESS; - case Status::CANCELLED: - return -ECANCELED; - case Status::NOT_RECOVERABLE: - return -ENOTRECOVERABLE; - case Status::UNKNOWN: - default: - return -EINVAL; - } -} - -/** -* @brief status_tToBinderResult converts legacy status_t codes to ScopedAStatus. -* The known errors are mapped from binder_status.h and directly propagated, -* rest of errors used by AGM are converted using ServiceSpecificException. -* @param errcode linux based error code. -* @return returns ScopedAStatus based on error code. -*/ - -inline ::ndk::ScopedAStatus status_tToBinderResult(int errcode) { - Status errStatus = convertStatus_tToExceptionCode(errcode); - if (errStatus != Status::UNKNOWN) { - return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage( - static_cast(errStatus), toString(errStatus).c_str())); - } - return ndk::ScopedAStatus(AStatus_fromStatus(static_cast(errcode))); -} - -/** -* @brief statusTFromBinderStatus converts ScopedAStatus to legacy status_t codes -* The known errors are mapped from binder_status.h and directly propagated, -* rest of errors used by AGM are converted using ServiceSpecificException. -* converts ScopedAStatus Exception code into error using the -* helper method statusTFromExceptionCode -* @param status ScopedAStatus code -* @param caller to print caller function, helpful during debugging. -* @return returns converted status_t code. -*/ -static inline int statusTFromBinderStatus(const ::ndk::ScopedAStatus &status, - const std::string &caller = "") { - if (status.isOk()) { - return ::android::OK; - } else if (status.getServiceSpecificError()) { - ALOGV("%s failed with %s", caller.c_str(), status.getDescription().c_str()); - return statusTFromExceptionCode(static_cast(status.getServiceSpecificError())); - } else { - ALOGV("%s failed with %s", caller.c_str(), status.getDescription().c_str()); - return status.getStatus(); - } -} \ No newline at end of file diff --git a/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/Utils.h b/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/Utils.h deleted file mode 100755 index d700f6a7..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidlconverter/inc/agm/Utils.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include "BinderStatus.h" - -#define MAX_KVPAIR 48 - -/** - * @brief Exit if number of kvpais exceeds max defined pairs -*/ -#define RETURN_IF_KVPAIR_EXCEEDS_RANGE(pair) \ - ({ \ - if (pair > MAX_KVPAIR) { \ - ALOGE("Num KVs %d more than expected: %d", pair, MAX_KVPAIR); \ - return status_tToBinderResult(-ENOMEM); \ - } \ - }) - -/* -* @brief Pass a unique_ptr to check if memory is allocated or not. -*/ -#define RETURN_IF_ALLOCATION_FAILED(ptr) \ - ({ \ - if (ptr.get() == NULL) { \ - ALOGE("%s could not allocate memory", __func__); \ - return status_tToBinderResult(-ENOMEM); \ - } \ - }) - -/** - * @brief Expects a std::unique_ptr - * checks if unique_ptr is allocated or not - * If memory is allocated then return unique_ptr - * otherwise exit with -ENOMEM status. -*/ - -#define VALUE_OR_RETURN(ptr) \ - ({ \ - auto temp = (ptr); \ - if (temp.get() == nullptr) { \ - ALOGE("%s could not allocate memory", __func__); \ - return status_tToBinderResult(-ENOMEM); \ - } \ - std::move(temp); \ - }) - -/** -* @brief allocator with custom deleter -* Takes a type T and size -* return the unique_ptr for type allocated with calloc -* When goes out of scope will be deallocated with free -* client needs to check if returned ptr is null or not. -* Usage: -* with calloc and free: -* struct agm_media_config *config = (struct agm_media_config*)calloc(1, -* sizeof(struct agm_media_config)); -* if (config == NULL) { -* ALOGE("%s: Cannot allocate memory for config\n", __func__); -* return -ENOMEM; -* } -* .... -* free(config); -* Now: -* auto config = VALUE_OR_RETURN(allocate(sizeof(agm_media_config))); -* allocate will allocate unique_ptr as per type agm_media_config -* VALUE_OR_RETRUN will return the unique_ptr if allocation is succesfull -* otherwise it will exit. -* custom deletor will take to deallocate memory using free when scope is cleared. -* @param size size to be allocated for type T -* @return unique_ptr of type T with size requested. -*/ - -using CustomDeletor = void (*)(void *); -template -std::unique_ptr allocate(int size) { - T *obj = reinterpret_cast(calloc(1, size)); - return std::unique_ptr{obj, free}; -} - -using AgmAifUniquePtrType = std::unique_ptr; - -/** -* @brief needsCodecSpecificInfo returns true for compress codecs which -* need extra codec specific information to be passed. -* @param format agm_media_format type -* @return whether needs codec specific information or not -*/ -static bool needsCodecSpecificInfo(agm_media_format format) { - switch (format) { - case AGM_FORMAT_AAC: - case AGM_FORMAT_FLAC: - case AGM_FORMAT_ALAC: - case AGM_FORMAT_APE: - case AGM_FORMAT_WMAPRO: - case AGM_FORMAT_WMASTD: - case AGM_FORMAT_OPUS: - return true; - default: - return false; - } -} \ No newline at end of file diff --git a/qcom/opensource/agm/ipc/aidl/aidlconverter/src/AgmAidlToLegacy.cpp b/qcom/opensource/agm/ipc/aidl/aidlconverter/src/AgmAidlToLegacy.cpp deleted file mode 100755 index 8e81d46f..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidlconverter/src/AgmAidlToLegacy.cpp +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AgmIpc::AidlToLegacy::Converter" - -#include -#include - -namespace aidl::vendor::qti::hardware::agm { - -void AidlToLegacy::convertCompressCodecInfo( - const ::aidl::vendor::qti::hardware::agm::AgmSessionConfig &aidlConfig, - struct agm_session_config *legacyConfig) { - if (aidlConfig.codec.has_value()) { - auto aidlCodec = aidlConfig.codec.value(); - auto codecType = aidlConfig.codec.value().getTag(); - ALOGV("compress codec type %s ", toString(codecType).c_str()); - switch (codecType) { - case AgmSessionCodec::aacDecoder: { - auto dec = aidlCodec.get(); - convertAacCompressDecoder(dec, &legacyConfig->codec.aac_dec); - break; - } - case AgmSessionCodec::flacDecoder: { - auto dec = aidlCodec.get(); - convertFlacCompressDecoder(dec, &legacyConfig->codec.flac_dec); - break; - } - case AgmSessionCodec::alacDecoder: { - auto dec = aidlCodec.get(); - convertAlacCompressDecoder(dec, &legacyConfig->codec.alac_dec); - break; - } - case AgmSessionCodec::apeDecoder: { - auto dec = aidlCodec.get(); - convertApeCompressDecoder(dec, &legacyConfig->codec.ape_dec); - break; - } - case AgmSessionCodec::wmaDecoder: { - auto dec = aidlCodec.get(); - convertWmaStandardCompressDecoder(dec, &legacyConfig->codec.wma_dec); - break; - } - case AgmSessionCodec::wmaproDecoder: { - auto dec = aidlCodec.get(); - convertWmaProCompressDecoder(dec, &legacyConfig->codec.wmapro_dec); - break; - } - case AgmSessionCodec::opusDecoder: { - auto dec = aidlCodec.get(); - convertOpusCompressDecoder(dec, &legacyConfig->codec.opus_dec); - break; - } - case AgmSessionCodec::aacEncoder: { - auto enc = aidlCodec.get(); - convertAacCompressEncoder(enc, &legacyConfig->codec.aac_enc); - break; - } - default: - ALOGE("unknow type %s ", toString(codecType).c_str()); - } - } -} - -void AidlToLegacy::convertAacCompressDecoder( - const ::aidl::vendor::qti::hardware::agm::AgmSessionAacDec &aidlDecoder, - struct agm_session_aac_dec *legacyDecoder) { - legacyDecoder->aac_fmt_flag = aidlDecoder.formatFlag; - legacyDecoder->audio_obj_type = aidlDecoder.objectType; - legacyDecoder->num_channels = aidlDecoder.channels; - legacyDecoder->total_size_of_PCE_bits = aidlDecoder.sizeOfPCEBits; - legacyDecoder->sample_rate = aidlDecoder.sampleRate; - ALOGI("%s config %s", __func__, aidlDecoder.toString().c_str()); -} - -void AidlToLegacy::convertFlacCompressDecoder( - const ::aidl::vendor::qti::hardware::agm::AgmSessionFlacDec &aidlDecoder, - struct agm_session_flac_dec *legacyDecoder) { - legacyDecoder->num_channels = aidlDecoder.channels; - legacyDecoder->sample_size = aidlDecoder.sampleSize; - legacyDecoder->min_blk_size = aidlDecoder.minBlockSize; - legacyDecoder->max_blk_size = aidlDecoder.maxBlockSize; - legacyDecoder->sample_rate = aidlDecoder.sampleRate; - legacyDecoder->min_frame_size = aidlDecoder.minFrameSize; - legacyDecoder->max_frame_size = aidlDecoder.maxFrameSize; - ALOGV("%s config %s", __func__, aidlDecoder.toString().c_str()); -} - -void AidlToLegacy::convertAlacCompressDecoder( - const ::aidl::vendor::qti::hardware::agm::AgmSessionAlacDec &aidlDecoder, - struct agm_session_alac_dec *legacyDecoder) { - legacyDecoder->frame_length = aidlDecoder.frameLength; - legacyDecoder->compatible_version = aidlDecoder.compatibleVersion; - legacyDecoder->bit_depth = aidlDecoder.bitDepth; - legacyDecoder->pb = aidlDecoder.pb; - legacyDecoder->mb = aidlDecoder.mb; - legacyDecoder->kb = aidlDecoder.kb; - legacyDecoder->num_channels = aidlDecoder.channels; - legacyDecoder->max_run = aidlDecoder.maxRun; - legacyDecoder->max_frame_bytes = aidlDecoder.maxFrameBytes; - legacyDecoder->avg_bit_rate = aidlDecoder.averageBitRate; - legacyDecoder->sample_rate = aidlDecoder.sampleRate; - legacyDecoder->channel_layout_tag = aidlDecoder.channelLayoutTag; - ALOGV("%s config %s", __func__, aidlDecoder.toString().c_str()); -} -void AidlToLegacy::convertApeCompressDecoder( - const ::aidl::vendor::qti::hardware::agm::AgmSessionApeDec &aidlDecoder, - struct agm_session_ape_dec *legacyDecoder) { - legacyDecoder->compatible_version = aidlDecoder.compatibleVersion; - legacyDecoder->compression_level = aidlDecoder.compressionLevel; - legacyDecoder->format_flags = aidlDecoder.formatFlags; - legacyDecoder->blocks_per_frame = aidlDecoder.blocksPerFrame; - legacyDecoder->final_frame_blocks = aidlDecoder.finalFrameBlocks; - legacyDecoder->total_frames = aidlDecoder.totalFrames; - legacyDecoder->bit_width = aidlDecoder.bitWidth; - legacyDecoder->num_channels = aidlDecoder.channels; - legacyDecoder->sample_rate = aidlDecoder.sampleRate; - legacyDecoder->seek_table_present = aidlDecoder.seekTablePresent; - ALOGV("%s config %s", __func__, aidlDecoder.toString().c_str()); -} - -void AidlToLegacy::convertWmaStandardCompressDecoder( - const ::aidl::vendor::qti::hardware::agm::AgmSessionWmaDec &aidlDecoder, - struct agm_session_wma_dec *legacyDecoder) { - legacyDecoder->fmt_tag = aidlDecoder.formatTag; - legacyDecoder->num_channels = aidlDecoder.channels; - legacyDecoder->sample_rate = aidlDecoder.sampleRate; - legacyDecoder->avg_bytes_per_sec = aidlDecoder.averageBytesPerSecond; - legacyDecoder->blk_align = aidlDecoder.blockAlign; - legacyDecoder->bits_per_sample = aidlDecoder.bitsPerSample; - legacyDecoder->channel_mask = aidlDecoder.channelMask; - legacyDecoder->enc_options = aidlDecoder.encoderOption; - legacyDecoder->reserved = aidlDecoder.reserved; - ALOGV("%s config %s", __func__, aidlDecoder.toString().c_str()); -} - -void AidlToLegacy::convertWmaProCompressDecoder( - const ::aidl::vendor::qti::hardware::agm::AgmSessionWmaproDec &aidlDecoder, - struct agm_session_wmapro_dec *legacyDecoder) { - legacyDecoder->fmt_tag = aidlDecoder.formatTag; - legacyDecoder->num_channels = aidlDecoder.channels; - legacyDecoder->sample_rate = aidlDecoder.sampleRate; - legacyDecoder->avg_bytes_per_sec = aidlDecoder.averageBytesPerSecond; - legacyDecoder->blk_align = aidlDecoder.blockAlign; - legacyDecoder->bits_per_sample = aidlDecoder.bitsPerSample; - legacyDecoder->channel_mask = aidlDecoder.channelMask; - legacyDecoder->enc_options = aidlDecoder.encoderOption; - legacyDecoder->advanced_enc_option = aidlDecoder.advancedEncoderOption; - legacyDecoder->advanced_enc_option2 = aidlDecoder.advancedEncoderOption2; - ALOGI("%s config %s", __func__, aidlDecoder.toString().c_str()); -} - -void AidlToLegacy::convertOpusCompressDecoder( - const ::aidl::vendor::qti::hardware::agm::AgmSessionOpusDec &aidlDecoder, - struct agm_session_opus_dec *legacyDecoder) { - legacyDecoder->bitstream_format = aidlDecoder.bitStreamFormat; - legacyDecoder->payload_type = aidlDecoder.type; - legacyDecoder->version = aidlDecoder.version; - legacyDecoder->num_channels = aidlDecoder.channels; - legacyDecoder->pre_skip = aidlDecoder.preSkip; - legacyDecoder->sample_rate = aidlDecoder.sampleRate; - legacyDecoder->mapping_family = aidlDecoder.mappingFamily; - legacyDecoder->stream_count = aidlDecoder.streamCount; - // both types are uint8 type with predefined size, so use hardcoded values - memcpy(legacyDecoder->channel_map, aidlDecoder.channelMap.data(), 8); - memcpy(legacyDecoder->reserved, aidlDecoder.reserved.data(), 3); - - ALOGI("%s config %s", __func__, aidlDecoder.toString().c_str()); -} - -void AidlToLegacy::convertAacCompressEncoder( - const ::aidl::vendor::qti::hardware::agm::AgmSessionAacEnc &aidlEncoder, - struct agm_session_aac_enc *legacyEncoder) { - legacyEncoder->aac_bit_rate = aidlEncoder.bitRate; - legacyEncoder->global_cutoff_freq = aidlEncoder.globalCutOffFrequency; - legacyEncoder->enc_cfg.aac_enc_mode = aidlEncoder.mode; - legacyEncoder->enc_cfg.aac_fmt_flag = aidlEncoder.formatFlags; - ALOGI("%s config %s", __func__, aidlEncoder.toString().c_str()); -} - -void AidlToLegacy::convertAgmMediaConfig( - const ::aidl::vendor::qti::hardware::agm::AgmMediaConfig &aidlConfig, - struct agm_media_config *legacyConfig) { - legacyConfig->rate = aidlConfig.rate; - legacyConfig->channels = aidlConfig.channels; - // How to check the range of enums ?? - legacyConfig->format = static_cast(aidlConfig.format); - legacyConfig->data_format = aidlConfig.dataFormat; -} - -void AidlToLegacy::convertAgmGroupMediaConfig( - const ::aidl::vendor::qti::hardware::agm::AgmGroupMediaConfig &aidlConfig, - struct agm_group_media_config *legacyConfig) { - legacyConfig->config.rate = aidlConfig.rate; - legacyConfig->config.channels = aidlConfig.channels; - legacyConfig->config.format = static_cast(aidlConfig.format); - legacyConfig->config.data_format = aidlConfig.dataFormat; - legacyConfig->slot_mask = aidlConfig.slotMask; -} - -void AidlToLegacy::convertAgmSessionConfig( - const ::aidl::vendor::qti::hardware::agm::AgmSessionConfig &aidlConfig, - struct agm_session_config *legacyConfig) { - // TODO check range of enum - legacyConfig->dir = static_cast(aidlConfig.direction); - legacyConfig->sess_mode = static_cast(aidlConfig.sessionMode); - legacyConfig->start_threshold = aidlConfig.startThreshold; - legacyConfig->stop_threshold = aidlConfig.stopThreshold; - legacyConfig->data_mode = static_cast(aidlConfig.dataMode); - legacyConfig->sess_flags = (aidlConfig.flags); - convertCompressCodecInfo(aidlConfig, legacyConfig); -} - -void AidlToLegacy::convertAgmBufferConfig( - const ::aidl::vendor::qti::hardware::agm::AgmBufferConfig &aidlConfig, - struct agm_buffer_config *legacyConfig) { - legacyConfig->count = aidlConfig.count; - legacyConfig->size = aidlConfig.size; - legacyConfig->max_metadata_size = aidlConfig.maxMetadataSize; -} - -void AidlToLegacy::convertAifInfoList( - const std::vector<::aidl::vendor::qti::hardware::agm::AifInfo> &aidlList, - struct aif_info *legacyAifList) { - for (unsigned long i = 0; i < aidlList.size(); i++) { - strlcpy(legacyAifList[i].aif_name, aidlList[i].aifName.c_str(), AIF_NAME_MAX_LEN); - legacyAifList[i].dir = (enum direction)aidlList[i].direction; - } -} - -void AidlToLegacy::convertAgmEventRegistrationConfig( - const ::aidl::vendor::qti::hardware::agm::AgmEventRegistrationConfig &aidlConfig, - struct agm_event_reg_cfg *legacyConfig) { - legacyConfig->module_instance_id = aidlConfig.moduleInstanceId; - legacyConfig->event_id = aidlConfig.eventId; - legacyConfig->is_register = aidlConfig.registerEvent; - legacyConfig->event_config_payload_size = aidlConfig.eventConfigPayload.size(); - memcpy(legacyConfig->event_config_payload, aidlConfig.eventConfigPayload.data(), - legacyConfig->event_config_payload_size); -} - -std::pair AidlToLegacy::getFdIntFromNativeHandle( - const aidl::android::hardware::common::NativeHandle &nativeHandle, bool doDup) { - std::pair fdIntPair = {-1, -1}; - if (!nativeHandle.fds.empty()) { - if (doDup) { - fdIntPair.first = dup(nativeHandle.fds.at(0).get()); - } else { - fdIntPair.first = (nativeHandle.fds.at(0).get()); - } - } - if (!nativeHandle.ints.empty()) { - fdIntPair.second = nativeHandle.ints.at(0); - } - - return std::move(fdIntPair); -} - -int AidlToLegacy::getFdFromNativeHandle( - const aidl::android::hardware::common::NativeHandle &nativeHandle) { - if (!nativeHandle.fds.empty()) { - return dup(nativeHandle.fds.at(0).get()); - } - return -1; -} - -void AidlToLegacy::convertAgmBuffer(const ::aidl::vendor::qti::hardware::agm::AgmBuff &aidlBuffer, - struct agm_buff *agmLegacyBuffer) { - uint32_t bufSize = aidlBuffer.buffer.size(); - agmLegacyBuffer->size = (size_t)bufSize; - agmLegacyBuffer->timestamp = aidlBuffer.timestamp; - agmLegacyBuffer->flags = aidlBuffer.flags; - memcpy(agmLegacyBuffer->addr, aidlBuffer.buffer.data(), bufSize); -} - -void AidlToLegacy::convertMmapBufInfo(const MmapBufInfo &aidlMmapBufferInfo, - struct agm_buf_info *legacyAgmBufferInfo, uint32_t flag) { - if (flag & DATA_BUF) { - legacyAgmBufferInfo->data_buf_fd = - AidlToLegacy::getFdFromNativeHandle(aidlMmapBufferInfo.dataFdHandle); - legacyAgmBufferInfo->data_buf_size = aidlMmapBufferInfo.dataSize; - } - if (flag & POS_BUF) { - legacyAgmBufferInfo->pos_buf_fd = - AidlToLegacy::getFdFromNativeHandle(aidlMmapBufferInfo.positionFdHandle); - legacyAgmBufferInfo->pos_buf_size = aidlMmapBufferInfo.posSize; - } -} - -void AidlToLegacy::convertAgmCalConfig(const AgmCalConfig &aidlCalConfig, - struct agm_cal_config *agmLegacyCalConfig) { - agmLegacyCalConfig->num_ckvs = aidlCalConfig.kv.size(); - for (unsigned long i = 0; i < aidlCalConfig.kv.size(); i++) { - agmLegacyCalConfig->kv[i].key = aidlCalConfig.kv[i].key; - agmLegacyCalConfig->kv[i].value = aidlCalConfig.kv[i].value; - } -} - -void AidlToLegacy::convertAgmTagConfig(const AgmTagConfig &aidlCalConfig, - struct agm_tag_config *agmLegacyTagConfig) { - agmLegacyTagConfig->num_tkvs = aidlCalConfig.kv.size(); - agmLegacyTagConfig->tag = aidlCalConfig.tag; - for (unsigned long i = 0; i < aidlCalConfig.kv.size(); i++) { - agmLegacyTagConfig->kv[i].key = aidlCalConfig.kv[i].key; - agmLegacyTagConfig->kv[i].value = aidlCalConfig.kv[i].value; - } -} -} \ No newline at end of file diff --git a/qcom/opensource/agm/ipc/aidl/aidlconverter/src/AgmLegacyToAidl.cpp b/qcom/opensource/agm/ipc/aidl/aidlconverter/src/AgmLegacyToAidl.cpp deleted file mode 100755 index 4e13db82..00000000 --- a/qcom/opensource/agm/ipc/aidl/aidlconverter/src/AgmLegacyToAidl.cpp +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AgmIpc::LegacyToAidl::Converter" - -#include -#include -#include -#include -#include "gsl_intf.h" - -AgmSessionAacDec LegacyToAidl::convertAacCompressDecoderToAidl( - struct agm_session_aac_dec *legacyDecoder) { - AgmSessionAacDec aidlDecoder; - aidlDecoder.formatFlag = legacyDecoder->aac_fmt_flag; - aidlDecoder.objectType = legacyDecoder->audio_obj_type; - aidlDecoder.channels = legacyDecoder->num_channels; - aidlDecoder.sizeOfPCEBits = legacyDecoder->total_size_of_PCE_bits; - aidlDecoder.sampleRate = legacyDecoder->sample_rate; - ALOGV("%s config %s", __func__, aidlDecoder.toString().c_str()); - return std::move(aidlDecoder); -} - -AgmSessionFlacDec LegacyToAidl::convertFlacCompressDecoderToAidl( - struct agm_session_flac_dec *legacyDecoder) { - AgmSessionFlacDec aidlDecoder; - aidlDecoder.channels = legacyDecoder->num_channels; - aidlDecoder.sampleSize = legacyDecoder->sample_size; - aidlDecoder.minBlockSize = legacyDecoder->min_blk_size; - aidlDecoder.maxBlockSize = legacyDecoder->max_blk_size; - aidlDecoder.sampleRate = legacyDecoder->sample_rate; - aidlDecoder.minFrameSize = legacyDecoder->min_frame_size; - aidlDecoder.maxFrameSize = legacyDecoder->max_frame_size; - ALOGV("%s config %s", __func__, aidlDecoder.toString().c_str()); - return std::move(aidlDecoder); -} - -AgmSessionAlacDec LegacyToAidl::convertAlacCompressDecoderToAidl( - struct agm_session_alac_dec *legacyDecoder) { - AgmSessionAlacDec aidlDecoder; - aidlDecoder.frameLength = legacyDecoder->frame_length; - aidlDecoder.compatibleVersion = legacyDecoder->compatible_version; - aidlDecoder.bitDepth = legacyDecoder->bit_depth; - aidlDecoder.pb = legacyDecoder->pb; - aidlDecoder.mb = legacyDecoder->mb; - aidlDecoder.kb = legacyDecoder->kb; - aidlDecoder.channels = legacyDecoder->num_channels; - aidlDecoder.maxRun = legacyDecoder->max_run; - aidlDecoder.maxFrameBytes = legacyDecoder->max_frame_bytes; - aidlDecoder.averageBitRate = legacyDecoder->avg_bit_rate; - aidlDecoder.sampleRate = legacyDecoder->sample_rate; - aidlDecoder.channelLayoutTag = legacyDecoder->channel_layout_tag; - ALOGI("%s config %s", __func__, aidlDecoder.toString().c_str()); - return std::move(aidlDecoder); -} - -AgmSessionApeDec LegacyToAidl::convertApeCompressDecoderToAidl( - struct agm_session_ape_dec *legacyDecoder) { - AgmSessionApeDec aidlDecoder; - aidlDecoder.compatibleVersion = legacyDecoder->compatible_version; - aidlDecoder.compressionLevel = legacyDecoder->compression_level; - aidlDecoder.formatFlags = legacyDecoder->format_flags; - aidlDecoder.blocksPerFrame = legacyDecoder->blocks_per_frame; - aidlDecoder.finalFrameBlocks = legacyDecoder->final_frame_blocks; - aidlDecoder.totalFrames = legacyDecoder->total_frames; - aidlDecoder.bitWidth = legacyDecoder->bit_width; - aidlDecoder.channels = legacyDecoder->num_channels; - aidlDecoder.sampleRate = legacyDecoder->sample_rate; - aidlDecoder.seekTablePresent = legacyDecoder->seek_table_present; - ALOGI("%s config %s", __func__, aidlDecoder.toString().c_str()); - return std::move(aidlDecoder); -} - -AgmSessionWmaproDec LegacyToAidl::convertWmaProCompressDecoderToAidl( - struct agm_session_wmapro_dec *legacyDecoder) { - AgmSessionWmaproDec aidlDecoder; - aidlDecoder.formatTag = legacyDecoder->fmt_tag; - aidlDecoder.channels = legacyDecoder->num_channels; - aidlDecoder.sampleRate = legacyDecoder->sample_rate; - aidlDecoder.averageBytesPerSecond = legacyDecoder->avg_bytes_per_sec; - aidlDecoder.blockAlign = legacyDecoder->blk_align; - aidlDecoder.bitsPerSample = legacyDecoder->bits_per_sample; - aidlDecoder.channelMask = legacyDecoder->channel_mask; - aidlDecoder.encoderOption = legacyDecoder->enc_options; - aidlDecoder.advancedEncoderOption = legacyDecoder->advanced_enc_option; - aidlDecoder.advancedEncoderOption2 = legacyDecoder->advanced_enc_option2; - ALOGI("%s config %s", __func__, aidlDecoder.toString().c_str()); - return std::move(aidlDecoder); -} - -AgmSessionWmaDec LegacyToAidl::convertWmaStandardCompressDecoderToAidl( - struct agm_session_wma_dec *legacyDecoder) { - AgmSessionWmaDec aidlDecoder; - aidlDecoder.formatTag = legacyDecoder->fmt_tag; - aidlDecoder.channels = legacyDecoder->num_channels; - aidlDecoder.sampleRate = legacyDecoder->sample_rate; - aidlDecoder.averageBytesPerSecond = legacyDecoder->avg_bytes_per_sec; - aidlDecoder.blockAlign = legacyDecoder->blk_align; - aidlDecoder.bitsPerSample = legacyDecoder->bits_per_sample; - aidlDecoder.channelMask = legacyDecoder->channel_mask; - aidlDecoder.encoderOption = legacyDecoder->enc_options; - aidlDecoder.reserved = legacyDecoder->reserved; - ALOGI("%s config %s", __func__, aidlDecoder.toString().c_str()); - return std::move(aidlDecoder); -} - -AgmSessionOpusDec LegacyToAidl::convertOpusCompressDecoderToAidl( - struct agm_session_opus_dec *legacyDecoder) { - AgmSessionOpusDec aidlDecoder; - aidlDecoder.bitStreamFormat = legacyDecoder->bitstream_format; - aidlDecoder.type = legacyDecoder->payload_type; - aidlDecoder.version = legacyDecoder->version; - aidlDecoder.channels = legacyDecoder->num_channels; - aidlDecoder.preSkip = legacyDecoder->pre_skip; - aidlDecoder.sampleRate = legacyDecoder->sample_rate; - aidlDecoder.mappingFamily = legacyDecoder->mapping_family; - aidlDecoder.streamCount = legacyDecoder->stream_count; - // both types are uint8 type with predefined size, so use hardcoded values - memcpy(aidlDecoder.channelMap.data(), legacyDecoder->channel_map, 8); - memcpy(aidlDecoder.reserved.data(), legacyDecoder->reserved, 3); - ALOGI("%s config %s", __func__, aidlDecoder.toString().c_str()); - return std::move(aidlDecoder); -} - -AgmSessionAacEnc LegacyToAidl::convertAacCompressEncoderToAidl( - struct agm_session_aac_enc *legacyEncoder) { - AgmSessionAacEnc aidlEncoder; - aidlEncoder.bitRate = legacyEncoder->aac_bit_rate; - aidlEncoder.globalCutOffFrequency = legacyEncoder->global_cutoff_freq; - aidlEncoder.mode = legacyEncoder->enc_cfg.aac_enc_mode; - aidlEncoder.formatFlags = legacyEncoder->enc_cfg.aac_fmt_flag; - ALOGI("%s config %s", __func__, aidlEncoder.toString().c_str()); - return std::move(aidlEncoder); -} - -AgmSessionCodec LegacyToAidl::convertCompressDecoderInfoToAidl( - union agm_session_codec *sessionCodec, agm_media_format format) { - AgmSessionCodec codec; - switch (format) { - case AGM_FORMAT_AAC: { - auto aacDec = convertAacCompressDecoderToAidl(&sessionCodec->aac_dec); - codec = AgmSessionCodec::make(aacDec); - break; - } - case AGM_FORMAT_FLAC: { - auto flacDec = convertFlacCompressDecoderToAidl(&sessionCodec->flac_dec); - codec = AgmSessionCodec::make(flacDec); - break; - } - case AGM_FORMAT_ALAC: { - auto alacDec = convertAlacCompressDecoderToAidl(&sessionCodec->alac_dec); - codec = AgmSessionCodec::make(alacDec); - break; - } - case AGM_FORMAT_APE: { - auto apeDec = convertApeCompressDecoderToAidl(&sessionCodec->ape_dec); - codec = AgmSessionCodec::make(apeDec); - break; - } - case AGM_FORMAT_WMAPRO: { - auto wmaproDec = convertWmaProCompressDecoderToAidl(&sessionCodec->wmapro_dec); - codec = AgmSessionCodec::make(wmaproDec); - break; - } - case AGM_FORMAT_WMASTD: { - auto wmaDec = convertWmaStandardCompressDecoderToAidl(&sessionCodec->wma_dec); - codec = AgmSessionCodec::make(wmaDec); - break; - } - case AGM_FORMAT_OPUS: { - auto opusDec = convertOpusCompressDecoderToAidl(&sessionCodec->opus_dec); - codec = AgmSessionCodec::make(opusDec); - break; - } - default: - break; - } - return codec; -} - -AgmSessionCodec LegacyToAidl::convertCompressEncoderInfoToAidl( - union agm_session_codec *sessionCodec, agm_media_format format) { - AgmSessionCodec codec; - switch (format) { - case AGM_FORMAT_AAC: { - auto enc = convertAacCompressEncoderToAidl(&sessionCodec->aac_enc); - codec = AgmSessionCodec::make(enc); - break; - } - default: - break; - } - return codec; -} - -AgmSessionCodec LegacyToAidl::convertCompressCodecInfoToAidl( - struct agm_session_config *legacyConfig, agm_media_format format) { - if (legacyConfig->dir == RX) { - return convertCompressDecoderInfoToAidl(&legacyConfig->codec, format); - } else if (legacyConfig->dir == TX) { - return convertCompressEncoderInfoToAidl(&legacyConfig->codec, format); - } - return {}; -} - -AgmSessionConfig LegacyToAidl::convertAgmSessionConfigToAidl( - struct agm_session_config *legacyConfig, agm_media_format format) { - AgmSessionConfig aidlConfig; - aidlConfig.direction = static_cast(legacyConfig->dir); - aidlConfig.sessionMode = static_cast(legacyConfig->sess_mode); - aidlConfig.startThreshold = legacyConfig->start_threshold; - aidlConfig.stopThreshold = legacyConfig->stop_threshold; - - // only for compressed formats having configs create configs - if (needsCodecSpecificInfo(format)) { - aidlConfig.codec = convertCompressCodecInfoToAidl(legacyConfig, format); - } - aidlConfig.dataMode = static_cast(legacyConfig->data_mode); - aidlConfig.flags = legacyConfig->sess_flags; - return aidlConfig; -} - -AgmMediaConfig LegacyToAidl::convertAgmMediaConfigToAidl(struct agm_media_config *legacyConfig) { - AgmMediaConfig aidlConfig; - aidlConfig.rate = legacyConfig->rate; - aidlConfig.channels = legacyConfig->channels; - aidlConfig.format = static_cast(legacyConfig->format); - aidlConfig.dataFormat = legacyConfig->data_format; - return aidlConfig; -} - -AgmBufferConfig LegacyToAidl::convertAgmBufferConfigToAidl( - struct agm_buffer_config *buffer_config) { - AgmBufferConfig aidlConfig; - aidlConfig.count = buffer_config->count; - aidlConfig.size = buffer_config->size; - aidlConfig.maxMetadataSize = buffer_config->max_metadata_size; - return aidlConfig; -} - -AgmGroupMediaConfig LegacyToAidl::convertAgmGroupMediaConfigToAidl( - struct agm_group_media_config *legacyConfig) { - AgmGroupMediaConfig aidlConfig; - aidlConfig.rate = legacyConfig->config.rate; - aidlConfig.channels = legacyConfig->config.channels; - aidlConfig.format = - static_cast(legacyConfig->config.format); // return value check?? TODO - aidlConfig.dataFormat = legacyConfig->config.data_format; - aidlConfig.slotMask = legacyConfig->slot_mask; - return aidlConfig; -} - -AgmTagConfig LegacyToAidl::convertAgmTagConfigToAidl(struct agm_tag_config *legacyConfig) { - AgmTagConfig aidlConfig; - aidlConfig.tag = legacyConfig->tag; - aidlConfig.kv.resize(legacyConfig->num_tkvs); - for (unsigned long i = 0; i < legacyConfig->num_tkvs; i++) { - aidlConfig.kv[i].key = legacyConfig->kv[i].key; - aidlConfig.kv[i].value = legacyConfig->kv[i].value; - } - return aidlConfig; -} - -AgmCalConfig LegacyToAidl::convertAgmCalConfigToAidl(struct agm_cal_config *legacyConfig) { - AgmCalConfig aidlConfig; - aidlConfig.kv.resize(legacyConfig->num_ckvs); - for (unsigned long i = 0; i < legacyConfig->num_ckvs; i++) { - aidlConfig.kv[i].key = legacyConfig->kv[i].key; - aidlConfig.kv[i].value = legacyConfig->kv[i].value; - } - return aidlConfig; -} - -AgmEventRegistrationConfig LegacyToAidl::convertAgmEventRegistrationConfigToAidl( - agm_event_reg_cfg *legacyConfig) { - AgmEventRegistrationConfig aidlConfig; - aidlConfig.moduleInstanceId = legacyConfig->module_instance_id; - aidlConfig.eventId = legacyConfig->event_id; - aidlConfig.registerEvent = legacyConfig->is_register; - aidlConfig.eventConfigPayload.resize(legacyConfig->event_config_payload_size); - memcpy(aidlConfig.eventConfigPayload.data(), legacyConfig->event_config_payload, - legacyConfig->event_config_payload_size); - return aidlConfig; -} - -AgmEventCallbackParameter LegacyToAidl::convertAgmEventCallbackParametersToAidl( - struct agm_event_cb_params *legacyParams) { - AgmEventCallbackParameter aidlParams; - aidlParams.sourceModuleId = legacyParams->source_module_id; - aidlParams.eventId = legacyParams->event_id; - aidlParams.eventPayload.resize(legacyParams->event_payload_size); - - memcpy(aidlParams.eventPayload.data(), legacyParams->event_payload, - legacyParams->event_payload_size); - return aidlParams; -} - -std::vector LegacyToAidl::convertRawPayloadToVector(void *payload, size_t size) { - std::vector aidlPayload(size); - memcpy(aidlPayload.data(), payload, size); - return aidlPayload; -} - -/* -* if intToCopy is -1, don't copy, otherwise emplace the int. -*/ - -aidl::android::hardware::common::NativeHandle fdToNativeHandle(int fd, int intToCopy = -1) { - aidl::android::hardware::common::NativeHandle handle; - handle.fds.emplace_back(dup(fd)); - if (intToCopy != -1) handle.ints.emplace_back(intToCopy); - return std::move(handle); -} - -AgmBuff LegacyToAidl::convertAgmBufferToAidl(struct agm_buff *legacyBuffer, bool externalMemory, - bool copyBuffers) { - AgmBuff aidlBuffer; - aidlBuffer.timestamp = legacyBuffer->timestamp; - aidlBuffer.flags = legacyBuffer->flags; - aidlBuffer.size = legacyBuffer->size; - aidlBuffer.buffer.resize(legacyBuffer->size); - - if (copyBuffers) { - if (legacyBuffer->size && legacyBuffer->addr) { - memcpy(aidlBuffer.buffer.data(), legacyBuffer->addr, legacyBuffer->size); - } else { - ALOGE("%s: buf size or addr is null", __func__); - return {}; - } - } - - if (externalMemory) { - aidlBuffer.metadata.resize(legacyBuffer->metadata_size); - if ((legacyBuffer->metadata_size > 0) && legacyBuffer->metadata) { - memcpy(aidlBuffer.metadata.data(), legacyBuffer->metadata, legacyBuffer->metadata_size); - } - - aidlBuffer.externalAllocInfo.allocHandle = fdToNativeHandle( - legacyBuffer->alloc_info.alloc_handle, legacyBuffer->alloc_info.alloc_handle); - aidlBuffer.externalAllocInfo.allocatedSize = legacyBuffer->alloc_info.alloc_size; - aidlBuffer.externalAllocInfo.offset = legacyBuffer->alloc_info.offset; - } - return std::move(aidlBuffer); -} - -int LegacyToAidl::getDupedFdFromAgmEventParams(struct agm_event_cb_params *eventParams) { - struct gsl_event_read_write_done_payload *gslReadWritePayload = - (struct gsl_event_read_write_done_payload *)eventParams->event_payload; - return gslReadWritePayload->buff.alloc_info.alloc_handle; -} - -void LegacyToAidl::cleanUpMetadataMemory(struct agm_event_cb_params *eventParams) { - struct gsl_event_read_write_done_payload *gslReadWritePayload = - (struct gsl_event_read_write_done_payload *)eventParams->event_payload; - if (gslReadWritePayload->buff.metadata) { - free(gslReadWritePayload->buff.metadata); - } -} - -AgmReadWriteEventCallbackParams LegacyToAidl::convertAgmReadWriteEventCallbackParamsToAidl( - struct agm_event_cb_params *eventParams, int inputFd) { - struct gsl_event_read_write_done_payload *gslReadWritePayload = - (struct gsl_event_read_write_done_payload *)eventParams->event_payload; - - AgmBuff agmBuffer; - agmBuffer.timestamp = gslReadWritePayload->buff.timestamp; - agmBuffer.flags = gslReadWritePayload->buff.flags; - agmBuffer.size = gslReadWritePayload->buff.size; - - agmBuffer.externalAllocInfo.allocHandle = - fdToNativeHandle(gslReadWritePayload->buff.alloc_info.alloc_handle, inputFd); - agmBuffer.externalAllocInfo.allocatedSize = gslReadWritePayload->buff.alloc_info.alloc_size; - agmBuffer.externalAllocInfo.offset = gslReadWritePayload->buff.alloc_info.offset; - - if (gslReadWritePayload->buff.metadata_size > 0) { - agmBuffer.metadata.resize(gslReadWritePayload->buff.metadata_size); - memcpy(agmBuffer.metadata.data(), gslReadWritePayload->buff.metadata, - gslReadWritePayload->buff.metadata_size); - } - - AgmEventReadWriteDonePayload readWritePayload; - readWritePayload.tag = gslReadWritePayload->tag; - readWritePayload.status = gslReadWritePayload->status; - readWritePayload.metadataStatus = gslReadWritePayload->md_status; - readWritePayload.buffer = std::move(agmBuffer); - - AgmReadWriteEventCallbackParams aidlReadWriteDoneParams; - aidlReadWriteDoneParams.sourceModuleId = eventParams->source_module_id; - aidlReadWriteDoneParams.eventId = eventParams->event_id; - aidlReadWriteDoneParams.payload = std::move(readWritePayload); - return std::move(aidlReadWriteDoneParams); -} - -void LegacyToAidl::convertMmapBufferInfoToAidl(struct agm_buf_info *agmLegacyBufferInfo, - MmapBufInfo *aidlBufferInfo, int flags) { - if (flags & DATA_BUF) { - ALOGV("%s data fd %d size %d", __func__, agmLegacyBufferInfo->data_buf_fd, - agmLegacyBufferInfo->data_buf_size); - aidlBufferInfo->dataFdHandle = fdToNativeHandle(agmLegacyBufferInfo->data_buf_fd); - aidlBufferInfo->dataSize = agmLegacyBufferInfo->data_buf_size; - } - if (flags & POS_BUF) { - ALOGV("%s pos fd %d size %d ", __func__, agmLegacyBufferInfo->pos_buf_fd, - agmLegacyBufferInfo->pos_buf_size); - aidlBufferInfo->positionFdHandle = fdToNativeHandle(agmLegacyBufferInfo->pos_buf_fd); - aidlBufferInfo->posSize = agmLegacyBufferInfo->pos_buf_size; - } -} - -std::vector LegacyToAidl::convertAifInfoListToAidl(struct aif_info *legacyList, - int listSize) { - std::vector aidlList; - aidlList.resize(listSize); - if (legacyList != NULL) { - for (unsigned long i = 0; i < aidlList.size(); i++) { - aidlList[i].aifName = legacyList[i].aif_name; - aidlList[i].direction = (Direction)legacyList[i].dir; - } - } - return std::move(aidlList); -} diff --git a/qcom/opensource/agm/ipc/aidl/client/AgmCallback.cpp b/qcom/opensource/agm/ipc/aidl/client/AgmCallback.cpp deleted file mode 100755 index 962cc845..00000000 --- a/qcom/opensource/agm/ipc/aidl/client/AgmCallback.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AgmIpc::ClientCallback" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include "AgmCallback.h" - -namespace aidl::vendor::qti::hardware::agm { - -AgmCallback::AgmCallback(uint32_t sessionId, agm_event_cb callback, uint32_t event, - void *clientData) - : mSessionId(sessionId), mCallback(callback), mEvent(event), mClientData(clientData) { - ALOGV("%s , sessionId %d, event %d ", __func__, mSessionId, mEvent); -} - -AgmCallback::~AgmCallback() { - ALOGV("%s dest.. , sessionId %d, event %d ", __func__, mSessionId, mEvent); -} - -::ndk::ScopedAStatus AgmCallback::eventCallback( - const ::aidl::vendor::qti::hardware::agm::AgmEventCallbackParameter &in_eventParam) { - ALOGV("%s size %d event %x, module %08x, mSession %d ", __func__, - in_eventParam.eventPayload.size(), in_eventParam.eventId, in_eventParam.sourceModuleId, - mSessionId); - - int payloadSize = in_eventParam.eventPayload.size(); - struct agm_event_cb_params *agmEventCallbackParam = NULL; - agmEventCallbackParam = (struct agm_event_cb_params *)calloc( - 1, (sizeof(struct agm_event_cb_params) + payloadSize)); - if (!agmEventCallbackParam) { - ALOGE("Not enough memory for agmEventCallbackParam"); - return ::ndk::ScopedAStatus::ok(); - } - - // TODO move to convert - agmEventCallbackParam->event_payload_size = payloadSize; - agmEventCallbackParam->event_id = in_eventParam.eventId; - agmEventCallbackParam->source_module_id = in_eventParam.sourceModuleId; - int8_t *src = (int8_t *)in_eventParam.eventPayload.data(); - int8_t *dst = (int8_t *)agmEventCallbackParam->event_payload; - memcpy(dst, src, payloadSize); - - mCallback(mSessionId, agmEventCallbackParam, mClientData); - free(agmEventCallbackParam); - - return ::ndk::ScopedAStatus::ok(); -} - -::ndk::ScopedAStatus AgmCallback::eventCallbackReadWriteDone( - const ::aidl::vendor::qti::hardware::agm::AgmReadWriteEventCallbackParams - &in_rwDonePayload) { - struct agm_event_cb_params *agmLegacyEventParams = NULL; - struct agm_event_read_write_done_payload agmLegacyReadWriteDonePayload; - struct agm_buff *buffer = &agmLegacyReadWriteDonePayload.buff; - - // memset(&agmLegacyReadWriteDonePayload, 0, sizeof(struct agm_event_read_write_done_payload)); - agmLegacyEventParams = (struct agm_event_cb_params *)calloc( - 1, (sizeof(struct agm_event_cb_params) + - sizeof(struct agm_event_read_write_done_payload))); - if (!agmLegacyEventParams) { - ALOGE("Not enough memory for agmLegacyEventParams"); - return status_tToBinderResult(-ENOMEM); - } - - agmLegacyEventParams->event_payload_size = sizeof(agmLegacyReadWriteDonePayload); - agmLegacyEventParams->event_id = in_rwDonePayload.eventId; - agmLegacyEventParams->source_module_id = in_rwDonePayload.sourceModuleId; - - agmLegacyReadWriteDonePayload.tag = in_rwDonePayload.payload.tag; - agmLegacyReadWriteDonePayload.status = in_rwDonePayload.payload.status; - agmLegacyReadWriteDonePayload.md_status = in_rwDonePayload.payload.metadataStatus; - buffer->timestamp = in_rwDonePayload.payload.buffer.timestamp; - buffer->flags = in_rwDonePayload.payload.buffer.flags; - buffer->size = in_rwDonePayload.payload.buffer.size; - - // fdInfo - auto fdInfo = AidlToLegacy::getFdIntFromNativeHandle( - in_rwDonePayload.payload.buffer.externalAllocInfo.allocHandle, false /*dodup*/); - - buffer->alloc_info.alloc_handle = fdInfo.second; // allochandle->data[1]; - ALOGV("alloc handleinput[0] %d and input[1] %d ", fdInfo.first, fdInfo.second); - buffer->alloc_info.alloc_size = in_rwDonePayload.payload.buffer.externalAllocInfo.allocatedSize; - buffer->alloc_info.offset = in_rwDonePayload.payload.buffer.externalAllocInfo.offset; - - if (!in_rwDonePayload.payload.buffer.metadata.empty()) { - buffer->metadata_size = in_rwDonePayload.payload.buffer.metadata.size(); - buffer->metadata = (uint8_t *)calloc(1, buffer->metadata_size); - if (!buffer->metadata) { - ALOGE("Not enough memory for buffer->metadata"); - free(agmLegacyEventParams); - return status_tToBinderResult(-ENOMEM); - } - memcpy(buffer->metadata, in_rwDonePayload.payload.buffer.metadata.data(), - buffer->metadata_size); - } - memcpy(agmLegacyEventParams->event_payload, &agmLegacyReadWriteDonePayload, - sizeof(agmLegacyReadWriteDonePayload)); - - mCallback(mSessionId, agmLegacyEventParams, mClientData); - if (buffer->metadata) free(buffer->metadata); - free(agmLegacyEventParams); - return ::ndk::ScopedAStatus::ok(); -} -} diff --git a/qcom/opensource/agm/ipc/aidl/client/AgmCallback.h b/qcom/opensource/agm/ipc/aidl/client/AgmCallback.h deleted file mode 100755 index a23aa056..00000000 --- a/qcom/opensource/agm/ipc/aidl/client/AgmCallback.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace aidl::vendor::qti::hardware::agm { -class AgmCallback : public BnAGMCallback { - public: - AgmCallback(uint32_t sessionId, agm_event_cb callback, uint32_t event, void* clientData); - virtual ~AgmCallback(); - - ::ndk::ScopedAStatus eventCallback( - const ::aidl::vendor::qti::hardware::agm::AgmEventCallbackParameter& in_eventParam) - override; - - ::ndk::ScopedAStatus eventCallbackReadWriteDone( - const ::aidl::vendor::qti::hardware::agm::AgmReadWriteEventCallbackParams& - in_rwDonePayload) override; - - private: - uint32_t mSessionId = 0; - agm_event_cb mCallback = NULL; - uint32_t mEvent = 0; - void* mClientData = NULL; -}; -} \ No newline at end of file diff --git a/qcom/opensource/agm/ipc/aidl/client/AgmClientWrapper.cpp b/qcom/opensource/agm/ipc/aidl/client/AgmClientWrapper.cpp deleted file mode 100755 index 131693a1..00000000 --- a/qcom/opensource/agm/ipc/aidl/client/AgmClientWrapper.cpp +++ /dev/null @@ -1,654 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define NDEBUG 0 -#define LOG_TAG "AgmIpc::Client" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include "AgmCallback.h" - -using ::aidl::vendor::qti::hardware::agm::IAGM; -using ::aidl::vendor::qti::hardware::agm::IAGMCallback; -using ::aidl::vendor::qti::hardware::agm::AidlToLegacy; -using ::aidl::vendor::qti::hardware::agm::AgmSessionMode; -using ::aidl::vendor::qti::hardware::agm::AifInfo; -using ::aidl::vendor::qti::hardware::agm::AgmCallback; -using ::aidl::vendor::qti::hardware::agm::MmapBufInfo; - -static std::shared_ptr gAgmClient = nullptr; -static ::ndk::ScopedAIBinder_DeathRecipient gDeathRecipient; -std::mutex gLock; - -#define RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client) \ - ({ \ - if (client.get() == nullptr) { \ - ALOGE(" %s Agm service doesn't exist ", __func__); \ - return -EINVAL; \ - } \ - }) - -void serviceDied(void *cookie) { - ALOGE("%s : AGM Service died ,cookie : %llu", __func__, (unsigned long long)cookie); - std::lock_guard guard(gLock); - gAgmClient = nullptr; -} - -std::shared_ptr getAgm() { - std::lock_guard guard(gLock); - if (gAgmClient == nullptr) { - const std::string instance = std::string() + IAGM::descriptor + "/default"; - ABinderProcess_startThreadPool(); - auto binder = ::ndk::SpAIBinder(AServiceManager_waitForService(instance.c_str())); - ALOGV("%s got binder %p", __func__, binder.get()); - - auto newClient = IAGM::fromBinder(binder); - - if (newClient == nullptr) { - ALOGE("could not get agmclient fromBinder"); - return nullptr; - } - gAgmClient = newClient; - ALOGI("%s gAgmClient %p ", __func__, gAgmClient.get()); - - gDeathRecipient = - ::ndk::ScopedAIBinder_DeathRecipient(AIBinder_DeathRecipient_new(&serviceDied)); - auto status = ::ndk::ScopedAStatus::fromStatus( - AIBinder_linkToDeath(binder.get(), gDeathRecipient.get(), (void *)serviceDied)); - - if (!status.isOk()) { - ALOGV("linking service to death failed: %d: %s", status.getStatus(), - status.getMessage()); - } else { - ALOGI("linked to death %d: %s", status.getStatus(), status.getMessage()); - } - } - ALOGV("%s gAgmClient %p ", __func__, gAgmClient.get()); - return gAgmClient; -} - -int agm_register_service_crash_callback(agm_service_crash_cb cb, uint64_t cookie) { - return 0; -} - -int agm_aif_set_media_config(uint32_t audio_intf, struct agm_media_config *media_config) { - ALOGV("%s audio_intf = %d", __func__, audio_intf); - - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlConfig = LegacyToAidl::convertAgmMediaConfigToAidl(media_config); - return statusTFromBinderStatus(client->ipc_agm_aif_set_media_config(audio_intf, aidlConfig)); -} - -int agm_session_set_config(uint64_t handle, struct agm_session_config *session_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config) { - ALOGV("%s handle = %llx ", __func__, (unsigned long long)handle); - - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlSessionConfig = - LegacyToAidl::convertAgmSessionConfigToAidl(session_config, media_config->format); - auto aidlMediaConfig = LegacyToAidl::convertAgmMediaConfigToAidl(media_config); - auto aidlBufferConfig = LegacyToAidl::convertAgmBufferConfigToAidl(buffer_config); - - return statusTFromBinderStatus(client->ipc_agm_session_set_config( - handle, aidlSessionConfig, aidlMediaConfig, aidlBufferConfig)); -} - -int agm_init() { - return 0; -} - -int agm_deinit() { - return 0; -} - -int agm_aif_set_metadata(uint32_t audio_intf, uint32_t size, uint8_t *metadata) { - ALOGV("%s audio_intf = %d, size =%d ", __func__, audio_intf, size); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlMetadata = LegacyToAidl::convertRawPayloadToVector(metadata, size); - - return statusTFromBinderStatus(client->ipc_agm_aif_set_metadata(audio_intf, aidlMetadata)); -} - -int agm_session_set_metadata(uint32_t session_id, uint32_t size, uint8_t *metadata) { - ALOGV("%s session_id = %d, size = %d", __func__, session_id, size); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlMetadata = LegacyToAidl::convertRawPayloadToVector(metadata, size); - - return statusTFromBinderStatus(client->ipc_agm_session_set_metadata(session_id, aidlMetadata)); -} - -int agm_session_aif_set_metadata(uint32_t session_id, uint32_t audio_intf, uint32_t size, - uint8_t *metadata) { - ALOGV("%s session_id = %d, aif = %d, size = %d", __func__, session_id, audio_intf, size); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlMetadata = LegacyToAidl::convertRawPayloadToVector(metadata, size); - - return statusTFromBinderStatus( - client->ipc_agm_session_aif_set_metadata(session_id, audio_intf, aidlMetadata)); -} - -int agm_session_close(uint64_t handle) { - ALOGV("%s handle = %llx ", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus(client->ipc_agm_session_close(handle)); -} - -int agm_session_prepare(uint64_t handle) { - ALOGV("%s handle = %llx ", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus(client->ipc_agm_session_prepare(handle)); -} - -int agm_session_start(uint64_t handle) { - ALOGV("%s handle = %llx ", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - return statusTFromBinderStatus(client->ipc_agm_session_start(handle)); -} - -int agm_session_stop(uint64_t handle) { - ALOGV("%s handle = %llx ", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus(client->ipc_agm_session_stop(handle)); -} - -int agm_session_pause(uint64_t handle) { - ALOGV("%s handle = %llx ", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus(client->ipc_agm_session_pause(handle)); -} - -int agm_session_flush(uint64_t handle) { - ALOGV("%s handle = %llx ", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus(client->ipc_agm_session_flush(handle)); -} - -int agm_sessionid_flush(uint32_t session_id) { - ALOGV("%s session id = %d", __func__, session_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus(client->ipc_agm_sessionid_flush(session_id)); -} - -int agm_session_resume(uint64_t handle) { - ALOGV("%s handle = %llx ", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus(client->ipc_agm_session_resume(handle)); -} - -int agm_session_suspend(uint64_t handle) { - ALOGV("%s handle = %llx ", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus(client->ipc_agm_session_suspend(handle)); -} - -int agm_session_open(uint32_t session_id, enum agm_session_mode sess_mode, uint64_t *handle) { - ALOGV("%s handle = %x , *handle = %x", __func__, handle, *handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlSessionMode = static_cast(sess_mode); - int64_t aidlHandle; - auto aidlStatus = client->ipc_agm_session_open(session_id, aidlSessionMode, &aidlHandle); - - *handle = convertAidlHandleToLegacy(aidlHandle); - auto ret = statusTFromBinderStatus(aidlStatus); - ALOGV("%s Received handle = %p, ret %d", __func__, (unsigned long long)*handle, ret); - - return ret; -} - -int agm_session_aif_connect(uint32_t session_id, uint32_t audio_intf, bool state) { - ALOGV("%s session_id =%d, aif = %d, state = %s", __func__, session_id, audio_intf, - state ? "true" : "false"); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus( - client->ipc_agm_session_aif_connect(session_id, audio_intf, state)); -} - -int agm_session_read(uint64_t handle, void *buf, size_t *byte_count) { - ALOGV("%s handle = %llx", __func__, (unsigned long long)handle); - - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - int32_t bytesToRead = (int32_t)(*byte_count); - std::vector aidlReturn; - - auto status = client->ipc_agm_session_read(handle, bytesToRead, &aidlReturn); - - if (status.isOk()) { - memcpy(buf, aidlReturn.data(), aidlReturn.size()); - *byte_count = aidlReturn.size(); - } - return statusTFromBinderStatus(status); -} - -int agm_session_write(uint64_t handle, void *buf, size_t *byte_count) { - ALOGV("%s handle = %llx, bytes %d ", __func__, (unsigned long long)handle, *byte_count); - - auto client = getAgm(); - - auto aidlBuffer = LegacyToAidl::convertRawPayloadToVector(buf, *byte_count); - - int32_t bytesWritten = 0; - auto ret = statusTFromBinderStatus( - client->ipc_agm_session_write(handle, aidlBuffer, &bytesWritten), __func__); - - if (ret != -ENOMEM) { - *byte_count = (size_t)bytesWritten; - } - - return ret; -} - -int agm_session_set_loopback(uint32_t capture_session_id, uint32_t playback_session_id, - bool state) { - ALOGV("%s called capture_session_id = %d, playback_session_id = %d", __func__, - capture_session_id, playback_session_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus( - client->ipc_agm_session_set_loopback(capture_session_id, playback_session_id, state)); -} - -size_t agm_get_hw_processed_buff_cnt(uint64_t handle, enum direction dir) { - ALOGV("%s handle = %llx", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlDirection = static_cast(dir); - return statusTFromBinderStatus( - client->ipc_agm_get_hw_processed_buff_cnt(handle, aidlDirection)); -} - -int agm_get_aif_info_list(struct aif_info *aif_list, size_t *num_aif_info) { - ALOGV("%s: Enter: noOfAif %d, aifListEmpty %d", __func__, *num_aif_info, (aif_list == NULL)); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - std::vector aidlAifList; - auto aidlStatus = client->ipc_agm_get_aif_info_list((int32_t)(*num_aif_info), &aidlAifList); - - if (aif_list != NULL) { - AidlToLegacy::convertAifInfoList(aidlAifList, aif_list); - } - - *num_aif_info = (size_t)aidlAifList.size(); - auto ret = statusTFromBinderStatus(aidlStatus); - ALOGV("%s: Exit size %d ret %d ", __func__, *num_aif_info); - return ret; -} - -int agm_session_aif_get_tag_module_info(uint32_t session_id, uint32_t aif_id, void *payload, - size_t *size) { - ALOGV("%s session_id =%d, aif_id = %d", __func__, session_id, aif_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - uint32_t aidlListSize = *size; // TODO cast - std::vector aidlModuleInfoList; - auto status = client->ipc_agm_session_aif_get_tag_module_info(session_id, aif_id, aidlListSize, - &aidlModuleInfoList); - if (status.isOk()) { - if (payload != NULL) memcpy(payload, aidlModuleInfoList.data(), aidlModuleInfoList.size()); - *size = aidlModuleInfoList.size(); - } - auto ret = statusTFromBinderStatus(status); - ALOGV("%s session_id =%d, aif_id = %d ret %d, size %d ", __func__, session_id, aif_id, ret, - *size); - return ret; -} - -int agm_session_get_params(uint32_t session_id, void *payload, size_t size) { - ALOGV("%s sessionId %d size %d ", __func__, session_id, size); - auto client = getAgm(); - - if (size <= 0) { - ALOGE("%s sessionId %d : Invalid input size %d ", __func__, session_id, size); - return -EINVAL; - } - - auto aidlPayload = LegacyToAidl::convertRawPayloadToVector(payload, size); - - std::vector aidlReturn; - auto status = client->ipc_agm_session_get_params(session_id, aidlPayload, &aidlReturn); - - if (aidlReturn.empty()) { - ALOGE("%s sessionId %d : Invalid input size %d ", __func__, session_id, size); - return -ENOMEM; - } - - if (status.isOk() && payload) { - memcpy(payload, aidlReturn.data(), size); - } - - return statusTFromBinderStatus(status); -} - -int agm_aif_set_params(uint32_t aif_id, void *payload, size_t size) { - ALOGV("%s aif_id = %d", __func__, aif_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlPayload = LegacyToAidl::convertRawPayloadToVector(payload, size); - - return statusTFromBinderStatus(client->ipc_agm_aif_set_params(aif_id, aidlPayload)); -} - -int agm_session_aif_set_params(uint32_t session_id, uint32_t aif_id, void *payload, size_t size) { - ALOGV("%s session_id =%d, aif_id = %d", __func__, session_id, aif_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlPayload = LegacyToAidl::convertRawPayloadToVector(payload, size); - - return statusTFromBinderStatus( - client->ipc_agm_session_aif_set_params(session_id, aif_id, aidlPayload)); -} - -int agm_session_set_params(uint32_t session_id, void *payload, size_t size) { - ALOGV("%s session_id =%d, size = %zu", __func__, session_id, size); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlPayload = LegacyToAidl::convertRawPayloadToVector(payload, size); - - return statusTFromBinderStatus(client->ipc_agm_session_set_params(session_id, aidlPayload)); -} - -int agm_set_params_with_tag(uint32_t session_id, uint32_t aif_id, - struct agm_tag_config *tag_config) { - ALOGV("%s session_id =%d, aif_id = %d", __func__, session_id, aif_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlTagConfig = LegacyToAidl::convertAgmTagConfigToAidl(tag_config); - - return statusTFromBinderStatus( - client->ipc_agm_set_params_with_tag(session_id, aif_id, aidlTagConfig)); -} - -int agm_set_params_with_tag_to_acdb(uint32_t session_id, uint32_t aif_id, void *payload, - size_t size) { - ALOGV("%s session_id =%d, aif_id = %d", __func__, session_id, aif_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - auto aidlPayload = LegacyToAidl::convertRawPayloadToVector(payload, size); - return statusTFromBinderStatus( - client->ipc_agm_set_params_with_tag_to_acdb(session_id, aif_id, aidlPayload)); -} - -int agm_set_params_to_acdb_tunnel(void *payload, size_t size) { - ALOGV("%s size = %d", __func__, size); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlPayload = LegacyToAidl::convertRawPayloadToVector(payload, size); - - return statusTFromBinderStatus(client->ipc_agm_set_params_to_acdb_tunnel(aidlPayload)); -} - -int agm_get_params_from_acdb_tunnel(void *payload, size_t *size) { - ALOGV("%s size = %d", __func__, size); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlPayload = LegacyToAidl::convertRawPayloadToVector(payload, *size); - - std::vector aidlReturn; - auto status = client->ipc_agm_get_params_from_acdb_tunnel(aidlPayload, &aidlReturn); - - if (status.isOk() && payload != NULL) { - memcpy(payload, aidlReturn.data(), aidlReturn.size()); - *size = aidlReturn.size(); - } - - return statusTFromBinderStatus(status); -} - -int agm_session_register_for_events(uint32_t session_id, struct agm_event_reg_cfg *evt_reg_cfg) { - ALOGV("%s session_id =%d size %d ", __func__, session_id, - evt_reg_cfg->event_config_payload_size); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlAgmEventRegConfig = LegacyToAidl::convertAgmEventRegistrationConfigToAidl(evt_reg_cfg); - - auto status = client->ipc_agm_session_register_for_events(session_id, aidlAgmEventRegConfig); - return statusTFromBinderStatus(status); -} - -int agm_session_aif_set_cal(uint32_t session_id, uint32_t aif_id, - struct agm_cal_config *cal_config) { - ALOGV("%s session_id =%d, aif_id = %d", __func__, session_id, aif_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlCalConfig = LegacyToAidl::convertAgmCalConfigToAidl(cal_config); - return statusTFromBinderStatus( - client->ipc_agm_session_aif_set_cal(session_id, aif_id, aidlCalConfig)); -} - -int agm_session_set_ec_ref(uint32_t capture_session_id, uint32_t aif_id, bool state) { - ALOGV("%s : capture_session_id = %d, aif_id = %d ", __func__, capture_session_id, aif_id); - - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - return statusTFromBinderStatus( - client->ipc_agm_session_set_ec_ref(capture_session_id, aif_id, state)); -} - -int agm_session_register_cb(uint32_t session_id, agm_event_cb cb, enum event_type evt_type, - void *client_data) { - ALOGV("%s session_id =%d, evt_type = %d, client_data = %p , register %d ", __func__, session_id, - evt_type, client_data, (cb != NULL)); - - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - std::shared_ptr aidlAgmCallback; - if (cb != NULL) { - aidlAgmCallback = - ::ndk::SharedRefBase::make(session_id, cb, evt_type, client_data); - ALOGV("%s, creating new callback %p agm ptr %p ", __func__, aidlAgmCallback.get(), cb); - } - - int64_t clientDataAidl = reinterpret_cast(client_data); - auto status = client->ipc_agm_session_register_callback(aidlAgmCallback, session_id, evt_type, - (cb != NULL), clientDataAidl); - return statusTFromBinderStatus(status); -} - -int agm_session_eos(uint64_t handle) { - ALOGV("%s handle = %llx", __func__, (unsigned long long)handle); - - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - return statusTFromBinderStatus(client->ipc_agm_session_eos(handle)); -} - -int agm_get_session_time(uint64_t handle, uint64_t *timestamp) { - ALOGV("%s handle = %llx", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - int64_t aidlTimestamp; - auto status = client->ipc_agm_get_session_time(handle, &aidlTimestamp); - - *timestamp = aidlTimestamp; - return statusTFromBinderStatus(status); -} - -int agm_get_buffer_timestamp(uint32_t session_id, uint64_t *timestamp) { - ALOGV("%s: session_id = %d", __func__, session_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - int64_t aidlTimestamp; - auto status = client->ipc_agm_get_buffer_timestamp(session_id, &aidlTimestamp); - *timestamp = aidlTimestamp; - return statusTFromBinderStatus(status); -} - -int agm_session_get_buf_info(uint32_t session_id, struct agm_buf_info *buf_info, uint32_t flag) { - ALOGV("%s: session_id = %d flag %d", __func__, session_id, flag); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - MmapBufInfo aidlMmapBufRet; - auto status = client->ipc_agm_session_get_buf_info(session_id, flag, &aidlMmapBufRet); - if (status.isOk()) { - AidlToLegacy::convertMmapBufInfo(aidlMmapBufRet, buf_info, flag); - } - return statusTFromBinderStatus(status); -} - -int agm_set_gapless_session_metadata(uint64_t handle, enum agm_gapless_silence_type type, - uint32_t silence) { - ALOGV("%s handle = %x", __func__, handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - AgmGaplessSilenceType aidlSilenceType = static_cast(type); - - return statusTFromBinderStatus( - client->ipc_agm_set_gapless_session_metadata(handle, aidlSilenceType, silence)); -} - -int agm_session_set_non_tunnel_mode_config(uint64_t handle, - struct agm_session_config *session_config, - struct agm_media_config *in_media_config, - struct agm_media_config *out_media_config, - struct agm_buffer_config *in_buffer_config, - struct agm_buffer_config *out_buffer_config) { - ALOGV("%s handle = %llx", __func__, (unsigned long long)handle); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlSessionConfig = - LegacyToAidl::convertAgmSessionConfigToAidl(session_config, in_media_config->format); - auto aidlInMediaConfig = LegacyToAidl::convertAgmMediaConfigToAidl(in_media_config); - auto aidlOutMediaConfig = LegacyToAidl::convertAgmMediaConfigToAidl(out_media_config); - auto aidlInBufferConfig = LegacyToAidl::convertAgmBufferConfigToAidl(in_buffer_config); - auto aidlOutBufferConfig = LegacyToAidl::convertAgmBufferConfigToAidl(out_buffer_config); - - return statusTFromBinderStatus(client->ipc_agm_session_set_non_tunnel_mode_config( - handle, aidlSessionConfig, aidlInMediaConfig, aidlOutMediaConfig, aidlInBufferConfig, - aidlOutBufferConfig)); -} - -int agm_session_write_with_metadata(uint64_t handle, struct agm_buff *buf, size_t *consumed_size) { - ALOGV("%s handle = %x", __func__, handle); - - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlBuffer = LegacyToAidl::convertAgmBufferToAidl(buf, true, false); - int32_t written = 0; - auto status = client->ipc_agm_session_write_with_metadata(handle, aidlBuffer, &written); - if (status.isOk()) { - *consumed_size = written; - } - return statusTFromBinderStatus(status); -} - -int agm_session_read_with_metadata(uint64_t handle, struct agm_buff *buf, uint32_t *captured_size) { - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlBuffer = LegacyToAidl::convertAgmBufferToAidl(buf, true, false /*copyBuffer*/); - - IAGM::AgmReadWithMetadataReturn aidlReturn; - // TODO change the API, on read return don't need AgmBuffer. - auto status = client->ipc_agm_session_read_with_metadata(handle, aidlBuffer, *captured_size, - &aidlReturn); - - return statusTFromBinderStatus(status); -} - -int agm_aif_group_set_media_config(uint32_t group_id, struct agm_group_media_config *media_config) { - ALOGV("%s called, group_id = %d ", __func__, group_id); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlConfig = LegacyToAidl::convertAgmGroupMediaConfigToAidl(media_config); - - return statusTFromBinderStatus( - client->ipc_agm_aif_group_set_media_config(group_id, aidlConfig)); -} - -int agm_get_group_aif_info_list(struct aif_info *aif_list, size_t *num_groups) { - ALOGV("%s called ", __func__); - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - std::vector aidlAifList; - auto aidlStatus = client->ipc_agm_get_group_aif_info_list((int32_t)(*num_groups), &aidlAifList); - - if (aif_list != NULL) { - AidlToLegacy::convertAifInfoList(aidlAifList, aif_list); - } - - *num_groups = (size_t)aidlAifList.size(); - ALOGV("%s: Exit size %d ", __func__, *num_groups); - return statusTFromBinderStatus(aidlStatus); -} - -int agm_session_write_datapath_params(uint32_t session_id, struct agm_buff *buf) { - ALOGV("%s session id = %d ", __func__, session_id); - - auto client = getAgm(); - RETURN_IF_AGM_SERVICE_NOT_REGISTERED(client); - - auto aidlBuffer = LegacyToAidl::convertAgmBufferToAidl(buf, false, true /*copyBuffer*/); - - return statusTFromBinderStatus( - client->ipc_agm_session_write_datapath_params(session_id, aidlBuffer)); -} - -int agm_dump(struct agm_dump_info *dump_info) { - return 0; -} diff --git a/qcom/opensource/agm/ipc/aidl/client/Android.mk b/qcom/opensource/agm/ipc/aidl/client/Android.mk deleted file mode 100755 index e780fb3f..00000000 --- a/qcom/opensource/agm/ipc/aidl/client/Android.mk +++ /dev/null @@ -1,26 +0,0 @@ -LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) -LOCAL_MODULE := libagmclient -LOCAL_MODULE_OWNER := qti -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -v -Wall -Wthread-safety -LOCAL_TIDY := true - -LOCAL_SRC_FILES := \ - AgmClientWrapper.cpp \ - AgmCallback.cpp - -LOCAL_SHARED_LIBRARIES := \ - liblog \ - libbase \ - libcutils \ - libutils \ - vendor.qti.hardware.agm-V1-ndk \ - libbinder_ndk - -LOCAL_STATIC_LIBRARIES := libagmaidltypeconverter libaidlcommonsupport - -LOCAL_HEADER_LIBRARIES := libagm_headers - -include $(BUILD_SHARED_LIBRARY) diff --git a/qcom/opensource/agm/ipc/aidl/server/AgmServerWrapper.cpp b/qcom/opensource/agm/ipc/aidl/server/AgmServerWrapper.cpp deleted file mode 100755 index 0212b7ca..00000000 --- a/qcom/opensource/agm/ipc/aidl/server/AgmServerWrapper.cpp +++ /dev/null @@ -1,945 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - - -#define NDEBUG 0 -#define LOG_TAG "AgmIpc::Server" - -#include -#include -#include - -#include "AgmServerWrapper.h" - -#include -#include -#include -#include -#include "gsl_intf.h" -using ndk::ScopedAStatus; - -namespace aidl::vendor::qti::hardware::agm { - -void SessionInfo::dump() { - ALOGV("session Id %d handle %llx, aif size %d", mSessionId, mHandle, mAifIds.size()); -} - -SessionInfo::~SessionInfo() { - ALOGV("%s session Id %d handle %llx, noOfAifs %d fdPairs %d", __func__, mSessionId, mHandle, - mAifIds.size(), mInOutFdPairs.size()); -} - -void SessionInfo::forceCloseSession() { - std::lock_guard guard(mLock); - if (mHandle) { - ALOGV("force closing session with handle %llx", mHandle); - agm_session_close(mHandle); - } - - // force clean up of aifIds. - for (const auto &aifId : mAifIds) { - agm_session_aif_set_params(mSessionId, aifId, NULL, 0); - agm_session_aif_connect(mSessionId, aifId, false); - agm_session_aif_set_metadata(mSessionId, aifId, 0, NULL); - } - - agm_session_set_metadata(mSessionId, 0, NULL); - agm_session_set_params(mSessionId, NULL, 0); -} - -void SessionInfo::connectSessionAif(uint32_t aifId, bool state) { - std::lock_guard guard(mLock); - ALOGV("%s session %d aifId %d state %d aif size %d ", __func__, mSessionId, aifId, state, - mAifIds.size()); - if (state) { - mAifIds.insert(aifId); - } else { - mAifIds.erase(aifId); - } - ALOGV("%s session %d aifId %d state %d aif size %d ", __func__, mSessionId, aifId, state, - mAifIds.size()); -} - -void SessionInfo::addSharedMemoryFdPairs(int inputFd, int dupFd) { - std::lock_guard guard(mLock); - ALOGV("%s session %d Fds[input %d - dup %d] size %d", __func__, mSessionId, inputFd, dupFd, - mInOutFdPairs.size()); - mInOutFdPairs.push_back(std::make_pair(inputFd, dupFd)); -} - -int SessionInfo::removeSharedMemoryFdPairs(int dupFd) { - std::lock_guard guard(mLock); - auto itr = mInOutFdPairs.begin(); - auto inputFd = -1; - for (; itr != mInOutFdPairs.end(); itr++) { - if (itr->second == dupFd) { - inputFd = itr->first; - itr = mInOutFdPairs.erase(itr); - break; - } - } - ALOGV("%s session %d Fds[input %d - dup %d] size %d", __func__, mSessionId, inputFd, dupFd, - mInOutFdPairs.size()); - return inputFd; -} - -AgmServerWrapper *ClientInfo::sAgmServerWrapper = nullptr; -void ClientInfo::setAgmServerWrapper(AgmServerWrapper *wrapper) { - sAgmServerWrapper = wrapper; -} - -void ClientInfo::onDeath(void *cookie) { - ClientInfo *client = static_cast(cookie); - ALOGI("Client died (pid): %llu", client->getPid()); - client->onDeath(); -} - -void ClientInfo::onDeath() { - sAgmServerWrapper->removeClient(mPid); -} - -void ClientInfo::registerCallback(const std::shared_ptr &callback, - int32_t in_sessionId, int32_t in_eventType, - int64_t in_clientData) { - std::lock_guard guard(mCallbackLock); - ALOGV("%s, adding callback for session %d size %d ", __func__, in_sessionId, - mCallbackInfo.size()); - agm_session_register_cb(in_sessionId, &ClientInfo::onCallback, (enum event_type)in_eventType, - (void *)callback.get()); - - auto linkRet = AIBinder_linkToDeath(callback->asBinder().get(), mDeathRecipient.get(), - this /* cookie */); - if (linkRet != STATUS_OK) { - ALOGV("%s, linkToDeath failed pid %d", __func__, mPid); - } else { - ALOGV("%s, linkToDeath success for client pid %d", __func__, mPid); - } - auto callbackInfo = - std::make_shared(callback, in_sessionId, in_eventType, in_clientData); - mCallbackInfo.emplace_back(callbackInfo); -} - -void ClientInfo::unregisterCallback(int32_t in_sessionId, int32_t in_eventType, - int64_t in_clientData) { - // remove based on sessionid, eventType, clientData from CallbackInfos. - std::lock_guard guard(mCallbackLock); - ALOGV("%s, before removing callback for session %d size %d ", __func__, in_sessionId, - mCallbackInfo.size()); - auto itr = std::find_if(mCallbackInfo.begin(), mCallbackInfo.end(), - [=](const std::shared_ptr &callback) { - return ((callback->getSessionId() == in_sessionId) && - (callback->getEventType() == in_eventType) && - (callback->getClientData() == in_clientData)); - }); - - std::shared_ptr registeredCallback = nullptr; - if (itr != mCallbackInfo.end()) { - registeredCallback = (*itr)->getCallback(); - agm_session_register_cb(in_sessionId, NULL, (enum event_type)in_eventType, - (void *)registeredCallback.get()); - mCallbackInfo.erase(itr); - AIBinder_unlinkToDeath(registeredCallback->asBinder().get(), mDeathRecipient.get(), - nullptr); - } - - ALOGV("%s, removing callback for session %d size %d ", __func__, in_sessionId, - mCallbackInfo.size()); -} - -void ClientInfo::clearCallbacks() { - std::lock_guard guard(mCallbackLock); - ALOGV("client going out of scope clear callback of size %d", mCallbackInfo.size()); - for (const auto &callback : mCallbackInfo) { - // unregister at agm level.. - agm_session_register_cb(callback->getSessionId(), NULL, - (enum event_type)callback->getEventType(), - (void *)callback->getCallback().get()); - } - mCallbackInfo.clear(); -} - -void ClientInfo::clearSessions() { - std::lock_guard guard(mSessionLock); - ALOGI("%s session size %d ", __func__, mSessionsInfoMap.size()); - for (const auto &session : mSessionsInfoMap) { - session.second->forceCloseSession(); - } - mSessionsInfoMap.clear(); -} - -std::shared_ptr ClientInfo::getSessionInfo_l(int32_t sessionId) { - if (mSessionsInfoMap.count(sessionId) == 0) { - ALOGV("new session %d ", sessionId); - mSessionsInfoMap[sessionId] = std::make_shared(sessionId); - } - return mSessionsInfoMap[sessionId]; -} - -void ClientInfo::addSessionHandle(uint32_t sessionId, uint64_t handle) { - std::lock_guard guard(mSessionLock); - - auto sessionInfo = getSessionInfo_l(sessionId); - sessionInfo->setHandle(handle); - ALOGI("%s sessionId %d handle %llx ", __func__, sessionId, handle); -} - -void ClientInfo::removeSessionHandle(uint64_t handle) { - std::lock_guard guard(mSessionLock); - ALOGV("%s, removeSessionhandle %llx in session of size %d ", __func__, handle, - mSessionsInfoMap.size()); - auto itr = mSessionsInfoMap.begin(); - for (; itr != mSessionsInfoMap.end();) { - auto sessionInfo = itr->second; - if (handle == sessionInfo->getHandle()) { - ALOGI("%s removing handle %llx for session %d", __func__, handle, itr->first); - mSessionsInfoMap.erase(itr); // TODO current behavior is similar to HIDL, on close -> - // remove sessionhandle - break; - } - itr++; - } - ALOGV("%s, Exit: removeSessionhandle %llx in session of size %d ", __func__, handle, - mSessionsInfoMap.size()); -} - -void ClientInfo::connectSessionAif(uint32_t sessionId, uint32_t aifId, bool state) { - std::lock_guard guard(mSessionLock); - ALOGV("%s sessionId %d aifId %d state %d", __func__, sessionId, aifId, state); - auto sessionInfo = getSessionInfo_l(sessionId); - sessionInfo->connectSessionAif(aifId, state); -} - -void ClientInfo::cleanup() { - // Do a cleanup related to client going out of scope. - ALOGI("%s client %d callbacks %d sessions %d ", __func__, mPid, - mCallbackInfo.size(), mSessionsInfoMap.size()); - clearCallbacks(); - clearSessions(); -} - -void ClientInfo::addSharedMemoryFdPairs(uint64_t handle, int inputFd, int dupFd) { - std::lock_guard guard(mSessionLock); - ALOGV("%s handle %llx, inputFd %d dupFd %d sessionSize %d", __func__, handle, inputFd, dupFd, - mSessionsInfoMap.size()); - for (auto &sessionInfo : mSessionsInfoMap) { - auto &sessionInfoObj = sessionInfo.second; - if (sessionInfoObj->getHandle() == handle) { - sessionInfoObj->addSharedMemoryFdPairs(inputFd, dupFd); - break; - } - } -} - -int ClientInfo::removeSharedMemoryFdPairs(uint32_t sessionId, int dupFd) { - std::lock_guard guard(mSessionLock); - - auto inputFd = -1; - for (auto &sessionInfo : mSessionsInfoMap) { - auto &sessionInfoObj = sessionInfo.second; - if (sessionInfo.first == sessionId) { - inputFd = sessionInfoObj->removeSharedMemoryFdPairs(dupFd); - break; - } - } - ALOGV("%s sessionId %d, inputFd %d dupFd %d sessionSize %d", __func__, sessionId, inputFd, - dupFd, mSessionsInfoMap.size()); - return inputFd; -} - -void ClientInfo::onCallback(uint32_t sessionId, struct agm_event_cb_params *eventParams, - void *clientData) { - uint32_t eventId = eventParams->event_id; - - IAGMCallback *callback = reinterpret_cast(clientData); - - if (!AIBinder_isAlive(callback->asBinder().get())) { - ALOGW("callback binder has died"); - return; - } - - if ((eventParams->event_payload_size > 0) && - ((eventId == AGM_EVENT_READ_DONE) || (eventId == AGM_EVENT_WRITE_DONE))) { - int dupFd = LegacyToAidl::getDupedFdFromAgmEventParams(eventParams); - int inputFd = sAgmServerWrapper->removeSharedMemoryFdPairs(sessionId, dupFd); - auto aidlReadWriteDoneParams = - LegacyToAidl::convertAgmReadWriteEventCallbackParamsToAidl(eventParams, inputFd); - callback->eventCallbackReadWriteDone(aidlReadWriteDoneParams); - LegacyToAidl::cleanUpMetadataMemory(eventParams); - } else { - auto aidlEventParams = LegacyToAidl::convertAgmEventCallbackParametersToAidl(eventParams); - callback->eventCallback(aidlEventParams); - } -} - -inline uint64_t convertAidlHandleToLegacy(int64_t handleAidl) { - return (static_cast(handleAidl)); -} - -void AgmServerWrapper::addSessionHandle(uint32_t sessionId, uint64_t handle) { - std::lock_guard guard(mLock); - ALOGV("%s, caller session %d", __func__, sessionId); - - auto client = getClient_l(); - client->addSessionHandle(sessionId, handle); -} - -void AgmServerWrapper::removeSessionHandle(uint64_t handle) { - std::lock_guard guard(mLock); - ALOGV("%s, caller handle %llx", __func__, handle); - - auto client = getClient_l(); - client->removeSessionHandle(handle); -} - -void AgmServerWrapper::addSharedMemoryFdPairs(uint64_t handle, int inputFd, int dupFd) { - std::lock_guard guard(mLock); - ALOGV("%s, caller handle %llx inputFd %d dupFd %d", __func__, handle, inputFd, dupFd); - - auto client = getClient_l(); - client->addSharedMemoryFdPairs(handle, inputFd, dupFd); -} - -int AgmServerWrapper::removeSharedMemoryFdPairs(uint32_t sessionId, int dupFd) { - std::lock_guard guard(mLock); - ALOGV("%s, caller sessionId %d dupFd %d", __func__, sessionId, dupFd); - - int inputFd = -1; - for (auto &client: mClients) { - auto &clientInfoObj = client.second; - inputFd = clientInfoObj->removeSharedMemoryFdPairs(sessionId, dupFd); - if (inputFd != -1) - return inputFd; - } - return inputFd; -} - -void AgmServerWrapper::connectSessionAif(uint32_t sessionId, uint32_t aifId, bool state) { - std::lock_guard guard(mLock); - ALOGV("%s, caller session %d aif %d state %d", __func__, sessionId, aifId, state); - - auto client = getClient_l(); - client->connectSessionAif(sessionId, aifId, state); -} - -void AgmServerWrapper::removeClient(int pid) { - std::lock_guard guard(mLock); - if (mClients.count(pid) != 0) { - ALOGI("%s removing client %d", __func__, pid); - mClients.erase(pid); - } else { - /* - * client is already gone, nothing to do. - */ - } -} - -std::shared_ptr AgmServerWrapper::getClient_l() { - int pid = AIBinder_getCallingPid(); - if (mClients.count(pid) == 0) { - ALOGV("%s new client pid %d, total clients %d ", __func__, pid, mClients.size()); - mClients[pid] = std::make_shared(pid); - ClientInfo::setAgmServerWrapper(this); - } - return mClients[pid]; -} - -AgmServerWrapper::AgmServerWrapper() { - mInitialized = (agm_init() == 0); - ALOGI("%s created", __func__); -} - -AgmServerWrapper::~AgmServerWrapper() { - ALOGI("%s destroyed", __func__); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_init() { - ALOGV("%s ", __func__); - return ScopedAStatus::ok(); -} -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_deinit() { - ALOGV("%s ", __func__); - return ScopedAStatus::ok(); -} -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_start(int64_t in_handle) { - ALOGV("%s called with handle = %llx", __func__, (unsigned long long)in_handle); - return status_tToBinderResult(agm_session_start(in_handle)); -} -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_stop(int64_t in_handle) { - ALOGV("%s called with handle = %llx", __func__, (unsigned long long)in_handle); - return status_tToBinderResult(agm_session_stop(in_handle)); -} -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_suspend(int64_t in_handle) { - ALOGV("%s called with handle = %llx", __func__, (unsigned long long)in_handle); - return status_tToBinderResult(agm_session_suspend(in_handle)); -} -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_close(int64_t in_handle) { - ALOGV("%s called with handle = %llx", __func__, (unsigned long long)in_handle); - removeSessionHandle(in_handle); - return status_tToBinderResult(agm_session_close(in_handle)); -} -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_eos(int64_t in_handle) { - ALOGV("%s called with handle = %llx", __func__, (unsigned long long)in_handle); - return status_tToBinderResult(agm_session_eos(in_handle)); -} -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_flush(int64_t in_handle) { - ALOGV("%s called with handle = %llx", __func__, (unsigned long long)in_handle); - return status_tToBinderResult(agm_session_flush(in_handle)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_register_callback( - const std::shared_ptr &in_callback, int32_t in_sessionId, - int32_t in_eventType, bool in_register, int64_t in_clientData) { - std::lock_guard guard(mLock); - ALOGV("%s called with sessionId = %llx register %d eventType %d", __func__, - (unsigned long long)in_sessionId, in_register, in_eventType); - - auto client = getClient_l(); - if (in_register) - client->registerCallback(in_callback, in_sessionId, in_eventType, in_clientData); - else - client->unregisterCallback(in_sessionId, in_eventType, in_clientData); - - return ScopedAStatus::ok(); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_get_buf_info(int32_t in_sessionId, - int32_t in_flag, - MmapBufInfo *_aidl_return) { - struct agm_buf_info agmLegacyBufferInfo; - - memset(&agmLegacyBufferInfo, 0, sizeof(struct agm_buf_info)); - int ret = agm_session_get_buf_info(in_sessionId, &agmLegacyBufferInfo, in_flag); - if (!ret) { - LegacyToAidl::convertMmapBufferInfoToAidl(&agmLegacyBufferInfo, _aidl_return, in_flag); - } - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_get_params( - int32_t in_sessionId, const std::vector &in_buffer, - std::vector *_aidl_return) { - ALOGV("%s sessionId %d, size %d ", __func__, in_sessionId, in_buffer.size()); - - auto agmLegacyPayload = VALUE_OR_RETURN(allocate(in_buffer.size())); - - memcpy(agmLegacyPayload.get(), in_buffer.data(), in_buffer.size()); - - int ret = agm_session_get_params(in_sessionId, agmLegacyPayload.get(), in_buffer.size()); - if (!ret) { - _aidl_return->resize(in_buffer.size()); - - if (_aidl_return->size() != in_buffer.size()) { - ALOGE("%s could not resize: required size %d, resized size %d ", __func__, - in_buffer.size(), _aidl_return->size()); - return status_tToBinderResult(-ENOMEM); - } - - memcpy(_aidl_return->data(), agmLegacyPayload.get(), in_buffer.size()); - } - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_open(int32_t in_sessionId, - AgmSessionMode in_sessionMode, - int64_t *_aidl_return) { - enum agm_session_mode sessionMode = static_cast(in_sessionMode); - ALOGV("%s: sessionId =%d sessionMode =%d", __func__, in_sessionId, sessionMode); - - uint64_t handle = 0; - int ret = agm_session_open(in_sessionId, sessionMode, &handle); - - *_aidl_return = static_cast(handle); // TODO; - if (!ret) { - addSessionHandle(in_sessionId, handle); - } - - ALOGV("%s handle received is : %llx, ret %d, rethandle %llx", __func__, - (unsigned long long)handle, ret, *_aidl_return); - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_pause(int64_t in_handle) { - ALOGV("%s handle = %llx", __func__, (unsigned long long)in_handle); - return status_tToBinderResult(agm_session_pause(in_handle)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_prepare(int64_t in_handle) { - ALOGV("%s handle = %llx", __func__, (unsigned long long)in_handle); - return status_tToBinderResult(agm_session_prepare(in_handle)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_read(int64_t in_handle, int32_t in_count, - std::vector *_aidl_return) { - auto agmLegacyBuffer = VALUE_OR_RETURN(allocate(in_count)); - void *agmLegacyBufferPtr = agmLegacyBuffer.get(); - size_t bytesRead = (size_t)in_count; - int ret = agm_session_read(in_handle, agmLegacyBufferPtr, &bytesRead); - _aidl_return->resize(bytesRead); - memcpy(_aidl_return->data(), agmLegacyBufferPtr, bytesRead); - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_read_with_metadata( - int64_t in_handle, const AgmBuff &in_buffer, int32_t in_capturedSize, - IAGM::AgmReadWithMetadataReturn *_aidl_return) { - struct agm_buff agmLegacyBuffer; - uint32_t captured_size = in_capturedSize; - - uint32_t bufSize = in_buffer.size; - agmLegacyBuffer.addr = (uint8_t *)calloc(1, bufSize); - if (!agmLegacyBuffer.addr) { - ALOGE("%s: failed to calloc", __func__); - return status_tToBinderResult(-ENOMEM); - } - agmLegacyBuffer.size = (size_t)bufSize; - agmLegacyBuffer.metadata_size = in_buffer.metadata.size(); - - // metadata is deallocated during READ_DONE callback. - agmLegacyBuffer.metadata = (uint8_t *)calloc(1, agmLegacyBuffer.metadata_size); - if (!agmLegacyBuffer.metadata) { - free(agmLegacyBuffer.addr); - ALOGE("%s: failed to calloc", __func__); - return status_tToBinderResult(-ENOMEM); - } - agmLegacyBuffer.timestamp = 0; - agmLegacyBuffer.flags = 0; - - auto fdHandle = AidlToLegacy::getFdIntFromNativeHandle(in_buffer.externalAllocInfo.allocHandle); - - agmLegacyBuffer.alloc_info.alloc_handle = (fdHandle.first); - addSharedMemoryFdPairs(in_handle, fdHandle.second, agmLegacyBuffer.alloc_info.alloc_handle); - - agmLegacyBuffer.alloc_info.alloc_size = in_buffer.externalAllocInfo.allocatedSize; - agmLegacyBuffer.alloc_info.offset = in_buffer.externalAllocInfo.offset; - - int32_t ret = agm_session_read_with_metadata(in_handle, &agmLegacyBuffer, &captured_size); - - if (agmLegacyBuffer.addr) free(agmLegacyBuffer.addr); - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_register_for_events( - int32_t in_sessionId, const AgmEventRegistrationConfig &in_evt_reg_cfg) { - ALOGV("%s sessionId %d ", __func__, in_sessionId); - auto allocSize = sizeof(struct agm_event_reg_cfg) + in_evt_reg_cfg.eventConfigPayload.size(); - auto agmLegacyEventRegConfig = VALUE_OR_RETURN(allocate(allocSize)); - AidlToLegacy::convertAgmEventRegistrationConfig(in_evt_reg_cfg, agmLegacyEventRegConfig.get()); - - return status_tToBinderResult( - agm_session_register_for_events(in_sessionId, agmLegacyEventRegConfig.get())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_resume(int64_t in_handle) { - ALOGV("%s called with handle = %llx", __func__, (unsigned long long)in_handle); - return status_tToBinderResult(agm_session_resume(in_handle)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_set_config( - int64_t in_handle, const AgmSessionConfig &in_sessionConfig, - const AgmMediaConfig &in_mediaConfig, const AgmBufferConfig &in_bufferConfig) { - auto agmLegacyMediaConfig = - VALUE_OR_RETURN(allocate(sizeof(struct agm_media_config))); - auto agmLegacySessionConfig = - VALUE_OR_RETURN(allocate(sizeof(struct agm_session_config))); - auto agmLegacyBufferConfig = - VALUE_OR_RETURN(allocate(sizeof(struct agm_buffer_config))); - - AidlToLegacy::convertAgmMediaConfig(in_mediaConfig, agmLegacyMediaConfig.get()); - AidlToLegacy::convertAgmSessionConfig(in_sessionConfig, agmLegacySessionConfig.get()); - AidlToLegacy::convertAgmBufferConfig(in_bufferConfig, agmLegacyBufferConfig.get()); - - return status_tToBinderResult(agm_session_set_config(in_handle, agmLegacySessionConfig.get(), - agmLegacyMediaConfig.get(), - agmLegacyBufferConfig.get())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_set_ec_ref(int32_t in_sessionId, - int32_t in_aif_id, - bool in_state) { - ALOGV("%s sessionId %d aifId %d state %d ", __func__, in_sessionId, in_aif_id, in_state); - return status_tToBinderResult(agm_session_set_ec_ref(in_sessionId, in_aif_id, in_state)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_set_loopback(int32_t in_captureSessionId, - int32_t in_playbackSessionId, - bool in_state) { - ALOGV("%s capture session %d playback session %d state %d ", __func__, in_captureSessionId, - in_playbackSessionId, in_state); - return status_tToBinderResult( - agm_session_set_loopback(in_captureSessionId, in_playbackSessionId, in_state)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_set_metadata( - int32_t in_sessionId, const std::vector &in_metadata) { - ALOGV("%s sessionId %d, size %d ", __func__, in_sessionId, in_metadata.size()); - auto metadataLegacy = VALUE_OR_RETURN(allocate(in_metadata.size())); - memcpy(metadataLegacy.get(), in_metadata.data(), in_metadata.size()); - return status_tToBinderResult( - agm_session_set_metadata(in_sessionId, in_metadata.size(), metadataLegacy.get())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_set_non_tunnel_mode_config( - int64_t in_handle, const AgmSessionConfig &in_sessionConfig, - const AgmMediaConfig &in_inMediaConfig, const AgmMediaConfig &in_outMediaConfig, - const AgmBufferConfig &in_inBufferConfig, const AgmBufferConfig &in_outBufferConfig) { - auto agmLegacyInMediaConfig = - VALUE_OR_RETURN(allocate(sizeof(struct agm_media_config))); - auto agmLegacyOutMediaConfig = - VALUE_OR_RETURN(allocate(sizeof(struct agm_media_config))); - auto agmLegacySessionConfig = - VALUE_OR_RETURN(allocate(sizeof(struct agm_session_config))); - auto agmLegacyInBufferConfig = - VALUE_OR_RETURN(allocate(sizeof(struct agm_buffer_config))); - auto agmLegacyOutBufferConfig = - VALUE_OR_RETURN(allocate(sizeof(struct agm_buffer_config))); - - AidlToLegacy::convertAgmMediaConfig(in_inMediaConfig, agmLegacyInMediaConfig.get()); - AidlToLegacy::convertAgmMediaConfig(in_outMediaConfig, agmLegacyOutMediaConfig.get()); - AidlToLegacy::convertAgmSessionConfig(in_sessionConfig, agmLegacySessionConfig.get()); - AidlToLegacy::convertAgmBufferConfig(in_inBufferConfig, agmLegacyInBufferConfig.get()); - AidlToLegacy::convertAgmBufferConfig(in_outBufferConfig, agmLegacyOutBufferConfig.get()); - - return status_tToBinderResult(agm_session_set_non_tunnel_mode_config( - in_handle, agmLegacySessionConfig.get(), agmLegacyInMediaConfig.get(), - agmLegacyOutMediaConfig.get(), agmLegacyInBufferConfig.get(), - agmLegacyOutBufferConfig.get())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_set_params( - int32_t in_sessionId, const std::vector &in_payload) { - size_t payloadSize = in_payload.size(); - ALOGV("%s : sessionId = %d size = %d", __func__, in_sessionId, payloadSize); - - auto legacyPayload = VALUE_OR_RETURN(allocate(payloadSize)); - memcpy(legacyPayload.get(), in_payload.data(), payloadSize); - return status_tToBinderResult( - agm_session_set_params(in_sessionId, legacyPayload.get(), payloadSize)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_write(int64_t in_handle, - const std::vector &in_buff, - int32_t *_aidl_return) { - size_t count = (size_t)in_buff.size(); - ALOGV("%s called with handle = %llx ", __func__, (unsigned long long)in_handle, count); - - auto buffer = VALUE_OR_RETURN(allocate(count)); - memcpy(buffer.get(), in_buff.data(), count); - int ret = agm_session_write(in_handle, buffer.get(), &count); - *_aidl_return = static_cast(count); - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_write_datapath_params( - int32_t in_sessionId, const AgmBuff &in_buff) { - ALOGW("%s sessionId %d", __func__, in_sessionId); - struct agm_buff agmLegacyBuffer; - uint32_t bufSize = in_buff.buffer.size(); - agmLegacyBuffer.addr = nullptr; - agmLegacyBuffer.metadata = nullptr; - - agmLegacyBuffer.addr = (uint8_t *)calloc(1, bufSize); - if (!agmLegacyBuffer.addr) { - ALOGE("%s: failed to allocate agm buffer", __func__); - return status_tToBinderResult(-ENOMEM); - } - - AidlToLegacy::convertAgmBuffer(in_buff, &agmLegacyBuffer); - - int ret = agm_session_write_datapath_params(in_sessionId, &agmLegacyBuffer); - - if (agmLegacyBuffer.addr != nullptr) free(agmLegacyBuffer.addr); - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_write_with_metadata(int64_t in_handle, - const AgmBuff &in_buff, - int32_t *_aidl_return) { - struct agm_buff agmLegacyBuffer; - uint32_t bufSize = in_buff.size; - agmLegacyBuffer.addr = nullptr; - agmLegacyBuffer.metadata = nullptr; - - agmLegacyBuffer.addr = (uint8_t *)calloc(1, bufSize); - if (!agmLegacyBuffer.addr) { - ALOGE("%s: failed to calloc", __func__); - return status_tToBinderResult(-ENOMEM); - } - - agmLegacyBuffer.size = (size_t)bufSize; - agmLegacyBuffer.timestamp = in_buff.timestamp; - agmLegacyBuffer.flags = in_buff.flags; - if (in_buff.metadata.size()) { - agmLegacyBuffer.metadata_size = in_buff.metadata.size(); - agmLegacyBuffer.metadata = (uint8_t *)calloc(1, agmLegacyBuffer.metadata_size); - if (!agmLegacyBuffer.metadata) { - ALOGE("%s: failed to calloc", __func__); - free(agmLegacyBuffer.addr); - return status_tToBinderResult(-ENOMEM); - } - memcpy(agmLegacyBuffer.metadata, in_buff.metadata.data(), agmLegacyBuffer.metadata_size); - } - - auto fdInfo = AidlToLegacy::getFdIntFromNativeHandle(in_buff.externalAllocInfo.allocHandle); - - agmLegacyBuffer.alloc_info.alloc_handle = fdInfo.first; - - addSharedMemoryFdPairs(in_handle, fdInfo.second, agmLegacyBuffer.alloc_info.alloc_handle); - - agmLegacyBuffer.alloc_info.alloc_size = in_buff.externalAllocInfo.allocatedSize; - agmLegacyBuffer.alloc_info.offset = in_buff.externalAllocInfo.offset; - - if (bufSize && agmLegacyBuffer.addr) memcpy(agmLegacyBuffer.addr, in_buff.buffer.data(), bufSize); - - size_t consumed_size = 0; - int32_t ret = agm_session_write_with_metadata(in_handle, &agmLegacyBuffer, &consumed_size); - - *_aidl_return = consumed_size; - if (agmLegacyBuffer.metadata != nullptr) free(agmLegacyBuffer.metadata); - if (agmLegacyBuffer.addr != nullptr) free(agmLegacyBuffer.addr); - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_aif_group_set_media_config( - int32_t in_groupId, const AgmGroupMediaConfig &in_config) { - ALOGV("%s called with aif_id = %d", __func__, in_groupId); - - auto agmLegacyConfig = VALUE_OR_RETURN( - allocate(sizeof(struct agm_group_media_config))); - AidlToLegacy::convertAgmGroupMediaConfig(in_config, agmLegacyConfig.get()); - return status_tToBinderResult( - agm_aif_group_set_media_config(in_groupId, agmLegacyConfig.get())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_aif_set_media_config( - int32_t in_aifId, const AgmMediaConfig &in_config) { - ALOGV("%s called with aif_id = %d", __func__, in_aifId); - - auto agmLegacyConfig = - VALUE_OR_RETURN(allocate(sizeof(struct agm_media_config))); - AidlToLegacy::convertAgmMediaConfig(in_config, agmLegacyConfig.get()); - - return status_tToBinderResult(agm_aif_set_media_config(in_aifId, agmLegacyConfig.get())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_aif_set_metadata( - int32_t in_aifId, const std::vector &in_metadata) { - ALOGV("%s called with aif_id = %d, size %d", __func__, in_aifId, in_metadata.size()); - - auto agmLegacyMetadata = VALUE_OR_RETURN(allocate(in_metadata.size())); - memcpy(agmLegacyMetadata.get(), in_metadata.data(), in_metadata.size()); - - return status_tToBinderResult( - agm_aif_set_metadata(in_aifId, in_metadata.size(), agmLegacyMetadata.get())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_aif_set_params( - int32_t in_aifId, const std::vector &in_payload) { - ALOGV("%s %d aifId %d size %d", __func__, in_aifId, in_payload.size()); - - auto agmLegacyPayload = VALUE_OR_RETURN(allocate(in_payload.size())); - memcpy(agmLegacyPayload.get(), in_payload.data(), in_payload.size()); - - return status_tToBinderResult( - agm_aif_set_params(in_aifId, agmLegacyPayload.get(), in_payload.size())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_aif_connect(int32_t in_sessionId, - int32_t in_aifId, - bool in_state) { - ALOGV("%s sessionId %d,aifId %d, state %d ", __func__, in_sessionId, in_aifId, in_state); - - connectSessionAif(in_sessionId, in_aifId, in_state); - return status_tToBinderResult(agm_session_aif_connect(in_sessionId, in_aifId, in_state)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_aif_get_tag_module_info( - int32_t in_sessionId, int32_t in_aifId, int32_t in_size, - std::vector *_aidl_return) { - ALOGV("%s : in_sessionId = %d, aif_id =%d, size = %d", __func__, in_sessionId, in_aifId, - in_size); - - uint8_t *agmLegacyPayload = NULL; - size_t payloadSize = (size_t)in_size; - - if (payloadSize) { - agmLegacyPayload = (uint8_t *)calloc(1, payloadSize); - if (agmLegacyPayload == NULL) { - ALOGE("%s: Cannot allocate memory for agm payload ", __func__); - return status_tToBinderResult(-ENOMEM); - } - } - - int32_t ret = agm_session_aif_get_tag_module_info(in_sessionId, in_aifId, agmLegacyPayload, - &payloadSize); - - ALOGV("%s: got size %d, ret %d ", __func__, payloadSize, ret); - _aidl_return->resize(payloadSize); - - if (agmLegacyPayload) memcpy(_aidl_return->data(), agmLegacyPayload, payloadSize); - - free(agmLegacyPayload); - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_aif_set_cal( - int32_t in_sessionId, int32_t in_aifId, const AgmCalConfig &in_calConfig) { - auto numKvPairs = in_calConfig.kv.size(); - ALOGV("%s : sessionId = %d, aifId = %d calKeys %d", __func__, in_sessionId, in_aifId, - numKvPairs); - - RETURN_IF_KVPAIR_EXCEEDS_RANGE(numKvPairs); - auto allocSize = sizeof(struct agm_cal_config) + numKvPairs * sizeof(struct agm_key_value); - auto agmLegacyCalConfig = VALUE_OR_RETURN(allocate(allocSize)); - - AidlToLegacy::convertAgmCalConfig(in_calConfig, agmLegacyCalConfig.get()); - return status_tToBinderResult( - agm_session_aif_set_cal(in_sessionId, in_aifId, agmLegacyCalConfig.get())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_aif_set_metadata( - int32_t in_sessionId, int32_t in_aifId, const std::vector &in_metadata) { - auto agmLegacyMetadata = VALUE_OR_RETURN(allocate(in_metadata.size())); - memcpy(agmLegacyMetadata.get(), in_metadata.data(), in_metadata.size()); - return status_tToBinderResult(agm_session_aif_set_metadata( - in_sessionId, in_aifId, in_metadata.size(), agmLegacyMetadata.get())); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_session_aif_set_params( - int32_t in_sessionId, int32_t in_aifId, const std::vector &in_payload) { - size_t payloadSize = in_payload.size(); - ALOGV("%s : sessionId = %d, aif_id =%d, size = %d", __func__, in_sessionId, in_aifId, - payloadSize); - - auto legacyPayload = VALUE_OR_RETURN(allocate(payloadSize)); - memcpy(legacyPayload.get(), in_payload.data(), payloadSize); - return status_tToBinderResult( - agm_session_aif_set_params(in_sessionId, in_aifId, legacyPayload.get(), payloadSize)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_get_aif_info_list( - int32_t in_numAifInfo, std::vector *_aidl_return) { - ALOGV("%s numberOfAif = %d ", __func__, in_numAifInfo); - - AgmAifUniquePtrType agmLegacyAifInfoListUPtr(nullptr, free); - - if (in_numAifInfo != 0) { - agmLegacyAifInfoListUPtr = - VALUE_OR_RETURN(allocate(sizeof(struct aif_info) * in_numAifInfo)); - } - struct aif_info *agmLegacyAifInfoList = agmLegacyAifInfoListUPtr.get(); - size_t numberOfAifs = (size_t)in_numAifInfo; - int32_t ret = agm_get_aif_info_list(agmLegacyAifInfoList, &numberOfAifs); - ALOGV("%s got agmAifs = %d, ret %d ", __func__, numberOfAifs, ret); - - *_aidl_return = LegacyToAidl::convertAifInfoListToAidl(agmLegacyAifInfoList, numberOfAifs); - return ScopedAStatus::ok(); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_get_buffer_timestamp(int32_t in_sessiondId, - int64_t *_aidl_return) { - uint64_t timestampLegacy; - int ret = agm_get_buffer_timestamp(in_sessiondId, ×tampLegacy); - *_aidl_return = timestampLegacy; - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_get_group_aif_info_list( - int32_t in_numberOfGroups, std::vector *_aidl_return) { - AgmAifUniquePtrType agmLegacyAifInfoListUPtr(nullptr, free); - if (in_numberOfGroups != 0) { - agmLegacyAifInfoListUPtr = - VALUE_OR_RETURN(allocate(sizeof(struct aif_info) * in_numberOfGroups)); - } - - struct aif_info *agmLegacyAifInfoList = agmLegacyAifInfoListUPtr.get(); - size_t numberOfGroupAifs = (size_t)in_numberOfGroups; - int32_t ret = agm_get_group_aif_info_list(agmLegacyAifInfoList, &numberOfGroupAifs); - - *_aidl_return = LegacyToAidl::convertAifInfoListToAidl(agmLegacyAifInfoList, numberOfGroupAifs); - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_get_hw_processed_buff_cnt(int64_t in_handle, - Direction in_direction) { - ALOGV("%s handle %llx", __func__, in_handle); - enum direction legacyDir = (enum direction)(in_direction); - return status_tToBinderResult(agm_get_hw_processed_buff_cnt(in_handle, legacyDir)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_get_params_from_acdb_tunnel( - const std::vector &in_payload, std::vector *_aidl_return) { - size_t payloadSize = in_payload.size(); - ALOGV("%s :size = %d", __func__, payloadSize); - - auto legacyPayload = VALUE_OR_RETURN(allocate(payloadSize)); - memcpy(legacyPayload.get(), in_payload.data(), payloadSize); - int32_t ret = agm_get_params_from_acdb_tunnel(legacyPayload.get(), &payloadSize); - _aidl_return->resize(payloadSize); - memcpy(_aidl_return->data(), legacyPayload.get(), payloadSize); - return status_tToBinderResult(ret); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_get_session_time(int64_t in_handle, - int64_t *_aidl_return) { - uint64_t timestampLegacy; - int ret = agm_get_session_time(in_handle, ×tampLegacy); - *_aidl_return = timestampLegacy; - return status_tToBinderResult(ret); -} -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_sessionid_flush(int32_t in_sessiondId) { - ALOGV("%s sessionId %d", __func__, in_sessiondId); - return status_tToBinderResult(agm_sessionid_flush(in_sessiondId)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_set_gapless_session_metadata( - int64_t in_handle, AgmGaplessSilenceType in_type, int32_t in_silence) { - ALOGV("%s handle %x", __func__, in_handle); - enum agm_gapless_silence_type agmLegacySilenceType = - static_cast(in_type); - return status_tToBinderResult( - agm_set_gapless_session_metadata(in_handle, agmLegacySilenceType, in_silence)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_set_params_to_acdb_tunnel( - const std::vector &in_payload) { - size_t payloadSize = in_payload.size(); - ALOGV("%s :size = %d", __func__, payloadSize); - auto legacyPayload = VALUE_OR_RETURN(allocate(payloadSize)); - - memcpy(legacyPayload.get(), in_payload.data(), payloadSize); - return status_tToBinderResult(agm_set_params_to_acdb_tunnel(legacyPayload.get(), payloadSize)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_set_params_with_tag( - int32_t in_sessiondId, int32_t in_aifId, const AgmTagConfig &in_tagConfig) { - ALOGV("%s : sessionId = %d, aif_id = %d", __func__, in_sessiondId, in_aifId); - int tkvSize = in_tagConfig.kv.size(); - RETURN_IF_KVPAIR_EXCEEDS_RANGE(tkvSize); - - size_t tagConfigSize = (sizeof(struct agm_tag_config) + (tkvSize) * sizeof(agm_key_value)); - - auto agmLegacyTagConfigUniquePtr = VALUE_OR_RETURN(allocate(tagConfigSize)); - struct agm_tag_config *agmLegacyTagConfig = agmLegacyTagConfigUniquePtr.get(); - - AidlToLegacy::convertAgmTagConfig(in_tagConfig, agmLegacyTagConfig); - - return status_tToBinderResult( - agm_set_params_with_tag(in_sessiondId, in_aifId, agmLegacyTagConfig)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_set_params_with_tag_to_acdb( - int32_t in_sessionId, int32_t in_aifId, const std::vector &in_payload) { - size_t payloadSize = in_payload.size(); - ALOGV("%s : sessionId = %d size = %d", __func__, in_sessionId, payloadSize); - auto legacyPayload = VALUE_OR_RETURN(allocate(payloadSize)); - memcpy(legacyPayload.get(), in_payload.data(), payloadSize); - return status_tToBinderResult(agm_set_params_with_tag_to_acdb( - in_sessionId, in_aifId, legacyPayload.get(), payloadSize)); -} - -::ndk::ScopedAStatus AgmServerWrapper::ipc_agm_dump(const AgmDumpInfo &in_dumpInfo) { - return ScopedAStatus::ok(); -} -} diff --git a/qcom/opensource/agm/ipc/aidl/server/AgmServerWrapper.h b/qcom/opensource/agm/ipc/aidl/server/AgmServerWrapper.h deleted file mode 100755 index a0c23422..00000000 --- a/qcom/opensource/agm/ipc/aidl/server/AgmServerWrapper.h +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include - -#include -#include -#include -#include - -namespace aidl::vendor::qti::hardware::agm { - -class SessionInfo { - uint64_t mHandle = 0; - std::mutex mLock; - uint32_t mSessionId; - - using FdPair = std::pair; - std::vector mInOutFdPairs; - std::unordered_set mAifIds; - - public: - SessionInfo(uint32_t sessionId) : mSessionId(sessionId) { - ALOGI("SessionInfo created for session %d", mSessionId); - } - ~SessionInfo(); - void setHandle(uint64_t handle) { mHandle = handle; } - - void addSharedMemoryFdPairs(int input, int dupFd); - // remove the Fd and return input fd for this. - int removeSharedMemoryFdPairs(int dupFd); - - uint64_t getHandle() { return mHandle; } - void connectSessionAif(uint32_t aifId, bool state); - - void forceCloseSession(); - void dump(); -}; - -class CallbackInfo { - uint32_t mSessionId; - int mEventType; - std::shared_ptr mCallback; - uint64_t mClientData; - - public: - CallbackInfo(const std::shared_ptr &callback, uint32_t sessionId, int eventType, - uint64_t clientData) { - mCallback = callback; - mSessionId = sessionId; - mEventType = eventType; - mClientData = clientData; - // ALOGV("%s, callback %p session %d event %d clientData %llu", __func__, callback.get(), - // sessionId, eventType, clientData); - } - - ~CallbackInfo() { - // ALOGV("%s, callback %p session %d event %d clientData %llu", __func__, mCallback.get(), - // mSessionId, mEventType, mClientData); - } - uint32_t getSessionId() { return mSessionId; } - int getEventType() { return mEventType; } - uint64_t getClientData() { return mClientData; } - std::shared_ptr getCallback() { return mCallback; } -}; - -/* -* Interface for common session operations. -*/ -class ISessionOps { - public: - virtual void addSessionHandle(uint32_t sessionId, uint64_t handle) = 0; - virtual void removeSessionHandle(uint64_t handle) = 0; - virtual void connectSessionAif(uint32_t sessionId, uint32_t aifId, bool state) = 0; - virtual void addSharedMemoryFdPairs(uint64_t handle, int input, int dupFd) = 0; - virtual int removeSharedMemoryFdPairs(uint32_t sessionId, int dupFd) = 0; - virtual ~ISessionOps() = default; -}; - -class AgmServerWrapper; - -class ClientInfo : public ISessionOps { - std::vector> mCallbackInfo; - - // sessionId vs sessionId relatedInfo - std::unordered_map> mSessionsInfoMap; - - int mPid = 0; - std::mutex mCallbackLock; - std::mutex mSessionLock; - ::ndk::ScopedAIBinder_DeathRecipient mDeathRecipient; - static AgmServerWrapper *sAgmServerWrapper; - - public: - ClientInfo(int pid) : mPid(pid) { - mDeathRecipient = ndk::ScopedAIBinder_DeathRecipient( - AIBinder_DeathRecipient_new(ClientInfo::onDeath)); - } - - static void setAgmServerWrapper(AgmServerWrapper *wrapper); - - // this could only happen when client goes out of scope - virtual ~ClientInfo() { cleanup(); } - void cleanup(); - int getPid() { return mPid; } - - void registerCallback(const std::shared_ptr &callback, int32_t in_sessionId, - int32_t in_eventType, int64_t in_clientData); - void unregisterCallback(int32_t in_sessionId, int32_t in_eventType, int64_t in_clientData); - - std::shared_ptr getCallback(int32_t in_sessionId, int32_t in_eventType, - int64_t in_clientData); - - // must be called with lock held. - // keeps the SessionInfo object for given sessionId. - // If it does not exist, creates a sessionInfo - // Currently added with addSessionHandle and - // removed with removeSessionHandle - std::shared_ptr getSessionInfo_l(int32_t in_sessionId); - - void clearCallbacks(); - void clearSessions(); - void addSessionHandle(uint32_t sessionId, uint64_t handle) override; - void removeSessionHandle(uint64_t handle) override; - void connectSessionAif(uint32_t sessionId, uint32_t aifId, bool state) override; - - void addSharedMemoryFdPairs(uint64_t handle, int input, int dupFd) override; - // remove the Fd and return input fd for this. - int removeSharedMemoryFdPairs(uint32_t sessionId, int dupFd) override; - - static void onDeath(void *cookie); - void onDeath(); - - static void onCallback(uint32_t sessionId, struct agm_event_cb_params *eventParams, - void *clientData); -}; - -class AgmServerWrapper : public BnAGM, public ISessionOps { - public: - explicit AgmServerWrapper(); - virtual ~AgmServerWrapper(); - bool isInitialized() { return mInitialized; } - - ::ndk::ScopedAStatus ipc_agm_init() override; - ::ndk::ScopedAStatus ipc_agm_deinit() override; - ::ndk::ScopedAStatus ipc_agm_session_start(int64_t in_handle) override; - ::ndk::ScopedAStatus ipc_agm_session_stop(int64_t in_handle) override; - ::ndk::ScopedAStatus ipc_agm_session_suspend(int64_t in_handle) override; - ::ndk::ScopedAStatus ipc_agm_session_close(int64_t in_handle) override; - ::ndk::ScopedAStatus ipc_agm_session_eos(int64_t in_handle) override; - ::ndk::ScopedAStatus ipc_agm_session_flush(int64_t in_handle) override; - ::ndk::ScopedAStatus ipc_agm_session_get_buf_info( - int32_t in_sessionId, int32_t in_flag, - ::aidl::vendor::qti::hardware::agm::MmapBufInfo *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_session_get_params(int32_t in_sessionId, - const std::vector &in_buffer, - std::vector *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_session_open( - int32_t in_sessionId, ::aidl::vendor::qti::hardware::agm::AgmSessionMode in_sessionMode, - int64_t *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_session_pause(int64_t in_handle) override; - ::ndk::ScopedAStatus ipc_agm_session_prepare(int64_t in_handle) override; - ::ndk::ScopedAStatus ipc_agm_session_read(int64_t in_handle, int32_t in_count, - std::vector *_aidl_return) override; - - ::ndk::ScopedAStatus ipc_agm_session_read_with_metadata( - int64_t in_handle, const ::aidl::vendor::qti::hardware::agm::AgmBuff &in_buffer, - int32_t in_capturedSize, - ::aidl::vendor::qti::hardware::agm::IAGM::AgmReadWithMetadataReturn *_aidl_return) - override; - - ::ndk::ScopedAStatus ipc_agm_session_register_callback( - const std::shared_ptr<::aidl::vendor::qti::hardware::agm::IAGMCallback> &in_callback, - int32_t in_sessionId, int32_t in_eventType, bool in_register, - int64_t in_clientData) override; - - ::ndk::ScopedAStatus ipc_agm_session_register_for_events( - int32_t in_sessionId, - const ::aidl::vendor::qti::hardware::agm::AgmEventRegistrationConfig &in_evt_reg_cfg) - override; - ::ndk::ScopedAStatus ipc_agm_session_resume(int64_t in_handle) override; - ::ndk::ScopedAStatus ipc_agm_session_set_config( - int64_t in_handle, - const ::aidl::vendor::qti::hardware::agm::AgmSessionConfig &in_sessionConfig, - const ::aidl::vendor::qti::hardware::agm::AgmMediaConfig &in_mediaConfig, - const ::aidl::vendor::qti::hardware::agm::AgmBufferConfig &in_bufferConfig) override; - - ::ndk::ScopedAStatus ipc_agm_session_set_ec_ref(int32_t in_sessionId, int32_t in_aifId, - bool in_state) override; - ::ndk::ScopedAStatus ipc_agm_session_set_loopback(int32_t in_captureSessionId, - int32_t in_playbackSessionId, - bool in_state) override; - ::ndk::ScopedAStatus ipc_agm_session_set_metadata( - int32_t in_sessionId, const std::vector &in_metadata) override; - - ::ndk::ScopedAStatus ipc_agm_session_set_non_tunnel_mode_config( - int64_t in_handle, - const ::aidl::vendor::qti::hardware::agm::AgmSessionConfig &in_sessionConfig, - const ::aidl::vendor::qti::hardware::agm::AgmMediaConfig &in_inMediaConfig, - const ::aidl::vendor::qti::hardware::agm::AgmMediaConfig &in_outMediaConfig, - const ::aidl::vendor::qti::hardware::agm::AgmBufferConfig &in_inBufferConfig, - const ::aidl::vendor::qti::hardware::agm::AgmBufferConfig &in_outBufferConfig) override; - - ::ndk::ScopedAStatus ipc_agm_session_set_params( - int32_t in_sessionId, const std::vector &in_payload) override; - ::ndk::ScopedAStatus ipc_agm_session_write(int64_t in_handle, - const std::vector &in_buff, - int32_t *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_session_write_datapath_params( - int32_t in_sessionId, - const ::aidl::vendor::qti::hardware::agm::AgmBuff &in_buff) override; - ::ndk::ScopedAStatus ipc_agm_session_write_with_metadata( - int64_t in_handle, const ::aidl::vendor::qti::hardware::agm::AgmBuff &in_buff, - int32_t *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_aif_group_set_media_config( - int32_t in_groupId, - const ::aidl::vendor::qti::hardware::agm::AgmGroupMediaConfig &in_config) override; - ::ndk::ScopedAStatus ipc_agm_aif_set_media_config( - int32_t in_aifId, - const ::aidl::vendor::qti::hardware::agm::AgmMediaConfig &in_config) override; - ::ndk::ScopedAStatus ipc_agm_aif_set_metadata(int32_t in_aifId, - const std::vector &in_metadata) override; - ::ndk::ScopedAStatus ipc_agm_aif_set_params(int32_t in_aifId, - const std::vector &in_payload) override; - ::ndk::ScopedAStatus ipc_agm_session_aif_connect(int32_t in_sessionId, int32_t in_aifId, - bool in_state) override; - ::ndk::ScopedAStatus ipc_agm_session_aif_get_tag_module_info( - int32_t in_sessionId, int32_t in_aifId, int32_t in_size, - std::vector *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_session_aif_set_cal( - int32_t in_sessionId, int32_t in_aifId, - const ::aidl::vendor::qti::hardware::agm::AgmCalConfig &in_calConfig) override; - ::ndk::ScopedAStatus ipc_agm_session_aif_set_metadata( - int32_t in_sessionId, int32_t in_aifId, - const std::vector &in_metadata) override; - ::ndk::ScopedAStatus ipc_agm_session_aif_set_params( - int32_t in_sessionId, int32_t in_aifId, - const std::vector &in_payload) override; - ::ndk::ScopedAStatus ipc_agm_get_aif_info_list( - int32_t in_numAifInfo, - std::vector<::aidl::vendor::qti::hardware::agm::AifInfo> *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_get_buffer_timestamp(int32_t in_sessiondId, - int64_t *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_get_group_aif_info_list( - int32_t in_numberOfGroups, - std::vector<::aidl::vendor::qti::hardware::agm::AifInfo> *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_get_hw_processed_buff_cnt( - int64_t in_handle, ::aidl::vendor::qti::hardware::agm::Direction in_direction) override; - ::ndk::ScopedAStatus ipc_agm_get_params_from_acdb_tunnel( - const std::vector &in_payload, std::vector *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_get_session_time(int64_t in_handle, - int64_t *_aidl_return) override; - ::ndk::ScopedAStatus ipc_agm_sessionid_flush(int32_t in_sessiondId) override; - ::ndk::ScopedAStatus ipc_agm_set_gapless_session_metadata( - int64_t in_handle, ::aidl::vendor::qti::hardware::agm::AgmGaplessSilenceType in_type, - int32_t in_silence) override; - ::ndk::ScopedAStatus ipc_agm_set_params_to_acdb_tunnel( - const std::vector &in_payload) override; - ::ndk::ScopedAStatus ipc_agm_set_params_with_tag( - int32_t in_sessiondId, int32_t in_aifId, - const ::aidl::vendor::qti::hardware::agm::AgmTagConfig &in_tagConfig) override; - ::ndk::ScopedAStatus ipc_agm_set_params_with_tag_to_acdb( - int32_t in_sessiondId, int32_t in_aifId, - const std::vector &in_payload) override; - ::ndk::ScopedAStatus ipc_agm_dump( - const ::aidl::vendor::qti::hardware::agm::AgmDumpInfo &in_dumpInfo) - override; - - void addSessionHandle(uint32_t sessionId, uint64_t handle) override; - void removeSessionHandle(uint64_t handle) override; - void connectSessionAif(uint32_t sessionId, uint32_t aifId, bool state) override; - - void addSharedMemoryFdPairs(uint64_t handle, int input, int dupFd) override; - // remove the Fd and return input fd for this. - int removeSharedMemoryFdPairs(uint32_t sessionId, int dupFd) override; - - // it returns the client as per caller pid, must be called with lock held - std::shared_ptr getClient_l(); - void removeClient(int pid); - - std::mutex mLock; - // pid vs clientInfo - std::unordered_map> mClients; - bool mInitialized = false; -}; -} \ No newline at end of file diff --git a/qcom/opensource/agm/ipc/aidl/server/Android.mk b/qcom/opensource/agm/ipc/aidl/server/Android.mk deleted file mode 100755 index 307fa4c1..00000000 --- a/qcom/opensource/agm/ipc/aidl/server/Android.mk +++ /dev/null @@ -1,32 +0,0 @@ - -LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) - -LOCAL_MODULE := libagmipcservice -LOCAL_MODULE_OWNER := qti -LOCAL_VENDOR_MODULE := true - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/inc - -LOCAL_CLANG := true -LOCAL_TIDY := true -LOCAL_CFLAGS += -v -Wall -Wthread-safety - -LOCAL_SRC_FILES := \ - Service.cpp \ - AgmServerWrapper.cpp - -LOCAL_STATIC_LIBRARIES := libagmaidltypeconverter libaidlcommonsupport - - -LOCAL_SHARED_LIBRARIES := \ - liblog \ - libbinder_ndk \ - libbase \ - libcutils \ - libutils \ - libar-gsl \ - libagm \ - vendor.qti.hardware.agm-V1-ndk - -include $(BUILD_SHARED_LIBRARY) \ No newline at end of file diff --git a/qcom/opensource/agm/ipc/aidl/server/Service.cpp b/qcom/opensource/agm/ipc/aidl/server/Service.cpp deleted file mode 100755 index 5e38b2e1..00000000 --- a/qcom/opensource/agm/ipc/aidl/server/Service.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AgmIpc::Service" - -#include -#include -#include - -#include "AgmServerWrapper.h" - -using namespace aidl::vendor::qti::hardware::agm; - -extern "C" __attribute__((visibility("default"))) binder_status_t registerService() { - ALOGI("register AGM Service"); - auto agmService = ::ndk::SharedRefBase::make(); - ndk::SpAIBinder agmBinder = agmService->asBinder(); - const std::string interfaceName = std::string() + IAGM::descriptor + "/default"; - if (!agmService->isInitialized()) { - ALOGE("failed to initialize AGM Service!"); - return -EINVAL; - } - - if (!AServiceManager_isDeclared(interfaceName.c_str())) { - ALOGW("%s interface %s is not declared in VINTF", __func__, interfaceName.c_str()); - } - - binder_status_t status = AServiceManager_addService(agmBinder.get(), interfaceName.c_str()); - ALOGI("register AGM Service interface %s registered %s status %d", interfaceName.c_str(), - (status == STATUS_OK) ? "yes" : "no", status); - return status; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmBuff.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmBuff.aidl deleted file mode 100755 index bdc96202..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmBuff.aidl +++ /dev/null @@ -1,26 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmExternAllocBuffInfo; - -@VintfStability -parcelable AgmBuff { - /**< timestamp in micro-secs */ - long timestamp; - /**< bitmasked flags for e.g. AGM_BUFF_FLAG_EOS */ - int flags; - /**< size of buffer in bytes */ - int size; - /**< offset at which audio data is present */ - int offset; - /**< data buffer */ - byte[] buffer; - /**< Blob for metadata */ - byte[] metadata; - /**< holds info for extern buff */ - AgmExternAllocBuffInfo externalAllocInfo; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmBufferConfig.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmBufferConfig.aidl deleted file mode 100755 index b1c742f1..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmBufferConfig.aidl +++ /dev/null @@ -1,16 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmBufferConfig { - /**< number of buffers */ - int count; - /**< size of each buffer */ - int size; - /**< max metadata size a client attaches to a buffer */ - int maxMetadataSize; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmCalConfig.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmCalConfig.aidl deleted file mode 100755 index 20b680b9..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmCalConfig.aidl +++ /dev/null @@ -1,14 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmKeyValue; - -@VintfStability -parcelable AgmCalConfig { - /**< tag key vector*/ - AgmKeyValue[] kv; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmDataMode.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmDataMode.aidl deleted file mode 100755 index 0089afda..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmDataMode.aidl +++ /dev/null @@ -1,17 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -@Backing(type="int") -enum AgmDataMode { - AGM_DATA_INVALID, - AGM_DATA_BLOCKING, - AGM_DATA_NON_BLOCKING, - AGM_DATA_PUSH_PULL, - AGM_DATA_EXTERN_MEM, - AGM_DATA_MODE_MAX, -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmDumpInfo.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmDumpInfo.aidl deleted file mode 100755 index fdb25a02..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmDumpInfo.aidl +++ /dev/null @@ -1,13 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmDumpInfo { - int signal; - int pid; - int uid; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventCallbackParameter.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventCallbackParameter.aidl deleted file mode 100755 index 2587c762..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventCallbackParameter.aidl +++ /dev/null @@ -1,16 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmEventCallbackParameter { - /**< identifies the module which generated event */ - int sourceModuleId; - /**< identifies the event */ - int eventId; - /**< payload associated with the event if any */ - byte[] eventPayload; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventId.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventId.aidl deleted file mode 100755 index ab354911..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventId.aidl +++ /dev/null @@ -1,23 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -/** - * Data Events that will be notified to client from AGM - */ -@VintfStability -@Backing(type="int") -enum AgmEventId { - // Indicates EOS rendered event - AGMEVENTEOSRENDERED = 0x0, - // Indicates buffer provided as part of read call has been filled. - AGMEVENTREADDONE = 0x1, - // Indicates buffer provided as part of write has been consumed - AGMEVENTWRITEDONE = 0x2, - // Indicates early EOS event - AGM_EVENT_EARLY_EOS = 0x08001126, - AGMEVENTIDMAX, -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventReadWriteDonePayload.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventReadWriteDonePayload.aidl deleted file mode 100755 index 3a5d1950..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventReadWriteDonePayload.aidl +++ /dev/null @@ -1,20 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmBuff; - -@VintfStability -parcelable AgmEventReadWriteDonePayload { - // tag that was used to read/write this buffer - int tag; - // data buffer status - int status; - // metadata status - int metadataStatus; - // buffer that was passed to agm_read/agm_write - AgmBuff buffer; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventRegistrationConfig.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventRegistrationConfig.aidl deleted file mode 100755 index 0451019d..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmEventRegistrationConfig.aidl +++ /dev/null @@ -1,21 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -/** - * Event registration structure. - */ -@VintfStability -parcelable AgmEventRegistrationConfig { - // Valid instance ID of module - int moduleInstanceId; - // Valid event ID of the module - int eventId; - // register or unregister 1 for register, 0 for unregister - byte registerEvent; - // module specifc event registration payload - byte[] eventConfigPayload; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmExternAllocBuffInfo.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmExternAllocBuffInfo.aidl deleted file mode 100755 index 50eb0933..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmExternAllocBuffInfo.aidl +++ /dev/null @@ -1,20 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import android.hardware.common.NativeHandle; -/** - * Externally allocated buffer info - */ -@VintfStability -parcelable AgmExternAllocBuffInfo { - // unique native handle identifying extern memory allocation - NativeHandle allocHandle; - // size of external allocation - int allocatedSize; - // offset of buffer within extern allocation - int offset; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmGaplessSilenceType.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmGaplessSilenceType.aidl deleted file mode 100755 index 1c39efaf..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmGaplessSilenceType.aidl +++ /dev/null @@ -1,18 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -/** - * Gapless playback Silence type - */ -@VintfStability -@Backing(type="int") -enum AgmGaplessSilenceType { - // Initial silence sample to be removed - INITIAL_SILENCE, - // Trailing silence sample to be removed - TRAILING_SILENCE, -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmGroupMediaConfig.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmGroupMediaConfig.aidl deleted file mode 100755 index 6b5faf44..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmGroupMediaConfig.aidl +++ /dev/null @@ -1,25 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmMediaFormat; - -/** - * Group Media Config - */ -@VintfStability -parcelable AgmGroupMediaConfig { - // sample rate - int rate; - // number of channels - int channels; - // media format in agm_media_format - AgmMediaFormat format; - // data format - int dataFormat; - // slot_mask for TDM - int slotMask; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmKeyValue.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmKeyValue.aidl deleted file mode 100755 index b2de640f..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmKeyValue.aidl +++ /dev/null @@ -1,12 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmKeyValue { - int key; - int value; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmMediaConfig.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmMediaConfig.aidl deleted file mode 100755 index fcf2d931..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmMediaConfig.aidl +++ /dev/null @@ -1,23 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmMediaFormat; - -/** - * Media Config - */ -@VintfStability -parcelable AgmMediaConfig { - // sample rate - int rate; - // number of channels - int channels; - // media format in agm_media_format - AgmMediaFormat format; - // data format - int dataFormat; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmMediaFormat.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmMediaFormat.aidl deleted file mode 100755 index b807525c..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmMediaFormat.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -@Backing(type="int") -enum AgmMediaFormat { - AGM_FORMAT_INVALID, - AGM_FORMAT_PCM_S8, /**< 8-bit signed */ - AGM_FORMAT_PCM_S16_LE, /**< 16-bit signed */ - AGM_FORMAT_PCM_S24_LE, /**< 24-bits in 4-bytes */ - AGM_FORMAT_PCM_S24_3LE, /**< 24-bits in 3-bytes */ - AGM_FORMAT_PCM_S32_LE, /**< 32-bit signed */ - AGM_FORMAT_MP3, /**< MP3 codec */ - AGM_FORMAT_AAC, /**< AAC codec */ - AGM_FORMAT_FLAC, /**< FLAC codec */ - AGM_FORMAT_ALAC, /**< ALAC codec */ - AGM_FORMAT_APE, /**< APE codec */ - AGM_FORMAT_WMASTD, /**< WMA codec */ - AGM_FORMAT_WMAPRO, /**< WMA pro codec */ - AGM_FORMAT_VORBIS, /**< Vorbis codec */ - AGM_FORMAT_AMR_NB, /**< AMR NB codec */ - AGM_FORMAT_AMR_WB, /**< AMR WB codec */ - AGM_FORMAT_AMR_WB_PLUS, /**< AMR WB Plus codec */ - AGM_FORMAT_EVRC, /**< EVRC codec */ - AGM_FORMAT_G711, /**< G711 codec */ - AGM_FORMAT_QCELP, /**< G711 codec */ - AGM_FORMAT_MAX, -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmReadWriteEventCallbackParams.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmReadWriteEventCallbackParams.aidl deleted file mode 100755 index 46d5aa13..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmReadWriteEventCallbackParams.aidl +++ /dev/null @@ -1,18 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmEventReadWriteDonePayload; - -@VintfStability -parcelable AgmReadWriteEventCallbackParams { - // identifies the module which generated event - int sourceModuleId; - // identifies the event - int eventId; - // payload associated with the event if any - AgmEventReadWriteDonePayload payload; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionAacDec.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionAacDec.aidl deleted file mode 100755 index f7d37fcd..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionAacDec.aidl +++ /dev/null @@ -1,23 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -/** - * AAC decoder parameters - */ -@VintfStability -parcelable AgmSessionAacDec { - // AAC format flag - int formatFlag; - // AAC obj type - int objectType; - // number of channels - int channels; - // PCE bits size - int sizeOfPCEBits; - // sample rate - int sampleRate; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionAacEnc.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionAacEnc.aidl deleted file mode 100755 index abfbdf54..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionAacEnc.aidl +++ /dev/null @@ -1,18 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmSessionAacEnc { - // encoder bitrate - int bitRate; - // global cutoff frequency - int globalCutOffFrequency; - // encoder mode - int mode; - // format flags - int formatFlags; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionAlacDec.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionAlacDec.aidl deleted file mode 100755 index 43b6c0a6..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionAlacDec.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmSessionAlacDec { - // Frame length - int frameLength; - // version - byte compatibleVersion; - // bit depth - byte bitDepth; - // tuning parameters - byte pb; - // tuning parameters - byte mb; - // tuning parameters - byte kb; - // number of channels - byte channels; - // max run - int maxRun; - // max frame bytes - int maxFrameBytes; - // average bit rate - int averageBitRate; - // sample rate - int sampleRate; - // channel layout tag - int channelLayoutTag; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionApeDec.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionApeDec.aidl deleted file mode 100755 index ea435283..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionApeDec.aidl +++ /dev/null @@ -1,20 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmSessionApeDec { - int compatibleVersion; /**< Version */ - int compressionLevel; /**< Compression Level */ - int formatFlags; /**< Format flags */ - int blocksPerFrame; /**< Blocks per frame */ - int finalFrameBlocks; /**< Final frame blocks */ - int totalFrames; /**< Total frames */ - int bitWidth; /**< Bit width */ - int channels; /**< Number of channels */ - int sampleRate; /**< Sample rate */ - int seekTablePresent; /**< Seek table present */ -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionCodec.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionCodec.aidl deleted file mode 100755 index 8d6d5097..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionCodec.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmSessionAacDec; -import vendor.qti.hardware.agm.AgmSessionAlacDec; -import vendor.qti.hardware.agm.AgmSessionApeDec; -import vendor.qti.hardware.agm.AgmSessionFlacDec; -import vendor.qti.hardware.agm.AgmSessionWmaDec; -import vendor.qti.hardware.agm.AgmSessionWmaproDec; -import vendor.qti.hardware.agm.AgmSessionOpusDec; -import vendor.qti.hardware.agm.AgmSessionAacEnc; - -@VintfStability -union AgmSessionCodec { - AgmSessionAacDec aacDecoder; /**< AAC decoder config */ - AgmSessionFlacDec flacDecoder; /**< Flac decoder config */ - AgmSessionAlacDec alacDecoder; /**< Alac decoder config */ - AgmSessionApeDec apeDecoder; /**< APE decoder config */ - AgmSessionWmaDec wmaDecoder; /**< WMA decoder config */ - AgmSessionWmaproDec wmaproDecoder; /**< WMAPro decoder config */ - AgmSessionOpusDec opusDecoder; /**< OPUS decoder config */ - AgmSessionAacEnc aacEncoder; /**< AAC encoder config */ -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionConfig.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionConfig.aidl deleted file mode 100755 index d018e5a4..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionConfig.aidl +++ /dev/null @@ -1,22 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmDataMode; -import vendor.qti.hardware.agm.AgmSessionCodec; -import vendor.qti.hardware.agm.AgmSessionMode; -import vendor.qti.hardware.agm.Direction; - -@VintfStability -parcelable AgmSessionConfig { - Direction direction; /**< TX or RX */ - AgmSessionMode sessionMode; /**< indicates mode of agm sesison, non-tunnel, or hostless */ - int startThreshold; /**< start_threshold: number of buffers * buffer size */ - int stopThreshold; /**< stop_threshold: number of buffers * buffer size */ - @nullable AgmSessionCodec codec; /**< codec configuration */ - AgmDataMode dataMode; /**< data mode */ - int flags; /**< pass session specific flags e.g enable inband SRCM event*/ -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionFlacDec.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionFlacDec.aidl deleted file mode 100755 index 55c22de3..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionFlacDec.aidl +++ /dev/null @@ -1,17 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmSessionFlacDec { - int channels; /**< Number of channels */ - int sampleSize; /**< Sample size */ - int minBlockSize; /**< Minimum block size */ - int maxBlockSize; /**< Maximum block size */ - int sampleRate; /**< Sample rate */ - int minFrameSize; /**< Minimum frame size */ - int maxFrameSize; /**< Maximum frame size */ -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionMode.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionMode.aidl deleted file mode 100755 index 5395b775..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionMode.aidl +++ /dev/null @@ -1,20 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -/** - * AGM session modes - */ - -@VintfStability -@Backing(type="int") -enum AgmSessionMode { - AGM_SESSION_DEFAULT, /**< Normal agm tunnel session*/ - AGM_SESSION_NO_HOST, /**< Hostless mode */ - AGM_SESSION_NON_TUNNEL, /**< Non tunnel mode */ - AGM_SESSION_NO_CONFIG, /**< No Config mode*/ - AGM_SESSION_COMPRESS, /**< Compress mode*/ -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionOpusDec.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionOpusDec.aidl deleted file mode 100755 index e908f731..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionOpusDec.aidl +++ /dev/null @@ -1,22 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmSessionOpusDec { - int bitStreamFormat; - int type; - byte version; - byte channels; - int preSkip; - long sampleRate; - int outputGain; - byte mappingFamily; - byte streamCount; - byte coupledCount; - byte [8] channelMap; - byte [3] reserved; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionWmaDec.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionWmaDec.aidl deleted file mode 100755 index a35fb25c..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionWmaDec.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmSessionWmaDec { - int formatTag; /**< Format Tag */ - int channels; /**< Number of channels */ - int sampleRate; /**< Sample rate */ - int averageBytesPerSecond; /**< Avg bytes per sec */ - int blockAlign; /**< Block align */ - int bitsPerSample; /**< Bits per sample */ - int channelMask; /**< Channel mask */ - int encoderOption; /**< Encoder options */ - int reserved; /**< reserved */ -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionWmaproDec.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionWmaproDec.aidl deleted file mode 100755 index 3a0164ff..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmSessionWmaproDec.aidl +++ /dev/null @@ -1,20 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -@VintfStability -parcelable AgmSessionWmaproDec { - int formatTag; /**< Format Tag */ - int channels; /**< Number of channels */ - int sampleRate; /**< Sample rate */ - int averageBytesPerSecond; /**< Avg bytes per sec */ - int blockAlign; /**< Block align */ - int bitsPerSample; /**< Bits per sample */ - int channelMask; /**< Channel mask */ - int encoderOption; /**< Encoder options */ - int advancedEncoderOption; /**< Adv encoder options */ - int advancedEncoderOption2; /**< Adv encoder options2 */ -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmTagConfig.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmTagConfig.aidl deleted file mode 100755 index 066f0f17..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AgmTagConfig.aidl +++ /dev/null @@ -1,16 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmKeyValue; - -@VintfStability -parcelable AgmTagConfig { - // tag id - int tag; - //tag key vector; - AgmKeyValue[] kv; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AifInfo.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AifInfo.aidl deleted file mode 100755 index 21cacf16..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/AifInfo.aidl +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.Direction; - -@VintfStability -parcelable AifInfo { - // AIF name - String aifName; - // direction Rx or Tx - Direction direction; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/Direction.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/Direction.aidl deleted file mode 100755 index 43148c38..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/Direction.aidl +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.agm; - -/** - * Session Direction - */ -@VintfStability -@Backing(type="int") -enum Direction { - Rx = 1, - Tx, -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/EventType.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/EventType.aidl deleted file mode 100755 index 39be123d..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/EventType.aidl +++ /dev/null @@ -1,16 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -/** - * Event types - */ -@VintfStability -@Backing(type="int") -enum EventType { - AGM_EVENT_DATA_PATH = 1, - AGM_EVENT_MODULE, -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/IAGM.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/IAGM.aidl deleted file mode 100755 index 7550ae15..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/IAGM.aidl +++ /dev/null @@ -1,544 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmBuff; -import vendor.qti.hardware.agm.AgmBufferConfig; -import vendor.qti.hardware.agm.AgmCalConfig; -import vendor.qti.hardware.agm.AgmDumpInfo; -import vendor.qti.hardware.agm.AgmEventRegistrationConfig; -import vendor.qti.hardware.agm.AgmGaplessSilenceType; -import vendor.qti.hardware.agm.AgmGroupMediaConfig; -import vendor.qti.hardware.agm.AgmMediaConfig; -import vendor.qti.hardware.agm.AgmSessionConfig; -import vendor.qti.hardware.agm.AgmSessionMode; -import vendor.qti.hardware.agm.AgmTagConfig; -import vendor.qti.hardware.agm.AifInfo; -import vendor.qti.hardware.agm.Direction; -import vendor.qti.hardware.agm.IAGMCallback; -import vendor.qti.hardware.agm.MmapBufInfo; - -@VintfStability -interface IAGM { - - /** - * Initialize agm. - * Clients can't directly access this method as init is done in context of server - * API is provided to keep in sync with native agm_api.h - */ - void ipc_agm_init(); - - /** - * De-Initialize agm. - * Clients can't directly access this method as deinit is done in context of server - * API is provided to keep in sync with native agm_api.h - */ - void ipc_agm_deinit(); - - /** - * Start the session. - * @param sessionId valid audio session id - * @param sessionMode mode in which this agm session is to be opened - * @return handle of opened session - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - long ipc_agm_session_open(in int sessionId, in AgmSessionMode sessionMode); - - /** - * Start the session. - * @param handle valid session handle obtained from ipc_agm_session_open - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_start(in long handle); - - /** - * Stop the session, session must be in started/paused state before stopping. - * @param handle valid session handle obtained from ipc_agm_session_open - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_stop(in long handle); - - /** - * suspend the session. session must be in started state before suspending - * @param handle valid session handle obtained from ipc_agm_session_open - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_suspend(in long handle); - - /** - * Pause the session, session must be in started state before pausing. - * @param handle valid session handle obtained from ipc_agm_session_open - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_pause(in long handle); - - /** - * Resume the session. session must be in paused state before resuming. - * @param handle valid session handle obtained from ipc_agm_session_open - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_resume(in long handle); - - /** - * prepare the session. - * @param handle valid session handle obtained from ipc_agm_session_open - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_prepare(in long handle); - - /** - * send eos of the session - * @param handle valid session handle obtained from ipc_agm_session_open - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_eos(in long handle); - - /** - * flush the session, session must be in pause state before flushing. - * @param handle valid session handle obtained from ipc_agm_session_open - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_flush(in long handle); - - /** - * Close the session. - * @param handle valid session handle obtained from ipc_agm_session_open - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_close(in long handle); - - /** - * Get shared memory MmapBufInfo of a given session - * @param sessionId valid audio session id - * @param flag determine data buf/pos buf - * @return MmapBufInfo shared memory in form of MmapBufInfo - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - MmapBufInfo ipc_agm_session_get_buf_info(in int sessionId, in int flag); - - /** - * Get Get parameters of the modules of a given session - * @param sessionId valid audio session id - * @param buffer payload for get parameter - * @return byte [] with result of get parameters - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - byte[] ipc_agm_session_get_params(in int sessionId , in byte[] buffer); - - /** - * Read data buffers from opened agm session - * @param handle session handle returned from agm_session_open - * @param count number of bytes requested to fill into - * @return byte [] buffer read from agm, use its size to get numbers of bytes read, - * could be different requested count - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - byte[] ipc_agm_session_read(in long handle, in int count); - - parcelable AgmReadWithMetadataReturn { - AgmBuff buffer; - int capturesSize; - } - - /** - * Read data buffers with metadata to session - * @param handle session handle returned from agm_session_open - * @param buffer AgmBuffer containing metadata info - * @param capturedSize Actual number of bytes that were captured - * @return AgmReadWithMetadataReturn containing buffer read and captureSize - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - AgmReadWithMetadataReturn ipc_agm_session_read_with_metadata(in long handle, - in AgmBuff buffer, in int capturedSize); - - /** - * Register/deregister a callback to listen to various events - * @param callback IAGMCallback instance to be registered, on event from lower layers, - * IAGMCallback's respective methods will be notified - * @param sessionId valid audio session id - * @param eventType event type to be monitored - * @param register number of bytes requested to fill into - * @param clientData client data - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_register_callback(in IAGMCallback callback, in int sessionId, - in int eventType, in boolean register, in long clientData); - - /** - * Register for events from Modules. Not needed for data path events. - * @param sessionId valid audio session id - * @param eventConfig event specific configuration - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_register_for_events(in int sessionId, - in AgmEventRegistrationConfig eventConfig); - - /** - * Set Session config - * @param handle session handle returned from agm_session_open - * @param sessionConfig valid stream configuration of the session - * @param mediaConfig valid media configuration of the session - * @param bufferConfig buffer configuration for the session, null if hostless - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_set_config(in long handle, in AgmSessionConfig sessionConfig, - in AgmMediaConfig mediaConfig, in AgmBufferConfig bufferConfig); - - /** - * Set echo reference on capture session - * @param sessionId valid audio session id - * @param aifId aifId on RX path. - * @param state flag to indicate to enable(true) or disable(false) echo reference - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_set_ec_ref(in int sessionId, in int aifId, in boolean state); - - /** - * Set loopback between capture and playback sessions - * @param captureSessionId a non zero capture session id - * @param playbackSessionId playback session id - * @param state flag to indicate to enable(true) or disable(false) loopback - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_set_loopback(in int captureSessionId, in int playbackSessionId, - in boolean state); - - /** - * Set metadata for the session - * @param sessionId valid audio session id - * @param metadata valid metadata for the session. - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_set_metadata(in int sessionId, in byte[] metadata); - - /** - * set config for non tunnel mode (rx and tx path) - * @param handle session handle returned from agm_session_open - * @param sessionConfig valid stream configuration of the session - * @param inMediaConfig valid media configuration of the input data - * @param outMediaConfig valid media configuration of the output data - * @param inBufferConfig valid buffer configuration of the input data - * @param outBufferConfig valid buffer configuration of the output data - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_set_non_tunnel_mode_config(in long handle, - in AgmSessionConfig sessionConfig, in AgmMediaConfig inMediaConfig, - in AgmMediaConfig outMediaConfig, in AgmBufferConfig inBufferConfig, - in AgmBufferConfig outBufferConfig); - - /** - * Set parameters for modules in stream - * @param sessionId valid audio session id - * @param payload payload for set parameters - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_set_params(in int sessionId, in byte[] payload); - - /** - * Write data buffers to the session - * @param handle session handle returned from agm_session_open - * @param buff buffer containing the data to be written - * @return number of bytes written - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - int ipc_agm_session_write(in long handle, in byte[] buff); - - /** - * Write buffers containing codec params to session on datapath - * @param sessionId valid audio session id - * @param buff AgmBuff where data will be copied from - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_write_datapath_params(in int sessionId, in AgmBuff buff); - - /** - * Write data buffers with metadata to session - * @param handle session handle returned from agm_session_open - * @param buff AgmBuff where data will be copied fromo - * @return number of bytes written - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - int ipc_agm_session_write_with_metadata(in long handle, in AgmBuff buff); - - /** - * Set media configuration for a group audio interface. - * @param groupId valid group id - * @param config valid media configuration for the audio interface - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_aif_group_set_media_config(in int groupId, in AgmGroupMediaConfig config); - - /** - * Set media configuration for an audio interface. - * @param aifId Valid audio interface id - * @param config valid media configuration for the audio interface - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_aif_set_media_config(in int aifId, in AgmMediaConfig config); - - /** - * Set metadata for an audio interface. - * @param aifId Valid audio interface id - * @param metadata valid metadata for the audio interface - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_aif_set_metadata(in int aifId, in byte[] metadata); - - /** - * Set parameters for modules in audio interface - * @param aifId Valid audio interface id - * @param payload parameter payload - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_aif_set_params(in int aifId, in byte[] payload); - - /** - * connect/disconnect the audio interface. - * @param sessionId valid audio session id - * @param aifId Valid audio interface id - * @param state connect or disconnect AIF to Session - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_aif_connect(in int sessionId, in int aifId, in boolean state); - - /** - * Read the module tag info for audio interface. - * @param sessionId valid audio session id - * @param aifId Valid audio interface id - * @param size if the value of size is zero, AGM will update required module - * info list of a given graph. if size equal or greater than the required size, - * AGM will copy the module info. - * @return byte [] payload containing tag module info list in the graph - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - byte[] ipc_agm_session_aif_get_tag_module_info(in int sessionId, in int aifId, in int size); - - /** - * Set calibration for modules in b/w stream and audio interface - * @param sessionId valid audio session id - * @param aifId Valid audio interface id - * @param calibration key vector - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_aif_set_cal(in int sessionId, in int aifId, - in AgmCalConfig calConfig); - - /** - * Set metadata for the session, audio interface pair. - * @param sessionId valid audio session id - * @param aifId Valid audio interface id - * @param metadata valid metadata for the session and audio interface - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_aif_set_metadata(in int sessionId, in int aifId, in byte[] metadata); - - /** - * Set parameters for modules in b/w stream and audio interface. - * @param sessionId valid audio session id - * @param aifId Valid audio interface id - * @param payload payload containing parameters - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_session_aif_set_params(in int sessionId, in int aifId, in byte[] payload); - - /** - * Get list of AIF info objects - * @param numAifInfo number of aif info items in the list. - * if numAifInfo value is listed as zero, AGM will update numAifInfo with - * the number of aif info items in AGM. - * if numAifInfo is greater than zero, - * AGM will copy client specified numAifInfo of items into out result. - * @return AifInfo[] vector of AifInfo objects - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - AifInfo[] ipc_agm_get_aif_info_list(in int numAifInfo); - - /** - * Get timestamp of last read buffer. - * @param sessionId valid audio session id - * @return valid timestamp - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - long ipc_agm_get_buffer_timestamp(in int sessiondId); - - /** - * Get list of group AIF objects. - * @param numberOfGroups valid audio session id - * number of group aif items in the list. - * if numberOfGroups value is listed as zero, AGM will update numberOfGroups with - * the number of group aif items in AGM. - * if numberOfGroups is greater than zero, - * AGM will copy client specified numberOfGroups of items into aif_list. - * @return AifInfo[] vector of AifInfo objects - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - AifInfo[] ipc_agm_get_group_aif_info_list(in int numberOfGroups); - - /** - * Get count of Buffer processed by h/w - * @param handle session handle returned from agm_session_open - * @param direction indicates whether to return the write or read buffer count - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_get_hw_processed_buff_cnt(in long handle, in Direction direction); - - /** - * Get parameters for modules at acdb without session - * @param payload payload with tag and calibration - * @return byte [] return the parameters for given payload - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - byte[] ipc_agm_get_params_from_acdb_tunnel(in byte[] payload); - - /** - * get timestamp of the session. - * @param handle session handle returned from agm_session_open - * @return valid timestamp if the operation is successful - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - long ipc_agm_get_session_time(in long handle); - - /** - * flush the session. session must be in pause state before flushing. - * @param sessiondId valid session id. - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_sessionid_flush(in int sessiondId); - - /** - * set gapless metadata of the session. - * @param handle session handle returned from agm_session_open - * @param type Silence Type (Initial or Trailing) - * @param silence Initial/Trailing silence samples to be removed - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_set_gapless_session_metadata(in long handle, in AgmGaplessSilenceType type, in int silence); - - /** - * Set parameters for modules at acdb without session - * @param payload payload with tag and calibration data - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_set_params_to_acdb_tunnel(in byte[] payload); - - /** - * Set parameters for modules in b/w stream and audio interface - * @param sessionId valid audio session id - * @param aifId Valid audio interface id - * @param tagConfig tag config structure with tag id and tag key vector - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_set_params_with_tag(in int sessiondId, in int aifId, - in AgmTagConfig tagConfig); - - /** - * Set parameters for modules in b/w stream and audio interface - * @param sessionId valid audio session id - * @param aifId Valid audio interface id - * @param payload payload with tag and calibration data - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_set_params_with_tag_to_acdb(in int sessiondId, in int aifId, in byte[] payload); - - /** - * Dump AGM information based on client - * @param dumpInfo dump info - * @throws ServiceSpecificException with one of the values defined in Status.aidl - * These exceptions are used to preserve the linux error codes over AIDL. - * check converstion details at: aidlconverter/inc/agm/BinderStatus.h - */ - void ipc_agm_dump(in AgmDumpInfo dumpInfo); -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/IAGMCallback.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/IAGMCallback.aidl deleted file mode 100755 index 8a837598..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/IAGMCallback.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import vendor.qti.hardware.agm.AgmEventCallbackParameter; -import vendor.qti.hardware.agm.AgmReadWriteEventCallbackParams; - -/* -* Interface used to register callback for events -*/ -@VintfStability -interface IAGMCallback { - /** - * callback triggerred on receiving generic events from native agm/gsl - * @param eventParam contains AgmEventCallbackParameter - */ - void eventCallback(in AgmEventCallbackParameter eventParam); - /** - * callback triggerred on READ_DONE/WRITE_DONE events from native agm/gsl - * mainly used for non tunnel. - * @param rwDonePayload contains AgmReadWriteEventCallbackParams - */ - void eventCallbackReadWriteDone(in AgmReadWriteEventCallbackParams rwDonePayload); -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/MmapBufInfo.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/MmapBufInfo.aidl deleted file mode 100755 index 95a6dd5b..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/MmapBufInfo.aidl +++ /dev/null @@ -1,16 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -import android.hardware.common.NativeHandle; - -@VintfStability -parcelable MmapBufInfo { - NativeHandle dataFdHandle; - int dataSize; - NativeHandle positionFdHandle; - int posSize; -} diff --git a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/Status.aidl b/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/Status.aidl deleted file mode 100755 index bee92905..00000000 --- a/qcom/opensource/agm/ipc/aidl/vendor/qti/hardware/agm/Status.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/** -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -package vendor.qti.hardware.agm; - -/** - * Status codes to propagagte Linux error codes over AIDL. - * Keep in sync with vendor/qcom/opensource/agm/service/src/utils.c - * Few error codes are supported by binder_status.h by default. - * For unsupported codes, create ServiceSpecificException and based on - * exception extract the error code at client side. - */ -@VintfStability -@Backing(type="int") -enum Status { - UNKNOWN = -1, - SUCCESS = 0, - IO_ERROR, - BUSY, - NO_SPACE, - INVALID_FD, - ADVERTISE_ERROR, - PROTOCOL_NOT_AVAILABLE, - NOT_SUPPORTED, - DOWN_WITH_SSR, - NOW_INPROGRESS, - ALREADY_INPROGRESS, - CANCELLED, - NOT_RECOVERABLE, -} \ No newline at end of file diff --git a/qcom/opensource/agm/plugins/Android.mk b/qcom/opensource/agm/plugins/Android.mk deleted file mode 100755 index d18c0256..00000000 --- a/qcom/opensource/agm/plugins/Android.mk +++ /dev/null @@ -1,6 +0,0 @@ -MY_LOCAL_PATH := $(call my-dir) -include $(MY_LOCAL_PATH)/tinyalsa/Android.mk -include $(MY_LOCAL_PATH)/tinyalsa/test/Android.mk -ifneq (,$(filter userdebug eng, $(TARGET_BUILD_VARIANT))) -include $(MY_LOCAL_PATH)/tinyalsa/test/gtest/Android.mk -endif \ No newline at end of file diff --git a/qcom/opensource/agm/plugins/alsalib/src/agm_ctl_plugin.c b/qcom/opensource/agm/plugins/alsalib/src/agm_ctl_plugin.c deleted file mode 100755 index 872ab230..00000000 --- a/qcom/opensource/agm/plugins/alsalib/src/agm_ctl_plugin.c +++ /dev/null @@ -1,1359 +0,0 @@ -/* -** Copyright (c) 2020-2021, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "PLUGIN: AGMCTL" - -#include -#include -#include -#include -#include -#include "utils.h" - -#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0])) -#define MIXER_NAME_LEN 128 -#define PCM_NAME_LEN 24 - -/* enum for different types of control */ -enum { - AGM_FE_CTL_START = 0, - AGM_FE_CTL_NAME_METADATA = AGM_FE_CTL_START, - AGM_FE_CTL_NAME_SET_PARAM, - AGM_FE_CTL_NAME_SET_PARAM_TAG, - AGM_FE_CTL_NAME_CONNECT, - AGM_FE_CTL_NAME_DISCONNECT, - AGM_FE_CTL_NAME_CONTROL, - AGM_FE_CTL_NAME_GET_TAG_INFO, - AGM_FE_CTL_NAME_EVENT, - AGM_FE_CTL_NAME_SET_CALIBRATION, - AGM_FE_CTL_NAME_GET_PARAM, - AGM_FE_CTL_NAME_BUF_INFO, - /* Add new common FE control enum here */ - AGM_FE_CTL_END, - AGM_TX_CTL_START = AGM_FE_CTL_END, - AGM_FE_TX_CTL_NAME_LOOPBACK = AGM_TX_CTL_START, - AGM_FE_TX_CTL_NAME_ECHOREF, - AGM_FE_TX_CTL_NAME_BUF_TSTAMP, - /* Add new Tx only FE control enum here */ - AGM_TX_CTL_END, - AGM_BE_CTL_START = AGM_TX_CTL_END, - AGM_BE_CTL_NAME_MEDIA_CONFIG = AGM_BE_CTL_START, - AGM_BE_CTL_NAME_METADATA, - AGM_BE_CTL_NAME_SET_PARAM, - /* Add new Backend control enum here */ - AGM_BE_CTL_END, -}; - -/* struct containing control attibutes for each controls */ -/* Any new control entry must be added here */ -static const struct agm_ctl_attribute_info { - int type; - unsigned int access; - unsigned int count; -} attr_info[AGM_BE_CTL_END] = { - /********************** START OF COMMON FE CONTROLS ***********************/ - [AGM_FE_CTL_NAME_METADATA] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 1024}, - [AGM_FE_CTL_NAME_SET_PARAM] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 128 * 1024}, - [AGM_FE_CTL_NAME_SET_PARAM_TAG] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 1024}, - [AGM_FE_CTL_NAME_CONNECT] = {SND_CTL_ELEM_TYPE_ENUMERATED, SND_CTL_EXT_ACCESS_READWRITE, 1}, - [AGM_FE_CTL_NAME_DISCONNECT] = {SND_CTL_ELEM_TYPE_ENUMERATED, SND_CTL_EXT_ACCESS_READWRITE, 1}, - [AGM_FE_CTL_NAME_CONTROL] = {SND_CTL_ELEM_TYPE_ENUMERATED, SND_CTL_EXT_ACCESS_READWRITE, 1}, - [AGM_FE_CTL_NAME_GET_TAG_INFO] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 1024}, - [AGM_FE_CTL_NAME_EVENT] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 512}, - [AGM_FE_CTL_NAME_SET_CALIBRATION] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 512}, - [AGM_FE_CTL_NAME_GET_PARAM] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 128 * 1024}, - [AGM_FE_CTL_NAME_BUF_INFO] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 512}, - /*********************** END OF COMMON FE CONTROLS ************************/ - /********************** START OF TX FE CONTROLS ***********************/ - [AGM_FE_TX_CTL_NAME_LOOPBACK] = {SND_CTL_ELEM_TYPE_ENUMERATED, SND_CTL_EXT_ACCESS_READWRITE, 1}, - [AGM_FE_TX_CTL_NAME_ECHOREF] = {SND_CTL_ELEM_TYPE_ENUMERATED, SND_CTL_EXT_ACCESS_READWRITE, 1}, - [AGM_FE_TX_CTL_NAME_BUF_TSTAMP] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 512}, - /*********************** END OF TX FE CONTROLS ************************/ - /************************** START OF BE CONTROLS **************************/ - [AGM_BE_CTL_NAME_MEDIA_CONFIG] = {SND_CTL_ELEM_TYPE_INTEGER, SND_CTL_EXT_ACCESS_READWRITE, 4}, - [AGM_BE_CTL_NAME_METADATA] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 1024}, - [AGM_BE_CTL_NAME_SET_PARAM] = {SND_CTL_ELEM_TYPE_BYTES, SND_CTL_EXT_ACCESS_TLV_READWRITE | - SND_CTL_EXT_ACCESS_TLV_CALLBACK, 64 * 1024}, - /*************************** END OF BE CONTROLS ***************************/ -}; - -/* control name for common frontend controls*/ -static char *agm_fe_ctl_name_extn[] = { - "metadata", - "setParam", - "setParamTag", - "connect", - "disconnect", - "control", - "getTaggedInfo", - "event", - "setCalibration", - "getParam", - "getBufInfo" - /* add new control entry here */ -}; - -/* control name for tx only frontend controls*/ -static char *agm_tx_ctl_name_extn[] = { - "loopback", - "echoReference", - "bufTimestamp", - /* add new control entry here */ -}; - -/* control name for backend controls*/ -static char *agm_be_ctl_name_extn[] = { - "rate ch fmt", - "metadata", - "setParam", - /* add new control entry here */ -}; - -/* struct containing information per control */ -struct agm_mixer_controls { - char mixer_name[MIXER_NAME_LEN + 1]; - int pcm_be_id; /* stores pcm_id for FE controls and AIF id for BE controls */ - uint32_t ctl_id; //enum for control - struct agmctl_priv *priv; -}; - -struct agmctl_priv { - snd_ctl_ext_t ext; - - int card; - void *card_node; - - size_t aif_count; - struct aif_info *aif_list; - - uint32_t rx_count; - char (*rx_names)[PCM_NAME_LEN + 1]; - int *rx_pcm_id; - - uint32_t pcm_count; - /* - * Mixer ctl data cache for - * "PCM control" - * Unused for BE devs - */ - int *pcm_mtd_ctl; - int *pcm_idx; - - /* - * Mixer ctl data cache for - * "PCM getParam" - * Unused for BE devs - */ - void *get_param_payload; - int get_param_payload_size; - - uint32_t total_ctl_cnt; - struct agm_mixer_controls *controls; -}; - -static enum agm_media_format alsa_to_agm_fmt(int fmt) -{ - enum agm_media_format agm_pcm_fmt = AGM_FORMAT_INVALID; - - switch (fmt) { - case SND_PCM_FORMAT_S8: - agm_pcm_fmt = AGM_FORMAT_PCM_S8; - break; - case SND_PCM_FORMAT_S16_LE: - agm_pcm_fmt = AGM_FORMAT_PCM_S16_LE; - break; - case SND_PCM_FORMAT_S24_LE: - agm_pcm_fmt = AGM_FORMAT_PCM_S24_LE; - break; - case SND_PCM_FORMAT_S24_3LE: - agm_pcm_fmt = AGM_FORMAT_PCM_S24_3LE; - break; - case SND_PCM_FORMAT_S32_LE: - agm_pcm_fmt = AGM_FORMAT_PCM_S32_LE; - break; - } - - return agm_pcm_fmt; -} - -static int agmctl_pcm_get_control_value(struct agmctl_priv *agmctl, int pcm_idx) -{ - int i; - - for (i = 0; i < agmctl->pcm_count; i++) { - if (agmctl->pcm_idx[i] == pcm_idx) - break; - } - if (i == agmctl->pcm_count) { - AGM_LOGD("%s: pcm id %d out of range\n", __func__, pcm_idx); - return -EINVAL; - } - - return agmctl->pcm_mtd_ctl[i]; -} - -static int agmctl_pcm_metadata_put(struct agm_mixer_controls *control, - unsigned char *data, size_t max_bytes) -{ - int pcm_idx = control->pcm_be_id; - int ret = 0, be_idx = -1; - int pcm_control; - - pcm_control = agmctl_pcm_get_control_value(control->priv, pcm_idx); - if (pcm_control > 0) { - be_idx = pcm_control - 1; - ret = agm_session_aif_set_metadata(pcm_idx, be_idx, max_bytes, data); - } else { - ret = agm_session_set_metadata(pcm_idx, max_bytes, data); - } - - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_session_metadata failed err %d for %d\n", - __func__, ret, pcm_idx); - return ret; -} - -static int agmctl_pcm_setparam_put(struct agm_mixer_controls *control, - unsigned char *data, size_t max_bytes) -{ - int pcm_idx = control->pcm_be_id; - int ret = 0, be_idx = -1; - int pcm_control; - - pcm_control = agmctl_pcm_get_control_value(control->priv, pcm_idx); - if (pcm_control > 0) { - be_idx = pcm_control - 1; - ret = agm_session_aif_set_params(pcm_idx, be_idx, - data, max_bytes); - } else { - ret = agm_session_set_params(pcm_idx, data, max_bytes); - } - - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_params failed err %d for %d\n", - __func__, ret, pcm_idx); - return ret; -} - -static int agmctl_pcm_setparamtag_put(struct agm_mixer_controls *control, - unsigned char *data, size_t max_bytes __unused) -{ - int pcm_idx = control->pcm_be_id; - int ret = 0, be_idx = -1; - int pcm_control; - - pcm_control = agmctl_pcm_get_control_value(control->priv, pcm_idx); - if (pcm_control <= 0) { - AGM_LOGE("%s: err: control not set to Backend\n", __func__); - return -EINVAL; - } - - be_idx = pcm_control - 1; - ret = agm_set_params_with_tag(pcm_idx, be_idx, (struct agm_tag_config *)data); - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_paramtag failed err %d for %d\n", - __func__, ret, pcm_idx); - return ret; -} - -static int agmctl_pcm_event_get(struct agm_mixer_controls *control __unused, - unsigned char *data __unused, size_t len __unused) -{ - /* TODO : Handle event */ - return 0; -} - -static int agmctl_pcm_event_put(struct agm_mixer_controls *control, - unsigned char *data, size_t max_bytes __unused) -{ - int pcm_idx = control->pcm_be_id; - struct agm_event_reg_cfg *evt_reg_cfg; - int ret = 0; - - evt_reg_cfg = (struct agm_event_reg_cfg *)data; - ret = agm_session_register_for_events(pcm_idx, evt_reg_cfg); - - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_event failed, err %d, session_id %u\n", - __func__, ret, pcm_idx); - return ret; -} - -static int agmctl_pcm_calibration_put(struct agm_mixer_controls *control, - unsigned char *data, size_t max_bytes __unused) -{ - struct agm_cal_config *cal_config = (struct agm_cal_config *)data; - int pcm_idx = control->pcm_be_id; - int ret, be_idx = -1; - int pcm_control; - - pcm_control = agmctl_pcm_get_control_value(control->priv, pcm_idx); - if (pcm_control <= 0) { - AGM_LOGE("%s: err: control not set to Backend\n", __func__); - return -EINVAL; - } - - be_idx = pcm_control - 1; - ret = agm_session_aif_set_cal(pcm_idx, be_idx, cal_config); - if (ret) - AGM_LOGE("%s: set_calbration failed, err %d, aif_id %u\n", - __func__, ret, be_idx); - return ret; -} - -static int agmctl_pcm_get_param_get(struct agm_mixer_controls *control, - unsigned char *data, size_t len) -{ - void *payload = data; - int pcm_idx = control->pcm_be_id; - int ret = 0; - - if (!control->priv->get_param_payload) { - AGM_LOGE("%s: put() for getParam not called\n", __func__); - return -EINVAL; - } - - if (len < control->priv->get_param_payload_size) { - AGM_LOGE("%s: Buffer size less than expected\n", __func__); - return -EINVAL; - } - - memcpy(data, control->priv->get_param_payload, control->priv->get_param_payload_size); - ret = agm_session_get_params(pcm_idx, payload, control->priv->get_param_payload_size); - - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: failed err %d for %d\n", __func__, ret, pcm_idx); - - free(control->priv->get_param_payload); - control->priv->get_param_payload = NULL; - control->priv->get_param_payload_size = 0; - return ret; -} - -static int agmctl_pcm_get_param_put(struct agm_mixer_controls *control, - unsigned char *data, size_t len) -{ - void *payload; - - if (control->priv->get_param_payload) { - free(control->priv->get_param_payload); - control->priv->get_param_payload = NULL; - } - payload = data; - control->priv->get_param_payload_size = len; - - control->priv->get_param_payload = calloc(1, control->priv->get_param_payload_size); - if (!control->priv->get_param_payload) - return -ENOMEM; - - memcpy(control->priv->get_param_payload, payload, control->priv->get_param_payload_size); - - return 0; -} - -static int agmctl_pcm_buf_timestamp_get(struct agm_mixer_controls *control, - unsigned char *data, size_t len __unused) -{ - int pcm_idx = control->pcm_be_id; - int ret; - uint64_t *timestamp = NULL; - - timestamp = (uint64_t *)data; - ret = agm_get_buffer_timestamp(pcm_idx, timestamp); - return ret; -} - -static int agmctl_pcm_tag_info_get(struct agm_mixer_controls *control, - unsigned char *data, size_t len) -{ - void *payload; - int pcm_idx = control->pcm_be_id; - int be_idx = -1, ret = 0; - size_t get_size = 0; - int pcm_control; - - pcm_control = agmctl_pcm_get_control_value(control->priv, pcm_idx); - if (pcm_control <= 0) { - AGM_LOGE("%s: err: control not set to Backend\n", __func__); - return -EINVAL; - } - - be_idx = pcm_control - 1; - ret = agm_session_aif_get_tag_module_info(pcm_idx, be_idx, - NULL, &get_size); - if (ret || get_size == 0 || len < get_size) { - AGM_LOGE("%s: invalid size, ret %d, tlv_size %zu, get_size %zu\n", - __func__, ret, len, get_size); - return -EINVAL; - } - - payload = (void *)data; - ret = agm_session_aif_get_tag_module_info(pcm_idx, be_idx, - payload, &get_size); - if (ret) - AGM_LOGE("%s: session_aif_get_tag_module_info failed err %d for %d\n", - __func__, ret, pcm_idx); - return ret; -} - -static int agmctl_pcm_connect_put(struct agm_mixer_controls *control, - unsigned int *item) -{ - bool state = true; - int be_idx = *item; - int rc, pcm_idx = control->pcm_be_id; - - if (control->ctl_id == AGM_FE_CTL_NAME_DISCONNECT) - state = false; - - rc = agm_session_aif_connect(pcm_idx, be_idx, state); - if (rc == -EALREADY) - rc = 0; - - if (rc) - AGM_LOGE("%s: connect failed err %d, pcm_idx %d be_idx %d\n", - __func__, rc, pcm_idx, be_idx); - - return rc; -} - -static int agmctl_pcm_loopback_put(struct agm_mixer_controls *control, - unsigned int *item) -{ - bool state = true; - int rx_idx = *item; - int rc, pcm_idx = control->pcm_be_id; - - if (rx_idx == 0) - state = false; - else - rx_idx = control->priv->rx_pcm_id[rx_idx - 1]; - - rc = agm_session_set_loopback(pcm_idx, rx_idx, state);; - if (rc == -EALREADY) - rc = 0; - - if (rc) - AGM_LOGE("%s: loopback failed err %d, rx_idx %d tx_idx %d\n", - __func__, rc, rx_idx, pcm_idx); - - return rc; -} - -static int agmctl_pcm_ecref_put(struct agm_mixer_controls *control, - unsigned int *item) -{ - bool state = true; - int be_idx = *item; - int rc, pcm_idx = control->pcm_be_id; - - if (be_idx == 0) - state = false; - else - be_idx--; - - rc = agm_session_set_ec_ref(pcm_idx, be_idx, state);; - if (rc == -EALREADY) - rc = 0; - - if (rc) - AGM_LOGE("%s: set ecref failed err %d, pcm_idx %d be_idx %d\n", - __func__, rc, pcm_idx, be_idx); - - return rc; -} - -static int agmctl_pcm_control_put(struct agm_mixer_controls *control, - unsigned int *item) -{ - int i, idx = control->pcm_be_id; - unsigned int val; - - val = *item; - if (val > control->priv->aif_count) { - AGM_LOGD("%s: invalid input pcm ctl id %d\n", __func__, val); - return -EINVAL; - } - - for (i = 0; i < control->priv->pcm_count; i++) { - if (control->priv->pcm_idx[i] == idx) - break; - } - if (i == control->priv->pcm_count) { - AGM_LOGD("%s: pcm id %d out of range\n", __func__, idx); - return -EINVAL; - } - - control->priv->pcm_mtd_ctl[i] = val; - - AGM_LOGD("%s: value = %u\n", __func__, val); - return 0; -} - -static int agmctl_pcm_buf_info_get(struct agm_mixer_controls *control, - unsigned char *data, size_t len __unused) -{ - struct agm_buf_info *buf_info; - int pcm_idx = control->pcm_be_id; - int ret = 0; - - buf_info = (struct agm_buf_info *) data; - - ret = agm_session_get_buf_info(pcm_idx, buf_info, DATA_BUF); - return ret; -} - -static int agmctl_be_metadata_put(struct agm_mixer_controls *control, - unsigned char *data, size_t len) -{ - int be_idx = control->pcm_be_id; - int ret = 0; - - ret = agm_aif_set_metadata(be_idx, len, data); - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_aif_metadata failed err %d for %d\n", - __func__, ret, be_idx); - return ret; -} - -static int agmctl_be_setparam_put(struct agm_mixer_controls *control, - unsigned char *data, size_t len) -{ - int be_idx = control->pcm_be_id; - int ret = 0; - - ret = agm_aif_set_metadata(be_idx, len, data); - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_params failed err %d for %d\n", - __func__, ret, be_idx); - return ret; -} - -static int agmctl_be_media_config_put(struct agm_mixer_controls *control, - long *val) -{ - struct agm_media_config media_fmt; - int be_idx = control->pcm_be_id; - int ret = 0; - - media_fmt.rate = val[0]; - media_fmt.channels = val[1]; - media_fmt.format = alsa_to_agm_fmt(val[2]); - media_fmt.data_format = val[3]; - - ret = agm_aif_set_media_config(be_idx, &media_fmt); - if (ret) - AGM_LOGE("%s: set_media_config failed, err %d, aif_id %u rate %u \ - channels %u fmt %u, data_fmt %u\n", - __func__, ret, be_idx, media_fmt.rate, media_fmt.channels, - media_fmt.format, media_fmt.data_format); - return ret; -} - -static int agmctl_form_common_fe_controls(struct agmctl_priv *agmctl, void *pcm_node, int *ctl_idx) -{ - int ret, i, pcm_id, ctl_per_pcm; - char *name; - - ctl_per_pcm = (int)ARRAY_SIZE(agm_fe_ctl_name_extn); - - ret = snd_card_def_get_str(pcm_node, "name", &name); - if (ret) { - AGM_LOGE("%s failed to get name\n", __func__); - return -EINVAL; - } - ret = snd_card_def_get_int(pcm_node, "id", &pcm_id); - if (ret) { - AGM_LOGE("%s failed to get id for %s\n", __func__, name); - return -EINVAL; - } - for (i = 0; i < ctl_per_pcm; i++) { - agmctl->controls[*ctl_idx].priv = agmctl; - agmctl->controls[*ctl_idx].pcm_be_id = pcm_id; - agmctl->controls[*ctl_idx].ctl_id = AGM_FE_CTL_START + i; - snprintf(agmctl->controls[*ctl_idx].mixer_name, MIXER_NAME_LEN, "%s %s", - name, agm_fe_ctl_name_extn[i]); - - AGM_LOGD("control[%d] is [%s]\n", *ctl_idx, agmctl->controls[*ctl_idx].mixer_name); - (*ctl_idx)++; - } - - return 0; -} - -static int agmctl_populate_rx_name(struct agmctl_priv *agmctl, void *pcm_node, int *rx_idx) -{ - int ret, pcm_id; - char *name, *rx_name; - - ret = snd_card_def_get_str(pcm_node, "name", &name); - if (ret) { - AGM_LOGE("%s failed to get name\n", __func__); - return -EINVAL; - } - ret = snd_card_def_get_int(pcm_node, "id", &pcm_id); - if (ret) { - AGM_LOGE("%s failed to get id for %s\n", __func__, name); - return -EINVAL; - } - - agmctl->rx_pcm_id[*rx_idx] = pcm_id; - rx_name = agmctl->rx_names[*rx_idx]; - strlcpy(rx_name, name, PCM_NAME_LEN); - - (*rx_idx)++; - - return 0; -} - -static int agmctl_form_tx_controls(struct agmctl_priv *agmctl, void *pcm_node, int *ctl_idx) -{ - int ret, i, pcm_id, ctl_per_pcm; - char *name; - - ctl_per_pcm = (int)ARRAY_SIZE(agm_tx_ctl_name_extn); - - ret = snd_card_def_get_str(pcm_node, "name", &name); - if (ret) { - AGM_LOGE("%s failed to get name\n", __func__); - return -EINVAL; - } - - ret = snd_card_def_get_int(pcm_node, "id", &pcm_id); - if (ret) { - AGM_LOGE("%s failed to get id for %s\n", __func__, name); - return -EINVAL; - } - - for (i = 0; i < ctl_per_pcm; i++) { - agmctl->controls[*ctl_idx].priv = agmctl; - agmctl->controls[*ctl_idx].pcm_be_id = pcm_id; - agmctl->controls[*ctl_idx].ctl_id = AGM_TX_CTL_START + i; - snprintf(agmctl->controls[*ctl_idx].mixer_name, MIXER_NAME_LEN, "%s %s", - name, agm_tx_ctl_name_extn[i]); - - AGM_LOGD("control[%d] is [%s]\n", *ctl_idx, agmctl->controls[*ctl_idx].mixer_name); - (*ctl_idx)++; - } - - return 0; -} - -static int agmctl_form_be_controls(struct agmctl_priv *agmctl, int be_idx, int *ctl_idx) -{ - int i, ctl_per_be; - - ctl_per_be = (int)ARRAY_SIZE(agm_be_ctl_name_extn); - - for (i = 0; i < ctl_per_be; i++) { - agmctl->controls[*ctl_idx].priv = agmctl; - agmctl->controls[*ctl_idx].pcm_be_id = be_idx; - agmctl->controls[*ctl_idx].ctl_id = AGM_BE_CTL_START + i; - snprintf(agmctl->controls[*ctl_idx].mixer_name, MIXER_NAME_LEN, "%s %s", - agmctl->aif_list[be_idx].aif_name, agm_be_ctl_name_extn[i]); - - AGM_LOGD("control[%d] is [%s]\n", *ctl_idx, agmctl->controls[*ctl_idx].mixer_name); - (*ctl_idx)++; - } - - return 0; -} - -static int amp_form_mixer_controls(struct agmctl_priv *agmctl, int *ctl_idx) -{ - void **pcm_node_list = NULL; - int num_pcms = 0, num_compr = 0; - int total_pcms, total_tx = 0, rx_idx = 0; - int ret, val = 0, i; - int ctl_per_pcm; - - /* Get both pcm and compressed node count */ - num_pcms = snd_card_def_get_num_node(agmctl->card_node, - SND_NODE_TYPE_PCM); - num_compr = snd_card_def_get_num_node(agmctl->card_node, - SND_NODE_TYPE_COMPR); - if (num_pcms <= 0 && num_compr <= 0) { - AGM_LOGE("%s: no pcms(%d)/compr(%d) nodes found for card %u\n", - __func__, num_pcms, num_compr, agmctl->card); - ret = -EINVAL; - goto done; - } - - /* It is valid that any card could have just PCMs or just comprs or both */ - num_pcms = (num_pcms < 0) ? 0 : num_pcms; - num_compr = (num_compr < 0) ? 0 : num_compr; - - total_pcms = num_pcms + num_compr; - ctl_per_pcm = (int)ARRAY_SIZE(agm_fe_ctl_name_extn); - agmctl->total_ctl_cnt = total_pcms * ctl_per_pcm; - - pcm_node_list = calloc(total_pcms, sizeof(*pcm_node_list)); - if (!pcm_node_list) { - AGM_LOGE("%s: alloc for pcm_node_list failed\n", __func__); - return -ENOMEM; - } - - agmctl->pcm_count = total_pcms; - agmctl->pcm_mtd_ctl = calloc(total_pcms, sizeof(int)); - if (!agmctl->pcm_mtd_ctl) { - ret = -ENOMEM; - goto done; - } - - agmctl->pcm_idx = calloc(total_pcms, sizeof(int)); - if (!agmctl->pcm_idx) { - ret = -ENOMEM; - goto done; - } - - if (num_pcms > 0) { - ret = snd_card_def_get_nodes_for_type(agmctl->card_node, - SND_NODE_TYPE_PCM, - pcm_node_list, num_pcms); - if (ret) { - AGM_LOGE("%s: failed to get pcm node list, err %d\n", - __func__, ret); - goto done; - } - } - - if (num_compr > 0) { - ret = snd_card_def_get_nodes_for_type(agmctl->card_node, - SND_NODE_TYPE_COMPR, - &pcm_node_list[num_pcms], - num_compr); - if (ret) { - AGM_LOGE("%s: failed to get compr node list, err %d\n", - __func__, ret); - goto done; - } - } - - /* count TX and RX PCMs + Comprs*/ - for (i = 0; i < total_pcms; i++) { - void *pcm_node = pcm_node_list[i]; - - snd_card_def_get_int(pcm_node, "id", &agmctl->pcm_idx[i]); - - val = 0; - snd_card_def_get_int(pcm_node, "playback", &val); - if (val == 1) - agmctl->rx_count++; - - val = 0; - snd_card_def_get_int(pcm_node, "capture", &val); - if (val == 1) - total_tx++; - } - - ctl_per_pcm = (int)ARRAY_SIZE(agm_tx_ctl_name_extn); - agmctl->total_ctl_cnt += total_tx * ctl_per_pcm; - agmctl->total_ctl_cnt += agmctl->aif_count * ARRAY_SIZE(agm_be_ctl_name_extn); - - AGM_LOGD("Total virtual controls:%d", agmctl->total_ctl_cnt); - agmctl->controls = calloc(agmctl->total_ctl_cnt, sizeof(struct agm_mixer_controls)); - if (!agmctl->controls) { - ret = -ENOMEM; - goto done; - } - - agmctl->rx_names = calloc(agmctl->rx_count, sizeof(*agmctl->rx_names)); - if (!agmctl->rx_names) { - ret = -ENOMEM; - goto done; - } - - agmctl->rx_pcm_id = calloc(agmctl->rx_count, sizeof(*agmctl->rx_pcm_id)); - if (!agmctl->rx_pcm_id) { - ret = -ENOMEM; - goto done; - } - - for (i = 0; i < total_pcms; i++) { - void *pcm_node = pcm_node_list[i]; - - agmctl_form_common_fe_controls(agmctl, pcm_node, ctl_idx); - - val = 0; - snd_card_def_get_int(pcm_node, "playback", &val); - if (val == 1) - agmctl_populate_rx_name(agmctl, pcm_node, &rx_idx); - - val = 0; - snd_card_def_get_int(pcm_node, "capture", &val); - if (val == 1) - agmctl_form_tx_controls(agmctl, pcm_node, ctl_idx); - } - - for (i = 0; i < agmctl->aif_count; i++) { - agmctl_form_be_controls(agmctl, i, ctl_idx); - } - -done: - if (pcm_node_list) - free(pcm_node_list); - - if (ret) { - if (agmctl->pcm_mtd_ctl) - free(agmctl->pcm_mtd_ctl); - - if (agmctl->pcm_idx) - free(agmctl->pcm_idx); - - if (agmctl->controls) - free(agmctl->controls); - - if (agmctl->rx_names) - free(agmctl->rx_names); - - if (agmctl->rx_pcm_id) - free(agmctl->rx_pcm_id); - } - return ret; -} - -static int agmctl_elem_count(snd_ctl_ext_t * ext) -{ - struct agmctl_priv *agmctl = ext->private_data; - - return agmctl->total_ctl_cnt; -} - -static int agmctl_elem_list(snd_ctl_ext_t * ext, unsigned int offset, - snd_ctl_elem_id_t * id) -{ - struct agmctl_priv *agmctl = ext->private_data; - - snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER); - - if (offset < agmctl->total_ctl_cnt) - snd_ctl_elem_id_set_name(id, agmctl->controls[offset].mixer_name); - - return 0; -} - -static snd_ctl_ext_key_t agmctl_find_elem(snd_ctl_ext_t * ext, - const snd_ctl_elem_id_t * id) -{ - const char *name; - unsigned int numid, i; - struct agmctl_priv *agmctl = ext->private_data; - - numid = snd_ctl_elem_id_get_numid(id); - if (numid > 0 && numid < agmctl->total_ctl_cnt) - return numid - 1; - - name = snd_ctl_elem_id_get_name(id); - - for (i = 0; i < agmctl->total_ctl_cnt; i++) { - if (strcmp(name, agmctl->controls[i].mixer_name) == 0) { - snd_ctl_elem_id_set_numid((snd_ctl_elem_id_t *)id, i + 1); - return i; - } - } - - return SND_CTL_EXT_KEY_NOT_FOUND; -} - -static int agmctl_get_attribute(snd_ctl_ext_t * ext, snd_ctl_ext_key_t key, - int *type, unsigned int *access, - unsigned int *count) -{ - struct agmctl_priv *agmctl = ext->private_data; - int ctl_id; - - if (key >= agmctl->total_ctl_cnt) { - AGM_LOGE("Invalid key %lu\n", key); - return -EINVAL; - } - - ctl_id = agmctl->controls[key].ctl_id; - - *type = attr_info[ctl_id].type; - *access = attr_info[ctl_id].access; - *count = attr_info[ctl_id].count; - return 0; -} - -static int agmctl_get_integer_info(snd_ctl_ext_t * ext, - snd_ctl_ext_key_t key, long *imin, - long *imax, long *istep) -{ - int rc = 0; - struct agmctl_priv *agmctl = ext->private_data; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - switch (agmctl->controls[key].ctl_id) { - case AGM_BE_CTL_NAME_MEDIA_CONFIG: - *istep = 1; - *imin = 0; - *imax = 384000; - break; - default: - rc = -EINVAL; - AGM_LOGE("Unsupported control %d\n", agmctl->controls[key].ctl_id); - break; - } - return rc; -} - -static int agmctl_get_enumerated_info(snd_ctl_ext_t *ext, - snd_ctl_ext_key_t key, - unsigned int *items) -{ - int rc = 0; - struct agmctl_priv *agmctl = ext->private_data; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - switch (agmctl->controls[key].ctl_id) { - case AGM_FE_CTL_NAME_CONNECT: - case AGM_FE_CTL_NAME_DISCONNECT: - *items = agmctl->aif_count; - break; - case AGM_FE_CTL_NAME_CONTROL: - case AGM_FE_TX_CTL_NAME_ECHOREF: - *items = agmctl->aif_count + 1; - break; - case AGM_FE_TX_CTL_NAME_LOOPBACK: - *items = agmctl->rx_count + 1; - break; - default: - AGM_LOGE("Unsupported control %d\n", agmctl->controls[key].ctl_id); - rc = -EINVAL; - break; - } - - return rc; -} - -static int agmctl_get_enumerated_name(snd_ctl_ext_t *ext, - snd_ctl_ext_key_t key, - unsigned int item, char *name, - size_t name_max_len) -{ - int rc = 0; - struct agmctl_priv *agmctl = ext->private_data; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - switch (agmctl->controls[key].ctl_id) { - case AGM_FE_CTL_NAME_CONNECT: - case AGM_FE_CTL_NAME_DISCONNECT: - if (item >= agmctl->aif_count) - break; - - strlcpy(name, agmctl->aif_list[item].aif_name, name_max_len); - break; - case AGM_FE_CTL_NAME_CONTROL: - case AGM_FE_TX_CTL_NAME_ECHOREF: - if (item > agmctl->aif_count) - break; - if (item == 0) - strlcpy(name, "ZERO", name_max_len); - else - strlcpy(name, agmctl->aif_list[item-1].aif_name, name_max_len); - - break; - case AGM_FE_TX_CTL_NAME_LOOPBACK: - if (item >= agmctl->rx_count) - break; - - if (item == 0) - strlcpy(name, "ZERO", name_max_len); - else - strlcpy(name, agmctl->rx_names[item - 1], name_max_len); - - break; - default: - rc = -EINVAL; - AGM_LOGE("Unsupported control %d\n", agmctl->controls[key].ctl_id); - break; - } - - return rc; -} - -static int agmctl_read_enumerated(snd_ctl_ext_t *ext, - snd_ctl_ext_key_t key, - unsigned int *item __unused) -{ - int rc = 0; - struct agmctl_priv *agmctl = ext->private_data; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - switch (agmctl->controls[key].ctl_id) { - case AGM_FE_CTL_NAME_CONNECT: - case AGM_FE_CTL_NAME_DISCONNECT: - case AGM_FE_CTL_NAME_CONTROL: - case AGM_FE_TX_CTL_NAME_LOOPBACK: - case AGM_FE_TX_CTL_NAME_ECHOREF: - break; - default: - rc = -EINVAL; - AGM_LOGE("Unsupported control %d\n", agmctl->controls[key].ctl_id); - break; - } - - return rc; -} - -static int agmctl_write_enumerated(snd_ctl_ext_t *ext, - snd_ctl_ext_key_t key, unsigned int *item) -{ - int rc = 0; - struct agmctl_priv *agmctl = ext->private_data; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - switch (agmctl->controls[key].ctl_id) { - case AGM_FE_CTL_NAME_CONNECT: - case AGM_FE_CTL_NAME_DISCONNECT: - rc = agmctl_pcm_connect_put(&agmctl->controls[key], item); - break; - case AGM_FE_TX_CTL_NAME_LOOPBACK: - rc = agmctl_pcm_loopback_put(&agmctl->controls[key], item); - break; - case AGM_FE_TX_CTL_NAME_ECHOREF: - rc = agmctl_pcm_ecref_put(&agmctl->controls[key], item); - break; - case AGM_FE_CTL_NAME_CONTROL: - rc = agmctl_pcm_control_put(&agmctl->controls[key], item); - break; - default: - rc = -EINVAL; - AGM_LOGE("Unsupported control %d\n", agmctl->controls[key].ctl_id); - break; - } - - return rc; -} - -static int agmctl_read_integer(snd_ctl_ext_t * ext, snd_ctl_ext_key_t key, - long *value __unused) -{ - int rc = 0; - struct agmctl_priv *agmctl = ext->private_data; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - switch (agmctl->controls[key].ctl_id) { - case AGM_BE_CTL_NAME_MEDIA_CONFIG: - break; - default: - rc = -EINVAL; - AGM_LOGE("Unsupported control %d\n", agmctl->controls[key].ctl_id); - break; - } - return rc; -} - -static int agmctl_write_integer(snd_ctl_ext_t * ext, snd_ctl_ext_key_t key, - long *value) -{ - int rc = 0; - struct agmctl_priv *agmctl = ext->private_data; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - switch (agmctl->controls[key].ctl_id) { - case AGM_BE_CTL_NAME_MEDIA_CONFIG: - rc = agmctl_be_media_config_put(&agmctl->controls[key], value); - break; - default: - rc = -EINVAL; - AGM_LOGE("Unsupported control %d\n", agmctl->controls[key].ctl_id); - break; - } - return rc; - -} - -static int agmctl_read_bytes(snd_ctl_ext_t *ext, snd_ctl_ext_key_t key, - unsigned char *tlv, size_t tlv_size) -{ - struct agmctl_priv *agmctl = ext->private_data; - int rc = 0; - unsigned char *data; - size_t len; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - len = (size_t)*(tlv + sizeof(unsigned int)); - data = (unsigned char *)(tlv + 2 * sizeof(unsigned int)); - - switch (agmctl->controls[key].ctl_id) { - case AGM_FE_CTL_NAME_GET_TAG_INFO: - rc = agmctl_pcm_tag_info_get(&agmctl->controls[key], data, len); - break; - case AGM_FE_TX_CTL_NAME_BUF_TSTAMP: - rc = agmctl_pcm_buf_timestamp_get(&agmctl->controls[key], data, len); - break; - case AGM_FE_CTL_NAME_BUF_INFO: - rc = agmctl_pcm_buf_info_get(&agmctl->controls[key], data, len); - break; - case AGM_FE_CTL_NAME_GET_PARAM: - rc = agmctl_pcm_get_param_get(&agmctl->controls[key], data, len); - break; - case AGM_FE_CTL_NAME_EVENT: - rc = agmctl_pcm_event_get(&agmctl->controls[key], data, len); - break; - default: - rc = -EINVAL; - AGM_LOGE("Unsupported control %d\n", agmctl->controls[key].ctl_id); - break; - } - return rc; -} - -static int agmctl_write_bytes(snd_ctl_ext_t *ext, snd_ctl_ext_key_t key, - unsigned char *tlv, size_t tlv_size) -{ - struct agmctl_priv *agmctl = ext->private_data; - int rc = 0; - unsigned char *data; - size_t len; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - len = (size_t)*(tlv + sizeof(unsigned int)); - data = (unsigned char *)(tlv + 2 * sizeof(unsigned int)); - - switch (agmctl->controls[key].ctl_id) { - case AGM_FE_CTL_NAME_METADATA: - rc = agmctl_pcm_metadata_put(&agmctl->controls[key], data, len); - break; - case AGM_FE_CTL_NAME_SET_PARAM: - rc = agmctl_pcm_setparam_put(&agmctl->controls[key], data, len); - break; - case AGM_FE_CTL_NAME_SET_PARAM_TAG: - rc = agmctl_pcm_setparamtag_put(&agmctl->controls[key], data, len); - break; - case AGM_FE_CTL_NAME_EVENT: - rc = agmctl_pcm_event_put(&agmctl->controls[key], data, len); - break; - case AGM_FE_CTL_NAME_SET_CALIBRATION: - rc = agmctl_pcm_calibration_put(&agmctl->controls[key], data, len); - break; - case AGM_FE_CTL_NAME_GET_PARAM: - rc = agmctl_pcm_get_param_put(&agmctl->controls[key], data, len); - break; - case AGM_BE_CTL_NAME_METADATA: - rc = agmctl_be_metadata_put(&agmctl->controls[key], data, len); - break; - case AGM_BE_CTL_NAME_SET_PARAM: - rc = agmctl_be_setparam_put(&agmctl->controls[key], data, len); - break; - default: - rc = -EINVAL; - AGM_LOGE("Unsupported control %d\n", agmctl->controls[key].ctl_id); - break; - } - return rc; -} - -int agm_ext_tlv_callback(snd_ctl_ext_t *ext, snd_ctl_ext_key_t key, - int op_flag, unsigned int numid __unused, - unsigned int *tlv, unsigned int tlv_size) -{ - struct agmctl_priv *agmctl = ext->private_data; - - if (key >= agmctl->total_ctl_cnt) - return -EINVAL; - - if (op_flag == 0) - return agmctl_read_bytes(ext, key, (unsigned char *)tlv, (size_t)tlv_size); - else if (op_flag == 1) - return agmctl_write_bytes(ext, key, (unsigned char *)tlv, (size_t)tlv_size); - else - return -EINVAL; -} - -static void agmctl_close(snd_ctl_ext_t * ext) -{ - struct agmctl_priv *agmctl = ext->private_data; - - snd_card_def_put_card(agmctl->card_node); - free(agmctl->aif_list); - free(agmctl); -} - -static const snd_ctl_ext_callback_t agm_ext_callback = { - .elem_count = agmctl_elem_count, - .elem_list = agmctl_elem_list, - .find_elem = agmctl_find_elem, - .get_attribute = agmctl_get_attribute, - .get_integer_info = agmctl_get_integer_info, - .get_enumerated_info = agmctl_get_enumerated_info, - .get_enumerated_name = agmctl_get_enumerated_name, - .read_enumerated = agmctl_read_enumerated, - .read_integer = agmctl_read_integer, - .write_enumerated = agmctl_write_enumerated, - .write_integer = agmctl_write_integer, - .read_bytes = agmctl_read_bytes, - .write_bytes = agmctl_write_bytes, - .close = agmctl_close, -}; - -SND_CTL_PLUGIN_DEFINE_FUNC(agm) -{ - snd_config_iterator_t it, next; - struct agmctl_priv *ctl = NULL; - long card = 0; - int rc = 0, ctl_idx = 0; - size_t aif_count = 0; - struct aif_info *aif_list = NULL; - - ctl = calloc(1, sizeof(*ctl)); - if (!ctl) - return -ENOMEM; - - snd_config_for_each(it, next, conf) { - snd_config_t *n = snd_config_iterator_entry(it); - const char *id; - if (snd_config_get_id(n, &id) < 0) - continue; - if (strcmp(id, "comment") == 0 || strcmp(id, "type") == 0 || strcmp(id, "hint") == 0) - continue; - if (strcmp(id, "card") == 0) { - if (snd_config_get_integer(n, &card) < 0) { - AGM_LOGE("Invalid type for %s", id); - rc = -EINVAL; - goto err_free_ctl; - } - ctl->card = card; - continue; - } - AGM_LOGE("Unknown field %s", id); - rc = -EINVAL; - goto err_free_ctl; - } - - rc = agm_get_aif_info_list(NULL, &aif_count); - if (rc || aif_count == 0) - goto err_free_ctl; - - aif_list = calloc(aif_count, sizeof(struct aif_info)); - if (!aif_list) - goto err_free_ctl; - - rc = agm_get_aif_info_list(aif_list, &aif_count); - if (rc) - goto err_free_aif_list; - - ctl->aif_count = aif_count; - ctl->aif_list = aif_list; - - ctl->card_node = snd_card_def_get_card(card); - if (!ctl->card_node) { - AGM_LOGE("%s: card node not found for card %ld\n", __func__, card); - rc = -EINVAL; - goto err_free_aif_list; - } - - rc = amp_form_mixer_controls(ctl, &ctl_idx); - if (rc) - goto err_put_card; - - ctl->ext.version = SND_CTL_EXT_VERSION; - ctl->ext.card_idx = 0; - strlcpy(ctl->ext.id, "agm", sizeof(ctl->ext.id)); - strlcpy(ctl->ext.driver, "AGM control plugin", - sizeof(ctl->ext.driver)); - strlcpy(ctl->ext.name, "agm", sizeof(ctl->ext.name)); - strlcpy(ctl->ext.longname, "AudioGraphManager", - sizeof(ctl->ext.longname)); - strlcpy(ctl->ext.mixername, "agm", - sizeof(ctl->ext.mixername)); - ctl->ext.poll_fd = -1; - - ctl->ext.callback = &agm_ext_callback; - ctl->ext.tlv.c = &agm_ext_tlv_callback; - ctl->ext.private_data = ctl; - - rc = snd_ctl_ext_create(&ctl->ext, name, mode); - if (rc < 0) - goto err_put_card; - - AGM_LOGD("%s: exit", __func__); - *handlep = ctl->ext.handle; - - return 0; - -err_put_card: - snd_card_def_put_card(ctl->card_node); -err_free_aif_list: - free(aif_list); -err_free_ctl: - free(ctl); - return rc; -} -SND_CTL_PLUGIN_SYMBOL(agm); diff --git a/qcom/opensource/agm/plugins/alsalib/src/agm_io_plugin.c b/qcom/opensource/agm/plugins/alsalib/src/agm_io_plugin.c deleted file mode 100755 index c28fa8d4..00000000 --- a/qcom/opensource/agm/plugins/alsalib/src/agm_io_plugin.c +++ /dev/null @@ -1,554 +0,0 @@ -/* -** Copyright (c) 2020-2021, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ -#define LOG_TAG "PLUGIN: AGMIO" -#include -#include - -#include -#include -#include - -#include -#include -#include -#include "utils.h" - -#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0])) - -enum { - AGM_IO_STATE_OPEN = 1, - AGM_IO_STATE_SETUP, - AGM_IO_STATE_PREPARED, - AGM_IO_STATE_RUNNING, -}; - -struct agmio_priv { - snd_pcm_ioplug_t io; - - int card; - int device; - - void *card_node; - void *pcm_node; - uint64_t handle; - struct agm_media_config *media_config; - struct agm_buffer_config *buffer_config; - struct agm_session_config *session_config; - unsigned int period_size; - size_t frame_size; - unsigned int state; - snd_pcm_uframes_t hw_pointer; - snd_pcm_uframes_t boundary; - int event_fd; -/* add private variables here */ -}; - -static int agm_get_session_handle(struct agmio_priv *priv, - uint64_t *handle) -{ - if (!priv) - return -EINVAL; - - *handle = priv->handle; - if (!*handle) - return -EINVAL; - - return 0; -} - -static int agm_io_start(snd_pcm_ioplug_t * io) -{ - struct agmio_priv *pcm = io->private_data; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(pcm, &handle); - if (ret) - return ret; - - if (pcm->state < AGM_IO_STATE_PREPARED) { - ret = agm_session_prepare(handle); - errno = ret; - if (ret) - return ret; - pcm->state = AGM_IO_STATE_PREPARED; - } - - if (pcm->state != AGM_IO_STATE_RUNNING) { - ret = agm_session_start(handle); - if (!ret) - pcm->state = AGM_IO_STATE_RUNNING; - } - - AGM_LOGD("%s: exit\n", __func__); - return ret; -} - -static int agm_io_stop(snd_pcm_ioplug_t * io) -{ - struct agmio_priv *pcm = io->private_data; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(pcm, &handle); - if (ret) - return ret; - ret = agm_session_stop(handle); - - AGM_LOGD("%s: exit\n", __func__); - return ret; -} - -static int agm_io_drain(snd_pcm_ioplug_t * io) -{ - AGM_LOGD("%s: exit\n", __func__); - return 0; -} - -static snd_pcm_sframes_t agm_io_pointer(snd_pcm_ioplug_t * io) -{ - struct agmio_priv *pcm = io->private_data; - snd_pcm_sframes_t new_hw_ptr; - - new_hw_ptr = pcm->hw_pointer; - if (io->stream == SND_PCM_STREAM_CAPTURE) { - if (pcm->hw_pointer == 0) - new_hw_ptr = io->period_size * pcm->frame_size; - } - - - AGM_LOGD("%s %d\n", __func__, io->state); - return new_hw_ptr; -} - -static snd_pcm_sframes_t agm_io_transfer(snd_pcm_ioplug_t * io, - const snd_pcm_channel_area_t * areas, - snd_pcm_uframes_t offset, - snd_pcm_uframes_t size) -{ - struct agmio_priv *pcm = io->private_data; - uint64_t handle; - uint8_t *buf = (uint8_t *) areas->addr + (areas->first + areas->step * offset) / 8; - size_t count; - int ret = 0; - - ret = agm_get_session_handle(pcm, &handle); - if (ret) - return ret; - - if (pcm->state != AGM_IO_STATE_RUNNING) { - ret = agm_io_start(io); - if (ret) - return ret; - } - - count = size * pcm->frame_size; - - if (io->stream == SND_PCM_STREAM_PLAYBACK) - ret = agm_session_write(handle, buf, &count); - else - ret = agm_session_read(handle, buf, &count); - - if (ret == 0) { - ret = snd_pcm_bytes_to_frames(io->pcm, count); - pcm->hw_pointer += ret; - } - - if (pcm->hw_pointer > pcm->boundary) - pcm->hw_pointer -= pcm->boundary; - - AGM_LOGD("%s: exit\n", __func__); - return ret; -} - -static int agm_io_prepare(snd_pcm_ioplug_t * io) -{ - uint64_t handle; - struct agmio_priv *pcm = io->private_data; - int ret = 0; - - ret = agm_get_session_handle(pcm, &handle); - if (ret) - return ret; - - ret = agm_session_prepare(handle); - - AGM_LOGD("%s: exit\n", __func__); - return ret; -} - -static int agm_io_hw_params(snd_pcm_ioplug_t * io, - snd_pcm_hw_params_t * params) -{ - struct agmio_priv *pcm = io->private_data; - struct agm_media_config *media_config; - struct agm_buffer_config *buffer_config; - struct agm_session_config *session_config = NULL; - uint64_t handle; - int ret = 0, sess_mode = 0; - - ret = agm_get_session_handle(pcm, &handle); - - pcm->frame_size = (snd_pcm_format_physical_width(io->format) * io->channels) / 8; - - media_config = pcm->media_config; - buffer_config = pcm->buffer_config; - session_config = pcm->session_config; - - media_config->rate = io->rate; - media_config->channels = io->channels; - media_config->format = io->format; - - buffer_config->count = io->buffer_size / io->period_size; - pcm->period_size = io->period_size; - buffer_config->size = io->period_size * pcm->frame_size; - pcm->hw_pointer = 0; - - snd_card_def_get_int(pcm->pcm_node, "session_mode", &sess_mode); - - session_config->dir = (io->stream == SND_PCM_STREAM_PLAYBACK) ? RX : TX; - session_config->sess_mode = sess_mode; - ret = agm_session_set_config(pcm->handle, session_config, - pcm->media_config, pcm->buffer_config); - if (!ret) - pcm->state = AGM_IO_STATE_SETUP; - - AGM_LOGD("%s: exit\n", __func__); - return ret; -} - -static int agm_io_sw_params(snd_pcm_ioplug_t *io, snd_pcm_sw_params_t *params) -{ - struct agmio_priv *pcm = io->private_data; - struct agm_session_config *session_config = NULL; - uint64_t handle = 0; - int ret = 0, sess_mode = 0; - snd_pcm_uframes_t start_threshold; - snd_pcm_uframes_t stop_threshold; - - ret = agm_get_session_handle(pcm, &handle); - if (ret) - return ret; - session_config = pcm->session_config; - - snd_card_def_get_int(pcm->pcm_node, "session_mode", &sess_mode); - - session_config->dir = (io->stream == SND_PCM_STREAM_PLAYBACK) ? RX : TX; - session_config->sess_mode = sess_mode; - snd_pcm_sw_params_get_start_threshold(params, &start_threshold); - snd_pcm_sw_params_get_stop_threshold(params, &stop_threshold); - snd_pcm_sw_params_get_boundary(params, &pcm->boundary); - session_config->start_threshold = (uint32_t)start_threshold; - session_config->stop_threshold = (uint32_t)stop_threshold; - ret = agm_session_set_config(pcm->handle, session_config, - pcm->media_config, pcm->buffer_config); - - AGM_LOGD("%s: exit\n", __func__); - return ret; -} - -static int agm_io_close(snd_pcm_ioplug_t * io) -{ - struct agmio_priv *pcm = io->private_data; - uint64_t handle; - int ret = 0; - - ret = agm_get_session_handle(pcm, &handle); - if (ret) - return ret; - - ret = agm_session_close(handle); - - snd_card_def_put_card(pcm->card_node); - free(pcm->buffer_config); - free(pcm->media_config); - free(pcm->session_config); - free(io->private_data); - - AGM_LOGD("%s: exit\n", __func__); - return 0; -} - -static int agm_io_pause(snd_pcm_ioplug_t * io, int enable) -{ - struct agmio_priv *pcm = io->private_data; - uint64_t handle; - int ret = 0; - - ret = agm_get_session_handle(pcm, &handle); - if (ret) - return ret; - - if (enable) - ret = agm_session_pause(handle); - else - ret = agm_session_resume(handle); - - AGM_LOGD("%s: exit\n", __func__); - return ret; -} - -static int agm_io_poll_desc_count(snd_pcm_ioplug_t *io) { - (void)io; - /* TODO : Needed for ULL usecases */ - AGM_LOGD("%s: exit\n", __func__); - return 1; -} - -static int agm_io_poll_desc(snd_pcm_ioplug_t *io, struct pollfd *pfd, - unsigned int space) -{ - struct agmio_priv *pcm = io->private_data; - - /* TODO : Needed for ULL usecases, Need update */ - if (space != 1) { - AGM_LOGE("%s space %u is not correct!\n", __func__, space); - return -EINVAL; - } - if (io->stream == SND_PCM_STREAM_PLAYBACK) { - pfd[0].fd = pcm->event_fd; - pfd[0].events = POLLOUT; - } else { - pfd[0].fd = pcm->event_fd; - pfd[0].events = POLLIN; - } - - AGM_LOGD("%s: exit\n", __func__); - return space; -} - -static int agm_io_poll_revents(snd_pcm_ioplug_t *io, struct pollfd *pfd, - unsigned int nfds, unsigned short *revents) -{ - struct agmio_priv *pcm = io->private_data; - - /* TODO : Needed for ULL usecases, Need update */ - if (nfds != 1) { - AGM_LOGE("%s nfds %u is not correct!\n", __func__, nfds); - return -EINVAL; - } - - if (pfd[0].revents & POLLIN) { - *revents = POLLIN; - } else if (pfd[0].revents & POLLOUT) { - *revents = POLLOUT; - } - return 0; -} - -static const snd_pcm_ioplug_callback_t agm_io_callback = { - .start = agm_io_start, - .stop = agm_io_stop, - .pointer = agm_io_pointer, - .drain = agm_io_drain, - .transfer = agm_io_transfer, - .prepare = agm_io_prepare, - .hw_params = agm_io_hw_params, - .sw_params = agm_io_sw_params, - .close = agm_io_close, - .pause = agm_io_pause, - .poll_descriptors_count = agm_io_poll_desc_count, - .poll_descriptors = agm_io_poll_desc, - .poll_revents = agm_io_poll_revents, -}; - -static int agm_hw_constraint(struct agmio_priv* priv) -{ - snd_pcm_ioplug_t *io = &priv->io; - int ret; - - static const snd_pcm_access_t access_list[] = { - SND_PCM_ACCESS_RW_INTERLEAVED, - SND_PCM_ACCESS_MMAP_INTERLEAVED - }; - static const unsigned int formats[] = { - SND_PCM_FORMAT_U8, - SND_PCM_FORMAT_S16_LE, - SND_PCM_FORMAT_S32_LE, - SND_PCM_FORMAT_S24_3LE, - SND_PCM_FORMAT_S24_LE, - }; - - ret = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_ACCESS, - ARRAY_SIZE(access_list), - access_list); - if (ret < 0) - return ret; - - ret = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_FORMAT, - ARRAY_SIZE(formats), formats); - if (ret < 0) - return ret; - - ret = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_CHANNELS, - 1, 8); - if (ret < 0) - return ret; - - ret = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_RATE, - 8000, 384000); - if (ret < 0) - return ret; - - ret = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_PERIOD_BYTES, - 64, 122880); - if (ret < 0) - return ret; - - ret = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_PERIODS, - 1, 8); - if (ret < 0) - return ret; - - return 0; -} - -SND_PCM_PLUGIN_DEFINE_FUNC(agm) -{ - snd_config_iterator_t it, next; - struct agmio_priv *priv = NULL; - long card = 0, device = 100; - struct agm_session_config *session_config; - struct agm_media_config *media_config; - struct agm_buffer_config *buffer_config; - void *card_node, *pcm_node; - enum agm_session_mode sess_mode = AGM_SESSION_DEFAULT; - uint64_t handle; - int ret = 0, session_id = device; - - priv = calloc(1, sizeof(*priv)); - if (!priv) - return -ENOMEM; - - media_config = calloc(1, sizeof(struct agm_media_config)); - if (!media_config) - return -ENOMEM; - - buffer_config = calloc(1, sizeof(struct agm_buffer_config)); - if (!buffer_config) - return -ENOMEM; - - session_config = calloc(1, sizeof(struct agm_session_config)); - if (!session_config) - return -ENOMEM; - - snd_config_for_each(it, next, conf) { - snd_config_t *n = snd_config_iterator_entry(it); - const char *id; - - if (snd_config_get_id(n, &id) < 0) - continue; - if (strcmp(id, "comment") == 0 || strcmp(id, "type") == 0 || strcmp(id, "hint") == 0) - continue; - if (strcmp(id, "card") == 0) { - if (snd_config_get_integer(n, &card) < 0) { - AGM_LOGE("Invalid type for %s", id); - ret = -EINVAL; - goto err_free_priv; - } - AGM_LOGD("card id is %d\n", card); - priv->card = card; - continue; - } - if (strcmp(id, "device") == 0) { - if (snd_config_get_integer(n, &device) < 0) { - AGM_LOGE("Invalid type for %s", id); - ret = -EINVAL; - goto err_free_priv; - } - AGM_LOGD("device id is %d\n", device); - priv->device = device; - continue; - } - } - - card_node = snd_card_def_get_card(card); - if (!card_node) { - AGM_LOGE("card node is NULL\n"); - ret = -EINVAL; - goto err_free_priv; - } - priv->card_node = card_node; - - pcm_node = snd_card_def_get_node(card_node, device, SND_NODE_TYPE_PCM); - if (!pcm_node) { - AGM_LOGE("pcm node is NULL\n"); - ret = -EINVAL; - goto err_free_priv; - } - priv->pcm_node = pcm_node; - - snd_card_def_get_int(pcm_node, "session_mode", &sess_mode); - - session_id = priv->device; - ret = agm_session_open(session_id, sess_mode, &handle); - if (ret) { - AGM_LOGE("handle is NULL\n"); - ret = -EINVAL; - goto err_free_priv; - } - - priv->media_config = media_config; - priv->buffer_config = buffer_config; - priv->session_config = session_config; - priv->handle = handle; - priv->event_fd = -1; - priv->state = AGM_IO_STATE_OPEN; - priv->io.version = SND_PCM_IOPLUG_VERSION; - priv->io.name = "AGM PCM I/O Plugin"; - priv->io.mmap_rw = 0; - priv->io.callback = &agm_io_callback; - priv->io.private_data = priv; - - ret = snd_pcm_ioplug_create(&priv->io, name, stream, mode); - if (ret < 0) { - AGM_LOGE("IO plugin create failed\n"); - goto err_free_priv; - } - - if ((priv->event_fd = eventfd(0, EFD_CLOEXEC)) == -1) { - AGM_LOGE("failed to create event_fd\n"); - ret = -EINVAL; - goto err_free_priv; - } - - ret = agm_hw_constraint(priv); - if (ret < 0) { - snd_pcm_ioplug_delete(&priv->io); - goto err_free_priv; - } - - *pcmp = priv->io.pcm; - return 0; -err_free_priv: - free(priv); - return ret; -} - -SND_PCM_PLUGIN_SYMBOL(agm); diff --git a/qcom/opensource/agm/plugins/tinyalsa/Android.mk b/qcom/opensource/agm/plugins/tinyalsa/Android.mk deleted file mode 100755 index 16fdf1e4..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/Android.mk +++ /dev/null @@ -1,124 +0,0 @@ -LOCAL_PATH := $(call my-dir) -# Build libagm_pcm_plugin -include $(CLEAR_VARS) - -LOCAL_MODULE := libagm_pcm_plugin -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -Wall -LOCAL_SRC_FILES := src/agm_pcm_plugin.c - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libarosal_headers - -LOCAL_SHARED_LIBRARIES := \ - libsndcardparser \ - libagmclient \ - libutils \ - libcutils \ - liblog - -#if android version is R, refer to qtitinyxx otherwise use upstream ones -#This assumes we would be using AR code only for Android R and subsequent versions. -ifneq ($(filter 11 R, $(PLATFORM_VERSION)),) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa -else -LOCAL_SHARED_LIBRARIES += libtinyalsa -endif - -ifeq ($(strip $(AUDIO_FEATURE_ENABLED_DYNAMIC_LOG)), true) -LOCAL_CFLAGS += -DDYNAMIC_LOG_ENABLED -LOCAL_C_INCLUDES += $(TOP)/external/expat/lib/expat.h -LOCAL_SHARED_LIBRARIES += libaudio_log_utils -LOCAL_SHARED_LIBRARIES += libexpat -LOCAL_HEADER_LIBRARIES += libaudiologutils_headers -endif - -include $(BUILD_SHARED_LIBRARY) - -# Build libagm_mixer_plugin -include $(CLEAR_VARS) - -LOCAL_MODULE := libagm_mixer_plugin -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true -LOCAL_SRC_FILES := src/agm_mixer_plugin.c - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libarosal_headers - -LOCAL_SHARED_LIBRARIES := \ - libsndcardparser \ - libagmclient \ - libcutils \ - libutils \ - liblog - -#if android version is R, refer to qtitinyxx otherwise use upstream ones -#This assumes we would be using AR code only for Android R and subsequent versions. -ifneq ($(filter 11 R, $(PLATFORM_VERSION)),) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa -else -LOCAL_SHARED_LIBRARIES += libtinyalsa -endif - -ifeq ($(strip $(AUDIO_FEATURE_ENABLED_DYNAMIC_LOG)), true) -LOCAL_CFLAGS += -DDYNAMIC_LOG_ENABLED -LOCAL_C_INCLUDES += $(TOP)/external/expat/lib/expat.h -LOCAL_SHARED_LIBRARIES += libaudio_log_utils -LOCAL_SHARED_LIBRARIES += libexpat -LOCAL_HEADER_LIBRARIES += libaudiologutils_headers -endif - -include $(BUILD_SHARED_LIBRARY) - -# Build libagm_compress_plugin -include $(CLEAR_VARS) - -LOCAL_MODULE := libagm_compress_plugin -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_C_INCLUDES += $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr/include -LOCAL_ADDITIONAL_DEPENDENCIES += $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr - -LOCAL_SRC_FILES := src/agm_compress_plugin.c - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libarosal_headers - -LOCAL_SHARED_LIBRARIES := \ - libsndcardparser \ - libagmclient \ - libutils \ - libcutils \ - liblog - -# Use flag based selection to use QTI vs open source tinycompress project - -ifeq ($(TARGET_USES_QTI_TINYCOMPRESS),true) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa\ - libqti-tinycompress -else -LOCAL_C_INCLUDES += $(TOP)/external/tinycompress/include -LOCAL_SHARED_LIBRARIES += libtinyalsa\ - libtinycompress -endif - -ifeq ($(strip $(AUDIO_FEATURE_ENABLED_DYNAMIC_LOG)), true) -LOCAL_CFLAGS += -DDYNAMIC_LOG_ENABLED -LOCAL_C_INCLUDES += $(TOP)/external/expat/lib/expat.h -LOCAL_SHARED_LIBRARIES += libaudio_log_utils -LOCAL_SHARED_LIBRARIES += libexpat -LOCAL_HEADER_LIBRARIES += libaudiologutils_headers -endif - -include $(BUILD_SHARED_LIBRARY) - diff --git a/qcom/opensource/agm/plugins/tinyalsa/Makefile.am b/qcom/opensource/agm/plugins/tinyalsa/Makefile.am deleted file mode 100755 index d6c78b4f..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/Makefile.am +++ /dev/null @@ -1,68 +0,0 @@ -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = agmplugin.pc -EXTRA_DIST = $(pkgconfig_DATA) - -library_includedir = $(includedir) - -AM_CFLAGS := -Wno-unused-parameter -if !BUILDSYSTEM_OPENWRT -AM_CFLAGS += -I $(top_srcdir)/include @AGM_CFLAGS@ -AM_CFLAGS += @GLIB_CFLAGS@ -Dstrlcpy=g_strlcpy -Dstrlcat=g_strlcat -include glib.h -AM_CFLAGS += -D__unused=__attribute__\(\(__unused__\)\) -DLINUX_ENABLED -AM_CFLAGS += @SNDPARSER_CFLAGS@ -AM_CFLAGS += -Wno-unused-parameter -AM_CFLAGS += -DDYNAMIC_LOG_ENABLED - -endif - -lib_LTLIBRARIES = libagm_pcm_plugin.la -libagm_pcm_plugin_la_SOURCES = src/agm_pcm_plugin.c -libagm_pcm_plugin_la_CFLAGS := $(AM_CFLAGS) -libagm_pcm_plugin_la_LDFLAGS = -ltinyalsa -lsndcardparser -avoid-version -shared -if BUILDSYSTEM_OPENWRT -libagm_pcm_plugin_la_LDFLAGS += -lagmclientwrapper -else -libagm_pcm_plugin_la_LDFLAGS += -lagmclientwrapper -laudio_log_utils -endif - -lib_LTLIBRARIES += libagm_pcm_passthrough_plugin.la -libagm_pcm_passthrough_plugin_la_SOURCES = src/agm_pcm_plugin.c -libagm_pcm_passthrough_plugin_la_CFLAGS := $(AM_CFLAGS) -libagm_pcm_passthrough_plugin_la_LDFLAGS = -ltinyalsa -lsndcardparser -avoid-version -shared -if BUILDSYSTEM_OPENWRT -libagm_pcm_passthrough_plugin_la_LDFLAGS += -lagm -else -libagm_pcm_passthrough_plugin_la_LDFLAGS += -lagm -laudio_log_utils -endif - - -lib_LTLIBRARIES += libagm_compress_plugin.la -libagm_compress_plugin_la_SOURCES = src/agm_compress_plugin.c -libagm_compress_plugin_la_CFLAGS := $(AM_CFLAGS) -libagm_compress_plugin_la_LDFLAGS = -ltinyalsa -ltinycompress -lsndcardparser -lpthread -avoid-version -laudio_log_utils -shared -lagmclientwrapper - -lib_LTLIBRARIES += libagm_compress_passthrough_plugin.la -libagm_compress_passthrough_plugin_la_SOURCES = src/agm_compress_plugin.c -libagm_compress_passthrough_plugin_la_CFLAGS := $(AM_CFLAGS) -libagm_compress_passthrough_plugin_la_LDFLAGS = -ltinyalsa -lsndcardparser -lpthread -avoid-version -laudio_log_utils -shared -lagm - -lib_LTLIBRARIES += libagm_mixer_plugin.la -libagm_mixer_plugin_la_SOURCES = src/agm_mixer_plugin.c -libagm_mixer_plugin_la_CFLAGS := $(AM_CFLAGS) -libagm_mixer_plugin_la_LDFLAGS = -ltinyalsa -lsndcardparser -avoid-version -shared -if BUILDSYSTEM_OPENWRT -libagm_mixer_plugin_la_LDFLAGS += -lagmclientwrapper -else -libagm_mixer_plugin_la_LDFLAGS += -lagmclientwrapper -laudio_log_utils -endif - -lib_LTLIBRARIES += libagm_mixer_passthrough_plugin.la -libagm_mixer_passthrough_plugin_la_SOURCES = src/agm_mixer_plugin.c -libagm_mixer_passthrough_plugin_la_CFLAGS := $(AM_CFLAGS) -libagm_mixer_passthrough_plugin_la_LDFLAGS = -ltinyalsa -lsndcardparser -avoid-version -shared -if BUILDSYSTEM_OPENWRT -libagm_mixer_passthrough_plugin_la_LDFLAGS += -lagm -else -libagm_mixer_passthrough_plugin_la_LDFLAGS += -lagm -libagm_mixer_passthrough_plugin_la_LDFLAGS += -laudio_log_utils -endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/README.md b/qcom/opensource/agm/plugins/tinyalsa/README.md deleted file mode 100755 index de7609a2..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/README.md +++ /dev/null @@ -1 +0,0 @@ -# agm_plugin \ No newline at end of file diff --git a/qcom/opensource/agm/plugins/tinyalsa/agmplugin.pc.in b/qcom/opensource/agm/plugins/tinyalsa/agmplugin.pc.in deleted file mode 100755 index 66068df1..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/agmplugin.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: agmplugin -Description: agm plugin library -Version: @VERSION@ -Libs: -L${libdir} -lagmplugin -Cflags: -I${includedir} diff --git a/qcom/opensource/agm/plugins/tinyalsa/configure.ac b/qcom/opensource/agm/plugins/tinyalsa/configure.ac deleted file mode 100755 index 079242d6..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/configure.ac +++ /dev/null @@ -1,57 +0,0 @@ -# Requires autoconf tool later than 2.61 -AC_PREREQ(2.69) -# Initialize the agm plugin package version 1.0.0 -AC_INIT([agmplugin],1.0.0) -# Does not strictly follow GNU Coding standards -AM_INIT_AUTOMAKE([foreign subdir-objects]) -# Disables auto rebuilding of configure, Makefile.ins -AM_MAINTAINER_MODE -# Verifies the --srcdir is correct by checking for the path -AC_CONFIG_SRCDIR([src/agm_mixer_plugin.c]) -# defines some macros variable to be included by source -AC_CONFIG_MACRO_DIR([m4]) - -# Checks for programs. -AC_PROG_CC -AM_PROG_CC_C_O -AC_PROG_CXX -AC_PROG_LIBTOOL -AC_PROG_AWK -AC_PROG_CPP -AC_PROG_INSTALL -AC_PROG_LN_S -AC_PROG_MAKE_SET -PKG_PROG_PKG_CONFIG -AC_ARG_WITH([glib], -AC_HELP_STRING([--with-glib], - [enable glib, Build against glib. Use this when building for HLOS systems which use glib])) - -if (test "x${with_glib}" = "xyes"); then - PKG_CHECK_MODULES(GTHREAD, gthread-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GThread >= 2.16 is required)) - PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GLib >= 2.16 is required)) - GLIB_CFLAGS="$GLIB_CFLAGS $GTHREAD_CFLAGS" - GLIB_LIBS="$GLIB_LIBS $GTHREAD_LIBS" - - AC_SUBST(GLIB_CFLAGS) - AC_SUBST(GLIB_LIBS) -fi - -AM_CONDITIONAL(USE_GLIB, test "x${with_glib}" = "xyes") - -# Checks for libraries -PKG_CHECK_MODULES([AGM], [agm]) -AC_SUBST([AGM_CFLAGS]) - -PKG_CHECK_MODULES([SNDPARSER], [sndparser]) -AC_SUBST([SNDPARSER_CFLAGS]) - -AC_ARG_WITH([openwrt], - AS_HELP_STRING([use openwrt (default is no)]), - [with_openwrt=$withval], - [with_openwrt=no]) -AM_CONDITIONAL([BUILDSYSTEM_OPENWRT], [test "x${with_openwrt}" = "xyes"]) - -AC_CONFIG_FILES([ Makefile agmplugin.pc ]) -AC_OUTPUT diff --git a/qcom/opensource/agm/plugins/tinyalsa/src/agm_compress_plugin.c b/qcom/opensource/agm/plugins/tinyalsa/src/agm_compress_plugin.c deleted file mode 100755 index f94550cd..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/src/agm_compress_plugin.c +++ /dev/null @@ -1,1174 +0,0 @@ -/* -** Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * - * Copyright (c) 2022-2024, Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - * -**/ -#define LOG_TAG "PLUGIN: compress" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_COMPRESS_PLUGIN -#include -#endif - -/* Default values */ -#define COMPR_PLAYBACK_MIN_FRAGMENT_SIZE (8 * 1024) -#define COMPR_PLAYBACK_MAX_FRAGMENT_SIZE (128 * 1024) -#define COMPR_PLAYBACK_MIN_NUM_FRAGMENTS (4) -#define COMPR_PLAYBACK_MAX_NUM_FRAGMENTS (16) - -struct agm_compress_priv { - struct agm_media_config media_config; - struct agm_buffer_config buffer_config; - struct agm_session_config session_config; - struct snd_compr_caps compr_cap; - uint64_t handle; - bool prepared; - uint64_t bytes_copied; /* Copied to DSP buffer */ - uint64_t total_buf_size; /* Total buffer size */ - - int64_t bytes_avail; /* avail size to write/read */ - - uint64_t bytes_received; /* from DSP */ - uint64_t bytes_read; /* Consumed by client */ - bool start_drain; - bool eos; - bool early_eos; - bool eos_received; - bool internal_unblock_eos; - bool internal_unblock_early_eos; - bool internal_unblock_write; - - enum agm_gapless_silence_type type; /* Silence Type (Initial/Trailing) */ - uint32_t silence; /* Samples to remove */ - - void *client_data; - void *card_node; - int session_id; - pthread_cond_t drain_cond; - pthread_mutex_t drain_lock; - pthread_cond_t eos_cond; - pthread_mutex_t eos_lock; - pthread_cond_t early_eos_cond; - pthread_mutex_t early_eos_lock; - pthread_mutex_t lock; - pthread_cond_t poll_cond; - pthread_mutex_t poll_lock; -}; - -void agm_session_update_codec_options(struct agm_session_config*, struct snd_compr_params *); - -static int agm_get_session_handle(struct agm_compress_priv *priv, - uint64_t *handle) -{ - if (!priv) - return -EINVAL; - - *handle = priv->handle; - if (!*handle) - return -EINVAL; - - return 0; -} - -void agm_compress_event_cb(uint32_t session_id __unused, - struct agm_event_cb_params *event_params, - void *client_data) -{ - struct compress_plugin *agm_compress_plugin = client_data; - struct agm_compress_priv *priv; - - if (!agm_compress_plugin) { - AGM_LOGE("%s: client_data is NULL\n", __func__); - return; - } - priv = agm_compress_plugin->priv; - if (!priv) { - AGM_LOGE("%s: Private data is NULL\n", __func__); - return; - } - if (!event_params) { - AGM_LOGE("%s: event params is NULL\n", __func__); - return; - } - - pthread_mutex_lock(&priv->lock); - AGM_LOGV("%s: enter: bytes_avail = %lld, event_id = %d\n", __func__, - (long long) priv->bytes_avail, event_params->event_id); - if (event_params->event_id == AGM_EVENT_WRITE_DONE) { - /* - * Write done cb is expected for every DSP write with - * fragment size even for partial buffers - */ - priv->bytes_avail += priv->buffer_config.size; - if (priv->bytes_avail > priv->total_buf_size) { - AGM_LOGE("%s: Error: bytes_avail %lld, total size = %llu\n", - __func__, priv->bytes_avail, (unsigned long long) priv->total_buf_size); - pthread_mutex_unlock(&priv->lock); - return; - } - - pthread_mutex_lock(&priv->drain_lock); - if (priv->start_drain && - (priv->bytes_avail == priv->total_buf_size)) - pthread_cond_signal(&priv->drain_cond); - pthread_mutex_unlock(&priv->drain_lock); - } else if (event_params->event_id == AGM_EVENT_READ_DONE) { - /* Read done cb expected for every DSP read with Fragment size */ - priv->bytes_avail += priv->buffer_config.size; - priv->bytes_received += priv->buffer_config.size; - } else if (event_params->event_id == AGM_EVENT_EOS_RENDERED) { - AGM_LOGD("%s: EOS event received \n", __func__); - /* Unblock eos wait if all the buffers are rendered */ - pthread_mutex_lock(&priv->eos_lock); - if (priv->eos) { - pthread_cond_signal(&priv->eos_cond); - priv->eos = false; - } else { - AGM_LOGD("%s: EOS received before drain called\n", __func__); - priv->eos_received = true; - } - pthread_mutex_unlock(&priv->eos_lock); - } else if (event_params->event_id == AGM_EVENT_EARLY_EOS) { - AGM_LOGD("%s: Early EOS event received \n", __func__); - /* Unblock early eos wait */ - pthread_mutex_lock(&priv->early_eos_lock); - if (priv->early_eos) { - priv->early_eos = false; - pthread_cond_signal(&priv->early_eos_cond); - } - pthread_mutex_unlock(&priv->early_eos_lock); - } else if (event_params->event_id == AGM_EVENT_EARLY_EOS_INTERNAL) { - AGM_LOGD("%s: Early EOS event received from internal unblock\n", __func__); - /* Unblock early eos wait */ - pthread_mutex_lock(&priv->early_eos_lock); - if (priv->early_eos) { - priv->early_eos = false; - pthread_cond_signal(&priv->early_eos_cond); - priv->internal_unblock_early_eos = true; - } - pthread_mutex_unlock(&priv->early_eos_lock); - } else { - AGM_LOGE("%s: error: Invalid event params id: %d\n", __func__, - event_params->event_id); - } - pthread_mutex_unlock(&priv->lock); - /* Signal Poll */ - pthread_mutex_lock(&priv->poll_lock); - pthread_cond_signal(&priv->poll_cond); - pthread_mutex_unlock(&priv->poll_lock); -} - -int agm_compress_write(struct compress_plugin *plugin, const void *buff, - size_t count) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret = 0; - int64_t size = count, buf_cnt; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - if (priv->eos_received) - priv->eos_received = false; - - if (count > priv->total_buf_size) { - AGM_LOGE("%s: Size %zu is greater than total buf size %llu\n", - __func__, count, (unsigned long long) priv->total_buf_size); - return -EINVAL; - } - - /* Call prepare in the first write as write() - will be called before start() */ - if (!priv->prepared) { - ret = agm_session_prepare(handle); - if (ret) { - errno = ret; - return ret; - } - priv->prepared = true; - } - - ret = agm_session_write(handle, (void *)buff, (size_t*)&size); - if (ret) { - errno = ret; - return ret; - } - - pthread_mutex_lock(&priv->lock); - buf_cnt = size / priv->buffer_config.size; - if (size % priv->buffer_config.size != 0) - buf_cnt +=1; - - /* Avalible buffer size is always multiple of fragment size */ - priv->bytes_avail -= (buf_cnt * priv->buffer_config.size); - if (priv->bytes_avail < 0) { - AGM_LOGE("%s: err: bytes_avail = %lld", __func__, (long long) priv->bytes_avail); - ret = -EINVAL; - goto err; - } - AGM_LOGV("%s: count = %zu, priv->bytes_avail: %lld\n", - __func__, count, (long long) priv->bytes_avail); - priv->bytes_copied += size; - ret = size; -err: - pthread_mutex_unlock(&priv->lock); - - return ret; -} - -int agm_compress_read(struct compress_plugin *plugin, void *buff, size_t count) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret = 0, buf_cnt = 0; - AGM_LOGV("Enter"); - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - if (count > priv->bytes_avail) { - AGM_LOGE("%s: Invalid requested size %zu", __func__, count); - return -EINVAL; - } - - ret = agm_session_read(handle, buff, &count); - if (ret < 0) { - errno = ret; - return ret; - } - pthread_mutex_lock(&priv->lock); - - priv->bytes_read += count; - - pthread_mutex_unlock(&priv->lock); - AGM_LOGV("Exit: read bytes: %d",count); - return count; -} - -int agm_compress_tstamp(struct compress_plugin *plugin, - struct snd_compr_tstamp *tstamp) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret = 0; - uint64_t timestamp = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - tstamp->sampling_rate = priv->media_config.rate; - tstamp->copied_total = priv->bytes_copied; - - /* - * for compress capture get latest buffer timestamp - * otherwise in case of playback use get session time - * which inturn queries SPR module in playback graph. - */ - if (priv->session_config.dir == TX) { - ret = agm_get_buffer_timestamp(priv->session_id, ×tamp); - } else { - ret = agm_get_session_time(handle, ×tamp); - } - - if (ret) { - errno = ret; - return ret; - } - timestamp *= tstamp->sampling_rate; - tstamp->pcm_io_frames = timestamp/1000000; - - return 0; -} - -int agm_compress_avail(struct compress_plugin *plugin, - struct snd_compr_avail *avail) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - agm_compress_tstamp(plugin, &avail->tstamp); - - pthread_mutex_lock(&priv->lock); - /* Avail size is always in multiples of fragment size */ - avail->avail = priv->bytes_avail; - AGM_LOGV("%s: size = %zu, *avail = %llu, pcm_io_frames: %d \ - sampling_rate: %u\n", __func__, - sizeof(struct snd_compr_avail), avail->avail, - avail->tstamp.pcm_io_frames, - avail->tstamp.sampling_rate); - pthread_mutex_unlock(&priv->lock); - - return ret; -} - -int agm_compress_get_caps(struct compress_plugin *plugin, - struct snd_compr_caps *caps) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - if (caps) { - memcpy(caps, &priv->compr_cap, sizeof(struct snd_compr_caps)); - } else { - ret = -EINVAL; - return ret; - } - - return 0; -} - -int agm_session_update_codec_config(struct agm_compress_priv *priv, - struct snd_compr_params *params) -{ - struct agm_media_config *media_cfg; - struct agm_session_config *sess_cfg; - union snd_codec_options *copt; - - media_cfg = &priv->media_config; - sess_cfg = &priv->session_config; - copt = ¶ms->codec.options; - - media_cfg->rate = params->codec.sample_rate; - media_cfg->channels = params->codec.ch_out; - - if (sess_cfg->dir == RX) { - switch (params->codec.id) { - case SND_AUDIOCODEC_MP3: - media_cfg->format = AGM_FORMAT_MP3; - break; - case SND_AUDIOCODEC_AAC: - media_cfg->format = AGM_FORMAT_AAC; - if (params->codec.format == SND_AUDIOSTREAMFORMAT_MP4LATM) - sess_cfg->codec.aac_dec.aac_fmt_flag = 0x04; - else if (params->codec.format == SND_AUDIOSTREAMFORMAT_ADIF) - sess_cfg->codec.aac_dec.aac_fmt_flag = 0x02; - else if (params->codec.format == SND_AUDIOSTREAMFORMAT_MP4ADTS) - sess_cfg->codec.aac_dec.aac_fmt_flag = 0x00; - else - sess_cfg->codec.aac_dec.aac_fmt_flag = 0x03; - sess_cfg->codec.aac_dec.num_channels = params->codec.ch_in; - sess_cfg->codec.aac_dec.sample_rate = media_cfg->rate; - break; - case SND_AUDIOCODEC_FLAC: - media_cfg->format = AGM_FORMAT_FLAC; - sess_cfg->codec.flac_dec.num_channels = params->codec.ch_in; - sess_cfg->codec.flac_dec.sample_rate = media_cfg->rate; - break; - #ifdef SND_AUDIOCODEC_ALAC - case SND_AUDIOCODEC_ALAC: - media_cfg->format = AGM_FORMAT_ALAC; - sess_cfg->codec.alac_dec.num_channels = params->codec.ch_in; - sess_cfg->codec.alac_dec.sample_rate = media_cfg->rate; - break; - #endif - #ifdef SND_AUDIOCODEC_APE - case SND_AUDIOCODEC_APE: - media_cfg->format = AGM_FORMAT_APE; - sess_cfg->codec.ape_dec.num_channels = params->codec.ch_in; - sess_cfg->codec.ape_dec.sample_rate = media_cfg->rate; - break; - #endif - case SND_AUDIOCODEC_WMA: - #ifdef SND_AUDIOPROFILE_WMA9_LOSSLESS - if ((params->codec.profile == SND_AUDIOPROFILE_WMA9_PRO) || - (params->codec.profile == SND_AUDIOPROFILE_WMA9_LOSSLESS) || - (params->codec.profile == SND_AUDIOPROFILE_WMA10_LOSSLESS)) { - #else - if ((params->codec.profile == SND_AUDIOMODE_WMAPRO_LEVELM0) || - (params->codec.profile == SND_AUDIOMODE_WMAPRO_LEVELM1) || - (params->codec.profile == SND_AUDIOMODE_WMAPRO_LEVELM2)) { - #endif - media_cfg->format = AGM_FORMAT_WMAPRO; - sess_cfg->codec.wmapro_dec.fmt_tag = params->codec.format; - sess_cfg->codec.wmapro_dec.num_channels = params->codec.ch_in; - sess_cfg->codec.wmapro_dec.sample_rate = media_cfg->rate; - } else { - media_cfg->format = AGM_FORMAT_WMASTD; - sess_cfg->codec.wma_dec.fmt_tag = params->codec.format; - sess_cfg->codec.wma_dec.num_channels = params->codec.ch_in; - sess_cfg->codec.wma_dec.sample_rate = media_cfg->rate; - } - break; - case SND_AUDIOCODEC_VORBIS: - media_cfg->format = AGM_FORMAT_VORBIS; - break; - case SND_AUDIOCODEC_BESPOKE: - if (copt->generic.reserved[0] == AGM_FORMAT_OPUS) { - media_cfg->format = AGM_FORMAT_OPUS; - sess_cfg->codec.opus_dec.num_channels = params->codec.ch_in; - sess_cfg->codec.opus_dec.sample_rate = media_cfg->rate; - } - break; - default: - break; - } - } - - // capture path - if (sess_cfg->dir == TX) { - switch (params->codec.id) { - case SND_AUDIOCODEC_AAC: - media_cfg->format = AGM_FORMAT_AAC; - - sess_cfg->codec.aac_enc.aac_bit_rate = params->codec.bit_rate; - sess_cfg->codec.aac_enc.global_cutoff_freq = - params->codec.rate_control; - sess_cfg->codec.aac_enc.enc_cfg.aac_enc_mode = - params->codec.profile; - sess_cfg->codec.aac_enc.enc_cfg.aac_fmt_flag = params->codec.format; - - AGM_LOGD( - "%s: requested configuration, AAC encode mode: %x, AAC format " - "flag: %x, AAC bit rate: %d, global_cutoff_freq: %d", - __func__, sess_cfg->codec.aac_enc.enc_cfg.aac_enc_mode, - sess_cfg->codec.aac_enc.enc_cfg.aac_fmt_flag, - sess_cfg->codec.aac_enc.aac_bit_rate, - sess_cfg->codec.aac_enc.global_cutoff_freq); - break; - - default: - break; - } - } - agm_session_update_codec_options(sess_cfg, params); - - AGM_LOGD("%s: format = %d rate = %d, channels = %d\n", __func__, - media_cfg->format, media_cfg->rate, media_cfg->channels); - return 0; -} - -int agm_compress_set_params(struct compress_plugin *plugin, - struct snd_compr_params *params) -{ - struct agm_compress_priv *priv = plugin->priv; - struct agm_buffer_config *buf_cfg; - struct agm_session_config *sess_cfg; - uint64_t handle; - int ret = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - buf_cfg = &priv->buffer_config; - buf_cfg->count = params->buffer.fragments; - buf_cfg->size = params->buffer.fragment_size; - /*explicitly set the metadata size to 0 */ - buf_cfg->max_metadata_size = 0; - priv->total_buf_size = buf_cfg->size * buf_cfg->count; - - sess_cfg = &priv->session_config; - - if (sess_cfg->dir == RX) - priv->bytes_avail = priv->total_buf_size; - else - priv->bytes_avail = priv->total_buf_size; - - sess_cfg->start_threshold = 0; - sess_cfg->stop_threshold = 0; - - if (sess_cfg->dir == RX) - sess_cfg->data_mode = AGM_DATA_NON_BLOCKING; - else - sess_cfg->data_mode = AGM_DATA_BLOCKING; - - /* Populate each codec format specific params */ - ret = agm_session_update_codec_config(priv, params); - if (ret) - return ret; - - ret = agm_session_set_config(priv->handle, sess_cfg, - &priv->media_config, buf_cfg); - if (ret) - return ret; - - AGM_LOGD("%s: exit fragments cnt = %d size = %zu\n", __func__, - buf_cfg->count, buf_cfg->size); - return ret; -} - -static int agm_compress_set_metadata(struct compress_plugin *plugin, - struct snd_compr_metadata *metadata) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - if (metadata->key == SNDRV_COMPRESS_ENCODER_PADDING) { - priv->type = TRAILING_SILENCE; - priv->silence = metadata->value[0]; - } - if (metadata->key == SNDRV_COMPRESS_ENCODER_DELAY) { - priv->type = INITIAL_SILENCE; - priv->silence = metadata->value[0]; - } - - ret = agm_set_gapless_session_metadata(handle, priv->type, - priv->silence); - if (ret) - ALOGE("%s: failed to send gapless metadata ret = %d\n", __func__, ret); - - return ret; -} - -static int agm_compress_start(struct compress_plugin *plugin) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - /** - * Unlike playback, for capture case, call - * agm_session_prepare it in start. - * For playback it is called in write. - * */ - if (!priv->prepared) { - ret = agm_session_prepare(handle); - if (ret) { - errno = ret; - return ret; - } - priv->prepared = true; - } - - ret = agm_session_start(handle); - if (ret) - errno = ret; - return ret; -} - -static int agm_compress_stop(struct compress_plugin *plugin) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - /* Unlock drain if its waiting for EOS rendered */ - pthread_mutex_lock(&priv->eos_lock); - if (priv->eos) { - pthread_cond_signal(&priv->eos_cond); - priv->internal_unblock_eos = true; - priv->eos = false; - } - priv->eos_received = true; - pthread_mutex_unlock(&priv->eos_lock); - - /* Unblock eos wait if early eos event cb has not been called */ - pthread_mutex_lock(&priv->early_eos_lock); - if (priv->early_eos) { - pthread_cond_signal(&priv->early_eos_cond); - priv->internal_unblock_early_eos = true; - priv->early_eos = false; - } - pthread_mutex_unlock(&priv->early_eos_lock); - - /* Signal Poll */ - pthread_mutex_lock(&priv->poll_lock); - pthread_cond_signal(&priv->poll_cond); - priv->internal_unblock_write = true; - pthread_mutex_unlock(&priv->poll_lock); - - ret = agm_session_stop(handle); - if (ret) { - errno = ret; - return ret; - } - /* stop will reset all the buffers and it called during seek also */ - priv->bytes_avail = priv->total_buf_size; - priv->bytes_copied = 0; - - return ret; -} - -static int agm_compress_pause(struct compress_plugin *plugin) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - ret = agm_session_pause(handle); - return ret; -} - -static int agm_compress_resume(struct compress_plugin *plugin) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - ret = agm_session_resume(handle); - return ret; -} - -static int agm_compress_drain(struct compress_plugin *plugin) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - AGM_LOGV("%s: priv->bytes_avail = %lld, priv->total_buf_size = %llu\n", - __func__, (long long) priv->bytes_avail, (unsigned long long) priv->total_buf_size); - /* No need to wait for all buffers to be consumed to issue EOS as - * write and EOS cmds are sequential - */ - /* TODO: how to handle wake up in SSR scenario */ - pthread_mutex_lock(&priv->eos_lock); - if (!priv->eos_received) { - priv->eos = true; - ret = agm_session_eos(handle); - if (ret) { - AGM_LOGE("%s: EOS fail\n", __func__); - errno = ret; - pthread_mutex_unlock(&priv->eos_lock); - return ret; - } - pthread_cond_wait(&priv->eos_cond, &priv->eos_lock); - AGM_LOGD("%s: out of eos wait\n", __func__); - if (priv->internal_unblock_eos) { - AGM_LOGD("%s: out of eos wait, internally unblocked\n", __func__); - priv->internal_unblock_eos = false; - ret = -ECANCELED; - errno = ret; - } - } - priv->eos_received = false; - pthread_mutex_unlock(&priv->eos_lock); - - return ret; -} - -static int agm_compress_partial_drain(struct compress_plugin *plugin) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - // Send EOS command and wait for EARLY EOS event - ret = agm_session_eos(handle); - pthread_mutex_lock(&priv->early_eos_lock); - if (!priv->eos_received) { - priv->early_eos = true; - if (ret) { - AGM_LOGE("%s: EOS fail\n", __func__); - pthread_mutex_unlock(&priv->early_eos_lock); - return ret; - } - pthread_cond_wait(&priv->early_eos_cond, &priv->early_eos_lock); - AGM_LOGD("%s: out of early eos wait\n", __func__); - if (priv->internal_unblock_early_eos) { - AGM_LOGD("%s: out of early eos wait, internally unblocked\n", __func__); - priv->internal_unblock_early_eos = false; - ret = -ECANCELED; - errno = ret; - } - } - pthread_mutex_unlock(&priv->early_eos_lock); - - AGM_LOGV("%s: exit\n", __func__); - return ret; -} - -static int agm_compress_next_track(struct compress_plugin *plugin) -{ - - AGM_LOGE("%s: next track \n", __func__); - - return 0; -} - -static int agm_compress_ioctl(struct compress_plugin *plugin, int cmd, ...) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret; - va_list ap; - void *arg; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - va_start(ap, cmd); - arg = va_arg(ap, void *); - va_end(ap); - - switch (cmd) { - case SNDRV_COMPRESS_SET_METADATA: - ret = agm_compress_set_metadata(plugin, arg); - break; - default: - break; - } - - return ret; -} - -static int agm_compress_poll(struct compress_plugin *plugin, - struct pollfd *fds, nfds_t nfds __unused, - int timeout) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - struct timespec poll_ts; - int ret = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - clock_gettime(CLOCK_MONOTONIC, &poll_ts); - poll_ts.tv_sec += timeout/1000; - /* Unblock poll wait if avail bytes to write/read is more than one fragment */ - pthread_mutex_lock(&priv->poll_lock); - /* If timeout is -1 then its infinite wait */ - if (timeout < 0) - ret = pthread_cond_wait(&priv->poll_cond, &priv->poll_lock); - else - ret = pthread_cond_timedwait(&priv->poll_cond, &priv->poll_lock, &poll_ts); - - if (priv->internal_unblock_write) { - AGM_LOGD("%s: out of early eos wait, internally unblocked\n", __func__); - priv->internal_unblock_write = false; - ret = -ECANCELED; - errno = ret; - pthread_mutex_unlock(&priv->poll_lock); - goto exit; - } - - pthread_mutex_unlock(&priv->poll_lock); - - if (ret == ETIMEDOUT) { - /* Poll() expects 0 return value in case of timeout */ - ret = 0; - } else { - fds->revents |= POLLOUT; - ret = POLLOUT; - } -exit : - return ret; -} - -void agm_compress_close(struct compress_plugin *plugin) -{ - struct agm_compress_priv *priv = plugin->priv; - uint64_t handle; - int ret = 0; - - AGM_LOGV("%s:%d\n", __func__, __LINE__); - ret = agm_get_session_handle(priv, &handle); - if (ret) - return; - - if (priv->session_config.dir == RX) { - ret = agm_session_register_cb(priv->session_id, NULL, - AGM_EVENT_DATA_PATH, plugin); - ret = agm_session_register_cb(priv->session_id, NULL, - AGM_EVENT_MODULE, plugin); - } - - ret = agm_session_close(handle); - if (ret) - AGM_LOGE("%s: agm_session_close failed \n", __func__); - - snd_card_def_put_card(priv->card_node); - /* Unblock eos wait if eos-rendered event cb has not been called */ - pthread_mutex_lock(&priv->eos_lock); - if (priv->eos) { - pthread_cond_signal(&priv->eos_cond); - priv->internal_unblock_eos = true; - priv->eos = false; - } - pthread_mutex_unlock(&priv->eos_lock); - - /* Unblock eos wait if early eos event cb has not been called */ - pthread_mutex_lock(&priv->early_eos_lock); - if (priv->early_eos) { - pthread_cond_signal(&priv->early_eos_cond); - priv->internal_unblock_early_eos = true; - priv->early_eos = false; - } - pthread_mutex_unlock(&priv->early_eos_lock); - - /* Signal Poll */ - pthread_mutex_lock(&priv->poll_lock); - pthread_cond_signal(&priv->poll_cond); - priv->internal_unblock_write = true; - pthread_mutex_unlock(&priv->poll_lock); - - /* Make sure callbacks are not running at this point */ - free(plugin->priv); - free(plugin); - - return; -} - -struct compress_plugin_ops agm_compress_ops = { - .close = agm_compress_close, - .get_caps = agm_compress_get_caps, - .set_params = agm_compress_set_params, - .avail = agm_compress_avail, - .tstamp = agm_compress_tstamp, - .write = agm_compress_write, - .read = agm_compress_read, - .start = agm_compress_start, - .stop = agm_compress_stop, - .pause = agm_compress_pause, - .resume = agm_compress_resume, - .drain = agm_compress_drain, - .partial_drain = agm_compress_partial_drain, - .next_track = agm_compress_next_track, - .ioctl = agm_compress_ioctl, - .poll = agm_compress_poll, -}; - -static int agm_populate_codec_caps(struct agm_compress_priv *priv) -{ - int codec_count = 0; - - if (priv->session_config.dir == RX) - priv->compr_cap.direction = SND_COMPRESS_PLAYBACK; - else - priv->compr_cap.direction = SND_COMPRESS_CAPTURE; - - priv->compr_cap.min_fragment_size = - COMPR_PLAYBACK_MIN_FRAGMENT_SIZE; - priv->compr_cap.max_fragment_size = - COMPR_PLAYBACK_MAX_FRAGMENT_SIZE; - priv->compr_cap.min_fragments = - COMPR_PLAYBACK_MIN_NUM_FRAGMENTS; - priv->compr_cap.max_fragments = - COMPR_PLAYBACK_MAX_NUM_FRAGMENTS; - - priv->compr_cap.codecs[codec_count++] = SND_AUDIOCODEC_MP3; - priv->compr_cap.codecs[codec_count++] = SND_AUDIOCODEC_AAC; - priv->compr_cap.codecs[codec_count++] = SND_AUDIOCODEC_WMA; - priv->compr_cap.codecs[codec_count++] = SND_AUDIOCODEC_FLAC; - priv->compr_cap.codecs[codec_count++] = SND_AUDIOCODEC_VORBIS; - priv->compr_cap.codecs[codec_count++] = SND_AUDIOCODEC_BESPOKE; -#ifdef SND_AUDIOCODEC_ALAC - priv->compr_cap.codecs[codec_count++] = SND_AUDIOCODEC_ALAC; -#endif -#ifdef SND_AUDIOCODEC_APE - priv->compr_cap.codecs[codec_count++] = SND_AUDIOCODEC_APE; -#endif - priv->compr_cap.num_codecs = codec_count; - - return 0; -}; - -COMPRESS_PLUGIN_OPEN_FN(agm_compress_plugin) -{ - struct compress_plugin *agm_compress_plugin; - struct agm_compress_priv *priv; - uint64_t handle; - int ret = 0, session_id = device; - int is_playback = 0, is_capture = 0, sess_mode = 0; - void *card_node, *compr_node; - - AGM_LOGV("%s: session_id: %d \n", __func__, device); - agm_compress_plugin = calloc(1, sizeof(struct compress_plugin)); - if (!agm_compress_plugin) - return -ENOMEM; - - priv = calloc(1, sizeof(struct agm_compress_priv)); - if (!priv) { - ret = -ENOMEM; - goto err_plugin_free; - } - - card_node = snd_card_def_get_card(card); - if (!card_node) { - ret = -EINVAL; - goto err_priv_free; - } - - compr_node = snd_card_def_get_node(card_node, device, SND_NODE_TYPE_COMPR); - if (!compr_node) { - ret = -EINVAL; - goto err_card_put; - } - - agm_compress_plugin->card = card; - agm_compress_plugin->ops = &agm_compress_ops; - agm_compress_plugin->node = compr_node; - agm_compress_plugin->priv = priv; - priv->card_node = card_node; - - ret = snd_card_def_get_int(agm_compress_plugin->node, "playback", - &is_playback); - if (ret) - goto err_card_put; - - ret = snd_card_def_get_int(agm_compress_plugin->node, "capture", - &is_capture); - if (ret) - goto err_card_put; - - ret = snd_card_def_get_int(agm_compress_plugin->node, "session_mode", - &sess_mode); - if (ret) - goto err_card_put; - - priv->session_config.sess_mode = sess_mode; - priv->session_config.dir = (flags & COMPRESS_IN) ? RX : TX; - priv->session_id = session_id; - AGM_LOGD("%s: requested agm session mode: %zu", __func__, - priv->session_config.sess_mode); - - if ((priv->session_config.dir == RX) && !is_playback) { - AGM_LOGE("%s: Playback is supported for device %d \n", - __func__, device); - goto err_card_put; - } - if ((priv->session_config.dir == TX) && !is_capture) { - AGM_LOGE("%s: Capture is supported for device %d \n", - __func__, device); - goto err_card_put; - } - - ret = agm_session_open(session_id, sess_mode, &handle); - if (ret) { - errno = ret; - goto err_card_put; - } - - // TODO introduce nonblock flag here - // instead of checking with direction and then registering callback - // use nonblock flag and then register call back - /** - * the agm call back aren't required for capture usecase. since - * the read calls to agm are data blocking. - * */ - if (priv->session_config.dir == RX) { - ret = agm_session_register_cb(session_id, &agm_compress_event_cb, - AGM_EVENT_DATA_PATH, agm_compress_plugin); - if (ret) - goto err_sess_cls; - - ret = agm_session_register_cb(session_id, &agm_compress_event_cb, - AGM_EVENT_MODULE, agm_compress_plugin); - if (ret) - goto err_sess_cls; - } - - agm_populate_codec_caps(priv); - priv->handle = handle; - *plugin = agm_compress_plugin; - pthread_mutex_init(&priv->lock, (const pthread_mutexattr_t *) NULL); - pthread_mutex_init(&priv->eos_lock, (const pthread_mutexattr_t *) NULL); - pthread_mutex_init(&priv->drain_lock, (const pthread_mutexattr_t *) NULL); - pthread_mutex_init(&priv->poll_lock, (const pthread_mutexattr_t *) NULL); - pthread_mutex_init(&priv->early_eos_lock, (const pthread_mutexattr_t *) NULL); - - return 0; - -err_sess_cls: - agm_session_close(handle); -err_card_put: - snd_card_def_put_card(card_node); -err_priv_free: - free(priv); -err_plugin_free: - free(agm_compress_plugin); - if (ret < 0) - return ret; - else - return -ret; -} - -void agm_session_update_codec_options(struct agm_session_config *sess_cfg, - struct snd_compr_params *params) -{ - - union snd_codec_options *copt = ¶ms->codec.options; - - // playback - if (sess_cfg->dir == RX) { - switch (params->codec.id) { - case SND_AUDIOCODEC_AAC: - sess_cfg->codec.aac_dec.audio_obj_type = copt->generic.reserved[0]; - sess_cfg->codec.aac_dec.total_size_of_PCE_bits = copt->generic.reserved[1]; - break; - case SND_AUDIOCODEC_FLAC: - sess_cfg->codec.flac_dec.sample_size = copt->generic.reserved[0]; - sess_cfg->codec.flac_dec.min_blk_size = copt->generic.reserved[1]; - sess_cfg->codec.flac_dec.max_blk_size = copt->generic.reserved[2]; - sess_cfg->codec.flac_dec.min_frame_size = copt->generic.reserved[3]; - sess_cfg->codec.flac_dec.max_frame_size = copt->generic.reserved[4]; - break; - #ifdef SND_AUDIOCODEC_ALAC - case SND_AUDIOCODEC_ALAC: - sess_cfg->codec.alac_dec.frame_length = copt->generic.reserved[0]; - sess_cfg->codec.alac_dec.compatible_version = copt->generic.reserved[1]; - sess_cfg->codec.alac_dec.bit_depth = copt->generic.reserved[2]; - sess_cfg->codec.alac_dec.pb = copt->generic.reserved[3]; - sess_cfg->codec.alac_dec.mb = copt->generic.reserved[4]; - sess_cfg->codec.alac_dec.kb = copt->generic.reserved[5]; - sess_cfg->codec.alac_dec.max_run = copt->generic.reserved[6]; - sess_cfg->codec.alac_dec.max_frame_bytes = copt->generic.reserved[7]; - sess_cfg->codec.alac_dec.avg_bit_rate = copt->generic.reserved[8]; - sess_cfg->codec.alac_dec.channel_layout_tag = copt->generic.reserved[9]; - break; - case SND_AUDIOCODEC_BESPOKE: - if (copt->generic.reserved[0] == (uint8_t)AGM_FORMAT_OPUS) { - sess_cfg->codec.opus_dec.bitstream_format = copt->generic.reserved[1]; - sess_cfg->codec.opus_dec.payload_type = copt->generic.reserved[2]; - sess_cfg->codec.opus_dec.version = copt->generic.reserved[3]; - sess_cfg->codec.opus_dec.num_channels = copt->generic.reserved[4]; - sess_cfg->codec.opus_dec.pre_skip = copt->generic.reserved[5]; - sess_cfg->codec.opus_dec.sample_rate = copt->generic.reserved[6]; - sess_cfg->codec.opus_dec.output_gain = copt->generic.reserved[7]; - sess_cfg->codec.opus_dec.mapping_family = copt->generic.reserved[8]; - sess_cfg->codec.opus_dec.stream_count = copt->generic.reserved[9]; - sess_cfg->codec.opus_dec.coupled_count = copt->generic.reserved[10]; - memcpy(&sess_cfg->codec.opus_dec.channel_map[0], &copt->generic.reserved[11], 4); - memcpy(&sess_cfg->codec.opus_dec.channel_map[4], &copt->generic.reserved[12], 4); - } - break; - #endif - #ifdef SND_AUDIOCODEC_APE - case SND_AUDIOCODEC_APE: - sess_cfg->codec.ape_dec.bit_width = copt->generic.reserved[0]; - sess_cfg->codec.ape_dec.compatible_version = copt->generic.reserved[1]; - sess_cfg->codec.ape_dec.compression_level = copt->generic.reserved[2]; - sess_cfg->codec.ape_dec.format_flags = copt->generic.reserved[3]; - sess_cfg->codec.ape_dec.blocks_per_frame = copt->generic.reserved[4]; - sess_cfg->codec.ape_dec.final_frame_blocks = copt->generic.reserved[5]; - sess_cfg->codec.ape_dec.total_frames = copt->generic.reserved[6]; - sess_cfg->codec.ape_dec.seek_table_present = copt->generic.reserved[7]; - break; - #endif - case SND_AUDIOCODEC_WMA: - #ifdef SND_AUDIOPROFILE_WMA9_LOSSLESS - if ((params->codec.profile == SND_AUDIOPROFILE_WMA9_PRO) || - (params->codec.profile == SND_AUDIOPROFILE_WMA9_LOSSLESS) || - (params->codec.profile == SND_AUDIOPROFILE_WMA10_LOSSLESS)) { - #else - if ((params->codec.profile == SND_AUDIOMODE_WMAPRO_LEVELM0) || - (params->codec.profile == SND_AUDIOMODE_WMAPRO_LEVELM1) || - (params->codec.profile == SND_AUDIOMODE_WMAPRO_LEVELM2)) { - #endif - sess_cfg->codec.wmapro_dec.avg_bytes_per_sec = copt->generic.reserved[0]; - sess_cfg->codec.wmapro_dec.blk_align = copt->generic.reserved[1]; - sess_cfg->codec.wmapro_dec.bits_per_sample = copt->generic.reserved[2]; - sess_cfg->codec.wmapro_dec.channel_mask = copt->generic.reserved[3]; - sess_cfg->codec.wmapro_dec.enc_options = copt->generic.reserved[4]; - sess_cfg->codec.wmapro_dec.advanced_enc_option = copt->generic.reserved[5]; - sess_cfg->codec.wmapro_dec.advanced_enc_option2 = copt->generic.reserved[6]; - } else { - sess_cfg->codec.wma_dec.avg_bytes_per_sec = copt->generic.reserved[0]; - sess_cfg->codec.wma_dec.blk_align = copt->generic.reserved[1]; - sess_cfg->codec.wma_dec.bits_per_sample = copt->generic.reserved[2]; - sess_cfg->codec.wma_dec.channel_mask = copt->generic.reserved[3]; - sess_cfg->codec.wma_dec.enc_options = copt->generic.reserved[4]; - } - break; - default: - break; - } - } - - // capture - if (sess_cfg->dir == TX) { - switch (params->codec.id) { - case SND_AUDIOCODEC_AAC: - break; - - default: - break; - } - } -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/src/agm_dummy_impl.c b/qcom/opensource/agm/plugins/tinyalsa/src/agm_dummy_impl.c deleted file mode 100755 index 051b1a9a..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/src/agm_dummy_impl.c +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2019, 2021 The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include - -#include -#include - -#define ARRAY_SIZE(a) \ - (sizeof(a) / sizeof(a[0])) - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_DUMMY_IMPL -#include -#endif - -int agm_session_write(struct session_obj *handle, void *buff, size_t count) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - - -int agm_session_read(struct session_obj *handle, void *buff, size_t count) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_session_stop(struct session_obj *handle) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_session_start(struct session_obj *handle) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_session_prepare(struct session_obj *handle) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_session_close(struct session_obj *handle) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_session_set_config(struct session_obj *handle, - struct agm_session_config *session_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_session_open(uint32_t session_id, enum agm_session_mode sess_mode, - struct session_obj **handle) -{ - struct session_obj *h = malloc(sizeof(100)); - AGM_LOGD("%s %d\n", __func__, __LINE__); - *handle = h; - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - - -int agm_audio_intf_set_media_config(uint32_t audio_intf, - struct agm_media_config *media_config) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_audio_intf_set_metadata(uint32_t audio_intf, - struct agm_meta_data *metadata) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_session_set_metadata(uint32_t session_id, - struct agm_meta_data *metadata) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_session_audio_inf_set_metadata(uint32_t session_id, - uint32_t audio_intf, - struct agm_meta_data *metadata) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} - -int agm_session_audio_inf_connect(uint32_t session_id, - uint32_t audio_intf, bool state) -{ - AGM_LOGD("%s: s_id %u, aif_id %u, %s\n", __func__, - session_id, audio_intf, - state ? "connect" : "disconnect"); - return 0; -} - -static struct aif_info be_list[] = { - { - .aif_name = "SLIM_0_RX", - .dir = RX, - }, - { - .aif_name = "SLIM_1_RX", - .dir = RX, - }, - { - .aif_name = "SLIM_0_TX", - .dir = TX, - }, - { - .aif_name = "SLIM_1_TX", - .dir = TX, - }, -}; - -int agm_get_aif_info_list(struct aif_info *aif_list, size_t *num_aif_info) -{ - int i; - - AGM_LOGD("%s %d\n", __func__, __LINE__); - if (*num_aif_info == 0) { - *num_aif_info = ARRAY_SIZE(be_list); - return 0; - } - for (i = 0; i < *num_aif_info; i++) - memcpy((aif_list + i), &be_list[i], sizeof(struct aif_info)); - return 0; -} - -int agm_session_set_loopback(uint32_t capture_session_id, - uint32_t playback_session_id) -{ - AGM_LOGD("%s %d\n", __func__, __LINE__); - return 0; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/src/agm_mixer_plugin.c b/qcom/opensource/agm/plugins/tinyalsa/src/agm_mixer_plugin.c deleted file mode 100755 index 53d12f34..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/src/agm_mixer_plugin.c +++ /dev/null @@ -1,2463 +0,0 @@ -/* -** Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. -** Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -/* agm_mixer.c all names (variable/functions) should have - amp_ (Agm Mixer Plugin) */ -#define LOG_TAG "PLUGIN: mixer" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include - -#include -#include - -#include -#include - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_MIXER_PLUGIN -#include -#endif - - -#define ARRAY_SIZE(a) \ - (sizeof(a) / sizeof(a[0])) - -#define AMP_PRIV_GET_CTL_PTR(p, idx) \ - (p->ctls + idx) - -#define AMP_PRIV_GET_CTL_NAME_PTR(p, idx) \ - (p->ctl_names[idx]) - -enum { - BE_CTL_NAME_MEDIA_CONFIG = 0, - BE_CTL_NAME_METADATA, - BE_CTL_NAME_SET_PARAM, -}; - -/* strings should be at the index as per the #defines */ -static char *amp_be_ctl_name_extn[] = { - "rate ch fmt", - "metadata", - "setParam", -}; - -enum { - STATIC_CTL_SET_ACDB_TUNNEL = 0, - STATIC_CTL_GET_ACDB_TUNNEL, -}; - -static char *static_acdb_ctl_name_extn[] = { - "setACDBTunnel", - "getACDBTunnel", -}; - -enum { - BE_GROUP_CTL_NAME_MEDIA_CONFIG = 0, -}; - -static char *amp_group_be_ctl_name_extn[] = { - "grp config", -}; - -enum { - PCM_CTL_NAME_CONNECT = 0, - PCM_CTL_NAME_DISCONNECT, - PCM_CTL_NAME_MTD_CONTROL, - PCM_CTL_NAME_METADATA, - PCM_CTL_NAME_SET_PARAM, - PCM_CTL_NAME_SET_PARAM_TAG = 5, - PCM_CTL_NAME_SET_PARAM_TAG_ACDB, - PCM_CTL_NAME_GET_TAG_INFO, - PCM_CTL_NAME_EVENT, - PCM_CTL_NAME_SET_CALIBRATION, - PCM_CTL_NAME_GET_PARAM, - PCM_CTL_NAME_BUF_INFO, - /* Add new ones here */ -}; - -/* strings should be at the index as per the #defines */ -static char *amp_pcm_ctl_name_extn[] = { - "connect", - "disconnect", - "control", - "metadata", - "setParam", - "setParamTag", - "setParamTagACDB", - "getTaggedInfo", - "event", - "setCalibration", - "getParam", - "getBufInfo", - /* Add new ones below, be sure to update enum as well */ -}; - -enum { - PCM_TX_CTL_NAME_LOOPBACK = 0, - PCM_TX_CTL_NAME_ECHOREF, - PCM_CTL_NAME_BUF_TSTAMP, - /* Add new ones here */ -}; -/* strings should be at the index as per the #defines */ -static char *amp_pcm_tx_ctl_names[] = { - "loopback", - "echoReference", - "bufTimestamp", - /* Add new ones here, be sure to update enum as well */ -}; - -enum { - PCM_RX_CTL_NAME_SIDETONE = 0, - PCM_RX_CTL_NAME_DATAPATH_PARAMS, - PCM_RX_CTL_NAME_FLUSH, -}; -/* strings should be at the index as per the enum */ -static char *amp_pcm_rx_ctl_names[] = { - "sidetone", - "datapathParams", - "flush", -}; - -struct amp_get_param_info { - void *get_param_payload; - int get_param_payload_size; -}; - -struct amp_dev_info { - char **names; - int *idx_arr; - int count; - struct snd_value_enum dev_enum; - enum direction dir; - - /* - * Mixer ctl data cache for - * "pcm metadata_control" - * Unused for BE devs - */ - int *pcm_mtd_ctl; - - /* - * Mixer ctl data cache for - * "pcm getParam" - * Unused for BE devs - */ - struct amp_get_param_info *get_param_info; -}; - -struct amp_be_group_info { - char **names; - int *idx_arr; - int count; -}; - -struct amp_priv { - unsigned int card; - void *card_node; - - struct aif_info *aif_list; - struct listnode events_list; - struct listnode events_paramlist; - - struct amp_dev_info rx_be_devs; - struct amp_dev_info tx_be_devs; - struct amp_dev_info rx_pcm_devs; - struct amp_dev_info tx_pcm_devs; - struct amp_dev_info acdb_tunnels; - - struct amp_be_group_info group_be_devs; - - struct snd_control *ctls; - char (*ctl_names)[AIF_NAME_MAX_LEN + 16]; - int ctl_count; - - struct snd_value_enum tx_be_enum; - struct snd_value_enum rx_be_enum; - - event_callback event_cb; - pthread_mutex_t lock; -}; - -struct event_params_node { - uint32_t session_id; - struct listnode node; - struct agm_event_cb_params event_params; -}; - -struct mixer_plugin_event_data { - struct ctl_event ev; - struct listnode node; -}; - -static enum agm_media_format alsa_to_agm_fmt(int fmt) -{ - enum agm_media_format agm_pcm_fmt = AGM_FORMAT_INVALID; - - switch (fmt) { - case SNDRV_PCM_FORMAT_S8: - agm_pcm_fmt = AGM_FORMAT_PCM_S8; - break; - case SNDRV_PCM_FORMAT_S16_LE: - agm_pcm_fmt = AGM_FORMAT_PCM_S16_LE; - break; - case SNDRV_PCM_FORMAT_S24_LE: - agm_pcm_fmt = AGM_FORMAT_PCM_S24_LE; - break; - case SNDRV_PCM_FORMAT_S24_3LE: - agm_pcm_fmt = AGM_FORMAT_PCM_S24_3LE; - break; - case SNDRV_PCM_FORMAT_S32_LE: - agm_pcm_fmt = AGM_FORMAT_PCM_S32_LE; - break; - } - - return agm_pcm_fmt; -} - -static struct amp_dev_info *amp_get_be_adi(struct amp_priv *amp_priv, - enum direction dir) -{ - if (dir == RX) - return &_priv->rx_be_devs; - else if (dir == TX) - return &_priv->tx_be_devs; - - return NULL; -} - -static void amp_free_dev_info(struct amp_dev_info *adi) -{ - if (adi->names) { - free(adi->names); - adi->names = NULL; - } - - if (adi->idx_arr) { - free(adi->idx_arr); - adi->idx_arr = NULL; - } - - if (adi->pcm_mtd_ctl) { - free(adi->pcm_mtd_ctl); - adi->pcm_mtd_ctl = NULL; - } - - if (adi->get_param_info) { - free(adi->get_param_info); - adi->get_param_info = NULL; - } - - adi->count = 0; -} - -static void amp_free_be_dev_info(struct amp_priv *amp_priv) -{ - amp_free_dev_info(&_priv->rx_be_devs); - amp_free_dev_info(&_priv->tx_be_devs); - - if (amp_priv->aif_list) { - free(amp_priv->aif_list); - amp_priv->aif_list = NULL; - } -} - -static void amp_free_group_be_dev_info(struct amp_priv *amp_priv) -{ - struct amp_be_group_info *grp_info = &_priv->group_be_devs; - int i; - - if (grp_info->names) { - for (i = 0; i < grp_info->count; i++) { - if (grp_info->names[i]) - free(grp_info->names[i]); - } - free(grp_info->names); - grp_info->names = NULL; - } - - if (grp_info->idx_arr) { - free(grp_info->idx_arr); - grp_info->idx_arr = NULL; - } -} - -static void amp_free_acdb_dev_info(struct amp_priv *amp_priv) -{ - amp_free_dev_info(&_priv->acdb_tunnels); -} - -static void amp_free_pcm_dev_info(struct amp_priv *amp_priv) -{ - amp_free_dev_info(&_priv->rx_pcm_devs); - amp_free_dev_info(&_priv->tx_pcm_devs); -} - -static void amp_free_ctls(struct amp_priv *amp_priv) -{ - if (amp_priv->ctl_names) { - free(amp_priv->ctl_names); - amp_priv->ctl_names = NULL; - } - - if (amp_priv->ctls) { - free(amp_priv->ctls); - amp_priv->ctls = NULL; - } - - amp_priv->ctl_count = 0; -} - -static void amp_add_event_params(struct amp_priv *amp_priv, - uint32_t session_id, - struct agm_event_cb_params *event_params) -{ - struct event_params_node *event_node; - struct agm_event_cb_params *eparams; - uint32_t len = event_params->event_payload_size; - - event_node = calloc(1, sizeof(struct event_params_node) + len); - if (!event_node) - return; - - event_node->session_id = session_id; - eparams = &event_node->event_params; - eparams->source_module_id = event_params->source_module_id; - eparams->event_id = event_params->event_id; - eparams->event_payload_size = len; - - memcpy(&eparams->event_payload, &event_params->event_payload, len); - list_add_tail(&_priv->events_paramlist, &event_node->node); -} - -void amp_event_cb(uint32_t session_id, struct agm_event_cb_params *event_params, - void *client_data) -{ - struct mixer_plugin *plugin = client_data; - struct amp_priv *amp_priv; - struct ctl_event event; - struct mixer_plugin_event_data *data; - char *stream = NULL; - char *ctl_name = "event"; - char *mixer_str = NULL; - int ctl_len, i; - struct amp_dev_info *adi = NULL; - - if (!plugin) - return; - - if (!plugin->subscribed) - return; - - amp_priv = plugin->priv; - if (!amp_priv) - return; - - /* Get device node name - * Check Rx device nodes followed by Tx. - */ - adi = &_priv->rx_pcm_devs; - for (i = 0; i < adi->count; i++) { - if(adi->idx_arr[i] == session_id) { - stream = adi->names[i]; - goto found; - } - } - - adi = &_priv->tx_pcm_devs; - for (i = 0; i < adi->count; i++) { - if(adi->idx_arr[i] == session_id) { - stream = adi->names[i]; - goto found; - } - } - - if (!stream) - return; -found: - pthread_mutex_lock(&_priv->lock); - amp_add_event_params(amp_priv, session_id, event_params); - event.type = SNDRV_CTL_EVENT_ELEM; - ctl_len = (int)(strlen(stream) + 1 + strlen(ctl_name) + 1); - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - pthread_mutex_unlock(&_priv->lock); - return; - } - - snprintf(mixer_str, ctl_len, "%s %s", stream, ctl_name); - strlcpy((char*)event.data.elem.id.name, mixer_str, sizeof(event.data.elem.id.name)); - - data = calloc(1, sizeof(struct mixer_plugin_event_data)); - if (!data) { - pthread_mutex_unlock(&_priv->lock); - goto done; - } - - data->ev = event; - list_add_tail(&_priv->events_list, &data->node); - pthread_mutex_unlock(&_priv->lock); - - if (amp_priv->event_cb) - amp_priv->event_cb(plugin); - -done: - free(mixer_str); -} - -static void amp_copy_be_names_from_aif_list(struct aif_info *aif_list, - size_t aif_cnt, struct amp_dev_info *adi, enum direction dir) -{ - struct aif_info *aif_info; - int i, be_idx = 0; - - be_idx = 0; - adi->names[be_idx] = "ZERO"; - adi->idx_arr[be_idx] = 0; - be_idx++; - - for (i = 0; i < aif_cnt; i++) { - aif_info = aif_list + i; - if (aif_info->dir != dir) - continue; - - adi->names[be_idx] = aif_info->aif_name; - adi->idx_arr[be_idx] = i; - be_idx++; - } - - adi->count = be_idx; - adi->dev_enum.items = adi->count; - adi->dev_enum.texts = adi->names; -} - -static void amp_copy_group_be_names_from_aif_list(struct aif_info *aif_list, - size_t grp_cnt, struct amp_be_group_info *grp_info) -{ - struct aif_info *aif_info; - int i, grp_idx = 0; - - for (i = 0; i < grp_cnt; i++) { - aif_info = aif_list + i; - - grp_info->names[grp_idx] = strdup(aif_info->aif_name); - grp_info->idx_arr[grp_idx] = i; - grp_idx++; - } -} - -static int amp_get_be_info(struct amp_priv *amp_priv) -{ - struct amp_dev_info *rx_adi = &_priv->rx_be_devs; - struct amp_dev_info *tx_adi = &_priv->tx_be_devs; - struct aif_info *aif_list, *aif_info; - size_t be_count = 0; - int ret = 0, i; - - ret = agm_get_aif_info_list(NULL, &be_count); - if (ret || be_count == 0) - return -EINVAL; - - aif_list = calloc(be_count, sizeof(struct aif_info)); - if (!aif_list) - return -ENOMEM; - - ret = agm_get_aif_info_list(aif_list, &be_count); - if (ret) - goto err_backends_get; - - rx_adi->count = 0; - tx_adi->count = 0; - - /* count rx and tx backends */ - for (i = 0; i < be_count; i++) { - aif_info = aif_list + i; - if (aif_info->dir == RX) - rx_adi->count++; - else if (aif_info->dir == TX) - tx_adi->count++; - } - - rx_adi->names = calloc(rx_adi->count + 1, sizeof(*rx_adi->names)); - rx_adi->idx_arr = calloc(rx_adi->count + 1, sizeof(*rx_adi->idx_arr)); - tx_adi->names = calloc(tx_adi->count + 1, sizeof(*tx_adi->names)); - tx_adi->idx_arr = calloc(tx_adi->count + 1, sizeof(*tx_adi->idx_arr)); - - if (!rx_adi->names || !tx_adi->names || - !rx_adi->idx_arr || !tx_adi->idx_arr) { - ret = -ENOMEM; - goto err_backends_get; - } - - /* form the rx backends enum array */ - amp_copy_be_names_from_aif_list(aif_list, be_count, rx_adi, RX); - amp_copy_be_names_from_aif_list(aif_list, be_count, tx_adi, TX); - - amp_priv->aif_list = aif_list; - return 0; - -err_backends_get: - if (aif_list) - free(aif_list); - amp_free_be_dev_info(amp_priv); - return ret; -} - -static int amp_get_group_be_info(struct amp_priv *amp_priv) -{ - struct amp_be_group_info *grp_info = &_priv->group_be_devs; - struct aif_info *aif_list = NULL; - size_t group_be_count = 0; - int ret = 0, i; - - ret = agm_get_group_aif_info_list(NULL, &group_be_count); - if (ret) - return -EINVAL; - - if (group_be_count == 0) - return 0; - - aif_list = calloc(group_be_count, sizeof(struct aif_info)); - if (!aif_list) - return -ENOMEM; - - ret = agm_get_group_aif_info_list(aif_list, &group_be_count); - if (ret) - goto err_backends_get; - - grp_info->count = group_be_count; - - grp_info->names = calloc(group_be_count, sizeof(*grp_info->names)); - grp_info->idx_arr = calloc(group_be_count, sizeof(*grp_info->idx_arr)); - - if (!grp_info->names || !grp_info->idx_arr) { - ret = -ENOMEM; - goto err_backends_get; - } - amp_copy_group_be_names_from_aif_list(aif_list, group_be_count, grp_info); - free(aif_list); - return 0; - -err_backends_get: - if (aif_list) - free(aif_list); - amp_free_group_be_dev_info(amp_priv); - return ret; -} - -static int amp_create_pcm_info_from_card(struct amp_dev_info *adi, - const char *dir, int num_pcms, void **pcm_node_list) -{ - int ret, i, val = 0, idx = 0; - - adi->names[idx] = "ZERO"; - adi->idx_arr[idx] = 0; - idx++; - - for (i = 0; i < num_pcms; i++) { - void *pcm_node = pcm_node_list[i]; - val = 0; - - snd_card_def_get_int(pcm_node, dir, &val); - if (val == 0) - continue; - - ret = snd_card_def_get_str(pcm_node, "name", - &adi->names[idx]); - if (ret) { - AGM_LOGE("%s failed to get name for %s pcm wih idx %d\n", - __func__, dir, idx); - return -EINVAL; - } - ret = snd_card_def_get_int(pcm_node, "id", - &adi->idx_arr[idx]); - if (ret) { - AGM_LOGE("%s failed to get name for %s pcm with idx %d\n", - __func__, dir, idx); - return -EINVAL; - } - - idx++; - } - - adi->count = idx; - - return 0; -} - -static int amp_get_pcm_info(struct amp_priv *amp_priv) -{ - struct amp_dev_info *rx_adi = &_priv->rx_pcm_devs; - struct amp_dev_info *tx_adi = &_priv->tx_pcm_devs; - void **pcm_node_list = NULL; - int num_pcms = 0, num_compr = 0, total_pcms, ret, val = 0, i; - - /* Get both pcm and compressed node count */ - num_pcms = snd_card_def_get_num_node(amp_priv->card_node, - SND_NODE_TYPE_PCM); - num_compr = snd_card_def_get_num_node(amp_priv->card_node, - SND_NODE_TYPE_COMPR); - if (num_pcms <= 0 && num_compr <= 0) { - AGM_LOGE("%s: no pcms(%d)/compr(%d) nodes found for card %u\n", - __func__, num_pcms, num_compr, amp_priv->card); - ret = -EINVAL; - goto done; - } - - /* It is valid that any card could have just PCMs or just comprs or both */ - if (num_pcms < 0) { - total_pcms = num_compr; - num_pcms = 0; - } else if (num_compr < 0) { - total_pcms = num_pcms; - num_compr = 0; - } - total_pcms = num_pcms + num_compr; - - pcm_node_list = calloc(total_pcms, sizeof(*pcm_node_list)); - if (!pcm_node_list) { - AGM_LOGE("%s: alloc for pcm_node_list failed\n", __func__); - return -ENOMEM; - } - - if (num_pcms > 0) { - ret = snd_card_def_get_nodes_for_type(amp_priv->card_node, - SND_NODE_TYPE_PCM, - pcm_node_list, num_pcms); - if (ret) { - AGM_LOGE("%s: failed to get pcm node list, err %d\n", - __func__, ret); - goto done; - } - } - - if (num_compr > 0) { - ret = snd_card_def_get_nodes_for_type(amp_priv->card_node, - SND_NODE_TYPE_COMPR, - &pcm_node_list[num_pcms], - num_compr); - if (ret) { - AGM_LOGE("%s: failed to get compr node list, err %d\n", - __func__, ret); - goto done; - } - } - - /* count TX and RX PCMs + Comprs*/ - for (i = 0; i < total_pcms; i++) { - void *pcm_node = pcm_node_list[i]; - val = 0; - - snd_card_def_get_int(pcm_node, "playback", &val); - if (val == 1) - rx_adi->count++; - } - - for (i = 0; i < total_pcms; i++) { - void *pcm_node = pcm_node_list[i]; - val = 0; - - snd_card_def_get_int(pcm_node, "capture", &val); - if (val == 1) - tx_adi->count++; - } - - /* Allocate rx and tx structures */ - rx_adi->names = calloc(rx_adi->count + 1, sizeof(*rx_adi->names)); - rx_adi->idx_arr = calloc(rx_adi->count + 1, sizeof(*rx_adi->idx_arr)); - tx_adi->names = calloc(tx_adi->count + 1, sizeof(*tx_adi->names)); - tx_adi->idx_arr = calloc(tx_adi->count + 1, sizeof(*tx_adi->idx_arr)); - - if (!rx_adi->names || !tx_adi->names || - !rx_adi->idx_arr || !tx_adi->idx_arr) { - ret = -ENOMEM; - goto err_alloc_rx_tx; - } - - - /* Fill in RX properties */ - ret = amp_create_pcm_info_from_card(rx_adi, "playback", - total_pcms, pcm_node_list); - if (ret) - goto err_alloc_rx_tx; - - ret = amp_create_pcm_info_from_card(tx_adi, "capture", - total_pcms, pcm_node_list); - if (ret) - goto err_alloc_rx_tx; - - rx_adi->dev_enum.items = rx_adi->count; - rx_adi->dev_enum.texts = rx_adi->names; - tx_adi->dev_enum.items = tx_adi->count; - tx_adi->dev_enum.texts = tx_adi->names; - goto done; - -err_alloc_rx_tx: - amp_free_pcm_dev_info(amp_priv); - -done: - if (pcm_node_list) - free(pcm_node_list); - - return ret; -} - -static int amp_get_acdb_info(struct amp_priv *amp_priv) -{ - struct amp_dev_info *acdb_adi = &_priv->acdb_tunnels; - void **pcm_node_list = NULL; - int total_pcms, ret = 0; - - total_pcms = 2; - acdb_adi->count = 2; - pcm_node_list = calloc(total_pcms, sizeof(*pcm_node_list)); - if (!pcm_node_list) { - AGM_LOGE("%s: alloc for pcm_node_list failed\n", __func__); - return -ENOMEM; - } - - /* Allocate rx and tx structures */ - acdb_adi->names = calloc(acdb_adi->count, sizeof(*acdb_adi->names)); - acdb_adi->idx_arr = calloc(acdb_adi->count, sizeof(*acdb_adi->idx_arr)); - if (!acdb_adi->names ||!acdb_adi->idx_arr) { - ret = -ENOMEM; - goto err_alloc_rx_tx; - } - - acdb_adi->dev_enum.items = acdb_adi->count; - acdb_adi->dev_enum.texts = acdb_adi->names; - goto done; - -err_alloc_rx_tx: - amp_free_pcm_dev_info(amp_priv); - -done: - if (pcm_node_list) - free(pcm_node_list); - - return ret; -} - -static void amp_register_event_callback(struct mixer_plugin *plugin, int enable) -{ - struct amp_priv *amp_priv = plugin->priv; - struct amp_dev_info *rx_adi = &_priv->rx_pcm_devs; - struct amp_dev_info *tx_adi = &_priv->tx_pcm_devs; - agm_event_cb cb; - int idx, session_id; - - if (enable) - cb = &_event_cb; - else - cb = NULL; - - for (idx = 1; idx < rx_adi->count; idx++) { - session_id = rx_adi->idx_arr[idx]; - agm_session_register_cb(session_id, cb, AGM_EVENT_MODULE, plugin); - } - - for (idx = 1; idx < tx_adi->count; idx++) { - session_id = tx_adi->idx_arr[idx]; - agm_session_register_cb(session_id, cb, AGM_EVENT_MODULE, plugin); - } -} - -static int amp_get_be_ctl_count(struct amp_priv *amp_priv) -{ - struct amp_dev_info *rx_adi = &_priv->rx_be_devs; - struct amp_dev_info *tx_adi = &_priv->tx_be_devs; - int count, ctl_per_be; - - ctl_per_be = (int)ARRAY_SIZE(amp_be_ctl_name_extn); - - count = 0; - - /* minus 1 is needed to ignore the ZERO string (name) */ - count += (rx_adi->count - 1) * ctl_per_be; - count += (tx_adi->count - 1) * ctl_per_be; - - return count; -} - -static int amp_get_group_be_ctl_count(struct amp_priv *amp_priv) -{ - struct amp_be_group_info *grp_info = &_priv->group_be_devs; - int count = 0, ctl_per_be_group; - - ctl_per_be_group = (int)ARRAY_SIZE(amp_group_be_ctl_name_extn); - - count += grp_info->count * ctl_per_be_group; - - return count; -} - -static int amp_get_pcm_ctl_count(struct amp_priv *amp_priv) -{ - struct amp_dev_info *rx_adi = &_priv->rx_pcm_devs; - struct amp_dev_info *tx_adi = &_priv->tx_pcm_devs; - int count, ctl_per_pcm; - - count = 0; - - /* Count common ctls applicable for both RX and TX pcms */ - ctl_per_pcm = (int)ARRAY_SIZE(amp_pcm_ctl_name_extn); - count += (rx_adi->count - 1) * ctl_per_pcm; - count += (tx_adi->count - 1) * ctl_per_pcm; - - /* Count only TX pcm specific controls */ - ctl_per_pcm = (int)ARRAY_SIZE(amp_pcm_tx_ctl_names); - count += (tx_adi->count -1) * ctl_per_pcm; - - /* Count only RX pcm specific controls */ - ctl_per_pcm = (int)ARRAY_SIZE(amp_pcm_rx_ctl_names); - count += (rx_adi->count - 1) * ctl_per_pcm; - - return count; -} - -static int amp_pcm_get_control_value(struct amp_priv *amp_priv __unused, - int pcm_idx, struct amp_dev_info *pcm_adi) -{ - int mtd_idx; - - /* Find the index for metadata_ctl for this pcm */ - for (mtd_idx = 1; mtd_idx < pcm_adi->count; mtd_idx++) { - if (pcm_idx == pcm_adi->idx_arr[mtd_idx]) - break; - } - - if (mtd_idx >= pcm_adi->count) { - AGM_LOGE("%s: metadata index not found for pcm_idx %d", - __func__, pcm_idx); - return -EINVAL; - } - - return pcm_adi->pcm_mtd_ctl[mtd_idx]; -} - -static int amp_be_media_fmt_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - //TODO: AGM should support get function. - AGM_LOGV("%s: enter\n", __func__); - return 0; -} - -static int amp_be_media_fmt_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - uint32_t audio_intf_id = ctl->private_value; - struct agm_media_config media_fmt; - int ret = 0; - - AGM_LOGV("%s: enter\n", __func__); - media_fmt.rate = (uint32_t)ev->value.integer.value[0]; - media_fmt.channels = (uint32_t)ev->value.integer.value[1]; - media_fmt.format = alsa_to_agm_fmt(ev->value.integer.value[2]); - media_fmt.data_format = (uint32_t)ev->value.integer.value[3]; - - ret = agm_aif_set_media_config(audio_intf_id, &media_fmt); - - if (ret) - AGM_LOGE("%s: set_media_config failed, err %d, aif_id %u rate %u \ - channels %u fmt %u, data_fmt %u\n", - __func__, ret, audio_intf_id, media_fmt.rate, - media_fmt.channels, media_fmt.format, - media_fmt.data_format); - return ret; -} - -static int amp_group_be_media_fmt_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - AGM_LOGV("%s: enter\n", __func__); - return 0; -} - -static int amp_group_be_media_fmt_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - struct amp_priv *amp_priv = plugin->priv; - uint32_t audio_intf_id = ctl->private_value; - struct agm_group_media_config media_fmt; - int ret = 0; - - AGM_LOGV("%s: enter\n", __func__); - media_fmt.config.rate = (uint32_t)ev->value.integer.value[0]; - media_fmt.config.channels = (uint32_t)ev->value.integer.value[1]; - media_fmt.config.format = alsa_to_agm_fmt(ev->value.integer.value[2]); - media_fmt.config.data_format = (uint32_t)ev->value.integer.value[3]; - media_fmt.slot_mask = (uint32_t)ev->value.integer.value[4]; - - ret = agm_aif_group_set_media_config(audio_intf_id, - &media_fmt); - - if (ret) - AGM_LOGE("%s: set_media_config failed, err %d, aif_id %u rate %u \ - channels %u fmt %u, data_fmt %u, slot_mask %u\n", - __func__, ret, audio_intf_id, media_fmt.config.rate, - media_fmt.config.channels, media_fmt.config.format, - media_fmt.config.data_format, media_fmt.slot_mask); - return ret; -} - -static int amp_pcm_buf_info_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - struct agm_buf_info *buf_info; - int pcm_idx = ctl->private_value; - int ret = 0; - - buf_info = (struct agm_buf_info *) ev->value.bytes.data; - - ret = agm_session_get_buf_info(pcm_idx, buf_info, DATA_BUF); - return ret; -} - -static int amp_pcm_buf_info_put(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - return 0; -} - -static int amp_be_set_param_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_tlv *ev __unused) -{ - /* get of set_param not implemented */ - return 0; -} - -static int amp_be_set_param_put(struct mixer_plugin *plugin __unused, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - uint32_t audio_intf_id = ctl->private_value; - void *payload = NULL; - size_t tlv_size = 0; - int ret; - - AGM_LOGV("%s: enter\n", __func__); - payload = &tlv->tlv[0]; - tlv_size = tlv->length; - - ret = agm_aif_set_params(audio_intf_id, payload, tlv_size); - if (ret) - AGM_LOGE("%s: set_params failed, err %d, aif_id %u\n", - __func__, ret, audio_intf_id); - - return ret; -} - -static int amp_be_metadata_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_tlv *tlv __unused) -{ - /* AGM should provide a get */ - AGM_LOGV("%s: enter\n", __func__); - return 0; -} - -static int amp_be_metadata_put(struct mixer_plugin *plugin __unused, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - uint32_t audio_intf_id = ctl->private_value; - void *payload = NULL; - uint32_t tlv_size; - int ret; - - AGM_LOGV("%s: enter\n", __func__); - if (!tlv) { - return -EINVAL; - } - - tlv_size = tlv->length; - if (tlv_size == 0) { - AGM_LOGE("%s: invalid array size %d\n", __func__, tlv_size); - return -EINVAL; - } - - payload = &tlv->tlv[0]; - if (!payload) - return -EINVAL; - - ret = agm_aif_set_metadata(audio_intf_id, tlv_size, payload); - - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_metadata failed, err %d, aid_id %u\n", - __func__, ret, audio_intf_id); - return ret; -} - -static int amp_pcm_aif_connect_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - /* TODO: Need AGM support to perform get */ - AGM_LOGV("%s: enter\n", __func__); - return 0; -} - -static int amp_pcm_aif_connect_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - struct amp_priv *amp_priv = plugin->priv; - struct amp_dev_info *pcm_adi = ctl->private_data; - struct amp_dev_info *be_adi; - int be_idx, pcm_idx = ctl->private_value; - unsigned int val; - int ret; - bool state; - - AGM_LOGV("%s: enter\n", __func__); - be_adi = amp_get_be_adi(amp_priv, pcm_adi->dir); - if (!be_adi) - return -EINVAL; - - val = ev->value.enumerated.item[0]; - - /* setting to ZERO is a no-op */ - if (val == 0) - return 0; - - /* - * same function caters to connect and disconnect mixer ctl. - * try to find "disconnect" in the ctl name to differentiate - * between connect and disconnect mixer ctl. - */ - if (strstr(ctl->name, "disconnect")) - state = false; - else - state = true; - - be_idx = be_adi->idx_arr[val]; - ret = agm_session_aif_connect(pcm_idx, be_idx, state); - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: connect failed err %d, pcm_idx %d be_idx %d\n", - __func__, ret, pcm_idx, be_idx); - - return ret; -} - -static int amp_pcm_mtd_control_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - int idx = ctl->private_value; - - ev->value.enumerated.item[0] = pcm_adi->pcm_mtd_ctl[idx]; - - AGM_LOGV("%s: enter, val = %u\n", __func__, - ev->value.enumerated.item[0]); - return 0; -} - -static int amp_pcm_mtd_control_put(struct mixer_plugin *plugin __unused, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - int idx = ctl->private_value; - unsigned int val; - - val = ev->value.enumerated.item[0]; - pcm_adi->pcm_mtd_ctl[idx] = val; - - AGM_LOGV("%s: value = %u\n", __func__, val); - return 0; -} - -static int amp_pcm_event_get(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - struct amp_priv *amp_priv = plugin->priv; - struct listnode *eparams_node, *temp; - struct event_params_node *event_node; - struct agm_event_cb_params *eparams; - int session_id = ctl->private_value; - uint32_t tlv_size, event_payload_size; - void *payload; - int ret = 0; - - AGM_LOGV("%s: enter\n", __func__); - payload = &tlv->tlv[0]; - if (!payload) - return -EINVAL; - - tlv_size = tlv->length; - if (tlv_size == 0) { - AGM_LOGE("%s: invalid array size %d\n", __func__, tlv_size); - return -EINVAL; - } - pthread_mutex_lock(&_priv->lock); - list_for_each_safe(eparams_node, temp, &_priv->events_paramlist) { - event_node = node_to_item(eparams_node, struct event_params_node, node); - if (event_node->session_id == session_id) { - eparams = &event_node->event_params; - event_payload_size = sizeof(struct agm_event_cb_params) + eparams->event_payload_size; - if (tlv_size < event_payload_size) { - AGM_LOGE("Expected %d size, received %d\n", event_payload_size, tlv_size); - ret = -EINVAL; - goto done; - } - memcpy(payload, eparams, - sizeof(struct agm_event_cb_params) - + eparams->event_payload_size); - list_remove(&event_node->node); - free(event_node); - goto done; - } - } - -done: - pthread_mutex_unlock(&_priv->lock); - return ret; -} - -static int amp_pcm_event_put(struct mixer_plugin *plugin __unused, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - struct agm_event_reg_cfg *evt_reg_cfg; - int session_id = ctl->private_value; - uint32_t tlv_size; - void *payload; - int ret; - - payload = &tlv->tlv[0]; - if (!payload) - return -EINVAL; - - tlv_size = tlv->length; - if (tlv_size == 0) { - AGM_LOGE("%s: invalid array size %d\n", __func__, tlv_size); - ret = -EINVAL; - return ret; - } - - evt_reg_cfg = (struct agm_event_reg_cfg *) payload; - ret = agm_session_register_for_events(session_id, evt_reg_cfg); - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_event failed, err %d, session_id %u\n", - __func__, ret, session_id); - - return ret; -} - -static int amp_pcm_metadata_get(struct mixer_plugin *plugin __unused, - struct snd_control *Ctl __unused, struct snd_ctl_tlv *tlv __unused) -{ - /* TODO: AGM needs to provide this in a API */ - AGM_LOGV("%s: enter\n", __func__); - return 0; -} - -static int amp_pcm_metadata_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - struct amp_dev_info *be_adi; - int pcm_idx = ctl->private_value; - int pcm_control, be_idx, ret; - uint32_t tlv_size; - void *payload; - - AGM_LOGV("%s: enter\n", __func__); - - pcm_control = amp_pcm_get_control_value(plugin->priv, pcm_idx, pcm_adi); - if (pcm_control < 0) - return pcm_control; - - payload = &tlv->tlv[0]; - if (!payload) - return -EINVAL; - - tlv_size = tlv->length; - if (tlv_size == 0) { - AGM_LOGE("%s: invalid array size %d\n", __func__, tlv_size); - ret = -EINVAL; - return ret; - } - - if (pcm_control == 0) { - ret = agm_session_set_metadata(pcm_idx, tlv_size, payload); - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_session_metadata failed err %d for %s\n", - __func__, ret, ctl->name); - return ret; - } - - /* pcm control is not 0, set the (session + be) metadata */ - be_adi = amp_get_be_adi(plugin->priv, pcm_adi->dir); - be_idx = be_adi->idx_arr[pcm_control]; - ret = agm_session_aif_set_metadata(pcm_idx, be_idx, tlv_size, payload); - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_aif_ses_metadata failed err %d for %s\n", - __func__, ret, ctl->name); - return ret; -} - -static int amp_pcm_buf_tstamp_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - int pcm_idx = ctl->private_value; - int ret = 0; - uint64_t *timestamp = NULL; - - timestamp = (uint64_t *)ev->value.bytes.data; - ret = agm_get_buffer_timestamp(pcm_idx, timestamp); - return ret; -} - -static int amp_pcm_buf_tstamp_put(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - return 0; -} - -static int amp_pcm_calibration_get(struct mixer_plugin *plugin __unused, - struct snd_control *Ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - /* TODO: AGM needs to provide this in a API */ - AGM_LOGV("%s: enter\n", __func__); - return 0; -} - -static int amp_pcm_calibration_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - struct amp_dev_info *be_adi; - struct agm_cal_config *cal_config; - int pcm_idx = ctl->private_value; - int pcm_control, ret, be_idx = -1; - - cal_config = (struct agm_cal_config *) ev->value.bytes.data; - - pcm_control = amp_pcm_get_control_value(plugin->priv, pcm_idx, pcm_adi); - if (pcm_control < 0) - return pcm_control; - - if (pcm_control > 0) { - be_adi = amp_get_be_adi(plugin->priv, pcm_adi->dir); - if (!be_adi) - return -EINVAL; - be_idx = be_adi->idx_arr[pcm_control]; - } - - - AGM_LOGV("%s: enter sesid:%d audif:%d\n", __func__, pcm_idx, be_idx); - ret = agm_session_aif_set_cal(pcm_idx, be_idx, cal_config); - if (ret) - AGM_LOGE("%s: set_calbration failed, err %d, aif_id %u\n", - __func__, ret, be_idx); - return ret; -} - -static int amp_pcm_set_acdb_tunnel_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_tlv *ev __unused) -{ - /* get of set_param not implemented */ - return 0; -} - -static int amp_pcm_set_acdb_tunnel_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - void *payload; - int ret = 0; - size_t tlv_size; - - payload = &tlv->tlv[0]; - tlv_size = tlv->length; - ret = agm_set_params_to_acdb_tunnel(payload, tlv_size); - - return ret; -} - -static int amp_pcm_get_acdb_tunnel_get(struct mixer_plugin *plugin , - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - struct amp_dev_info *be_adi; - void *payload; - int pcm_idx = ctl->private_value; - int ret = 0; - size_t tlv_size; - int pcm_control, be_idx = -1; - - AGM_LOGV("%s: enter\n", __func__); - - if (!pcm_adi->get_param_info[pcm_idx].get_param_payload) { - AGM_LOGE("%s: put() for getParam not called\n", __func__); - return -EINVAL; - } - - payload = &tlv->tlv[0]; - tlv_size = tlv->length; - - if (tlv_size < pcm_adi->get_param_info[pcm_idx].get_param_payload_size) { - AGM_LOGE("%s: Buffer size less than expected\n", __func__); - return -EINVAL; - } - - memcpy(payload, pcm_adi->get_param_info[pcm_idx].get_param_payload, - pcm_adi->get_param_info[pcm_idx].get_param_payload_size); - ret = agm_get_params_from_acdb_tunnel(payload, &tlv_size); - - if (ret) - AGM_LOGE("%s: failed err %d for %s\n", __func__, ret, ctl->name); - - free(pcm_adi->get_param_info[pcm_idx].get_param_payload); - pcm_adi->get_param_info[pcm_idx].get_param_payload = NULL; - pcm_adi->get_param_info[pcm_idx].get_param_payload_size = 0; - - return ret; -} - -static int amp_pcm_get_acdb_tunnel_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - int pcm_idx = ctl->private_value; - void *payload; - - if (pcm_adi->get_param_info[pcm_idx].get_param_payload) { - free(pcm_adi->get_param_info[pcm_idx].get_param_payload); - pcm_adi->get_param_info[pcm_idx].get_param_payload = NULL; - } - payload = &tlv->tlv[0]; - - pcm_adi->get_param_info[pcm_idx].get_param_payload_size = tlv->length; - pcm_adi->get_param_info[pcm_idx].get_param_payload = - calloc(1, pcm_adi->get_param_info[pcm_idx].get_param_payload_size); - if (!pcm_adi->get_param_info[pcm_idx].get_param_payload) - return -ENOMEM; - - memcpy(pcm_adi->get_param_info[pcm_idx].get_param_payload, payload, - pcm_adi->get_param_info[pcm_idx].get_param_payload_size); - - return 0; -} - - -static int amp_pcm_set_param_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_tlv *ev __unused) -{ - /* get of set_param not implemented */ - return 0; -} - -static int amp_pcm_set_param_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - struct amp_dev_info *be_adi; - void *payload; - int pcm_idx = ctl->private_value; - int pcm_control, be_idx = -1, ret = 0; - size_t tlv_size; - bool is_param_tag = false; - bool is_param_tag_acdb = false; - - AGM_LOGV("%s: enter\n", __func__); - - if (strstr(ctl->name, "setParamTag")) - is_param_tag = true; - - if (strstr(ctl->name, "setParamTagACDB")) - is_param_tag_acdb = true; - - payload = &tlv->tlv[0]; - tlv_size = tlv->length; - pcm_control = amp_pcm_get_control_value(plugin->priv, pcm_idx, pcm_adi); - if (pcm_control < 0) - return pcm_control; - - if (pcm_control > 0) { - /* control is not 0, set the (session + be) set_param */ - be_adi = amp_get_be_adi(plugin->priv, pcm_adi->dir); - be_idx = be_adi->idx_arr[pcm_control]; - } - - if (is_param_tag_acdb) { - ret = agm_set_params_with_tag_to_acdb(pcm_idx, be_idx, - payload, tlv_size); - } else if (is_param_tag) { - ret = agm_set_params_with_tag(pcm_idx, be_idx, payload); - } else { - if (pcm_control == 0) { - ret = agm_session_set_params(pcm_idx, payload, tlv_size); - } else { - ret = agm_session_aif_set_params(pcm_idx, be_idx, - payload, tlv_size); - } - } - - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set_params failed err %d for %s is_param_tag %s\n", - __func__, ret, ctl->name, is_param_tag ? "true" : "false"); - return ret; -} - -static int amp_pcm_get_param_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - void *payload; - int pcm_idx; - int idx = ctl->private_value; - int ret = 0; - size_t tlv_size; - - AGM_LOGV("%s: enter\n", __func__); - - payload = &tlv->tlv[0]; - tlv_size = tlv->length; - pcm_idx = pcm_adi->idx_arr[idx]; - - if (!pcm_adi->get_param_info[idx].get_param_payload) { - AGM_LOGE("%s: put() for getParam not called\n", __func__); - return -EINVAL; - } - - if (tlv_size < pcm_adi->get_param_info[idx].get_param_payload_size) { - AGM_LOGE("%s: Buffer size less than expected\n", __func__); - return -EINVAL; - } - - memcpy(payload, pcm_adi->get_param_info[idx].get_param_payload, - pcm_adi->get_param_info[idx].get_param_payload_size); - ret = agm_session_get_params(pcm_idx, payload, tlv_size); - - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: failed err %d for %s\n", __func__, ret, ctl->name); - - free(pcm_adi->get_param_info[idx].get_param_payload); - pcm_adi->get_param_info[idx].get_param_payload = NULL; - pcm_adi->get_param_info[idx].get_param_payload_size = 0; - errno = ret; - return ret; -} - -static int amp_pcm_get_param_put(struct mixer_plugin *plugin __unused, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - int idx = ctl->private_value; - void *payload; - - AGM_LOGV("%s: enter\n", __func__); - - if (pcm_adi->get_param_info[idx].get_param_payload) { - free(pcm_adi->get_param_info[idx].get_param_payload); - pcm_adi->get_param_info[idx].get_param_payload = NULL; - } - payload = &tlv->tlv[0]; - pcm_adi->get_param_info[idx].get_param_payload_size = tlv->length; - - pcm_adi->get_param_info[idx].get_param_payload = calloc(1, - pcm_adi->get_param_info[idx].get_param_payload_size); - if (!pcm_adi->get_param_info[idx].get_param_payload) - return -ENOMEM; - - memcpy(pcm_adi->get_param_info[idx].get_param_payload, payload, - pcm_adi->get_param_info[idx].get_param_payload_size); - - return 0; -} - -static int amp_pcm_tag_info_get(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_tlv *tlv) -{ - struct amp_dev_info *pcm_adi = ctl->private_data; - struct amp_dev_info *be_adi; - void *payload; - int pcm_idx = ctl->private_value; - int pcm_control, be_idx = -1, ret = 0; - size_t tlv_size, get_size = 0; - - AGM_LOGV("%s: enter\n", __func__); - - pcm_control = amp_pcm_get_control_value(plugin->priv, pcm_idx, pcm_adi); - if (pcm_control < 0) - return pcm_control; - - payload = &tlv->tlv[0]; - tlv_size = tlv->length; - - if (pcm_control > 0) { - /* control is not 0, get the (session + be) get_tag_info */ - be_adi = amp_get_be_adi(plugin->priv, pcm_adi->dir); - be_idx = be_adi->idx_arr[pcm_control]; - } - - get_size = tlv_size; - ret = agm_session_aif_get_tag_module_info(pcm_idx, be_idx, - payload, &get_size); - if (ret || get_size == 0 || tlv_size < get_size) - AGM_LOGE("%s: failed with err %d, tlv_size %zu, get_size %zu for %s\n", - __func__, ret, tlv_size, get_size, ctl->name); - - return ret; -} - -static int amp_pcm_tag_info_put(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_tlv *tlv __unused) -{ - /* Set for getTaggedInfo mixer control is not supported */ - return 0; -} - -static int amp_pcm_loopback_get(struct mixer_plugin *plugin __unused, - struct snd_control *Ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - /* TODO: AGM API not available */ - AGM_LOGV("%s: enter\n", __func__); - return 0; -} - -static int amp_pcm_loopback_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - struct amp_priv *amp_priv = plugin->priv; - struct amp_dev_info *pcm_rx_adi; - int rx_pcm_idx, tx_pcm_idx = ctl->private_value; - unsigned int val; - bool state = true; - int ret; - - AGM_LOGV("%s: enter\n", __func__); - pcm_rx_adi = &_priv->rx_pcm_devs; - if (!pcm_rx_adi) - return -EINVAL; - - val = ev->value.enumerated.item[0]; - - /* setting to ZERO is a no-op */ - if (val == 0) { - rx_pcm_idx = 0; - state = false; - } else { - rx_pcm_idx = pcm_rx_adi->idx_arr[val]; - } - - ret = agm_session_set_loopback(tx_pcm_idx, rx_pcm_idx, state); - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: loopback failed err %d, tx_pcm_idx %d rx_pcm_idx %d\n", - __func__, ret, tx_pcm_idx, rx_pcm_idx); - - return 0; -} - -static int amp_pcm_echoref_get(struct mixer_plugin *plugin __unused, - struct snd_control *Ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - /* TODO: AGM API not available */ - AGM_LOGV("%s: enter\n", __func__); - return 0; -} - -static int amp_pcm_echoref_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - struct amp_priv *amp_priv = plugin->priv; - struct amp_dev_info *be_adi; - int be_idx, pcm_idx = ctl->private_value; - unsigned int val; - int ret; - bool state = true; - - AGM_LOGV("%s: enter\n", __func__); - be_adi = amp_get_be_adi(amp_priv, RX); - if (!be_adi) - return -EINVAL; - - val = ev->value.enumerated.item[0]; - - /* setting to ZERO is reset echoref */ - if (val == 0) - state = false; - - be_idx = be_adi->idx_arr[val]; - ret = agm_session_set_ec_ref(pcm_idx, be_idx, state); - if (ret == -EALREADY) - ret = 0; - - if (ret) - AGM_LOGE("%s: set ecref failed err %d, pcm_idx %d be_idx %d\n", - __func__, ret, pcm_idx, be_idx); - - return ret; -} - -static int amp_pcm_sidetone_get(struct mixer_plugin *plugin __unused, - struct snd_control *Ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - /* TODO: AGM API not available */ - AGM_LOGV("%s: enter\n", __func__); - return 0; -} - -static int amp_pcm_sidetone_put(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - //TODO - return 0; -} - -static int amp_pcm_write_datapath_params_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - return 0; -} - -static int amp_pcm_write_datapath_params_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - struct agm_buff *buffer; - int pcm_idx = ctl->private_value; - int ret; - - AGM_LOGV("%s: enter sesid:%d ev pointer %p\n", __func__, pcm_idx, ev->value.bytes.data); - buffer = (struct agm_buff *)ev->value.bytes.data; - - ret = agm_session_write_datapath_params(pcm_idx, buffer); - if (ret) - AGM_LOGE("%s: write_with_metadata failed, err %d\n", - __func__, ret); - return ret; -} - -/* Dummy implementation for flush_get */ -static int amp_pcm_flush_get(struct mixer_plugin *plugin __unused, - struct snd_control *ctl __unused, struct snd_ctl_elem_value *ev __unused) -{ - return 0; -} - -static int amp_pcm_flush_put(struct mixer_plugin *plugin, - struct snd_control *ctl, struct snd_ctl_elem_value *ev) -{ - uint32_t pcm_idx = ctl->private_value; - bool flush = !!(ev->value.integer.value[0]); - int ret = 0; - - if (flush) - ret = agm_sessionid_flush(pcm_idx); - - return ret; -} - -/* 512 max bytes for non-tlv controls, reserving 16 for future use */ -static struct snd_value_bytes pcm_calibration_bytes = - SND_VALUE_BYTES(512 - 16); -static struct snd_value_bytes pcm_buf_tstamp_bytes = - SND_VALUE_BYTES(512 - 16); -static struct snd_value_tlv_bytes be_metadata_bytes = - SND_VALUE_TLV_BYTES(1024, amp_be_metadata_get, amp_be_metadata_put); -static struct snd_value_tlv_bytes pcm_metadata_bytes = - SND_VALUE_TLV_BYTES(1024, amp_pcm_metadata_get, amp_pcm_metadata_put); -static struct snd_value_tlv_bytes pcm_taginfo_bytes = - SND_VALUE_TLV_BYTES(1024, amp_pcm_tag_info_get, amp_pcm_tag_info_put); -static struct snd_value_tlv_bytes pcm_setparamtag_bytes = - SND_VALUE_TLV_BYTES(256 * 1024, amp_pcm_set_param_get, amp_pcm_set_param_put); -static struct snd_value_tlv_bytes pcm_setparamtagacdb_bytes = - SND_VALUE_TLV_BYTES(256 * 1024, amp_pcm_set_param_get, amp_pcm_set_param_put); -static struct snd_value_tlv_bytes pcm_setacdbtunnel_bytes = - SND_VALUE_TLV_BYTES(256 * 1024, amp_pcm_set_acdb_tunnel_get, amp_pcm_set_acdb_tunnel_put); -static struct snd_value_tlv_bytes pcm_getacdbtunnel_bytes = - SND_VALUE_TLV_BYTES(256 * 1024, amp_pcm_get_acdb_tunnel_get, amp_pcm_get_acdb_tunnel_put); -static struct snd_value_tlv_bytes pcm_setparam_bytes = - SND_VALUE_TLV_BYTES(1024 * 1024, amp_pcm_set_param_get, amp_pcm_set_param_put); -static struct snd_value_tlv_bytes pcm_getparam_bytes = - SND_VALUE_TLV_BYTES(128 * 1024, amp_pcm_get_param_get, amp_pcm_get_param_put); -static struct snd_value_tlv_bytes pcm_event_bytes = - SND_VALUE_TLV_BYTES(128 * 1024, amp_pcm_event_get, amp_pcm_event_put); -static struct snd_value_bytes pcm_buf_info_bytes = - SND_VALUE_BYTES(512 - 16); -static struct snd_value_bytes pcm_write_datapath_params_bytes = - SND_VALUE_BYTES(512 - 16); - -static struct snd_value_int media_fmt_int = - SND_VALUE_INTEGER(4, 0, 384000, 1); - -static struct snd_value_int group_media_fmt_int = - SND_VALUE_INTEGER(5, 0, 384000, 1); - -static struct snd_value_int flush_param_int = - SND_VALUE_INTEGER(1, 0, 1, 1); - -static struct snd_value_tlv_bytes be_setparam_bytes = - SND_VALUE_TLV_BYTES(64 * 1024, amp_be_set_param_get, amp_be_set_param_put); - -/* PCM related mixer controls here */ -static void amp_create_connect_ctl(struct amp_priv *amp_priv, - char *pname, int ctl_idx, struct snd_value_enum *e, - int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - pname, amp_pcm_ctl_name_extn[PCM_CTL_NAME_CONNECT]); - INIT_SND_CONTROL_ENUM(ctl, ctl_name, amp_pcm_aif_connect_get, - amp_pcm_aif_connect_put, e, pval, pdata); -} - -static void amp_create_disconnect_ctl(struct amp_priv *amp_priv, - char *pname, int ctl_idx, struct snd_value_enum *e, - int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - pname, amp_pcm_ctl_name_extn[PCM_CTL_NAME_DISCONNECT]); - INIT_SND_CONTROL_ENUM(ctl, ctl_name, amp_pcm_aif_connect_get, - amp_pcm_aif_connect_put, e, pval, pdata); -} - -static void amp_create_mtd_control_ctl(struct amp_priv *amp_priv, - char *pname, int ctl_idx, struct snd_value_enum *e, - int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - pname, amp_pcm_ctl_name_extn[PCM_CTL_NAME_MTD_CONTROL]); - INIT_SND_CONTROL_ENUM(ctl, ctl_name, amp_pcm_mtd_control_get, - amp_pcm_mtd_control_put, e, pval, pdata); - -} - -static void amp_create_pcm_event_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_ctl_name_extn[PCM_CTL_NAME_EVENT]); - - INIT_SND_CONTROL_TLV_BYTES(ctl, ctl_name, pcm_event_bytes, - pval, pdata); -} - -static void amp_create_pcm_metadata_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_ctl_name_extn[PCM_CTL_NAME_METADATA]); - - INIT_SND_CONTROL_TLV_BYTES(ctl, ctl_name, pcm_metadata_bytes, - pval, pdata); -} - -static void amp_create_pcm_set_param_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata, - bool istagged_setparam, bool is_acdb) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - if (!istagged_setparam) { - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_ctl_name_extn[PCM_CTL_NAME_SET_PARAM]); - INIT_SND_CONTROL_TLV_BYTES(ctl, ctl_name, pcm_setparam_bytes, - pval, pdata); - } else { - if (!is_acdb) { - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_ctl_name_extn[PCM_CTL_NAME_SET_PARAM_TAG]); - INIT_SND_CONTROL_TLV_BYTES(ctl, ctl_name, pcm_setparamtag_bytes, - pval, pdata); - } else { - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_ctl_name_extn[PCM_CTL_NAME_SET_PARAM_TAG_ACDB]); - INIT_SND_CONTROL_TLV_BYTES(ctl, ctl_name, pcm_setparamtagacdb_bytes, - pval, pdata); - } - } - -} - -static void amp_create_pcm_get_param_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_ctl_name_extn[PCM_CTL_NAME_GET_PARAM]); - INIT_SND_CONTROL_TLV_BYTES(ctl, ctl_name, pcm_getparam_bytes, - pval, pdata); - -} - -static void amp_create_pcm_get_tag_info_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_ctl_name_extn[PCM_CTL_NAME_GET_TAG_INFO]); - - INIT_SND_CONTROL_TLV_BYTES(ctl, ctl_name, pcm_taginfo_bytes, - pval, pdata); -} - -/* TX only mixer control creations here */ -static void amp_create_pcm_loopback_ctl(struct amp_priv *amp_priv, - char *pname, int ctl_idx, struct snd_value_enum *e, - int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - pname, amp_pcm_tx_ctl_names[PCM_TX_CTL_NAME_LOOPBACK]); - INIT_SND_CONTROL_ENUM(ctl, ctl_name, amp_pcm_loopback_get, - amp_pcm_loopback_put, e, pval, pdata); -} - -static void amp_create_pcm_echoref_ctl(struct amp_priv *amp_priv, - char *pname, int ctl_idx, struct snd_value_enum *e, - int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - pname, amp_pcm_tx_ctl_names[PCM_TX_CTL_NAME_ECHOREF]); - INIT_SND_CONTROL_ENUM(ctl, ctl_name, amp_pcm_echoref_get, - amp_pcm_echoref_put, e, pval, pdata); -} - -/* RX only mixer control creations here */ -static void amp_create_pcm_sidetone_ctl(struct amp_priv *amp_priv, - char *pname, int ctl_idx, struct snd_value_enum *e, - int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - pname, amp_pcm_rx_ctl_names[PCM_RX_CTL_NAME_SIDETONE]); - INIT_SND_CONTROL_ENUM(ctl, ctl_name, amp_pcm_sidetone_get, - amp_pcm_sidetone_put, e, pval, pdata); -} - - -static void amp_create_pcm_calibration_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_ctl_name_extn[PCM_CTL_NAME_SET_CALIBRATION]); - - INIT_SND_CONTROL_BYTES(ctl, ctl_name, amp_pcm_calibration_get, - amp_pcm_calibration_put, pcm_calibration_bytes, - pval, pdata); -} - -static void amp_create_pcm_buf_tstamp_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_tx_ctl_names[PCM_CTL_NAME_BUF_TSTAMP]); - - INIT_SND_CONTROL_BYTES(ctl, ctl_name, amp_pcm_buf_tstamp_get, - amp_pcm_buf_tstamp_put, pcm_buf_tstamp_bytes, - pval, pdata); -} - -static void amp_create_pcm_bufinfo_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_ctl_name_extn[PCM_CTL_NAME_BUF_INFO]); - - INIT_SND_CONTROL_BYTES(ctl, ctl_name, amp_pcm_buf_info_get, - amp_pcm_buf_info_put, pcm_buf_info_bytes, - pval, pdata); -} - -static void amp_create_pcm_write_with_metadata_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_rx_ctl_names[PCM_RX_CTL_NAME_DATAPATH_PARAMS]); - - INIT_SND_CONTROL_BYTES(ctl, ctl_name, amp_pcm_write_datapath_params_get, - amp_pcm_write_datapath_params_put, pcm_write_datapath_params_bytes, - pval, pdata); -} - -/* static mixer control for ACDB parameter set */ -static void amp_create_acdb_tunnel_set_ctl(struct amp_priv *amp_priv, - int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - - INIT_SND_CONTROL_TLV_BYTES(ctl, - static_acdb_ctl_name_extn[STATIC_CTL_SET_ACDB_TUNNEL], - pcm_setacdbtunnel_bytes, pval, pdata); -} - -static void amp_create_acdb_tunnel_get_ctl(struct amp_priv *amp_priv, - int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - - INIT_SND_CONTROL_TLV_BYTES(ctl, - static_acdb_ctl_name_extn[STATIC_CTL_GET_ACDB_TUNNEL], - pcm_getacdbtunnel_bytes, pval, pdata); -} - -static void amp_create_pcm_flush_ctl(struct amp_priv *amp_priv, - char *name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - name, amp_pcm_rx_ctl_names[PCM_RX_CTL_NAME_FLUSH]); - - INIT_SND_CONTROL_INTEGER(ctl, ctl_name, amp_pcm_flush_get, - amp_pcm_flush_put, flush_param_int, pval, pdata); -} - -/* BE related mixer control creations here */ -static void amp_create_metadata_ctl(struct amp_priv *amp_priv, - char *be_name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - be_name, amp_be_ctl_name_extn[BE_CTL_NAME_METADATA]); - - INIT_SND_CONTROL_TLV_BYTES(ctl, ctl_name, be_metadata_bytes, - pval, pdata); -} - -static void amp_create_media_fmt_ctl(struct amp_priv *amp_priv, - char *be_name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - be_name, amp_be_ctl_name_extn[BE_CTL_NAME_MEDIA_CONFIG]); - INIT_SND_CONTROL_INTEGER(ctl, ctl_name, amp_be_media_fmt_get, - amp_be_media_fmt_put, media_fmt_int, pval, pdata); -} - -static void amp_create_be_set_param_ctl(struct amp_priv *amp_priv, - char *be_name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - be_name, amp_be_ctl_name_extn[BE_CTL_NAME_SET_PARAM]); - INIT_SND_CONTROL_TLV_BYTES(ctl, ctl_name, be_setparam_bytes, - pval, pdata); -} - -static int amp_form_be_ctls(struct amp_priv *amp_priv, int ctl_idx, int ctl_cnt __unused) -{ - struct amp_dev_info *rx_adi = &_priv->rx_be_devs; - struct amp_dev_info *tx_adi = &_priv->tx_be_devs; - int i; - - for (i = 1; i < rx_adi->count; i++) { - amp_create_media_fmt_ctl(amp_priv, rx_adi->names[i], ctl_idx, - rx_adi->idx_arr[i], rx_adi); - ctl_idx++; - amp_create_metadata_ctl(amp_priv, rx_adi->names[i], ctl_idx, - rx_adi->idx_arr[i], rx_adi); - ctl_idx++; - amp_create_be_set_param_ctl(amp_priv, rx_adi->names[i], ctl_idx, - rx_adi->idx_arr[i], rx_adi); - ctl_idx++; - } - - for (i = 1; i < tx_adi->count; i++) { - amp_create_media_fmt_ctl(amp_priv, tx_adi->names[i], ctl_idx, - tx_adi->idx_arr[i], tx_adi); - ctl_idx++; - amp_create_metadata_ctl(amp_priv, tx_adi->names[i], ctl_idx, - tx_adi->idx_arr[i], tx_adi); - ctl_idx++; - amp_create_be_set_param_ctl(amp_priv, tx_adi->names[i], ctl_idx, - tx_adi->idx_arr[i], tx_adi); - ctl_idx++; - } - - return 0; -} - -static void amp_create_group_be_media_fmt_ctl(struct amp_priv *amp_priv, - char *group_be_name, int ctl_idx, int pval, void *pdata) -{ - struct snd_control *ctl = AMP_PRIV_GET_CTL_PTR(amp_priv, ctl_idx); - char *ctl_name = AMP_PRIV_GET_CTL_NAME_PTR(amp_priv, ctl_idx); - - snprintf(ctl_name, AIF_NAME_MAX_LEN + 16, "%s %s", - group_be_name, amp_group_be_ctl_name_extn[BE_GROUP_CTL_NAME_MEDIA_CONFIG]); - INIT_SND_CONTROL_INTEGER(ctl, ctl_name, amp_group_be_media_fmt_get, - amp_group_be_media_fmt_put, group_media_fmt_int, pval, pdata); -} - -static int amp_form_group_be_ctls(struct amp_priv *amp_priv, int ctl_idx, int ctl_cnt __unused) -{ - struct amp_be_group_info *grp_info = &_priv->group_be_devs; - int i; - - for (i = 0; i < grp_info->count; i++) { - amp_create_group_be_media_fmt_ctl(amp_priv, grp_info->names[i], ctl_idx, - grp_info->idx_arr[i], grp_info); - ctl_idx++; - } - return 0; -} - -static int amp_form_common_pcm_ctls(struct amp_priv *amp_priv, int *ctl_idx, - struct amp_dev_info *pcm_adi, struct amp_dev_info *be_adi) -{ - int i; - - pcm_adi->pcm_mtd_ctl = calloc(pcm_adi->count, sizeof(int)); - if (!pcm_adi->pcm_mtd_ctl) - return -ENOMEM; - - pcm_adi->get_param_info = (struct amp_get_param_info *)calloc(pcm_adi->count, sizeof(struct amp_get_param_info)); - if (!pcm_adi->get_param_info) { - free(pcm_adi->pcm_mtd_ctl); - return -ENOMEM; - } - - for (i = 1; i < pcm_adi->count; i++) { - char *name = pcm_adi->names[i]; - int idx = pcm_adi->idx_arr[i]; - amp_create_connect_ctl(amp_priv, name, (*ctl_idx)++, - &be_adi->dev_enum, idx, pcm_adi); - amp_create_disconnect_ctl(amp_priv, name, (*ctl_idx)++, - &be_adi->dev_enum, idx, pcm_adi); - amp_create_mtd_control_ctl(amp_priv, name, (*ctl_idx)++, - &be_adi->dev_enum, i, pcm_adi); - amp_create_pcm_metadata_ctl(amp_priv, name, (*ctl_idx)++, - idx, pcm_adi); - amp_create_pcm_set_param_ctl(amp_priv, name, (*ctl_idx)++, - idx, pcm_adi, false, false); - amp_create_pcm_set_param_ctl(amp_priv, name, (*ctl_idx)++, - idx, pcm_adi, true, false); - amp_create_pcm_set_param_ctl(amp_priv, name, (*ctl_idx)++, - idx, pcm_adi, true, true); - amp_create_pcm_get_tag_info_ctl(amp_priv, name, (*ctl_idx)++, - idx, pcm_adi); - amp_create_pcm_event_ctl(amp_priv, name, (*ctl_idx)++, - idx, pcm_adi); - amp_create_pcm_calibration_ctl(amp_priv, name, (*ctl_idx)++, - idx, pcm_adi); - amp_create_pcm_get_param_ctl(amp_priv, name, (*ctl_idx)++, - i, pcm_adi); - amp_create_pcm_bufinfo_ctl(amp_priv, name, (*ctl_idx)++, - idx, pcm_adi); - } - - return 0; -} - -static int amp_form_tx_pcm_ctls(struct amp_priv *amp_priv, int *ctl_idx) -{ - struct amp_dev_info *rx_adi = &_priv->rx_pcm_devs; - struct amp_dev_info *tx_adi = &_priv->tx_pcm_devs; - struct amp_dev_info *be_rx_adi = &_priv->rx_be_devs; - int i; - - for (i = 1; i < tx_adi->count; i++) { - char *name = tx_adi->names[i]; - int idx = tx_adi->idx_arr[i]; - - /* create loopback controls, enum values are RX PCMs*/ - amp_create_pcm_loopback_ctl(amp_priv, name, (*ctl_idx)++, - &rx_adi->dev_enum, idx, tx_adi); - /* Echo Reference has backend RX as enum values */ - amp_create_pcm_echoref_ctl(amp_priv, name, (*ctl_idx)++, - &be_rx_adi->dev_enum, idx, tx_adi); - amp_create_pcm_buf_tstamp_ctl(amp_priv, name, (*ctl_idx)++, - idx, tx_adi); - } - - return 0; -} - -static int amp_form_rx_pcm_ctls(struct amp_priv *amp_priv, int *ctl_idx) -{ - struct amp_dev_info *rx_adi = &_priv->rx_pcm_devs; - struct amp_dev_info *be_tx_adi = &_priv->tx_be_devs; - int i; - - for (i = 1; i < rx_adi->count; i++) { - char *name = rx_adi->names[i]; - int idx = rx_adi->idx_arr[i]; - - /* Create sidetone control, enum values are TX backends */ - amp_create_pcm_sidetone_ctl(amp_priv, name, (*ctl_idx)++, - &be_tx_adi->dev_enum, idx, rx_adi); - amp_create_pcm_write_with_metadata_ctl(amp_priv, name, (*ctl_idx)++, - idx, rx_adi); - amp_create_pcm_flush_ctl(amp_priv, name, (*ctl_idx)++, - idx, rx_adi); - } - - return 0; -} - -static int amp_form_pcm_ctls(struct amp_priv *amp_priv, int ctl_idx, int ctl_cnt __unused) -{ - struct amp_dev_info *rx_adi = &_priv->rx_pcm_devs; - struct amp_dev_info *tx_adi = &_priv->tx_pcm_devs; - struct amp_dev_info *be_rx_adi = &_priv->rx_be_devs; - struct amp_dev_info *be_tx_adi = &_priv->tx_be_devs; - int ret; - - /* Form common controls for RX pcms */ - ret = amp_form_common_pcm_ctls(amp_priv, &ctl_idx, rx_adi, be_rx_adi); - if (ret) - return ret; - - /* Form RX PCM specific mixer controls */ - ret = amp_form_rx_pcm_ctls(amp_priv, &ctl_idx); - if (ret) - return ret; - - /* Form common controls for TX pcms */ - ret = amp_form_common_pcm_ctls(amp_priv, &ctl_idx, tx_adi, be_tx_adi); - if (ret) - return ret; - - /* Form TX PCM specific mixer controls */ - ret = amp_form_tx_pcm_ctls(amp_priv, &ctl_idx); - if (ret) - return ret; - - return 0; -} - -static int amp_form_acdb_ctls(struct amp_priv *amp_priv, int ctl_idx) -{ - struct amp_dev_info *acdb_adi = &_priv->acdb_tunnels; - acdb_adi->get_param_info = - (struct amp_get_param_info *)calloc(acdb_adi->count, - sizeof(struct amp_get_param_info)); - - if (!acdb_adi->get_param_info) - return -ENOMEM; - - amp_create_acdb_tunnel_set_ctl(amp_priv, ctl_idx++, acdb_adi->idx_arr[0], - acdb_adi); - amp_create_acdb_tunnel_get_ctl(amp_priv, ctl_idx, acdb_adi->idx_arr[1], - acdb_adi); - - return 0; -} - -static ssize_t amp_read_event(struct mixer_plugin *plugin, - struct ctl_event *ev, size_t size) -{ - struct amp_priv *amp_priv = plugin->priv; - ssize_t result = 0; - - while (size >= sizeof(struct ctl_event)) { - struct mixer_plugin_event_data *data; - - pthread_mutex_lock(&_priv->lock); - if (list_empty(&_priv->events_list)) { - pthread_mutex_unlock(&_priv->lock); - return result; - } - - data = node_to_item(amp_priv->events_list.next, - struct mixer_plugin_event_data, node); - memcpy(ev, &data->ev, sizeof(struct ctl_event)); - - list_remove(&data->node); - free(data); - pthread_mutex_unlock(&_priv->lock); - - ev += sizeof(struct ctl_event); - size -= sizeof(struct ctl_event); - result += sizeof(struct ctl_event); - } - - return result; -} - -static int amp_subscribe_events(struct mixer_plugin *plugin, - event_callback event_cb) -{ - struct amp_priv *amp_priv = plugin->priv; - struct listnode *eparams_node, *ev_node, *temp, *temp2; - struct event_params_node *event_node; - struct mixer_plugin_event_data *ev_data; - - AGM_LOGV("%s: enter\n", __func__); - - amp_priv->event_cb = event_cb; - - /* clear all event params on unsubscribe */ - if (event_cb == NULL) { - list_for_each_safe(eparams_node, temp, &_priv->events_paramlist) { - event_node = node_to_item(eparams_node, struct event_params_node, node); - list_remove(&event_node->node); - free(event_node); - } - - list_for_each_safe(ev_node, temp2, &_priv->events_list) { - ev_data = node_to_item(ev_node, struct mixer_plugin_event_data, node); - list_remove(&ev_data->node); - free(ev_data); - } - } - return 0; -} - -static void amp_close(struct mixer_plugin **plugin) -{ - struct mixer_plugin *amp = *plugin; - struct amp_priv *amp_priv = amp->priv; - - /* unblock mixer event during close */ - if (amp_priv->event_cb) - amp_priv->event_cb(amp); - amp_register_event_callback(amp, 0); - amp_subscribe_events(amp, NULL); - snd_card_def_put_card(amp_priv->card_node); - amp_free_pcm_dev_info(amp_priv); - amp_free_group_be_dev_info(amp_priv); - amp_free_be_dev_info(amp_priv); - amp_free_ctls(amp_priv); - pthread_mutex_destroy(&_priv->lock); - free(amp_priv); - free(*plugin); - plugin = NULL; -} - -struct mixer_plugin_ops amp_ops = { - .close = amp_close, - .subscribe_events = amp_subscribe_events, - .read_event = amp_read_event, -}; - -MIXER_PLUGIN_OPEN_FN(agm_mixer_plugin) -{ - struct mixer_plugin *amp; - struct amp_priv *amp_priv; - struct pcm_adi; - int ret = 0; - int be_ctl_cnt, pcm_ctl_cnt, total_ctl_cnt = 0; - int be_grp_ctl_cnt = 0; - - AGM_LOGI("%s: enter, card %u\n", __func__, card); - - amp = calloc(1, sizeof(*amp)); - if (!amp) { - AGM_LOGE("agm mixer plugin alloc failed\n"); - return -ENOMEM; - } - - amp_priv = calloc(1, sizeof(*amp_priv)); - if (!amp_priv) { - AGM_LOGE("amp priv data alloc failed\n"); - ret = -ENOMEM; - goto err_priv_alloc; - } - - amp_priv->card = card; - amp_priv->card_node = snd_card_def_get_card(amp_priv->card); - if (!amp_priv->card_node) { - AGM_LOGE("%s: card node not found for card %d\n", - __func__, amp_priv->card); - ret = -EINVAL; - goto err_get_card; - } - - amp_priv->rx_be_devs.dir = RX; - amp_priv->tx_be_devs.dir = TX; - amp_priv->rx_pcm_devs.dir = RX; - amp_priv->tx_pcm_devs.dir = TX; - - ret = amp_get_be_info(amp_priv); - if (ret) - goto err_get_be_info; - - ret = amp_get_group_be_info(amp_priv); - if (ret) - goto err_get_be_group_info; - - ret = amp_get_pcm_info(amp_priv); - if (ret) - goto err_get_pcm_info; - - ret = amp_get_acdb_info(amp_priv); - if (ret) - goto err_get_acdb_info; - - /* Get total count of controls to be registered */ - be_ctl_cnt = amp_get_be_ctl_count(amp_priv); - total_ctl_cnt += be_ctl_cnt; - be_grp_ctl_cnt = amp_get_group_be_ctl_count(amp_priv); - total_ctl_cnt += be_grp_ctl_cnt; - pcm_ctl_cnt = amp_get_pcm_ctl_count(amp_priv); - total_ctl_cnt += pcm_ctl_cnt; - /* add two static mixer control for acdb param set and get*/ - total_ctl_cnt += 2; - /* - * Create the controls to be registered - * When changing this code, be careful to make sure to create - * exactly the same number of controls as of total_ctl_cnt; - */ - amp_priv->ctls = calloc(total_ctl_cnt, sizeof(*amp_priv->ctls)); - amp_priv->ctl_names = calloc(total_ctl_cnt, sizeof(*amp_priv->ctl_names)); - if (!amp_priv->ctls || !amp_priv->ctl_names) - goto err_ctls_alloc; - - ret = amp_form_be_ctls(amp_priv, 0, be_ctl_cnt); - if (ret) - goto err_ctls_alloc; - - if (be_grp_ctl_cnt) { - ret = amp_form_group_be_ctls(amp_priv, be_ctl_cnt, be_grp_ctl_cnt); - if (ret) - goto err_ctls_alloc; - } - - ret = amp_form_pcm_ctls(amp_priv, be_ctl_cnt + be_grp_ctl_cnt, pcm_ctl_cnt); - if (ret) - goto err_ctls_alloc; - - ret = amp_form_acdb_ctls(amp_priv, be_ctl_cnt + be_grp_ctl_cnt + pcm_ctl_cnt); - if (ret) - goto err_ctls_alloc; - - /* Register the controls */ - if (total_ctl_cnt > 0) { - amp_priv->ctl_count = total_ctl_cnt; - amp->controls = amp_priv->ctls; - amp->num_controls = amp_priv->ctl_count; - } - - amp->ops = &_ops; - amp->priv = amp_priv; - *plugin = amp; - - amp_register_event_callback(amp, 1); - list_init(&_priv->events_paramlist); - list_init(&_priv->events_list); - pthread_mutex_init(&_priv->lock, (const pthread_mutexattr_t *) NULL); - AGM_LOGV("%s: total_ctl_cnt = %d\n", __func__, total_ctl_cnt); - - return 0; - -err_ctls_alloc: - amp_free_ctls(amp_priv); - amp_free_acdb_dev_info(amp_priv); - -err_get_acdb_info: - amp_free_pcm_dev_info(amp_priv); - -err_get_pcm_info: - if (be_grp_ctl_cnt) - amp_free_group_be_dev_info(amp_priv); - -err_get_be_group_info: - amp_free_be_dev_info(amp_priv); - -err_get_be_info: - snd_card_def_put_card(amp_priv->card_node); - -err_get_card: - free(amp_priv); - -err_priv_alloc: - free(amp); - return -ENOMEM; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/src/agm_pcm_plugin.c b/qcom/opensource/agm/plugins/tinyalsa/src/agm_pcm_plugin.c deleted file mode 100755 index 7274da6c..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/src/agm_pcm_plugin.c +++ /dev/null @@ -1,1042 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * - * Copyright (c) 2022-2024, Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - * - */ - -#define LOG_TAG "PLUGIN: pcm" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_PCM_PLUGIN -#include -#endif - -/* 2 words of uint32_t = 64 bits of mask */ -#define PCM_MASK_SIZE (2) -#define PCM_FORMAT_BIT(x) ((uint64_t)1 << x) - -/* pull-push mode macros */ -#define AGM_PULL_PUSH_IDX_RETRY_COUNT 2 -#define AGM_PULL_PUSH_FRAME_CNT_RETRY_COUNT 5 - -/* multiplier of timeout for wating for mmap buffers */ -#define MMAP_TOUT_MULTI 4 - -struct agm_shared_pos_buffer { - volatile uint32_t frame_counter; - volatile uint32_t read_index; - volatile uint32_t wall_clock_us_lsw; - volatile uint32_t wall_clock_us_msw; -}; - -struct pcm_plugin_pos_buf_info { - void *pos_buf_addr; - unsigned int boundary; /* pcm boundary */ - snd_pcm_uframes_t hw_ptr; /* RO: hw ptr (0...boundary-1) */ - snd_pcm_uframes_t hw_ptr_base; - unsigned int crossed_boundary_cnt; - struct timespec tstamp; - snd_pcm_uframes_t appl_ptr; /* RW: appl ptr (0...boundary-1) */ - snd_pcm_uframes_t avail_min; /* RW: min available frames for wakeup */ - uint32_t wall_clk_msw; - uint32_t wall_clk_lsw; - uint32_t frame_counter; -}; - -struct agm_mmap_buffer_port { - void* mmap_buffer_addr; - snd_pcm_uframes_t mmap_buffer_length; -}; - -struct agm_pcm_priv { - struct agm_media_config *media_config; - struct agm_buffer_config *buffer_config; - struct agm_session_config *session_config; - struct agm_buf_info *buf_info; - struct pcm_plugin_pos_buf_info *pos_buf; - uint64_t handle; - void *card_node; - int session_id; - unsigned int period_size; - snd_pcm_uframes_t total_size_frames; - /* idx: 0: out port, 1: in port */ - struct agm_mmap_buffer_port mmap_buffer_port[2]; - bool mmap_status; - uint32_t mmap_buf_tout; -}; - -struct pcm_plugin_hw_constraints agm_pcm_constrs = { - .access = 0, - .format = 0, - .bit_width = { - .min = 16, - .max = 32, - }, - .channels = { - .min = 1, - .max = 8, - }, - .rate = { - .min = 8000, - .max = 384000, - }, - .periods = { - .min = 1, - .max = 8, - }, - .period_bytes = { - .min = 96, - .max = 122880, - }, -}; - -static inline struct snd_interval *param_to_interval(struct snd_pcm_hw_params *p, - int n) -{ - return &(p->intervals[n - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]); -} - -static inline int param_is_interval(int p) -{ - return (p >= SNDRV_PCM_HW_PARAM_FIRST_INTERVAL) && - (p <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL); -} - -static unsigned int param_get_int(struct snd_pcm_hw_params *p, int n) -{ - if (param_is_interval(n)) { - struct snd_interval *i = param_to_interval(p, n); - if (i->integer) - return i->max; - } - return 0; -} - -static inline struct snd_mask *param_to_mask(struct snd_pcm_hw_params *p, int n) -{ - return &(p->masks[n - SNDRV_PCM_HW_PARAM_FIRST_MASK]); -} - -static inline int param_is_mask(int p) -{ - return (p >= SNDRV_PCM_HW_PARAM_FIRST_MASK) && - (p <= SNDRV_PCM_HW_PARAM_LAST_MASK); -} - -static inline int snd_mask_val(const struct snd_mask *mask) -{ - int i; - for (i = 0; i < PCM_MASK_SIZE; i++) { - if (mask->bits[i]) - return ffs(mask->bits[i]) + (i << 5) - 1; - } - return 0; -} - -static unsigned int agm_format_to_bits(enum pcm_format format) -{ - switch (format) { - case AGM_FORMAT_PCM_S32_LE: - case AGM_FORMAT_PCM_S24_LE: - return 32; - case AGM_FORMAT_PCM_S24_3LE: - return 24; - default: - case AGM_FORMAT_PCM_S16_LE: - return 16; - }; -} - -static enum agm_media_format alsa_to_agm_format(int format) -{ - switch (format) { - case SNDRV_PCM_FORMAT_S32_LE: - return AGM_FORMAT_PCM_S32_LE; - case SNDRV_PCM_FORMAT_S8: - return AGM_FORMAT_PCM_S8; - case SNDRV_PCM_FORMAT_S24_3LE: - return AGM_FORMAT_PCM_S24_3LE; - case SNDRV_PCM_FORMAT_S24_LE: - return AGM_FORMAT_PCM_S24_LE; - default: - case SNDRV_PCM_FORMAT_S16_LE: - return AGM_FORMAT_PCM_S16_LE; - }; -} - -static enum agm_media_format param_get_mask_val(struct snd_pcm_hw_params *p, - int n) -{ - if (param_is_mask(n)) { - struct snd_mask *m = param_to_mask(p, n); - int val = snd_mask_val(m); - - return alsa_to_agm_format(val); - } - return 0; -} - -static unsigned int agm_pcm_frames_to_bytes(struct agm_media_config *config, - unsigned int frames) -{ - return frames * config->channels * - (agm_format_to_bits(config->format) >> 3); -} - -static unsigned int agm_pcm_bytes_to_frames(unsigned int bytes, - struct agm_media_config *config) -{ - unsigned int frame_bits = config->channels * - agm_format_to_bits(config->format); - - return bytes * 8 / frame_bits; -} - -static int agm_get_session_handle(struct agm_pcm_priv *priv, - uint64_t *handle) -{ - if (!priv) - return -EINVAL; - - *handle = priv->handle; - if (!*handle) - return -EINVAL; - - return 0; -} - -static void agm_pcm_plugin_apply_appl_ptr(struct agm_pcm_priv *priv, - snd_pcm_uframes_t appl_ptr) -{ - struct pcm_plugin_pos_buf_info *pos = priv->pos_buf; - - pos->appl_ptr = appl_ptr; -} - -static void agm_pcm_plugin_apply_avail_min(struct agm_pcm_priv *priv, - snd_pcm_uframes_t avail_min) -{ - struct pcm_plugin_pos_buf_info *pos = priv->pos_buf; - - pos->avail_min = avail_min; -} - -static snd_pcm_uframes_t agm_pcm_plugin_get_avail_min(struct agm_pcm_priv *priv) -{ - struct pcm_plugin_pos_buf_info *pos = priv->pos_buf; - - return pos->avail_min; -} - -static snd_pcm_uframes_t agm_pcm_plugin_get_appl_ptr(struct agm_pcm_priv *priv) -{ - struct pcm_plugin_pos_buf_info *pos = priv->pos_buf; - - return pos->appl_ptr; -} - -static snd_pcm_uframes_t agm_pcm_plugin_get_hw_ptr(struct agm_pcm_priv *priv) -{ - struct pcm_plugin_pos_buf_info *pos = priv->pos_buf; - - return pos->hw_ptr; -} - -static int agm_pcm_plugin_get_shared_pos(struct pcm_plugin_pos_buf_info *pos_buf, - uint32_t *read_index, uint32_t *wall_clk_msw, - uint32_t *wall_clk_lsw) -{ - struct agm_shared_pos_buffer *buf; - int i, j; - uint32_t frame_cnt1, frame_cnt2; - - buf = (struct agm_shared_pos_buffer *)pos_buf->pos_buf_addr; - for (i = 0; i < AGM_PULL_PUSH_IDX_RETRY_COUNT; ++i) { - for (j = 0; j < AGM_PULL_PUSH_FRAME_CNT_RETRY_COUNT; ++j) { - frame_cnt1 = buf->frame_counter; - if (frame_cnt1 != 0) - break; - } - *wall_clk_msw = buf->wall_clock_us_msw; - *wall_clk_lsw = buf->wall_clock_us_lsw; - *read_index = buf->read_index; /* 0,.... Circ_buf_size-1 */ - frame_cnt2 = buf->frame_counter; - - if (frame_cnt1 != frame_cnt2) - continue; - - pos_buf->frame_counter = frame_cnt1; - return 0; - } - - return -EAGAIN; -} - -static int agm_pcm_plugin_update_hw_ptr(struct agm_pcm_priv *priv) -{ - int retries = 10; - snd_pcm_sframes_t circ_buf_pos; - snd_pcm_uframes_t pos, old_hw_ptr, new_hw_ptr, hw_base; - uint32_t read_index, wall_clk_msw, wall_clk_lsw; - int64_t delta_wall_clk_us = 0; - uint32_t delta_wall_clk_frames = 0; - uint64_t sub_res = 0; - int ret = 0; - uint32_t period_size = priv->period_size; /** in frames */ - uint32_t crossed_boundary = 0; - snd_pcm_uframes_t boundary = 0; - uint32_t old_frame_counter = priv->pos_buf->frame_counter; - - do { - ret = agm_pcm_plugin_get_shared_pos(priv->pos_buf, - &read_index, &wall_clk_msw, &wall_clk_lsw); - } while (ret == -EAGAIN && --retries); - - if (ret == 0) { - circ_buf_pos = agm_pcm_bytes_to_frames(read_index, priv->media_config); - pos = (circ_buf_pos / period_size) * period_size; - old_hw_ptr = agm_pcm_plugin_get_hw_ptr(priv); - hw_base = priv->pos_buf->hw_ptr_base; - - // Update new_hw_ptr - __builtin_uaddl_overflow(hw_base, pos, &new_hw_ptr); - __builtin_umull_overflow(priv->pos_buf->boundary, - priv->pos_buf->crossed_boundary_cnt, &boundary); - __builtin_uaddl_overflow(new_hw_ptr, boundary, &new_hw_ptr); - - // Set delta_wall_clk_us only if cached wall clk is non-zero - if (priv->pos_buf->wall_clk_msw || priv->pos_buf->wall_clk_lsw) { - uint64_t dsp_wall_clk = (((uint64_t)wall_clk_msw) << 32 | wall_clk_lsw); - uint64_t cached_wall_clk = (((uint64_t)priv->pos_buf->wall_clk_msw) << 32 | - priv->pos_buf->wall_clk_lsw); - // Compute delta only if diff is greater than zero - if (dsp_wall_clk > cached_wall_clk) { - __builtin_usubl_overflow(dsp_wall_clk,cached_wall_clk,&sub_res); - delta_wall_clk_us = (int64_t)sub_res; - } - } - // Identify the number of times of shared buffer length that the - // hw ptr has jumped through by checking wall clock time delta - // and assuming read ptr moved at a constant rate - if (delta_wall_clk_us > 0 ) { - __builtin_mul_overflow(delta_wall_clk_us / 1000000, - (priv->media_config->rate * priv->media_config->channels), - &delta_wall_clk_frames); - crossed_boundary = delta_wall_clk_frames / priv->total_size_frames; - } - - // More than 1 loop of shared buffer completed by hw_ptr - // No need to check if new_hw_ptr < old_hw_ptr, as new_hw_ptr - // has crossed old_hw_ptr atleast once if not more - if (crossed_boundary > 0) { - hw_base += (crossed_boundary * priv->total_size_frames); - if (hw_base >= priv->pos_buf->boundary) { - priv->pos_buf->crossed_boundary_cnt += hw_base / priv->pos_buf->boundary; - hw_base = 0; - } - __builtin_uaddl_overflow(hw_base, pos, &new_hw_ptr); - __builtin_uaddl_overflow(new_hw_ptr, - priv->pos_buf->boundary * priv->pos_buf->crossed_boundary_cnt, &new_hw_ptr); - priv->pos_buf->hw_ptr_base = hw_base; - AGM_LOGD("%s: crossed_boundary = %u, new_hw_ptr=%ld \n", - __func__, crossed_boundary, new_hw_ptr); - AGM_LOGD("%s: delta_wall_clk_frames = %lx, delta_wall_clk_us=%ld \n", - __func__, delta_wall_clk_frames, delta_wall_clk_us); - AGM_LOGD("%s: shared buffer length = %lx \n", - __func__, priv->total_size_frames); - } else { - if (new_hw_ptr < old_hw_ptr) { - hw_base += priv->total_size_frames; - if (hw_base >= priv->pos_buf->boundary) { - hw_base = 0; - priv->pos_buf->crossed_boundary_cnt += 1; - } - __builtin_uaddl_overflow(hw_base, pos, &new_hw_ptr); - __builtin_umull_overflow(priv->pos_buf->boundary, - priv->pos_buf->crossed_boundary_cnt, &boundary); - __builtin_uaddl_overflow(new_hw_ptr, boundary, &new_hw_ptr); - priv->pos_buf->hw_ptr_base = hw_base; - } - } - - priv->pos_buf->hw_ptr = new_hw_ptr; - // cache wall clk only when there's data update in shared buffer - if (priv->pos_buf->frame_counter != old_frame_counter) { - priv->pos_buf->wall_clk_lsw = wall_clk_lsw; - priv->pos_buf->wall_clk_msw = wall_clk_msw; - } - clock_gettime(CLOCK_MONOTONIC, &priv->pos_buf->tstamp); - } - - return ret; -} - -static void agm_get_shared_buffer_addr(struct pcm_plugin *plugin, - void **addr, snd_pcm_uframes_t *length) -{ - struct agm_pcm_priv *priv = plugin->priv; - enum direction dir; - - dir = (plugin->mode & PCM_IN) ? TX : RX; - *addr = priv->mmap_buffer_port[dir-1].mmap_buffer_addr; - *length = priv->mmap_buffer_port[dir-1].mmap_buffer_length; -} - -static int agm_pcm_plugin_reset(struct pcm_plugin *plugin) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint64_t handle; - int ret = 0; - void *mmap_addr = NULL; - snd_pcm_uframes_t mmap_length = 0; - - if (!(plugin->mode & PCM_NOIRQ)) - return -EOPNOTSUPP; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - if (!priv->buf_info) - return -EINVAL; - - agm_get_shared_buffer_addr(plugin,&mmap_addr,&mmap_length); - if (mmap_addr && mmap_length != 0) { - memset(mmap_addr,0,mmap_length); - } else { - AGM_LOGE("%s: failed to clear shared buffer\n", __func__); - ret = -EINVAL; - } - agm_pcm_plugin_update_hw_ptr(priv); - priv->pos_buf->hw_ptr = (snd_pcm_uframes_t)(priv->pos_buf->hw_ptr % priv->total_size_frames); - priv->pos_buf->hw_ptr_base = 0; - priv->pos_buf->wall_clk_msw = 0; - priv->pos_buf->wall_clk_lsw = 0; - priv->pos_buf->crossed_boundary_cnt = 0; - AGM_LOGD("%s: reset hw_ptr to %d \n", __func__, priv->pos_buf->hw_ptr); - return ret; -} - -static int agm_pcm_hw_params(struct pcm_plugin *plugin, - struct snd_pcm_hw_params *params) -{ - struct agm_pcm_priv *priv = plugin->priv; - struct agm_media_config *media_config; - struct agm_buffer_config *buffer_config; - struct agm_session_config *session_config = NULL; - uint64_t handle; - int ret = 0, sess_mode = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - media_config = priv->media_config; - buffer_config = priv->buffer_config; - session_config = priv->session_config; - - media_config->rate = param_get_int(params, SNDRV_PCM_HW_PARAM_RATE); - media_config->channels = param_get_int(params, SNDRV_PCM_HW_PARAM_CHANNELS); - media_config->format = param_get_mask_val(params, SNDRV_PCM_HW_PARAM_FORMAT); - - buffer_config->count = param_get_int(params, SNDRV_PCM_HW_PARAM_PERIODS); - buffer_config->max_metadata_size = 0; - priv->period_size = param_get_int(params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE); - /* period size in bytes */ - buffer_config->size = agm_pcm_frames_to_bytes(media_config, - priv->period_size); - priv->total_size_frames = buffer_config->count * - priv->period_size; /* in frames */ - - snd_card_def_get_int(plugin->node, "session_mode", &sess_mode); - session_config->dir = (plugin->mode & PCM_IN) ? TX : RX; - session_config->sess_mode = sess_mode; - AGM_LOGD("%s: mode: %d\n", __func__, plugin->mode); - if ((plugin->mode & PCM_MMAP) && (plugin->mode & PCM_NOIRQ)) - session_config->data_mode = AGM_DATA_PUSH_PULL; - - ret = agm_session_set_config(priv->handle, session_config, - priv->media_config, priv->buffer_config); - return ret; -} - -static int agm_pcm_sw_params(struct pcm_plugin *plugin, - struct snd_pcm_sw_params *sparams) -{ - struct agm_pcm_priv *priv = plugin->priv; - struct agm_session_config *session_config = NULL; - uint64_t handle = 0; - int ret = 0, sess_mode = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - session_config = priv->session_config; - - snd_card_def_get_int(plugin->node, "session_mode", &sess_mode); - - session_config->dir = (plugin->mode & PCM_IN) ? TX : RX; - session_config->sess_mode = sess_mode; - session_config->start_threshold = (uint32_t)sparams->start_threshold; - session_config->stop_threshold = (uint32_t)sparams->stop_threshold; - - ret = agm_session_set_config(priv->handle, session_config, - priv->media_config, priv->buffer_config); - return ret; -} - -static int agm_pcm_sync_ptr(struct pcm_plugin *plugin, - struct snd_pcm_sync_ptr *sync_ptr) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint64_t handle; - int ret = 0; - - if (!(plugin->mode & PCM_NOIRQ)) - return -EOPNOTSUPP; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - if (!priv->buf_info) - return -EINVAL; - - if (sync_ptr->flags & SNDRV_PCM_SYNC_PTR_HWSYNC) { - /** sync hw ptr */ - ret = agm_pcm_plugin_update_hw_ptr(priv); - if (ret < 0) - return ret; - } - - if (!(sync_ptr->flags & SNDRV_PCM_SYNC_PTR_APPL)) { - agm_pcm_plugin_apply_appl_ptr(priv, sync_ptr->c.control.appl_ptr); - } else { - sync_ptr->c.control.appl_ptr = agm_pcm_plugin_get_appl_ptr(priv); - } - - if (!(sync_ptr->flags & SNDRV_PCM_SYNC_PTR_AVAIL_MIN)) { - agm_pcm_plugin_apply_avail_min(priv, sync_ptr->c.control.avail_min); - } else { - sync_ptr->c.control.avail_min = agm_pcm_plugin_get_avail_min(priv); - } - - sync_ptr->s.status.hw_ptr = agm_pcm_plugin_get_hw_ptr(priv); - sync_ptr->s.status.tstamp = priv->pos_buf->tstamp; - - return ret; -} - -static int agm_pcm_writei_frames(struct pcm_plugin *plugin, struct snd_xferi *x) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint64_t handle; - void *buff; - size_t count; - int ret = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - buff = x->buf; - count = x->frames * (priv->media_config->channels * - agm_format_to_bits(priv->media_config->format) / 8); - - ret = agm_session_write(handle, buff, &count); - errno = ret; - - return ret; -} - -static int agm_pcm_readi_frames(struct pcm_plugin *plugin, struct snd_xferi *x) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint64_t handle; - void *buff; - size_t count; - int ret = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - buff = x->buf; - count = x->frames * (priv->media_config->channels * - agm_format_to_bits(priv->media_config->format) / 8); - ret = agm_session_read(handle, buff, &count); - errno = ret; - - return ret; -} - -static int agm_pcm_ttstamp(struct pcm_plugin *plugin, int *tstamp __unused) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint64_t handle; - int ret = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - /* TODO : Add AGM API call */ - return 0; -} - -static int agm_pcm_prepare(struct pcm_plugin *plugin) -{ - uint64_t handle; - struct agm_pcm_priv *priv = plugin->priv; - int ret = 0; - - if (priv->pos_buf) { - priv->pos_buf->wall_clk_msw = 0; - priv->pos_buf->wall_clk_lsw = 0; - } - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - ret = agm_session_prepare(handle); - errno = ret; - - return ret; -} - -static int agm_pcm_start(struct pcm_plugin *plugin) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - ret = agm_session_start(handle); - errno = ret; - - return ret; -} - -static int agm_pcm_drop(struct pcm_plugin *plugin) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint64_t handle; - int ret; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - ret = agm_session_stop(handle); - errno = ret; - - return ret; -} - -static int agm_pcm_close(struct pcm_plugin *plugin) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint64_t handle; - enum direction dir; - int ret = 0; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - ret = agm_session_close(handle); - errno = ret; - - snd_card_def_put_card(priv->card_node); - free(priv->buffer_config); - free(priv->media_config); - free(priv->session_config); - // unmap memory in case agm_pcm_munmap not called before close - if (priv->mmap_status) { - if (plugin->mode & PCM_NOIRQ) { - if (priv->pos_buf) { - munmap(priv->pos_buf->pos_buf_addr, - priv->buf_info->pos_buf_size); - free(priv->pos_buf); - priv->pos_buf = NULL; - } - } - dir = (plugin->mode & PCM_IN) ? TX : RX; - munmap(priv->mmap_buffer_port[dir-1].mmap_buffer_addr, - priv->mmap_buffer_port[dir-1].mmap_buffer_length); - priv->mmap_status = false; - } - if (priv->buf_info) { - if (priv->buf_info->data_buf_fd != -1) - close(priv->buf_info->data_buf_fd); - if (priv->buf_info->pos_buf_fd != -1) - close(priv->buf_info->pos_buf_fd); - free(priv->buf_info); - } - free(plugin->priv); - free(plugin); - - return ret; -} - -static snd_pcm_sframes_t agm_pcm_get_avail(struct pcm_plugin *plugin) -{ - struct agm_pcm_priv *priv = plugin->priv; - snd_pcm_sframes_t avail = 0; - enum direction dir; - - dir = (plugin->mode & PCM_IN) ? TX : RX; - - if (dir == RX) { - snd_pcm_uframes_t temp_value = 0; - // In first condition, if there is no overflow, temp_value holds the addition result; - // if there is overflow, __builtin_add_overflow returns true, then exit if clause. - // In second condition, if there is overflow, __builtin_sub_overflow returns true and - // we reset avail to 0. If there is no overflow, avail holds the final result and exit. - if (!__builtin_add_overflow(priv->pos_buf->hw_ptr, priv->total_size_frames, - &temp_value) && - __builtin_sub_overflow(temp_value, priv->pos_buf->appl_ptr, &avail)) { - avail = 0; - } - - if (avail < 0) - avail += priv->pos_buf->boundary; - else if ((snd_pcm_uframes_t)avail >= priv->pos_buf->boundary) - avail -= priv->pos_buf->boundary; - } else if (dir == TX) { - __builtin_sub_overflow(priv->pos_buf->hw_ptr, priv->pos_buf->appl_ptr, &avail); - if (avail < 0) - avail += priv->pos_buf->boundary; - } - - return avail; -} - -static int agm_pcm_poll(struct pcm_plugin *plugin, struct pollfd *pfd, - nfds_t nfds __attribute__ ((unused)), int timeout) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint32_t period_size = priv->period_size; - snd_pcm_sframes_t avail; - int ret = 0; - uint32_t period_to_msec = period_size / (priv->media_config->rate / 1000); - - avail = agm_pcm_get_avail(plugin); - - if (avail < period_size) { - if (timeout == 0) //wait for 1msec - timeout = 1; - usleep(timeout * 1000); - ret = agm_pcm_plugin_update_hw_ptr(priv); - if (ret == 0) - avail = agm_pcm_get_avail(plugin); - } - - if (avail >= period_size) { - if (plugin->mode & PCM_IN) { - pfd->revents = POLLIN | POLLOUT; - ret = POLLIN; - } else { - pfd->revents = POLLOUT; - ret = POLLOUT; - } - priv->mmap_buf_tout = 0; - } else { - ret = 0; /* TIMEOUT */ - priv->mmap_buf_tout += timeout; - if (priv->mmap_buf_tout > (period_to_msec * MMAP_TOUT_MULTI)) { - AGM_LOGE("timeout in waiting for mmap buffer"); - priv->mmap_buf_tout = 0; - errno = ETIMEDOUT; - return -ETIMEDOUT; - } - } - - return ret; -} - -static void* agm_pcm_mmap(struct pcm_plugin *plugin, void *addr __unused, size_t length, int prot __unused, - int flags __unused, off_t offset) -{ - struct agm_pcm_priv *priv = plugin->priv; - struct agm_buf_info *buf_info = NULL; - struct pcm_plugin_pos_buf_info *pos = NULL; - uint64_t handle; - int flag = DATA_BUF; - int ret = 0; - unsigned int boundary; - void *mmap_addr = NULL; - enum direction dir; - if (offset != 0) - return MAP_FAILED; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return MAP_FAILED; - - if (!priv->buf_info) { - buf_info = calloc(1, sizeof(struct agm_buf_info)); - if (!buf_info) - return MAP_FAILED; - - if (plugin->mode & PCM_NOIRQ) - flag |= POS_BUF; - - ret = agm_session_get_buf_info(priv->session_id, buf_info, flag); - if (ret) { - free(buf_info); - return MAP_FAILED; - } - priv->buf_info = buf_info; - } - if (plugin->mode & PCM_NOIRQ) { - if (!priv->pos_buf) { - pos = calloc(1, sizeof(struct pcm_plugin_pos_buf_info)); - if (!pos) - return MAP_FAILED; - - pos->pos_buf_addr = mmap(0, priv->buf_info->pos_buf_size, - PROT_READ | PROT_WRITE, MAP_SHARED, - priv->buf_info->pos_buf_fd, 0); - if (pos->pos_buf_addr == MAP_FAILED) - return MAP_FAILED; - - priv->pos_buf = pos; - - boundary = priv->total_size_frames; - while (boundary * 2 <= 0x7fffffffUL - priv->total_size_frames) - boundary *= 2; - - priv->pos_buf->boundary = boundary; - AGM_LOGE("%s: boundary: 0x%x, size_frames: 0x%lx\n", - __func__, boundary, priv->total_size_frames); - } - } - - if (length > priv->buf_info->data_buf_size) - return MAP_FAILED; - - dir = (plugin->mode & PCM_IN) ? TX : RX; - mmap_addr = mmap(0, length, - PROT_READ | PROT_WRITE, MAP_SHARED, - priv->buf_info->data_buf_fd, 0); - if (mmap_addr != MAP_FAILED) { - priv->mmap_buffer_port[dir-1].mmap_buffer_addr = mmap_addr; - priv->mmap_buffer_port[dir-1].mmap_buffer_length = length; - } - priv->mmap_status = true; - return mmap_addr; -} - -static int agm_pcm_munmap(struct pcm_plugin *plugin, void *addr, size_t length) -{ - struct agm_pcm_priv *priv = plugin->priv; - - priv->mmap_status = false; - if (plugin->mode & PCM_NOIRQ) { - if (priv->pos_buf) { - munmap(priv->pos_buf->pos_buf_addr, - priv->buf_info->pos_buf_size); - free(priv->pos_buf); - priv->pos_buf = NULL; - } - } - return munmap(addr, length); -} - -static int agm_pcm_ioctl(struct pcm_plugin *plugin, int cmd, ...) -{ - struct agm_pcm_priv *priv = plugin->priv; - uint64_t handle; - int ret = 0; - va_list ap; - void *arg; - - ret = agm_get_session_handle(priv, &handle); - if (ret) - return ret; - - va_start(ap, cmd); - arg = va_arg(ap, void *); - va_end(ap); - - switch (cmd) { - case SNDRV_PCM_IOCTL_RESET: - ret = agm_pcm_plugin_reset(plugin); - break; - default: - break; - } - - return ret; -} - -struct pcm_plugin_ops agm_pcm_ops = { - .close = agm_pcm_close, - .hw_params = agm_pcm_hw_params, - .sw_params = agm_pcm_sw_params, - .sync_ptr = agm_pcm_sync_ptr, - .writei_frames = agm_pcm_writei_frames, - .readi_frames = agm_pcm_readi_frames, - .ttstamp = agm_pcm_ttstamp, - .prepare = agm_pcm_prepare, - .start = agm_pcm_start, - .drop = agm_pcm_drop, - .mmap = agm_pcm_mmap, - .munmap = agm_pcm_munmap, - .poll = agm_pcm_poll, - .ioctl = agm_pcm_ioctl, -}; - -PCM_PLUGIN_OPEN_FN(agm_pcm_plugin) -{ - struct pcm_plugin *agm_pcm_plugin; - struct agm_pcm_priv *priv; - struct agm_session_config *session_config; - struct agm_media_config *media_config; - struct agm_buffer_config *buffer_config; - uint64_t handle; - enum agm_session_mode sess_mode = AGM_SESSION_DEFAULT; - int ret = 0, session_id = device; - void *card_node, *pcm_node; - - agm_pcm_plugin = calloc(1, sizeof(struct pcm_plugin)); - if (!agm_pcm_plugin) - return -ENOMEM; - - priv = calloc(1, sizeof(struct agm_pcm_priv)); - if (!priv) { - ret = -ENOMEM; - goto err_plugin_free; - } - - media_config = calloc(1, sizeof(struct agm_media_config)); - if (!media_config) { - ret = -ENOMEM; - goto err_priv_free; - } - - buffer_config = calloc(1, sizeof(struct agm_buffer_config)); - if (!buffer_config) { - ret = -ENOMEM; - goto err_media_free; - } - - session_config = calloc(1, sizeof(struct agm_session_config)); - if (!session_config) { - ret = -ENOMEM; - goto err_buf_free; - } - - card_node = snd_card_def_get_card(card); - if (!card_node) { - ret = -EINVAL; - goto err_session_free; - } - - pcm_node = snd_card_def_get_node(card_node, device, SND_NODE_TYPE_PCM); - if (!pcm_node) { - ret = -EINVAL; - goto err_card_put; - } - - agm_pcm_constrs.access = (PCM_FORMAT_BIT(SNDRV_PCM_ACCESS_RW_INTERLEAVED) | - PCM_FORMAT_BIT(SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)); - agm_pcm_constrs.format = (PCM_FORMAT_BIT(SNDRV_PCM_FORMAT_S16_LE) | - PCM_FORMAT_BIT(SNDRV_PCM_FORMAT_S24_LE) | - PCM_FORMAT_BIT(SNDRV_PCM_FORMAT_S24_3LE) | - PCM_FORMAT_BIT(SNDRV_PCM_FORMAT_S32_LE)); - - agm_pcm_plugin->card = card; - agm_pcm_plugin->ops = &agm_pcm_ops; - agm_pcm_plugin->node = pcm_node; - agm_pcm_plugin->mode = mode; - agm_pcm_plugin->constraints = &agm_pcm_constrs; - agm_pcm_plugin->priv = priv; - - priv->media_config = media_config; - priv->buffer_config = buffer_config; - priv->session_config = session_config; - priv->card_node = card_node; - priv->session_id = session_id; - priv->mmap_status = false; - snd_card_def_get_int(pcm_node, "session_mode", &sess_mode); - - ret = agm_session_open(session_id, sess_mode, &handle); - if (ret) { - errno = ret; - goto err_card_put; - } - priv->handle = handle; - *plugin = agm_pcm_plugin; - - return 0; - -err_card_put: - snd_card_def_put_card(card_node); -err_session_free: - free(session_config); -err_buf_free: - free(buffer_config); -err_media_free: - free(media_config); -err_priv_free: - free(priv); -err_plugin_free: - free(agm_pcm_plugin); - if (ret < 0) - return ret; - else - return -ret; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/AgmCap.cpp b/qcom/opensource/agm/plugins/tinyalsa/test/AgmCap.cpp deleted file mode 100755 index 97d82d7a..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/AgmCap.cpp +++ /dev/null @@ -1,443 +0,0 @@ -/* -** Copyright (c) 2019, 2021, The Linux Foundation. All rights reserved. -** -** Copyright 2011, The Android Open Source Project -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of The Android Open Source Project nor the names of -** its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -** ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE -** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -** DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022-2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "agmmixer.h" - -#define ID_RIFF 0x46464952 -#define ID_WAVE 0x45564157 -#define ID_FMT 0x20746d66 -#define ID_DATA 0x61746164 - -#define FORMAT_PCM 1 - -struct wav_header { - uint32_t riff_id; - uint32_t riff_sz; - uint32_t riff_fmt; - uint32_t fmt_id; - uint32_t fmt_sz; - uint16_t audio_format; - uint16_t num_channels; - uint32_t sample_rate; - uint32_t byte_rate; - uint16_t block_align; - uint16_t bits_per_sample; - uint32_t data_id; - uint32_t data_sz; -}; - -int capturing = 1; - -static unsigned int capture_sample(FILE *file, unsigned int card, unsigned int device, - unsigned int usb_device, unsigned int channels, unsigned int rate, - enum pcm_format format, unsigned int period_size, - unsigned int period_count, unsigned int cap_time, - struct device_config *dev_config, unsigned int stream_kv, - unsigned int device_kv, unsigned int instance_kv, - unsigned int devicepp_kv); - -static void sigint_handler(int sig) -{ - capturing = 0; -} - -static void usage(void) -{ - printf(" Usage: %s file.wav [-help print usage] [-D card] [-d device]\n" - " [-c channels] [-r rate] [-b bits] [-p period_size]\n" - " [-n n_periods] [-T capture time] [-i intf_name] [-dkv device_kv]\n" - " [-dppkv deviceppkv] : Assign 0 if no device pp in the graph\n" - " [-ikv instance_kv] : Assign 0 if no instance kv in the graph\n" - " [-skv stream_kv]\n" - " [-is_24_LE] : [0-1] Only to be used if user wants to record 32 bps clip\n" - " [-usb_d usb device]\n" - " 0: If bps is 32, and format should be S32_LE\n" - " 1: If bps is 24, and format should be S24_LE\n"); -} - -int main(int argc, char **argv) -{ - FILE *file; - struct wav_header header; - unsigned int card = 100; - unsigned int device = 101; - unsigned int usb_device = 1; - unsigned int channels = 2; - unsigned int rate = 44100; - unsigned int bits = 16; - unsigned int frames; - unsigned int period_size = 1024; - unsigned int period_count = 4; - unsigned int cap_time = 0; - char *intf_name = NULL; - unsigned int device_kv = 0; - struct device_config config; - enum pcm_format format; - int ret = 0; - unsigned int devicepp_kv = 0; - unsigned int stream_kv = 0; - unsigned int instance_kv = INSTANCE_1; - bool is_24_LE = false; - - if (argc < 2) { - usage(); - return 1; - } - - file = fopen(argv[1], "wb"); - if (!file) { - printf("Unable to create file '%s'\n", argv[1]); - return 1; - } - - /* parse command line arguments */ - argv += 2; - while (*argv) { - if (strcmp(*argv, "-d") == 0) { - argv++; - if (*argv) - device = atoi(*argv); - } else if (strcmp(*argv, "-c") == 0) { - argv++; - if (*argv) - channels = atoi(*argv); - } else if (strcmp(*argv, "-r") == 0) { - argv++; - if (*argv) - rate = atoi(*argv); - } else if (strcmp(*argv, "-b") == 0) { - argv++; - if (*argv) - bits = atoi(*argv); - } else if (strcmp(*argv, "-D") == 0) { - argv++; - if (*argv) - card = atoi(*argv); - } else if (strcmp(*argv, "-p") == 0) { - argv++; - if (*argv) - period_size = atoi(*argv); - } else if (strcmp(*argv, "-n") == 0) { - argv++; - if (*argv) - period_count = atoi(*argv); - } else if (strcmp(*argv, "-T") == 0) { - argv++; - if (*argv) - cap_time = atoi(*argv); - } else if (strcmp(*argv, "-i") == 0) { - argv++; - if (*argv) - intf_name = *argv; - } else if (strcmp(*argv, "-dkv") == 0) { - argv++; - if (*argv) - device_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-skv") == 0) { - argv++; - if (*argv) - stream_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-ikv") == 0) { - argv++; - if (*argv) - instance_kv = atoi(*argv); - } else if (strcmp(*argv, "-dppkv") == 0) { - argv++; - if (*argv) - devicepp_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-is_24_LE") == 0) { - argv++; - if (*argv) - is_24_LE = atoi(*argv); - } else if (strcmp(*argv, "-usb_d") == 0) { - argv++; - if (*argv) - usb_device = atoi(*argv); - }else if (strcmp(*argv, "-help") == 0) { - usage(); - } - if (*argv) - argv++; - } - - header.riff_id = ID_RIFF; - header.riff_sz = 0; - header.riff_fmt = ID_WAVE; - header.fmt_id = ID_FMT; - header.fmt_sz = 16; - header.audio_format = FORMAT_PCM; - header.num_channels = channels; - header.sample_rate = rate; - - switch (bits) { - case 32: - if (is_24_LE) - format = PCM_FORMAT_S24_LE; - else - format = PCM_FORMAT_S32_LE; - break; - case 24: - format = PCM_FORMAT_S24_3LE; - break; - case 16: - format = PCM_FORMAT_S16_LE; - break; - default: - printf("%u bits is not supported.\n", bits); - fclose(file); - return 1; - } - - if (intf_name == NULL) - return 1; - - ret = get_device_media_config(BACKEND_CONF_FILE, intf_name, &config); - if (ret) { - printf("Invalid input, entry not found for %s\n", intf_name); - fclose(file); - return ret; - } - if (config.format != PCM_FORMAT_INVALID) { - printf("Valid format from backend_conf %d\n", config.format); - config.bits = get_pcm_bit_width(config.format); - } - - header.bits_per_sample = pcm_format_to_bits(format); - header.byte_rate = (header.bits_per_sample / 8) * channels * rate; - header.block_align = channels * (header.bits_per_sample / 8); - header.data_id = ID_DATA; - - /* leave enough room for header */ - fseek(file, sizeof(struct wav_header), SEEK_SET); - - /* install signal handler and begin capturing */ - signal(SIGINT, sigint_handler); - signal(SIGHUP, sigint_handler); - signal(SIGTERM, sigint_handler); - frames = capture_sample(file, card, device, usb_device, header.num_channels, - header.sample_rate, format, - period_size, period_count, cap_time, &config, - stream_kv, device_kv, instance_kv, devicepp_kv); - printf("Captured %u frames\n", frames); - - /* write header now all information is known */ - header.data_sz = frames * header.block_align; - header.riff_sz = header.data_sz + sizeof(header) - 8; - fseek(file, 0, SEEK_SET); - fwrite(&header, sizeof(struct wav_header), 1, file); - - fclose(file); - - return 0; -} - -unsigned int capture_sample(FILE *file, unsigned int card, unsigned int device, - unsigned int usb_device, unsigned int channels, unsigned int rate, - enum pcm_format format, unsigned int period_size, - unsigned int period_count, unsigned int cap_time, - struct device_config *dev_config, unsigned int stream_kv, - unsigned int device_kv, unsigned int instance_kv, unsigned int devicepp_kv) -{ - struct pcm_config config; - struct pcm *pcm; - struct mixer *mixer; - char *buffer; - char *intf_name = dev_config->name; - unsigned int size; - unsigned int bytes_read = 0; - unsigned int frames = 0; - struct timespec end; - struct timespec now; - uint32_t miid = 0; - int ret = 0; - struct usbAudioConfig cfg; - uint8_t* payload = NULL; - size_t payloadSize = 0; - - stream_kv = stream_kv ? stream_kv : PCM_RECORD; - - memset(&config, 0, sizeof(config)); - config.channels = channels; - config.rate = rate; - config.period_size = period_size; - config.period_count = period_count; - config.format = format; - config.start_threshold = 0; - config.stop_threshold = 0; - config.silence_threshold = 0; - - if (NULL == intf_name) { - printf("No interface name mentioned, Exiting !!!\n"); - return 0; - } - - mixer = mixer_open(card); - if (!mixer) { - printf("Failed to open mixer\n"); - return 0; - } - - if(strcmp(intf_name, "USB_AUDIO-TX") == 0) { - dev_config->rate = rate; - dev_config->ch = channels; - } - - /* set device/audio_intf media config mixer control */ - if (set_agm_device_media_config(mixer, intf_name, dev_config)) { - printf("Failed to set device media config\n"); - goto err_close_mixer; - } - - /* set audio interface metadata mixer control */ - if (set_agm_audio_intf_metadata(mixer, intf_name, device_kv, CAPTURE, - dev_config->rate, dev_config->bits, stream_kv)) { - printf("Failed to set device metadata\n"); - goto err_close_mixer; - } - - /* set stream metadata mixer control */ - if (set_agm_capture_stream_metadata(mixer, device, stream_kv, CAPTURE, STREAM_PCM, - instance_kv)) { - printf("Failed to set pcm metadata\n"); - goto err_close_mixer; - } - - if (devicepp_kv != 0) { - if (set_agm_streamdevice_metadata(mixer, device, stream_kv, CAPTURE, STREAM_PCM, - intf_name, devicepp_kv)) { - printf("Failed to set pcm metadata\n"); - goto err_close_mixer; - } - } - - ret = agm_mixer_get_miid (mixer, device, intf_name, STREAM_PCM, TAG_STREAM_MFC, &miid); - if (ret) { - printf("MFC not present for this graph\n"); - } else { - if (configure_mfc(mixer, device, intf_name, TAG_STREAM_MFC, - STREAM_PCM, rate, channels, get_pcm_bit_width(format), miid)) { - printf("Failed to configure stream mfc\n"); - goto err_close_mixer; - } - } - - if (strcmp(intf_name, "USB_AUDIO-TX") == 0) { - ret = agm_mixer_get_miid (mixer, device, intf_name, STREAM_PCM, DEVICE_HW_ENDPOINT_TX, &miid); - if (ret == 0) { - cfg.usb_token = (usb_device << 16)|0x1; - cfg.svc_interval = 0; - get_agm_usb_audio_config_payload(&payload, &payloadSize, miid, &cfg); - - if (payloadSize) { - ret = set_agm_device_custom_payload(mixer, intf_name, payload, payloadSize); - } else { - ret = -1; - printf("set_agm_device_custom_payload failed\n"); - goto err_close_mixer; - } - } else { - printf("Failed to get miid for USB_AUDIO-TX\n"); - goto err_close_mixer; - } - - } - - /* connect pcm stream to audio intf */ - if (connect_agm_audio_intf_to_stream(mixer, device, intf_name, STREAM_PCM, true)) { - printf("Failed to connect pcm to audio interface\n"); - goto err_close_mixer; - } - - pcm = pcm_open(card, device, PCM_IN, &config); - if (!pcm || !pcm_is_ready(pcm)) { - printf("Unable to open PCM device (%s)\n", - pcm_get_error(pcm)); - goto err_close_mixer; - } - - size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm)); - buffer = (char *)malloc(size); - if (!buffer) { - printf("Unable to allocate %u bytes\n", size); - goto err_close_pcm; - } - - printf("Capturing sample: %u ch, %u hz, %u bit\n", channels, rate, - pcm_format_to_bits(format)); - - if (pcm_start(pcm) < 0) { - printf("start error\n"); - goto err_close_pcm; - } - - clock_gettime(CLOCK_MONOTONIC, &now); - end.tv_sec = now.tv_sec + cap_time; - end.tv_nsec = now.tv_nsec; - - while (capturing && !pcm_read(pcm, buffer, size)) { - if (fwrite(buffer, 1, size, file) != size) { - printf("Error capturing sample\n"); - break; - } - bytes_read += size; - if (cap_time) { - clock_gettime(CLOCK_MONOTONIC, &now); - if (now.tv_sec > end.tv_sec || - (now.tv_sec == end.tv_sec && now.tv_nsec >= end.tv_nsec)) - break; - } - } - - frames = pcm_bytes_to_frames(pcm, bytes_read); - free(buffer); - - pcm_stop(pcm); -err_close_pcm: - connect_agm_audio_intf_to_stream(mixer, device, intf_name, STREAM_PCM, false); - pcm_close(pcm); -err_close_mixer: - if (payload) { - free(payload); - } - mixer_close(mixer); - return frames; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/AgmMixerWrapper.h b/qcom/opensource/agm/plugins/tinyalsa/test/AgmMixerWrapper.h deleted file mode 100755 index 44c9a9e4..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/AgmMixerWrapper.h +++ /dev/null @@ -1,234 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __AGMMIXERWRAPPER_H__ -#define __AGMMIXERWRAPPER_H__ - -#include -#include "agmmixer.h" - -class AgmMixerWrapper { -protected: - struct mixer *mixer; - struct device_config deviceConfig; - struct group_config groupConfig; - struct usbAudioConfig usbAudioConfig; - -public: - virtual ~AgmMixerWrapper() = default; - virtual int mixerOpen(unsigned int card) = 0; - virtual int mixerClose(void) = 0; - virtual struct device_config getDeviceMediaConfig(char* filename, char *intf_name) = 0; - virtual int setDeviceMediaConfig(char *intf_name, struct device_config *config) = 0; - virtual int setAudioInterfaceMetadata(char *intf_name, unsigned int dkv, - enum usecase_type usecase, int rate, int bitwidth, uint32_t stream_kv) = 0; - virtual int setStreamMetadata(int device, uint32_t stream_kv, unsigned int instance_kv) = 0; - virtual int setStreamDeviceMetadata(int device, uint32_t stream_kv, char *intf_name, - unsigned int devicepp_kv) = 0; - virtual int connectAudioInterfaceToStream(unsigned int device, char *intf_name) = 0; - virtual int configureMFC(int device, char *intf_name, struct device_config) = 0; - virtual struct group_config getGroupConfig(char *intf_name) = 0; - virtual int setGroupConfig(unsigned int device, char *intf_name, unsigned int device_kv, struct group_config config, unsigned int channels) = 0; - virtual int setDeviceCustomPayload(char *intf_name, int device, unsigned int usb_device) = 0; - virtual int disconnectAudioInterfaceToStream(unsigned int device, char *intf_name) = 0; -}; - -class AgmMixerWrapperImpl: public AgmMixerWrapper { -public: - int mixerOpen(unsigned int card) override { - int ret = 0; - mixer = mixer_open(card); - if (!mixer) { - std::cout << "Failed to open mixer" << std::endl; - ret = -1; - } - return ret; - } - - int mixerClose(void) override { - mixer_close(mixer); - return 0; - } - - struct device_config getDeviceMediaConfig(char* filename, char *intf_name) override { - if (get_device_media_config(BACKEND_CONF_FILE, intf_name, &deviceConfig)) { - std::cout << "Invalid input, entry not found for :" << intf_name << std::endl; - } - - if (deviceConfig.format != PCM_FORMAT_INVALID) { - deviceConfig.bits = get_pcm_bit_width(deviceConfig.format); - } - return deviceConfig; - } - - int setDeviceMediaConfig(char *intf_name, struct device_config *config) override { - int ret = 0; - ret = set_agm_device_media_config(mixer, intf_name, config); - if (ret) { - std::cout << "Failed to set agm device media config " << ret << std::endl; - } - return ret; - } - - int setAudioInterfaceMetadata(char *intf_name, unsigned int dkv, - enum usecase_type usecase, int rate, int bitwidth, uint32_t stream_kv) override { - int ret = 0; - ret = set_agm_audio_intf_metadata(mixer, intf_name, dkv, usecase, - rate, bitwidth, stream_kv); - if (ret) { - std::cout << "Failed to set device metadata " << ret << std::endl; - } - return ret; - } - - int setStreamMetadata(int device, uint32_t stream_kv, unsigned int instance_kv) override { - return set_agm_stream_metadata(mixer, device, stream_kv, PLAYBACK, STREAM_PCM, instance_kv); - } - - int setStreamDeviceMetadata(int device, uint32_t stream_kv, char *intf_name, - unsigned int devicepp_kv) override { - int ret = 0; - - if (devicepp_kv == 0) { - std::cout << "There is no devicepp keyvector" << std::endl; - return -1; - } - - ret = set_agm_streamdevice_metadata(mixer, device, stream_kv, PLAYBACK, STREAM_PCM, intf_name, - devicepp_kv); - if (ret) { - std::cout << "Failed to set streamdevice metadata " << ret << std::endl; - } - - return ret; - } - - int setDeviceCustomPayload(char *intf_name, int device, unsigned int usb_device) override { - int ret = 0; - unsigned int miid = 0; - struct usbAudioConfig cfg; - uint8_t* payload; - size_t payloadSize; - ret = agm_mixer_get_miid (mixer, device, intf_name, STREAM_PCM, DEVICE_HW_ENDPOINT_RX, &miid); - if (ret) { - std::cout << "Failed to get miid for USB_AUDIO-TX " << ret << std::endl; - return ret; - } - - cfg.usb_token = usb_device << 16; - cfg.svc_interval = 0; - get_agm_usb_audio_config_payload(&payload, &payloadSize, miid, &cfg); - - if (payloadSize) { - ret = set_agm_device_custom_payload(mixer, intf_name, payload, payloadSize); - } else { - ret = -1; - std::cout << "set_agm_device_custom_payload failed" << std::endl; - } - return ret; - } - - int connectAudioInterfaceToStream(unsigned int device, char *intf_name) override { - int ret = 0; - ret = connect_agm_audio_intf_to_stream(mixer, device, intf_name, STREAM_PCM, true); - if (ret) { - std::cout << "Failed to connect pcm to audio interface " << ret << std::endl; - } - return ret; - } - - virtual int configureMFC(int device, char *intf_name, struct device_config config) override { - int ret = 0; - unsigned int miid = 0; - ret = agm_mixer_get_miid(mixer, device, intf_name, STREAM_PCM, PER_STREAM_PER_DEVICE_MFC, &miid); - if (ret) { - std::cout << "MFC not present for this graph " << ret << std::endl; - return ret; - } - - ret = configure_mfc(mixer, device, intf_name, PER_STREAM_PER_DEVICE_MFC, - STREAM_PCM, config.rate, config.ch, - config.bits, miid); - if (ret) { - std::cout << "Failed to configure pspd mfc " << ret << std::endl; - return ret; - } - - return ret; - } - - struct group_config getGroupConfig(char *intf_name) override { - if (isVirtualInterface(intf_name)) { - if (get_group_device_info(BACKEND_CONF_FILE, intf_name, &groupConfig)) { - std::cout << "Failed to get grp device config" << std::endl; - } - } - return groupConfig; - } - - int setGroupConfig(unsigned int device, char *intf_name, unsigned int device_kv, struct group_config config, unsigned int channels) override { - int ret = 0; - if (isVirtualInterface(intf_name)) { - ret = set_agm_group_device_config(mixer, intf_name, &config); - if (ret) { - std::cout << "Failed to set grp device config " << ret << std::endl; - return ret; - } - - if ((device_kv == SPEAKER) || (device_kv == HANDSET)) { - ret = set_agm_group_mux_config(mixer, device, &config, intf_name, channels); - if (ret) { - std::cout << "Failed to set grp device config " << ret << std::endl; - return ret; - } - } - } - return ret; - } - - int disconnectAudioInterfaceToStream(unsigned int device, char *intf_name) override { - int ret = 0; - ret = connect_agm_audio_intf_to_stream(mixer, device, intf_name, STREAM_PCM, false); - if (ret) { - std::cout << "Failed to disconnect pcm to audio interface " << ret << std::endl; - } - return ret; - } - -private: - char* isVirtualInterface(char *intfName) { - return strstr(intfName, "VIRT-"); - } -}; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/AgmPcmWrapper.h b/qcom/opensource/agm/plugins/tinyalsa/test/AgmPcmWrapper.h deleted file mode 100755 index ca8605a0..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/AgmPcmWrapper.h +++ /dev/null @@ -1,98 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __AGMPCMWRAPPER_H__ -#define __AGMPCMWRAPPER_H__ - -#include -#include "agmmixer.h" - -class AgmPcmWrapper { -protected: - struct pcm *pcm; - -public: - virtual ~AgmPcmWrapper() = default; - virtual int pcmOpen(unsigned int card, unsigned int device, struct pcm_config *config) = 0; - virtual int pcmFramesToBytes(void) = 0; - virtual int pcmStart(void) = 0; - virtual int pcmWrite(char *buffer, int num_read) = 0; - virtual int pcmStop(void) = 0; - virtual int pcmClose(void) = 0; -}; - -class AgmPcmWrapperImpl: public AgmPcmWrapper { -public: - int pcmOpen(unsigned int card, unsigned int device, struct pcm_config *config) override { - int ret = 0; - pcm = pcm_open(card, device, PCM_OUT, config); - if (!pcm || !pcm_is_ready(pcm)) { - std::cout << "Unable to open PCM device " << device << " (" << pcm_get_error(pcm) << ")" << std::endl; - ret = -1; - } - return ret; - } - - int pcmFramesToBytes(void) override { - return pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm)); - } - - int pcmStart(void) override { - int ret = 0; - ret = pcm_start(pcm); - if (ret < 0) { - std::cout << "start error" << std::endl; - pcm_close(pcm); - } - return ret; - } - - int pcmWrite(char *buffer, int num_read) override { - int ret = 0; - ret = pcm_write(pcm, buffer, num_read); - if (ret < 0) { - std::cout << "Error playing sample" << std::endl; - } - return ret; - } - - int pcmStop(void) override { - return pcm_stop(pcm); - } - - int pcmClose(void) override { - return pcm_close(pcm); - } -}; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/AgmPlay.cpp b/qcom/opensource/agm/plugins/tinyalsa/test/AgmPlay.cpp deleted file mode 100755 index 02d227b2..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/AgmPlay.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* -** Copyright (c) 2019, 2021, The Linux Foundation. All rights reserved. -** -** Copyright 2011, The Android Open Source Project -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of The Android Open Source Project nor the names of -** its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -** ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE -** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -** DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022-2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include "AgmPlayer.h" -#include "PlaybackCommandParser.h" - -int main(int argc, char **argv) -{ - std::ifstream file; - HeaderParser* riffWaveParser = new RiffWaveParser(); - HeaderParser* chunkParser = new ChunkParser(); - PlaybackCommandParser playbackCommandParser; - - if (argc < 3) { - playbackCommandParser.usage(); - exit(1); - } - - file.open(argv[1], std::ios::binary); - if (!file) { - std::cout << "Unable to open file" << std::endl; - exit(1); - } - - riffWaveParser->parseHeader(file); - if (!riffWaveParser->isValid()) { - std::cout << "It is not a riff/wave file" << std::endl; - file.close(); - exit(1); - } - - chunkParser->parseHeader(file); - playbackCommandParser.parseCommandLine(argv); - - if (playbackCommandParser.getPlaybackCommand().getInterfaceName() == nullptr) { - std::cout << "interface name is NULL" << std::endl; - file.close(); - exit(1); - } - - AgmPlayer agmPlayer; - agmPlayer.playSample(file, chunkParser->getFormat(), playbackCommandParser.getPlaybackCommand()); - - file.close(); - return 0; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/AgmPlayer.cpp b/qcom/opensource/agm/plugins/tinyalsa/test/AgmPlayer.cpp deleted file mode 100755 index 67c2fd37..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/AgmPlayer.cpp +++ /dev/null @@ -1,314 +0,0 @@ -/* -** Copyright (c) 2019, 2021, The Linux Foundation. All rights reserved. -** -** Copyright 2011, The Android Open Source Project -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of The Android Open Source Project nor the names of -** its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -** ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE -** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -** DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022-2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include "AgmPlayer.h" -#include "SignalHandler.h" - -int AgmPlayer::playSample(std::ifstream& file, ChunkFormat format, PlaybackCommand playbackCommand) -{ - int ret = 0; - - getPlaybackInfo(&playbackCommand); - setPlaybackInfo(format); - - ret = openMixer(card); - if (ret < 0) { - return ret; - } - - allocConfigMemory(); - ret = setDeviceConfig(); - if (ret < 0) { - goto err; - } - - ret = setStreamConfig(); - if (ret < 0) { - goto err; - } - - ret = setDevicePostProcessingConfig(); - if (ret < 0) { - goto err; - } - - ret = startPlayback(file); - if (ret < 0) { - goto err; - } - stopPlayback(); - -err: - deallocConfigMemory(); - closeMixer(); - return ret; -} - -void AgmPlayer::getPlaybackInfo(PlaybackCommand* playbackCommand) -{ - card = playbackCommand->getCard(); - device = playbackCommand->getDevice(); - device_kv = playbackCommand->getDeviceKeyVector(); - stream_kv = playbackCommand->getStreamKeyVector(); - instance_kv = playbackCommand->getInstanceKeyVector(); - devicepp_kv = playbackCommand->getDeviceppKeyVector(); - haptics = playbackCommand->getHaptics(); - intf_name = playbackCommand->getInterfaceName(); - intf_num = playbackCommand->getInterfaceNumber(); - is_24_LE = playbackCommand->is24LE(); - usb_device = playbackCommand->getUsbDevice(); - channels = playbackCommand->getChannel(); - rate = playbackCommand->getSampleRate(); - bits = playbackCommand->getBitWidth(); -} - -void AgmPlayer::setPlaybackInfo(ChunkFormat format) -{ - config.channels = format.num_channels; - config.rate = format.sample_rate; - - switch (format.bits_per_sample) { - case 32: - config.format = is_24_LE? PCM_FORMAT_S24_LE : PCM_FORMAT_S32_LE; - break; - case 24: - config.format = PCM_FORMAT_S24_3LE; - break; - case 16: - config.format = PCM_FORMAT_S16_LE; - break; - default: - std::cout << "Unsupported bit width" << std::endl; - break; - } - - if (haptics) { - playback_path = HAPTICS; - stream_kv = stream_kv ? stream_kv : HAPTICS_PLAYBACK; - } else { - playback_path = PLAYBACK; - stream_kv = stream_kv ? stream_kv : PCM_LL_PLAYBACK; - } -} - -int AgmPlayer::openMixer(unsigned int card) -{ - return agmMixer->mixerOpen(card); -} - -int AgmPlayer::closeMixer(void) -{ - return agmMixer->mixerClose(); -} - -void AgmPlayer::allocConfigMemory(void) -{ - dev_config = new device_config[intf_num]; - if (!dev_config) { - std::cout << "Failed to allocate memory for dev config" << std::endl; - return; - } - - grp_config = new group_config[intf_num]; - if (!grp_config) { - std::cout << "Failed to allocate memory for group config" << std::endl; - return; - } -} - -void AgmPlayer::deallocConfigMemory(void) -{ - if (dev_config) { - delete[] dev_config; - dev_config = nullptr; - } - - if (grp_config) { - delete[] grp_config; - grp_config = nullptr; - } -} - -bool AgmPlayer::isUSBInterface(int index) -{ - if(intf_name[index] != NULL && strcmp(intf_name[index], "USB_AUDIO-RX") == 0) { - return true; - } - return false; -} - -void AgmPlayer::getDeviceMediaConfig(int index) -{ - if(isUSBInterface(index)) { - dev_config[index].rate = rate; - dev_config[index].ch = channels; - dev_config[index].bits = bits; - } - else { - dev_config[index] = agmMixer->getDeviceMediaConfig(BACKEND_CONF_FILE, intf_name[index]); - } -} - -int AgmPlayer::setDeviceConfig(void) -{ - int ret = 0; - - for (int index = 0; index < intf_num; index++) { - getDeviceMediaConfig(index); - - ret = agmMixer->setDeviceMediaConfig(intf_name[index], &dev_config[index]); - if (ret) - return ret; - - ret = agmMixer->setAudioInterfaceMetadata(intf_name[index], device_kv[index], playback_path, - dev_config[index].rate, dev_config[index].bits, stream_kv); - if (ret) - return ret; - } - - return ret; -} - -int AgmPlayer::setStreamConfig(void) -{ - return agmMixer->setStreamMetadata(device, stream_kv, instance_kv); -} - -int AgmPlayer::setDevicePostProcessingConfig(void) -{ - int ret = 0; - - for (int index = 0; index < intf_num; index++) { - ret = agmMixer->setStreamDeviceMetadata(device, stream_kv, intf_name[index], devicepp_kv[index]); - if (ret) - return ret; - - if (isUSBInterface(index)) { - ret = agmMixer->setDeviceCustomPayload(intf_name[index], device, usb_device); - if (ret) - return ret; - } - - ret = agmMixer->connectAudioInterfaceToStream(device, intf_name[index]); - if (ret) - return ret; - - ret = agmMixer->configureMFC(device, intf_name[index], dev_config[index]); - if (ret) - return ret; - - grp_config[index] = agmMixer->getGroupConfig(intf_name[index]); - ret = agmMixer->setGroupConfig(device, intf_name[index], device_kv[index], grp_config[index], dev_config[index].ch); - if (ret) - return ret; - } - - return ret; -} - -int AgmPlayer::startPlayback(std::ifstream& file) -{ - int size = 0; - int num_read = 0; - int ret = 0; - char *buffer; - SignalHandler stream; - - ret = agmPcm->pcmOpen(card, device, &config); - if (ret < 0) - return ret; - - size = agmPcm->pcmFramesToBytes(); - buffer = new char[size]; - if (!buffer) { - std::cout << "Unable to allocate " << size << " bytes" << std::endl; - return -ENOMEM; - } - - ret = agmPcm->pcmStart(); - if (ret < 0) - goto err; - - stream.open(); - do { - file.read(buffer, size); - num_read = file.gcount(); - if (num_read > 0) { - ret = agmPcm->pcmWrite(buffer, num_read); - if (ret < 0) - break; - } - } while (!stream.isClosed() && num_read > 0); - -err: - if (buffer) { - delete[] buffer; - buffer = nullptr; - } - return ret; -} - -void AgmPlayer::stopPlayback(void) -{ - agmPcm->pcmStop(); - for (int index = 0; index < intf_num; index++) { - agmMixer->disconnectAudioInterfaceToStream(device, intf_name[index]); - } - agmPcm->pcmClose(); -} - -AgmPlayer::AgmPlayer() -{ - agmMixer = new AgmMixerWrapperImpl(); - agmPcm = new AgmPcmWrapperImpl(); - - memset(&config, 0, sizeof(config)); - config.period_size = 1024; - config.period_count = 4; - config.format = PCM_FORMAT_S16_LE; - config.start_threshold = 0; - config.stop_threshold = 0; - config.silence_threshold = 0; -}; - -AgmPlayer::AgmPlayer(AgmMixerWrapper *agmMixer, AgmPcmWrapper *agmPcm) - : agmMixer(agmMixer), agmPcm(agmPcm) -{ - memset(&config, 0, sizeof(config)); - config.period_size = 1024; - config.period_count = 4; - config.format = PCM_FORMAT_S16_LE; - config.start_threshold = 0; - config.stop_threshold = 0; - config.silence_threshold = 0; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/AgmPlayer.h b/qcom/opensource/agm/plugins/tinyalsa/test/AgmPlayer.h deleted file mode 100755 index 700181b3..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/AgmPlayer.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __AGMPLAY_H__ -#define __AGMPLAY_H__ - -#include -#include "ChunkParser.h" -#include "RiffWaveParser.h" -#include "PlaybackCommand.h" -#include "AgmMixerWrapper.h" -#include "AgmPcmWrapper.h" - - -class AgmPlayer { -public: - AgmPlayer(); - AgmPlayer(AgmMixerWrapper *agmMixer, AgmPcmWrapper *agmPcm); - ~AgmPlayer() {}; - int playSample(std::ifstream& file, ChunkFormat fmt, PlaybackCommand playbackCommand); - -private: - unsigned int card; - unsigned int device; - unsigned int *device_kv; - unsigned int stream_kv; - unsigned int instance_kv; - unsigned int *devicepp_kv; - unsigned int usb_device; - unsigned int channels; - unsigned int rate; - unsigned int bits; - bool haptics; - char **intf_name; - int intf_num; - bool is_24_LE; - struct pcm_config config; - struct group_config *grp_config; - struct device_config *dev_config; - enum usecase_type playback_path; - AgmMixerWrapper *agmMixer; - AgmPcmWrapper *agmPcm; - - int openMixer(unsigned int card); - int closeMixer(void); - void getPlaybackInfo(PlaybackCommand* playbackCommand); - void setPlaybackInfo(ChunkFormat format); - void allocConfigMemory(void); - void deallocConfigMemory(void); - bool isUSBInterface(int index); - void getDeviceMediaConfig(int index); - int setDeviceConfig(void); - int setStreamConfig(void); - int setDevicePostProcessingConfig(void); - int startPlayback(std::ifstream& file); - void stopPlayback(void); -}; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/Android.mk b/qcom/opensource/agm/plugins/tinyalsa/test/Android.mk deleted file mode 100755 index 6a82df65..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/Android.mk +++ /dev/null @@ -1,217 +0,0 @@ -LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) - -LOCAL_MODULE := libagmmixer -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -Wno-unused-parameter -Wno-unused-result -LOCAL_SRC_FILES := agmmixer.c - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libacdb_headers - -#if android version is R, refer to qtitinyxx otherwise use upstream ones -#This assumes we would be using AR code only for Android R and subsequent versions. -ifneq ($(filter 11 R, $(PLATFORM_VERSION)),) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa -else -LOCAL_SHARED_LIBRARIES += libtinyalsa -endif - - -LOCAL_SHARED_LIBRARIES += \ - libexpat - -include $(BUILD_SHARED_LIBRARY) - -# Build agmplay -include $(CLEAR_VARS) - -LOCAL_MODULE := agmplay -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -Wno-unused-parameter -Wno-unused-result -LOCAL_CFLAGS += -DBACKEND_CONF_FILE=\"/vendor/etc/backend_conf.xml\" -LOCAL_CFLAGS += -fexceptions -LOCAL_SRC_FILES := AgmPlay.cpp \ -AgmPlayer.cpp \ -RiffWaveParser.cpp \ -ChunkParser.cpp \ -PlaybackCommand.cpp \ -PlaybackCommandParser.cpp - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libacdb_headers - -#if android version is R, refer to qtitinyxx otherwise use upstream ones -#This assumes we would be using AR code only for Android R and subsequent versions. -ifneq ($(filter 11 R, $(PLATFORM_VERSION)),) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa -else -LOCAL_SHARED_LIBRARIES += libtinyalsa -endif - -LOCAL_SHARED_LIBRARIES += \ - libagmmixer - -include $(BUILD_EXECUTABLE) -include $(CLEAR_VARS) - -LOCAL_MODULE := agmcap -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -Wno-unused-parameter -Wno-unused-result -LOCAL_CFLAGS += -DBACKEND_CONF_FILE=\"/vendor/etc/backend_conf.xml\" -LOCAL_SRC_FILES := AgmCap.cpp - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libacdb_headers - -#if android version is R, refer to qtitinyxx otherwise use upstream ones -#This assumes we would be using AR code only for Android R and subsequent versions. -ifneq ($(filter 11 R, $(PLATFORM_VERSION)),) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa -else -LOCAL_SHARED_LIBRARIES += libtinyalsa -endif - -LOCAL_SHARED_LIBRARIES += \ - libagmmixer - -include $(BUILD_EXECUTABLE) - -include $(CLEAR_VARS) - -LOCAL_MODULE := agmhostless -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -Wno-unused-parameter -Wno-unused-result -LOCAL_CFLAGS += -DBACKEND_CONF_FILE=\"/vendor/etc/backend_conf.xml\" -LOCAL_SRC_FILES := agmhostless.c - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libacdb_headers - -#if android version is R, refer to qtitinyxx otherwise use upstream ones -#This assumes we would be using AR code only for Android R and subsequent versions. -ifneq ($(filter 11 R, $(PLATFORM_VERSION)),) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa -else -LOCAL_SHARED_LIBRARIES += libtinyalsa -endif - -LOCAL_SHARED_LIBRARIES += \ - libagmmixer - -include $(BUILD_EXECUTABLE) - -include $(CLEAR_VARS) - -LOCAL_MODULE := agmcompressplay -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -Wno-unused-parameter -Wno-unused-result -LOCAL_CFLAGS += -DBACKEND_CONF_FILE=\"/vendor/etc/backend_conf.xml\" - -LOCAL_C_INCLUDES += $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr/include -LOCAL_ADDITIONAL_DEPENDENCIES += $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr - -LOCAL_SRC_FILES := agmcompressplay.c - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libacdb_headers - -# Use flag based selection to use QTI vs open source tinycompress project - -ifeq ($(TARGET_USES_QTI_TINYCOMPRESS),true) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa\ - libqti-tinycompress -else -LOCAL_C_INCLUDES += $(TOP)/external/tinycompress/include -LOCAL_SHARED_LIBRARIES += libtinyalsa\ - libtinycompress -endif - -LOCAL_SHARED_LIBRARIES += \ - libagmmixer - -include $(BUILD_EXECUTABLE) - -include $(CLEAR_VARS) - -LOCAL_MODULE := agmcompresscap -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -Wno-unused-parameter -Wno-unused-result -LOCAL_CFLAGS += -DBACKEND_CONF_FILE=\"/vendor/etc/backend_conf.xml\" - -LOCAL_C_INCLUDES += $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr/include -LOCAL_ADDITIONAL_DEPENDENCIES += $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr - -LOCAL_SRC_FILES := agmcompresscap.c - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libacdb_headers - -# Use flag based selection to use QTI vs open source tinycompress project - -ifeq ($(TARGET_USES_QTI_TINYCOMPRESS),true) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa\ - libqti-tinycompress -else -LOCAL_C_INCLUDES += $(TOP)/external/tinycompress/include -LOCAL_SHARED_LIBRARIES += libtinyalsa\ - libtinycompress -endif - -LOCAL_SHARED_LIBRARIES += \ - libagmmixer - -include $(BUILD_EXECUTABLE) - -include $(CLEAR_VARS) - -LOCAL_MODULE := agmvoiceui -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -Wno-unused-parameter -Wno-unused-result -LOCAL_CFLAGS += -DBACKEND_CONF_FILE=\"/vendor/etc/backend_conf.xml\" -LOCAL_SRC_FILES := agm_voiceui.c - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libacdb_headers - -#if android version is R, refer to qtitinyxx otherwise use upstream ones -#This assumes we would be using AR code only for Android R and subsequent versions. -ifneq ($(filter 11 R, $(PLATFORM_VERSION)),) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa -else -LOCAL_SHARED_LIBRARIES += libtinyalsa -endif - -LOCAL_SHARED_LIBRARIES += \ - libagmmixer - -include $(BUILD_EXECUTABLE) - diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/ChunkParser.cpp b/qcom/opensource/agm/plugins/tinyalsa/test/ChunkParser.cpp deleted file mode 100755 index 47243dc0..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/ChunkParser.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include "ChunkParser.h" - -void ChunkParser::readHeader(std::ifstream& file) -{ - int more_chunks = 1; - - do { - file.read((char*)&chunkId, sizeof(chunkId)); - file.read((char*)&chunkSize, sizeof(chunkSize)); - - switch (chunkId) { - case ID_FMT: - parseChunkFormat(file); - break; - case ID_DATA: - more_chunks = 0; - break; - default: - file.seekg(getChunkSize(), std::ios::cur); - } - } while (more_chunks); -} - -ChunkFormat ChunkParser::getChuckAudioFormat(void) -{ - return chunkFormat; -} - -void ChunkParser::parseChunkFormat(std::ifstream& file) -{ - file.read((char*)&chunkFormat, sizeof(chunkFormat)); - if (getChunkSize() > sizeof(chunkFormat)) - file.seekg(getChunkSize() - sizeof(chunkFormat), std::ios::cur); -} - -uint32_t ChunkParser::getChunkSize(void) -{ - return chunkSize; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/ChunkParser.h b/qcom/opensource/agm/plugins/tinyalsa/test/ChunkParser.h deleted file mode 100755 index 464c2bbf..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/ChunkParser.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __CHUNKPARSER_H__ -#define __CHUNKPARSER_H__ - -#include "HeaderParser.h" - -const uint32_t ID_FMT = 0x20746d66; -const uint32_t ID_DATA = 0x61746164; - -class ChunkParser : public HeaderParser { -private: - uint32_t chunkId; - uint32_t chunkSize; - uint32_t getChunkSize(void); - ChunkFormat chunkFormat; - void parseChunkFormat(std::ifstream& file); - -public: - ~ChunkParser() {} - -protected: - void readHeader(std::ifstream& file) override; - ChunkFormat getChuckAudioFormat(void) override; -}; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/HeaderParser.h b/qcom/opensource/agm/plugins/tinyalsa/test/HeaderParser.h deleted file mode 100755 index 488a45f0..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/HeaderParser.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __HEADERPARSER_H__ -#define __HEADERPARSER_H__ - -#include - -class ChunkFormat { -public: - uint16_t audio_format; - uint16_t num_channels; - uint32_t sample_rate; - uint32_t byte_rate; - uint16_t block_align; - uint16_t bits_per_sample; -}; - -class HeaderParser -{ -public: - void parseHeader(std::ifstream& file) { - readHeader(file); - } - - bool isValid(void) { - return isValidFile(); - } - - ChunkFormat getFormat(void) { - return getChuckAudioFormat(); - } - - virtual ~HeaderParser() {} - -protected: - ChunkFormat format; - - virtual void readHeader(std::ifstream& file) = 0; - virtual bool isValidFile(void) { return true; }; - virtual ChunkFormat getChuckAudioFormat(void) { return format; }; -}; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/Makefile.am b/qcom/opensource/agm/plugins/tinyalsa/test/Makefile.am deleted file mode 100755 index 0b220571..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/Makefile.am +++ /dev/null @@ -1,60 +0,0 @@ -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = agmtest.pc -EXTRA_DIST = $(pkgconfig_DATA) - -AM_CFLAGS := -Wno-unused-parameter -Wno-unused-result -if !BUILDSYSTEM_OPENWRT -AM_CFLAGS += -I $(PKG_CONFIG_SYSROOT_DIR)/usr/include/ -endif -AM_CFLAGS += @GLIB_CFLAGS@ -Dstrlcpy=g_strlcpy -Dstrlcat=g_strlcat -include glib.h -AM_CFLAGS += @MMHEADERS_CFLAGS@ - -AM_CFLAGS += -DBACKEND_CONF_FILE=\"/etc/backend_conf.xml\" - -lib_LTLIBRARIES = libagmmixer.la -libagmmixer_la_SOURCES = agmmixer.c -libagmmixer_la_CFLAGS := $(AM_CFLAGS) -libagmmixer_la_LDFLAGS = -lcutils -ldl -lexpat -ltinyalsa -avoid-version - -bin_PROGRAMS := agmplay -agmplay_SOURCES := agmplay.c - -agmplay_la_CFLAGS := $(AM_CFLAGS) -agmplay_LDADD := -ltinyalsa libagmmixer.la - -bin_PROGRAMS += agmcap -agmcap_SOURCES := agmcap.c - -agmcap_la_CFLAGS := $(AM_CFLAGS) -agmcap_LDADD := -ltinyalsa libagmmixer.la - -bin_PROGRAMS += agmhostless -agmhostless_SOURCES := agmhostless.c - -agmhostless_la_CFLAGS := $(AM_CFLAGS) -agmhostless_LDADD := -ltinyalsa libagmmixer.la - -if !BUILDSYSTEM_OPENWRT -bin_PROGRAMS += agmcompressplay -agmcompressplay_SOURCES := agmcompressplay.c - -agmcompressplay_la_CFLAGS := $(AM_CFLAGS) -agmcompressplay_LDADD := -ltinycompress -ltinyalsa libagmmixer.la - -bin_PROGRAMS += agmcompresscap -agmcompresscap_SOURCES := agmcompresscap.c - -agmcompresscap_la_CFLAGS := $(AM_CFLAGS) -agmcompresscap_LDADD := -ltinycompress -ltinyalsa libagmmixer.la -endif - -bin_PROGRAMS += agmvoiceui -agmvoiceui_SOURCES := agm_voiceui.c - -agmvoiceui_la_CFLAGS := $(AM_CFLAGS) -agmvoiceui_LDADD := -lpthread -ltinyalsa libagmmixer.la -# install xml files under /etc -root_etcdir = "/etc" -root_etc_SCRIPTS = backend_conf.xml -install-data-hook: - chmod go-x $(DESTDIR)$(root_etcdir)/backend_conf.xml diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/MockAgmMixerWrapper.h b/qcom/opensource/agm/plugins/tinyalsa/test/MockAgmMixerWrapper.h deleted file mode 100755 index 88f23a3c..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/MockAgmMixerWrapper.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __MOCK_AGMMIXERWRAPPER_H__ -#define __MOCK_AGMMIXERWRAPPER_H__ - -#include "AgmMixerWrapper.h" - -class MockAgmMixerWrapper : public AgmMixerWrapper { - public: - MOCK_METHOD(int, mixerOpen, (unsigned int card), (override)); - MOCK_METHOD(int, mixerClose, (), (override)); - MOCK_METHOD(struct device_config, getDeviceMediaConfig, (char* filename, char *intf_name), (override)); - MOCK_METHOD(int, setDeviceMediaConfig, (char *intf_name, struct device_config *config), (override)); - MOCK_METHOD(int, setAudioInterfaceMetadata, (char *intf_name, unsigned int dkv, enum usecase_type usecase, int rate, int bitwidth, uint32_t stream_kv), (override)); - MOCK_METHOD(int, setStreamMetadata, (int device, uint32_t stream_kv, unsigned int instance_kv), (override)); - MOCK_METHOD(int, setStreamDeviceMetadata, (int device, uint32_t stream_kv, char *intf_name, unsigned int devicepp_kv), (override)); - MOCK_METHOD(int, connectAudioInterfaceToStream, (unsigned int device, char *intf_name), (override)); - MOCK_METHOD(int, configureMFC, (int device, char *intf_name, struct device_config), (override)); - MOCK_METHOD(struct group_config, getGroupConfig, (char *intf_name), (override)); - MOCK_METHOD(int, setGroupConfig, (unsigned int device, char *intf_name, unsigned int device_kv, struct group_config config, unsigned int channels), (override)); - MOCK_METHOD(int, setDeviceCustomPayload, (char *intf_name, int device, unsigned int usb_device), (override)); - MOCK_METHOD(int, disconnectAudioInterfaceToStream, (unsigned int device, char *intf_name), (override)); -}; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/MockAgmPcmWrapper.h b/qcom/opensource/agm/plugins/tinyalsa/test/MockAgmPcmWrapper.h deleted file mode 100755 index 69c85ca9..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/MockAgmPcmWrapper.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __MOCK_AGMPCMWRAPPER_H__ -#define __MOCK_AGMPCMWRAPPER_H__ - -#include "AgmPcmWrapper.h" - -class MockAgmPcmWrapper : public AgmPcmWrapper { - public: - MOCK_METHOD(int, pcmOpen, (unsigned int card, unsigned int device, struct pcm_config *config), (override)); - MOCK_METHOD(int, pcmFramesToBytes, (), (override)); - MOCK_METHOD(int, pcmStart, (), (override)); - MOCK_METHOD(int, pcmWrite, (char *buffer, int num_read), (override)); - MOCK_METHOD(int, pcmStop, (), (override)); - MOCK_METHOD(int, pcmClose, (), (override)); -}; -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommand.cpp b/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommand.cpp deleted file mode 100755 index 87047de0..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommand.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include -#include "PlaybackCommand.h" - -void PlaybackCommand::setCard(char **argv) -{ - argv++; - if (*argv) - card = atoi(*argv); -} - -void PlaybackCommand::setDevice(char **argv) -{ - argv++; - if (*argv) - device = atoi(*argv); -} - -void PlaybackCommand::setInterfaceNumber(char **argv) -{ - argv++; - if (*argv) - intf_num = atoi(*argv); -} - -void PlaybackCommand::setStreamKeyVector(char **argv) -{ - argv++; - if (*argv) - stream_kv = convert_char_to_hex(*argv); -} - -void PlaybackCommand::setInstanceKeyVector(char **argv) -{ - argv++; - if (*argv) { - instance_kv = atoi(*argv); - } -} - -void PlaybackCommand::setHaptics(char **argv) -{ - argv++; - if (*argv) - haptics = atoi(*argv); -} - -void PlaybackCommand::setInterfaceName(char **argv) -{ - intf_name = (char**) malloc(intf_num * sizeof(char*)); - if (!intf_name) { - std::cout << "insufficient memory" << std::endl; - exit(1); - } - - for (int i = 0; i < intf_num ; i++){ - argv++; - if (*argv) - intf_name[i] = *argv; - } -} - -void PlaybackCommand::set24LE(char **argv) -{ - argv++; - if (*argv) { - is_24_LE = atoi(*argv); - } -} - -void PlaybackCommand::setDeviceppKeyVector(char **argv) -{ - devicepp_kv = new unsigned int[intf_num]; - if (!devicepp_kv) { - std::cout << "insufficient memory" << std::endl; - exit(1); - } - - for (int i = 0; i < intf_num ; i++) { - devicepp_kv[i] = DEVICEPP_RX_AUDIO_MBDRC; - } - - for (int i = 0; i < intf_num ; i++) - { - argv++; - if (*argv) { - devicepp_kv[i] = convert_char_to_hex(*argv); - } - } -} - -void PlaybackCommand::setDeviceKeyVector(char **argv) -{ - device_kv = new unsigned int[intf_num]; - if (!device_kv) { - std::cout << "insufficient memory" << std::endl; - exit(1); - } - for (int i = 0; i < intf_num ; i++) { - argv++; - if (*argv) { - device_kv[i] = convert_char_to_hex(*argv); - } - } -} - -void PlaybackCommand::setChannel(char **argv) -{ - argv++; - if (*argv) - channels = atoi(*argv); -} - -void PlaybackCommand::setSampleRate(char **argv) -{ - argv++; - if (*argv) - rate = atoi(*argv); -} - -void PlaybackCommand::setBitWidth(char **argv) -{ - argv++; - if (*argv) - bits = atoi(*argv); -} - -void PlaybackCommand::setUsbDevice(char **argv) -{ - argv++; - if (*argv) - usb_device = atoi(*argv); -} - -unsigned int PlaybackCommand::getCard(void) -{ - return card; -} - -unsigned int PlaybackCommand::getDevice(void) -{ - return device; -} - -int PlaybackCommand::getInterfaceNumber() -{ - return intf_num; -} - -unsigned int PlaybackCommand::getStreamKeyVector() -{ - return stream_kv; -} - -unsigned int PlaybackCommand::getInstanceKeyVector() -{ - return instance_kv; -} - -bool PlaybackCommand::getHaptics() -{ - return haptics; -} - -char **PlaybackCommand::getInterfaceName() -{ - return intf_name; -} - -bool PlaybackCommand::is24LE() -{ - return is_24_LE; -} - -unsigned int *PlaybackCommand::getDeviceppKeyVector() -{ - return devicepp_kv; -} - -unsigned int *PlaybackCommand::getDeviceKeyVector() -{ - return device_kv; -} - -unsigned int PlaybackCommand::getChannel() -{ - return channels; -} - -unsigned int PlaybackCommand::getSampleRate() -{ - return rate; -} - -unsigned int PlaybackCommand::getBitWidth() -{ - return bits; -} - -unsigned int PlaybackCommand::getUsbDevice() -{ - return usb_device; -} \ No newline at end of file diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommand.h b/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommand.h deleted file mode 100755 index 6bcb2c56..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommand.h +++ /dev/null @@ -1,128 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __PLAYBACKCOMMAND_H__ -#define __PLAYBACKCOMMAND_H__ - -#include "agmmixer.h" - -class PlaybackCommand { -private: - unsigned int card; - unsigned int device; - int intf_num; - unsigned int stream_kv; - unsigned int instance_kv; - unsigned int *devicepp_kv; - unsigned int *device_kv; - unsigned int usb_device; - unsigned int channels; - unsigned int rate; - unsigned int bits; - char **intf_name; - bool haptics; - bool is_24_LE; - -public: - PlaybackCommand() - : card(100), - device(100), - intf_num(1), - stream_kv(0), - instance_kv(INSTANCE_1), - haptics(false), - intf_name(nullptr), - is_24_LE(false), - devicepp_kv(nullptr), - device_kv(nullptr), - usb_device(1), - channels(2), - rate(48000), - bits(16) - { - devicepp_kv = new unsigned int[intf_num]; - device_kv = new unsigned int[intf_num]; - - if (!device_kv || !devicepp_kv) { - std::cout << " insufficient memory" << std::endl; - exit(1); - } - - device_kv[0] = SPEAKER; - devicepp_kv[0] = DEVICEPP_RX_AUDIO_MBDRC; - } - - ~PlaybackCommand() - { - if (!devicepp_kv) { - delete[] devicepp_kv; - devicepp_kv = nullptr; - } - if (!device_kv) { - delete[] device_kv; - device_kv = nullptr; - } - } - - void setCard(char **argv); - void setDevice(char **argv); - void setInterfaceNumber(char **argv); - void setStreamKeyVector(char **argv); - void setInstanceKeyVector(char **argv); - void setHaptics(char **argv); - void setInterfaceName(char **argv); - void set24LE(char **argv); - void setDeviceKeyVector(char **argv); - void setDeviceppKeyVector(char **argv); - void setChannel(char **argv); - void setSampleRate(char **argv); - void setBitWidth(char **argv); - void setUsbDevice(char **argv); - - unsigned int getCard(); - unsigned int getDevice(); - int getInterfaceNumber(); - unsigned int getStreamKeyVector(); - unsigned int getInstanceKeyVector(); - bool getHaptics(); - char **getInterfaceName(); - bool is24LE(); - unsigned int *getDeviceKeyVector(); - unsigned int *getDeviceppKeyVector(); - unsigned int getChannel(); - unsigned int getSampleRate(); - unsigned int getBitWidth(); - unsigned int getUsbDevice(); -}; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommandParser.cpp b/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommandParser.cpp deleted file mode 100755 index 429c7f27..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommandParser.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include "PlaybackCommandParser.h" - -void PlaybackCommandParser::parseCommandLine(char **argv) -{ - argv += 2; - while (*argv) { - if (strcmp(*argv, "-d") == 0) { - playbackCommand.setDevice(argv); - } else if (strcmp(*argv, "-D") == 0) { - playbackCommand.setCard(argv); - } else if (strcmp(*argv, "-num_intf") == 0) { - playbackCommand.setInterfaceNumber(argv); - } else if (strcmp(*argv, "-i") == 0) { - playbackCommand.setInterfaceName(argv); - } else if (strcmp(*argv, "-h") == 0) { - playbackCommand.setHaptics(argv); - } else if (strcmp(*argv, "-dkv") == 0) { - playbackCommand.setDeviceKeyVector(argv); - } else if (strcmp(*argv, "-skv") == 0) { - playbackCommand.setStreamKeyVector(argv); - } else if (strcmp(*argv, "-ikv") == 0) { - playbackCommand.setInstanceKeyVector(argv); - } else if (strcmp(*argv, "-dppkv") == 0) { - playbackCommand.setDeviceppKeyVector(argv); - } else if (strcmp(*argv, "-is_24_LE") == 0) { - playbackCommand.set24LE(argv); - } else if (strcmp(*argv, "-c") == 0) { - playbackCommand.setChannel(argv); - } else if (strcmp(*argv, "-r") == 0) { - playbackCommand.setSampleRate(argv); - } else if (strcmp(*argv, "-b") == 0) { - playbackCommand.setBitWidth(argv); - } else if (strcmp(*argv, "-usb_d") == 0) { - playbackCommand.setUsbDevice(argv); - } else if (strcmp(*argv, "-help") == 0) { - usage(); - } - - if (*argv) - argv++; - } -} - -PlaybackCommand& PlaybackCommandParser::getPlaybackCommand() { - return playbackCommand; -} - -void PlaybackCommandParser::usage(void) -{ - std::cout << "Usage: %s file.wav [-help print usage] [-D card] [-d device]" << std::endl; - std::cout << "[-c channels] [-r rate] [-b bits]" << std::endl; - std::cout << " [-num_intf num of interfaces followed by interface name]" << std::endl; - std::cout << " [-i intf_name] : Can be multiple if num_intf is more than 1" << std::endl; - std::cout << " [-dkv device_kv] : Can be multiple if num_intf is more than 1" << std::endl; - std::cout << " [-dppkv deviceppkv] : Assign 0 if no device pp in the graph" << std::endl; - std::cout << " [-ikv instance_kv] : Assign 0 if no instance kv in the graph" << std::endl; - std::cout << " [-skv stream_kv] [-h haptics usecase]" << std::endl; - std::cout << " [is_24_LE] : [0-1] Only to be used if user wants to play S24_LE clip" << std::endl; - std::cout << " [-usb_d usb device]" << std::endl; - std::cout << " 0: If clip bps is 32, and format is S32_LE" << std::endl; - std::cout << " 1: If clip bps is 24, and format is S24_LE" << std::endl; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommandParser.h b/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommandParser.h deleted file mode 100755 index 0ef634c3..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/PlaybackCommandParser.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __PLAYBACKCOMMANDPARSER_H__ -#define __PLAYBACKCOMMANDPARSER_H__ - -#include -#include "PlaybackCommand.h" - -class PlaybackCommandParser { -private: - PlaybackCommand playbackCommand; - -public: - ~PlaybackCommandParser() {}; - void parseCommandLine(char **argv); - PlaybackCommand& getPlaybackCommand(); - void usage(void); -}; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/README.md b/qcom/opensource/agm/plugins/tinyalsa/test/README.md deleted file mode 100755 index eab92e8f..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/README.md +++ /dev/null @@ -1 +0,0 @@ -# tinyalsa_agmtest \ No newline at end of file diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/RiffWaveParser.cpp b/qcom/opensource/agm/plugins/tinyalsa/test/RiffWaveParser.cpp deleted file mode 100755 index 0349a466..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/RiffWaveParser.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include "RiffWaveParser.h" - -void RiffWaveParser::readHeader(std::ifstream& file) -{ - file.read((char*)&riffId, sizeof(riffId)); - file.read((char*)&riffSize, sizeof(riffSize)); - file.read((char*)&waveId, sizeof(waveId)); -} - -bool RiffWaveParser::isValidFile(void) -{ - if ((riffId != ID_RIFF) || (waveId != ID_WAVE)) { - return false; - } - return true; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/RiffWaveParser.h b/qcom/opensource/agm/plugins/tinyalsa/test/RiffWaveParser.h deleted file mode 100755 index 0e0bc213..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/RiffWaveParser.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __RIFFWAVEPARSER_H__ -#define __RIFFWAVEPARSER_H__ - -#include "HeaderParser.h" - -const uint32_t ID_RIFF = 0x46464952; -const uint32_t ID_WAVE = 0x45564157; - -class RiffWaveParser : public HeaderParser { -private: - uint32_t riffId; - uint32_t riffSize; - uint32_t waveId; - -public: - ~RiffWaveParser() {} - -protected: - void readHeader(std::ifstream& file) override; - bool isValidFile(void) override; -}; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/SignalHandler.h b/qcom/opensource/agm/plugins/tinyalsa/test/SignalHandler.h deleted file mode 100755 index 54185d70..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/SignalHandler.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __SIGNALHANDLER_H__ -#define __SIGNALHANDLER_H__ - -#include - -class SignalHandler { -public: - SignalHandler() : closed(false) {} - - void open() { - signal(SIGINT, SignalHandler::signalHandler); - } - - void close() { - closed = true; - } - - bool isClosed() { - return closed; - } - - void Handler(int sig) { - signal(sig, SIG_IGN); - close(); - } - - -private: - bool closed; - static SignalHandler instance; - - static void signalHandler(int sig) { - instance.Handler(sig); - } -}; - -SignalHandler SignalHandler::instance; - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/agm_voiceui.c b/qcom/opensource/agm/plugins/tinyalsa/test/agm_voiceui.c deleted file mode 100755 index 818f9972..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/agm_voiceui.c +++ /dev/null @@ -1,476 +0,0 @@ -/* -** Copyright (c) 2019, 2021, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "agmmixer.h" - -static pthread_t event_thread; -static int done = 0; - -char *audio_interface_name[] = { - "CODEC_DMA-LPAIF_VA-TX-0", - "CODEC_DMA-LPAIF_VA-TX-1", - "CODEC_DMA-LPAIF_RXTX-TX-3", - "MI2S-LPAIF_AXI-TX-PRIMARY", - "TDM-LPAIF_AXI-TX-PRIMARY", - "AUXPCM-LPAIF_AXI-TX-PRIMARY", -}; - -char *ec_aif_name[] = { - "CODEC_DMA-LPAIF_WSA-RX-0", - "CODEC_DMA-LPAIF_WSA-RX-1", - "MI2S-LPAIF_AXI-RX-PRIMARY", - "TDM-LPAIF_AXI-RX-PRIMARY", - "AUXPCM-LPAIF_AXI-RX-PRIMARY", -}; - -static void read_event_data(struct mixer *mixer, char *mixer_str) -{ - struct mixer_ctl *ctl; - char *buf = NULL; - unsigned int num_values; - int i, ret; - struct agm_event_cb_params *params; - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - num_values = mixer_ctl_get_num_values(ctl); - printf("%s - %d\n", __func__, num_values); - buf = calloc(1, num_values); - if (!buf) { - printf("Failed to allocate memory for buffer\n"); - return; - } - - ret = mixer_ctl_get_array(ctl, buf, num_values); - if (ret < 0) { - printf("Failed to mixer_ctl_get_array\n"); - free(buf); - return; - } - - params = (struct agm_event_cb_params *)buf; - printf("%s params.source_module_id %x\n", __func__, params->source_module_id); - printf("%s params.event_id %d\n", __func__, params->event_id); - printf("%s params.event_payload_size %x\n", __func__, params->event_payload_size); -} - -static void event_wait_thread_loop(void *context) -{ - struct mixer *mixer = (struct mixer *)context; - int ret = 0; - struct ctl_event mixer_event = {0}; - - printf("subscribing for event\n"); - mixer_subscribe_events(mixer, 1); - - printf("going to wait for event\n"); - ret = mixer_wait_event(mixer, 30000); - if (ret < 0) { - printf("%s: mixer_wait_event err!, ret = %d\n", __func__, ret); - } else if (ret > 0) { - ret = mixer_read_event(mixer, &mixer_event); - if (ret >= 0) { - printf("Event Received %s\n", mixer_event.data.elem.id.name); - read_event_data(mixer, mixer_event.data.elem.id.name); - } else { - printf("%s: mixer_read failed, ret = %d\n", __func__, ret); - } - done = 1; - } - - mixer_subscribe_events(mixer, 0); -} - -static void record_lab_buffer(struct pcm *pcm, unsigned int cap_time) -{ - struct timespec end; - struct timespec now; - unsigned int size; - char *buffer; - FILE *file; - int ret; - - ret = pthread_join(event_thread, (void **) NULL); - if (ret < 0) { - printf("%s: Unable to join event thread\n", __func__); - return; - } - - if (!done) - return; - - file = fopen("/data/voice_rec.wav", "wb"); - if (!file) { - printf("Unable to create voice_rec file\n"); - return; - } - - size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm)); - buffer = malloc(size); - if (!buffer) { - printf("Unable to allocate %u bytes\n", size); - fclose(file); - return; - } - - clock_gettime(CLOCK_MONOTONIC, &now); - end.tv_sec = now.tv_sec + cap_time; - end.tv_nsec = now.tv_nsec; - - while (!pcm_read(pcm, buffer, size)) { - if (fwrite(buffer, 1, size, file) != size) { - printf("Error capturing sample\n"); - break; - } - if (cap_time) { - clock_gettime(CLOCK_MONOTONIC, &now); - if (now.tv_sec > end.tv_sec || - (now.tv_sec == end.tv_sec && now.tv_nsec >= end.tv_nsec)) - break; - } - } - - free(buffer); - fclose(file); -} - -static int get_file_size(char *filename) -{ - FILE *fp; - int size = 0; - - fp = fopen(filename, "rb"); - if (!fp) { - printf("%s: Unable to open file '%s'\n", __func__, filename); - return 0; - } - fseek(fp, 0, SEEK_END); - size = ftell(fp); - printf("%s - sizeof %s is %d\n", __func__, filename, size); - fseek(fp, 0, SEEK_SET); - fclose(fp); - return size; -} - -static void fill_payload(char *filename, int size, void *payload) -{ - FILE *fp; - int bytes_read; - - fp = fopen(filename, "rb"); - if (!fp) { - printf("%s: Unable to open file '%s'\n", __func__, filename); - return; - } - - bytes_read = fread((char*)payload, 1, size , fp); - if (bytes_read != size) { - printf("%s failed to read data from file %s, bytes read = %d\n", __func__, filename, bytes_read); - } - fclose(fp); -} - -static void* merge_payload(uint32_t miid, int num, int *sum, ...) -{ - va_list valist; - int i = 0, total_size = 0, offset = 0; - int *size = calloc(num, sizeof(int)); - char **temp = calloc(num, sizeof(char *)); - void *payload = NULL; - uint8_t *buf; - uint32_t *module_instance_id = NULL; - - if (!size || !temp) { - printf("Failed to allocate memory for size and temp\n"); - return NULL; - } - - va_start(valist, num); - for (i = 0; i < num; i++) { - temp[i] = va_arg(valist, char *); - size[i] = get_file_size(temp[i]); - total_size += size[i]; - } - va_end(valist); - - payload = calloc(1, total_size); - if (!payload) - return NULL; - - buf = payload; - for (i = 0; i < num; i++) { - fill_payload(temp[i], size[i], buf); - // Update SVA miid - module_instance_id = (uint32_t *)buf; - *module_instance_id = miid; - buf += size[i]; - } - *sum = total_size; - /* TODO : free memory */ - return payload; -} - -void voice_ui_test(unsigned int card, unsigned int device, unsigned int audio_intf, unsigned int cap_time, int ec_aif, - unsigned int device_kv, unsigned int stream_kv, unsigned int instance_kv, unsigned int devicepp_kv) -{ - struct mixer *mixer; - char *intf_name = audio_interface_name[audio_intf]; - char *ec_intf_name = NULL; - struct pcm_config config; - struct pcm *pcm; - struct device_config dev_config; - int ret = 0; - enum pcm_format format = PCM_FORMAT_S16_LE; - uint32_t miid = 0, param_size = 0; - void *param_buf = NULL; - - memset(&config, 0, sizeof(config)); - config.channels = 2; - config.rate = 48000; - config.period_size = 1024; - config.period_count = 4; - config.format = format; - config.start_threshold = 0; - config.stop_threshold = 0; - config.silence_threshold = 0; - stream_kv = stream_kv ? stream_kv : VOICE_UI; - - dev_config.rate = config.rate; - dev_config.ch = config.channels; - dev_config.bits = get_pcm_bit_width(config.format); - dev_config.format = config.format; - mixer = mixer_open(card); - if (!mixer) { - printf("Failed to open mixer\n"); - return; - } - - /* set device/audio_intf media config mixer control */ - if (set_agm_device_media_config(mixer, intf_name, &dev_config)) { - printf("Failed to set device media config\n"); - goto err_close_mixer; - } - - /* set audio interface metadata mixer control */ - if (set_agm_audio_intf_metadata(mixer, intf_name, 0, CAPTURE, config.rate, - pcm_format_to_bits(format), stream_kv)) { - printf("Failed to set device metadata\n"); - goto err_close_mixer; - } - - /* set stream metadata mixer control */ - if (set_agm_stream_metadata(mixer, device, stream_kv, CAPTURE, STREAM_PCM, - instance_kv)) { - printf("Failed to set pcm metadata\n"); - goto err_close_mixer; - } - - if (devicepp_kv != 0) { - if (set_agm_streamdevice_metadata(mixer, device, stream_kv, CAPTURE, STREAM_PCM, - intf_name, devicepp_kv)) { - printf("Failed to set pcm metadata\n"); - goto err_close_mixer; - } - } - /* connect pcm stream to audio intf */ - if (connect_agm_audio_intf_to_stream(mixer, device, intf_name, STREAM_PCM, true)) { - printf("Failed to connect pcm to audio interface\n"); - goto err_close_mixer; - } - - ret = agm_mixer_get_miid(mixer, device, intf_name, STREAM_PCM, DEVICE_SVA, &miid); - if (ret) { - printf("%s Get MIID from tag data failed\n", __func__); - goto err_close_mixer; - } - - param_buf = merge_payload(miid, 3, ¶m_size, "/vendor/etc/sound_model", - "/vendor/etc/wakeup_config", "/vendor/etc/buffer_config"); - - if (agm_mixer_set_param(mixer, device, STREAM_PCM, param_buf, param_size)) { - printf("setparam failed\n"); - goto err_close_mixer; - } - - pcm = pcm_open(card, device, PCM_IN, &config); - if (!pcm || !pcm_is_ready(pcm)) { - printf("Unable to open PCM device (%s)\n", - pcm_get_error(pcm)); - goto err_close_mixer; - } - -#if 0 - /* Load Sound Model */ - if (agm_mixer_set_param_with_file(mixer, device, STREAM_PCM, "/etc/sound_model")) { - printf("soundmodel load failed\n"); - goto err_close_pcm; - } - - /* Register voice wakeup config */ - if (agm_mixer_set_param_with_file(mixer, device, STREAM_PCM, "/etc/wakeup_config")) { - printf("wakeup config registration failed\n"); - goto err_close_pcm; - } -#endif -// Call API to register event with GSL here -// Same as GSL_CMD_REGISTER_CUSTOM_EVENT - if (agm_mixer_register_event(mixer, device, STREAM_PCM, miid, 1)) { - printf("GSL event registration failed\n"); - goto err_close_pcm; - } - -#if 0 - /* Register buffer config */ - if (agm_mixer_set_param_with_file(mixer, device, STREAM_PCM, "/etc/buffer_config")) { - printf("buffer config registration failed\n"); - goto err_close_pcm; - } -#endif - /* Setup EC ref path */ - if (ec_aif != -1) { - if (agm_mixer_set_ecref_path(mixer, device, STREAM_PCM, ec_aif_name[ec_aif])) { - printf("EC ref path failed\n"); - goto err_close_pcm; - } - } - - if (pcm_start(pcm) < 0) { // This internally calls pcm_prepare too. - printf("start error\n"); - goto err_close_pcm; - } - - pthread_create(&event_thread, - (const pthread_attr_t *) NULL, event_wait_thread_loop, mixer); - - record_lab_buffer(pcm, cap_time); - - /* Reset Engine */ - if (agm_mixer_set_param_with_file(mixer, device, STREAM_PCM, "/vendor/etc/engine_reset")) { - printf("stream setup duration configuration failed\n"); - goto err_close_pcm; - } - -err_close_pcm: - if (ec_aif != -1) - agm_mixer_set_ecref_path(mixer, device, STREAM_PCM, "ZERO"); - pcm_close(pcm); -err_close_mixer: - mixer_close(mixer); - printf("completed event test\n"); -} - -int main(int argc, char **argv) -{ - unsigned int device = 100; - unsigned int card = 0; - unsigned int audio_intf = 0; - int ec_aif = -1; - unsigned int cap_time = 5; - unsigned int device_kv = 0; - unsigned int devicepp_kv = DEVICEPP_TX_FLUENCE_FFECNS; - unsigned int stream_kv = 0; - unsigned int instance_kv = INSTANCE_1; - - argv += 1; - while (*argv) { - if (strcmp(*argv, "-d") == 0) { - argv++; - if (*argv) - device = atoi(*argv); - } - if (*argv && strcmp(*argv, "-D") == 0) { - argv++; - if (*argv) - card = atoi(*argv); - } - if (*argv && strcmp(*argv, "-i") == 0) { - argv++; - if (*argv) - audio_intf = atoi(*argv); - if (audio_intf >= sizeof(audio_interface_name)/sizeof(char *)) { - printf("Invalid audio interface index denoted by -i\n"); - return 1; - } - } - if (*argv && strcmp(*argv, "-e") == 0) { - argv++; - if (*argv) - ec_aif = atoi(*argv); - if (ec_aif >= sizeof(ec_aif_name)/sizeof(char *)) { - printf("Invalid echoref audio interface index denoted by -i\n"); - return 1; - } - } - if (*argv && strcmp(*argv, "-T") == 0) { - argv++; - if (*argv) - cap_time = atoi(*argv); - } else if (*argv && strcmp(*argv, "-dkv") == 0) { - argv++; - if (*argv) - device_kv = convert_char_to_hex(*argv); - } else if (*argv && strcmp(*argv, "-skv") == 0) { - argv++; - if (*argv) - stream_kv = convert_char_to_hex(*argv); - } else if (*argv && strcmp(*argv, "-ikv") == 0) { - argv++; - if (*argv) - instance_kv = atoi(*argv); - } else if (*argv && strcmp(*argv, "-dppkv") == 0) { - argv++; - if (*argv) - devicepp_kv = convert_char_to_hex(*argv); - } - - if (*argv) - argv++; - } - - voice_ui_test(card, device, audio_intf, cap_time, ec_aif, device_kv, stream_kv, - instance_kv, devicepp_kv); - return 0; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/agmcap.c b/qcom/opensource/agm/plugins/tinyalsa/test/agmcap.c deleted file mode 100755 index a30480f7..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/agmcap.c +++ /dev/null @@ -1,445 +0,0 @@ -/* -** Copyright (c) 2019, 2021, The Linux Foundation. All rights reserved. -** -** Copyright 2011, The Android Open Source Project -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of The Android Open Source Project nor the names of -** its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -** ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE -** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -** DAMAGE. -** -** Changes from Qualcomm Innovation Center, Inc. are provided under the following license: -** Copyright (c) 2022-2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "agmmixer.h" - -#define ID_RIFF 0x46464952 -#define ID_WAVE 0x45564157 -#define ID_FMT 0x20746d66 -#define ID_DATA 0x61746164 - -#define FORMAT_PCM 1 - -struct wav_header { - uint32_t riff_id; - uint32_t riff_sz; - uint32_t riff_fmt; - uint32_t fmt_id; - uint32_t fmt_sz; - uint16_t audio_format; - uint16_t num_channels; - uint32_t sample_rate; - uint32_t byte_rate; - uint16_t block_align; - uint16_t bits_per_sample; - uint32_t data_id; - uint32_t data_sz; -}; - -int capturing = 1; - -static unsigned int capture_sample(FILE *file, unsigned int card, unsigned int device, - unsigned int usb_device, unsigned int channels, unsigned int rate, - unsigned int bits, enum pcm_format format, unsigned int period_size, - unsigned int period_count, unsigned int cap_time, - struct device_config *dev_config, unsigned int stream_kv, - unsigned int device_kv, unsigned int instance_kv, - unsigned int devicepp_kv); - -static void sigint_handler(int sig) -{ - capturing = 0; -} - -static void usage(void) -{ - printf(" Usage: %s file.wav [-help print usage] [-D card] [-d device]\n" - " [-c channels] [-r rate] [-b bits] [-p period_size]\n" - " [-n n_periods] [-T capture time] [-i intf_name] [-dkv device_kv]\n" - " [-dppkv deviceppkv] : Assign 0 if no device pp in the graph\n" - " [-ikv instance_kv] : Assign 0 if no instance kv in the graph\n" - " [-skv stream_kv]\n" - " [-is_24_LE] : [0-1] Only to be used if user wants to record 32 bps clip\n" - " [-usb_d usb device]\n" - " 0: If bps is 32, and format should be S32_LE\n" - " 1: If bps is 24, and format should be S24_LE\n"); -} - -int main(int argc, char **argv) -{ - FILE *file; - struct wav_header header; - unsigned int card = 100; - unsigned int device = 101; - unsigned int usb_device = 1; - unsigned int channels = 2; - unsigned int rate = 44100; - unsigned int bits = 16; - unsigned int frames; - unsigned int period_size = 1024; - unsigned int period_count = 4; - unsigned int cap_time = 0; - char *intf_name = NULL; - unsigned int device_kv = 0; - struct device_config config; - enum pcm_format format; - int ret = 0; - unsigned int devicepp_kv = 0; - unsigned int stream_kv = 0; - unsigned int instance_kv = INSTANCE_1; - bool is_24_LE = false; - - if (argc < 2) { - usage(); - return 1; - } - - file = fopen(argv[1], "wb"); - if (!file) { - printf("Unable to create file '%s'\n", argv[1]); - return 1; - } - - /* parse command line arguments */ - argv += 2; - while (*argv) { - if (strcmp(*argv, "-d") == 0) { - argv++; - if (*argv) - device = atoi(*argv); - } else if (strcmp(*argv, "-c") == 0) { - argv++; - if (*argv) - channels = atoi(*argv); - } else if (strcmp(*argv, "-r") == 0) { - argv++; - if (*argv) - rate = atoi(*argv); - } else if (strcmp(*argv, "-b") == 0) { - argv++; - if (*argv) - bits = atoi(*argv); - } else if (strcmp(*argv, "-D") == 0) { - argv++; - if (*argv) - card = atoi(*argv); - } else if (strcmp(*argv, "-p") == 0) { - argv++; - if (*argv) - period_size = atoi(*argv); - } else if (strcmp(*argv, "-n") == 0) { - argv++; - if (*argv) - period_count = atoi(*argv); - } else if (strcmp(*argv, "-T") == 0) { - argv++; - if (*argv) - cap_time = atoi(*argv); - } else if (strcmp(*argv, "-i") == 0) { - argv++; - if (*argv) - intf_name = *argv; - } else if (strcmp(*argv, "-dkv") == 0) { - argv++; - if (*argv) - device_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-skv") == 0) { - argv++; - if (*argv) - stream_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-ikv") == 0) { - argv++; - if (*argv) - instance_kv = atoi(*argv); - } else if (strcmp(*argv, "-dppkv") == 0) { - argv++; - if (*argv) - devicepp_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-is_24_LE") == 0) { - argv++; - if (*argv) - is_24_LE = atoi(*argv); - } else if (strcmp(*argv, "-usb_d") == 0) { - argv++; - if (*argv) - usb_device = atoi(*argv); - }else if (strcmp(*argv, "-help") == 0) { - usage(); - } - if (*argv) - argv++; - } - - header.riff_id = ID_RIFF; - header.riff_sz = 0; - header.riff_fmt = ID_WAVE; - header.fmt_id = ID_FMT; - header.fmt_sz = 16; - header.audio_format = FORMAT_PCM; - header.num_channels = channels; - header.sample_rate = rate; - - switch (bits) { - case 32: - if (is_24_LE) - format = PCM_FORMAT_S24_LE; - else - format = PCM_FORMAT_S32_LE; - break; - case 24: - format = PCM_FORMAT_S24_3LE; - break; - case 16: - format = PCM_FORMAT_S16_LE; - break; - default: - printf("%u bits is not supported.\n", bits); - fclose(file); - return 1; - } - - if (intf_name == NULL) - return 1; - - ret = get_device_media_config(BACKEND_CONF_FILE, intf_name, &config); - if (ret) { - printf("Invalid input, entry not found for %s\n", intf_name); - fclose(file); - return ret; - } - if (config.format != PCM_FORMAT_INVALID) { - printf("Valid format from backend_conf %d\n", config.format); - config.bits = get_pcm_bit_width(config.format); - } - - header.bits_per_sample = pcm_format_to_bits(format); - header.byte_rate = (header.bits_per_sample / 8) * channels * rate; - header.block_align = channels * (header.bits_per_sample / 8); - header.data_id = ID_DATA; - - /* leave enough room for header */ - fseek(file, sizeof(struct wav_header), SEEK_SET); - - /* install signal handler and begin capturing */ - signal(SIGINT, sigint_handler); - signal(SIGHUP, sigint_handler); - signal(SIGTERM, sigint_handler); - frames = capture_sample(file, card, device, usb_device, header.num_channels, - header.sample_rate, bits, format, - period_size, period_count, cap_time, &config, - stream_kv, device_kv, instance_kv, devicepp_kv); - printf("Captured %u frames\n", frames); - - /* write header now all information is known */ - header.data_sz = frames * header.block_align; - header.riff_sz = header.data_sz + sizeof(header) - 8; - fseek(file, 0, SEEK_SET); - fwrite(&header, sizeof(struct wav_header), 1, file); - - fclose(file); - - return 0; -} - -unsigned int capture_sample(FILE *file, unsigned int card, unsigned int device, - unsigned int usb_device, unsigned int channels, unsigned int rate, - unsigned int bits, enum pcm_format format, unsigned int period_size, - unsigned int period_count, unsigned int cap_time, - struct device_config *dev_config, unsigned int stream_kv, - unsigned int device_kv, unsigned int instance_kv, unsigned int devicepp_kv) -{ - struct pcm_config config; - struct pcm *pcm; - struct mixer *mixer; - char *buffer; - char *intf_name = dev_config->name; - unsigned int size; - unsigned int bytes_read = 0; - unsigned int frames = 0; - struct timespec end; - struct timespec now; - uint32_t miid = 0; - int ret = 0; - struct usbAudioConfig cfg; - uint8_t* payload = NULL; - size_t payloadSize = 0; - - stream_kv = stream_kv ? stream_kv : PCM_RECORD; - - memset(&config, 0, sizeof(config)); - config.channels = channels; - config.rate = rate; - config.period_size = period_size; - config.period_count = period_count; - config.format = format; - config.start_threshold = 0; - config.stop_threshold = 0; - config.silence_threshold = 0; - - if (NULL == intf_name) { - printf("No interface name mentioned, Exiting !!!\n"); - return 0; - } - - mixer = mixer_open(card); - if (!mixer) { - printf("Failed to open mixer\n"); - return 0; - } - - if(strcmp(intf_name, "USB_AUDIO-TX") == 0) { - dev_config->rate = rate; - dev_config->ch = channels; - dev_config->bits = bits; - dev_config->format = PCM_FORMAT_INVALID; - } - - /* set device/audio_intf media config mixer control */ - if (set_agm_device_media_config(mixer, intf_name, dev_config)) { - printf("Failed to set device media config\n"); - goto err_close_mixer; - } - - /* set audio interface metadata mixer control */ - if (set_agm_audio_intf_metadata(mixer, intf_name, device_kv, CAPTURE, - dev_config->rate, dev_config->bits, stream_kv)) { - printf("Failed to set device metadata\n"); - goto err_close_mixer; - } - - /* set stream metadata mixer control */ - if (set_agm_capture_stream_metadata(mixer, device, stream_kv, CAPTURE, STREAM_PCM, - instance_kv)) { - printf("Failed to set pcm metadata\n"); - goto err_close_mixer; - } - - if (devicepp_kv != 0) { - if (set_agm_streamdevice_metadata(mixer, device, stream_kv, CAPTURE, STREAM_PCM, - intf_name, devicepp_kv)) { - printf("Failed to set pcm metadata\n"); - goto err_close_mixer; - } - } - - ret = agm_mixer_get_miid (mixer, device, intf_name, STREAM_PCM, TAG_STREAM_MFC, &miid); - if (ret) { - printf("MFC not present for this graph\n"); - } else { - if (configure_mfc(mixer, device, intf_name, TAG_STREAM_MFC, - STREAM_PCM, rate, channels, get_pcm_bit_width(format), miid)) { - printf("Failed to configure stream mfc\n"); - goto err_close_mixer; - } - } - - if (strcmp(intf_name, "USB_AUDIO-TX") == 0) { - ret = agm_mixer_get_miid (mixer, device, intf_name, STREAM_PCM, DEVICE_HW_ENDPOINT_TX, &miid); - if (ret == 0) { - cfg.usb_token = (usb_device << 16)|0x1; - cfg.svc_interval = 0; - get_agm_usb_audio_config_payload(&payload, &payloadSize, miid, &cfg); - - if (payloadSize) { - ret = set_agm_device_custom_payload(mixer, intf_name, payload, payloadSize); - } else { - ret = -1; - printf("set_agm_device_custom_payload failed\n"); - goto err_close_mixer; - } - } else { - printf("Failed to get miid for USB_AUDIO-TX\n"); - goto err_close_mixer; - } - - } - - /* connect pcm stream to audio intf */ - if (connect_agm_audio_intf_to_stream(mixer, device, intf_name, STREAM_PCM, true)) { - printf("Failed to connect pcm to audio interface\n"); - goto err_close_mixer; - } - - pcm = pcm_open(card, device, PCM_IN, &config); - if (!pcm || !pcm_is_ready(pcm)) { - printf("Unable to open PCM device (%s)\n", - pcm_get_error(pcm)); - goto err_close_mixer; - } - - size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm)); - buffer = malloc(size); - if (!buffer) { - printf("Unable to allocate %u bytes\n", size); - goto err_close_pcm; - } - - printf("Capturing sample: %u ch, %u hz, %u bit\n", channels, rate, - pcm_format_to_bits(format)); - - if (pcm_start(pcm) < 0) { - printf("start error\n"); - goto err_close_pcm; - } - - clock_gettime(CLOCK_MONOTONIC, &now); - end.tv_sec = now.tv_sec + cap_time; - end.tv_nsec = now.tv_nsec; - - while (capturing && !pcm_read(pcm, buffer, size)) { - if (fwrite(buffer, 1, size, file) != size) { - printf("Error capturing sample\n"); - break; - } - bytes_read += size; - if (cap_time) { - clock_gettime(CLOCK_MONOTONIC, &now); - if (now.tv_sec > end.tv_sec || - (now.tv_sec == end.tv_sec && now.tv_nsec >= end.tv_nsec)) - break; - } - } - - frames = pcm_bytes_to_frames(pcm, bytes_read); - free(buffer); - - pcm_stop(pcm); -err_close_pcm: - connect_agm_audio_intf_to_stream(mixer, device, intf_name, STREAM_PCM, false); - pcm_close(pcm); -err_close_mixer: - if (payload) { - free(payload); - } - mixer_close(mixer); - return frames; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/agmcompresscap.c b/qcom/opensource/agm/plugins/tinyalsa/test/agmcompresscap.c deleted file mode 100755 index c7241bb1..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/agmcompresscap.c +++ /dev/null @@ -1,594 +0,0 @@ -/* - * Copyright (c) 2019, The Linux Foundation. All rights reserved. - * This code is used under the BSD license. - * - * BSD LICENSE - * - * Copyright (c) 2011-2012, Intel Corporation - * Copyright (c) 2013-2014, Wolfson Microelectronic Ltd. - * All rights reserved. - * - * Author: Vinod Koul - * Author: Charles Keepax - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * Neither the name of Intel Corporation nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - * - * LGPL LICENSE - * - * Copyright (c) 2011-2012, Intel Corporation - * Copyright (c) 2013-2014, Wolfson Microelectronic Ltd. - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU Lesser General Public License, - * version 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public - * License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to - * the Free Software Foundation, Inc., - * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#define __force -//#define __bitwise -#define __user -#include -#include -#include - -#include "agmmixer.h" - -static int verbose; -static int file; -static FILE *finfo; -static bool streamed; - -static const unsigned int DEFAULT_CHANNELS = 1; -static const unsigned int DEFAULT_RATE = 44100; -static const unsigned int DEFAULT_FORMAT = SNDRV_PCM_FORMAT_S16_LE; - -struct riff_chunk { - char desc[4]; - uint32_t size; -} __attribute__((__packed__)); - -struct wave_header { - struct { - struct riff_chunk chunk; - char format[4]; - } __attribute__((__packed__)) riff; - - struct { - struct riff_chunk chunk; - uint16_t type; - uint16_t channels; - uint32_t rate; - uint32_t byterate; - uint16_t blockalign; - uint16_t samplebits; - } __attribute__((__packed__)) fmt; - - struct { - struct riff_chunk chunk; - } __attribute__((__packed__)) data; -} __attribute__((__packed__)); - -static const struct wave_header blank_wave_header = { - .riff = { - .chunk = { - .desc = "RIFF", - }, - .format = "WAVE", - }, - .fmt = { - .chunk = { - .desc = "fmt ", /* Note the space is important here */ - .size = sizeof(blank_wave_header.fmt) - - sizeof(blank_wave_header.fmt.chunk), - }, - .type = 0x01, /* PCM */ - }, - .data = { - .chunk = { - .desc = "data", - }, - }, -}; - -static void init_wave_header(struct wave_header *header, uint16_t channels, - uint32_t rate, uint16_t samplebits) -{ - memcpy(header, &blank_wave_header, sizeof(blank_wave_header)); - - header->fmt.channels = channels; - header->fmt.rate = rate; - header->fmt.byterate = channels * rate * (samplebits / 8); - header->fmt.blockalign = channels * (samplebits / 8); - header->fmt.samplebits = samplebits; -} - -static void size_wave_header(struct wave_header *header, uint32_t size) -{ - header->riff.chunk.size = sizeof(*header) - - sizeof(header->riff.chunk) + size; - header->data.chunk.size = size; -} - -static void usage(void) -{ - fprintf(stderr, "usage: crec [OPTIONS] [filename]\n" - "-D\tcard number\n" - "-d\tdevice node\n" - "-buf\tbuffer size\n" - "-f\tfragments\n" - "-v\tverbose mode\n" - "-l\tlength of record in seconds\n" - " [-help print usage]\n" - " [-c channels] [-r rate] [-b bits]\n" - " [-n n_periods] [-i intf_name] [-dkv device_kv]\n" - " [-dppkv deviceppkv] : Assign 0 if no device pp in the graph\n" - " [-ikv instance_kv] : Assign 0 if no instance kv in the graph\n" - " [-skv stream_kv]"); - - exit(EXIT_FAILURE); -} - -static int print_time(struct compress *compress) -{ - unsigned int avail; - struct timespec tstamp; - - if (compress_get_hpointer(compress, &avail, &tstamp) != 0) { - fprintf(stderr, "Error querying timestamp\n"); - fprintf(stderr, "ERR: %s\n", compress_get_error(compress)); - return -1; - } else { - fprintf(finfo, "DSP recorded %jd.%jd\n", - (intmax_t)tstamp.tv_sec, (intmax_t)tstamp.tv_nsec*1000); - } - return 0; -} - -static int finish_record(void) -{ - struct wave_header header; - int ret; - size_t nread, written; - - if (!file) - return -ENOENT; - - /* can't rewind if streaming to stdout */ - if (streamed) - return 0; - - /* Get amount of data written to file */ - ret = lseek(file, 0, SEEK_END); - if (ret < 0) - return -errno; - - written = ret; - if (written < sizeof(header)) - return -ENOENT; - written -= sizeof(header); - - /* Sync file header from file */ - ret = lseek(file, 0, SEEK_SET); - if (ret < 0) - return -errno; - - nread = read(file, &header, sizeof(header)); - if (nread != sizeof(header)) - return -errno; - - /* Update file header */ - ret = lseek(file, 0, SEEK_SET); - if (ret < 0) - return -errno; - - size_wave_header(&header, written); - - written = write(file, &header, sizeof(header)); - if (written != sizeof(header)) - return -errno; - - return 0; -} - -static void capture_samples(char *name, unsigned int card, unsigned int device, - unsigned long buffer_size, unsigned int frag, - unsigned int length, unsigned int rate, - unsigned int channels, unsigned int format, struct device_config *dev_config, unsigned int stream_kv, - unsigned int device_kv, unsigned int instance_kv, unsigned int devicepp_kv) -{ - struct compr_config config; - struct snd_codec codec; - struct compress *compress; - struct mixer *mixer; - struct wave_header header; - char *buffer; - size_t written; - int read, ret; - unsigned int size, total_read = 0; - unsigned int samplebits; - uint32_t miid = 0; - char *intf_name = dev_config->name; - //TODO: Change default stream_kv to COMPRESS_RECORD later. - stream_kv = stream_kv ? stream_kv : PCM_RECORD; - - switch (format) { - case SNDRV_PCM_FORMAT_S32_LE: - samplebits = 32; - break; - default: - samplebits = 16; - break; - } - - /* Convert length from seconds to bytes */ - length = length * rate * (samplebits / 8) * channels; - - if (verbose) - fprintf(finfo, "%s: entry, reading %u bytes\n", __func__, length); - if (!name) { - file = STDOUT_FILENO; - exit(EXIT_FAILURE); - } else { - file = open(name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); - if (file == -1) { - fprintf(stderr, "Unable to open file '%s'\n", name); - exit(EXIT_FAILURE); - } - } - - /* Write a header, will update with size once record is complete */ - if (!streamed) { - init_wave_header(&header, channels, rate, samplebits); - written = write(file, &header, sizeof(header)); - if (written != sizeof(header)) { - fprintf(stderr, "Error writing output file header: %s\n", - strerror(errno)); - goto file_exit; - } - } - - memset(&codec, 0, sizeof(codec)); - memset(&config, 0, sizeof(config)); - codec.id = SND_AUDIOCODEC_PCM; - codec.ch_in = channels; - codec.ch_out = channels; - codec.sample_rate = rate; - if (!codec.sample_rate) { - fprintf(stderr, "invalid sample rate %d\n", rate); - goto file_exit; - } - codec.format = format; - if ((buffer_size != 0) && (frag != 0)) { - config.fragment_size = buffer_size/frag; - config.fragments = frag; - } - config.codec = &codec; - - mixer = mixer_open(card); - if (!mixer) { - printf("Failed to open mixer\n"); - goto file_exit; - } - - /* set device/audio_intf media config mixer control */ - if (set_agm_device_media_config(mixer, intf_name, dev_config)) { - printf("Failed to set device media config\n"); - goto mixer_exit; - } - - /* set audio interface metadata mixer control */ - if (set_agm_audio_intf_metadata(mixer, intf_name, device_kv, CAPTURE, - dev_config->rate, dev_config->bits, stream_kv)) { - printf("Failed to set device metadata\n"); - goto mixer_exit; - } - - /* set audio interface metadata mixer control */ - /* Change pcm_record to compress_record */ - if (set_agm_capture_stream_metadata(mixer, device, stream_kv, CAPTURE, STREAM_COMPRESS, - instance_kv)) { - printf("Failed to set pcm metadata\n"); - goto mixer_exit; - } - - if (devicepp_kv != 0) { - if (set_agm_streamdevice_metadata(mixer, device, stream_kv, CAPTURE, STREAM_COMPRESS, - intf_name, devicepp_kv)) { - printf("Failed to set pcm metadata\n"); - goto mixer_exit; - } - } - - ret = agm_mixer_get_miid (mixer, device, intf_name, STREAM_COMPRESS, TAG_STREAM_MFC, &miid); - if (ret) { - printf("MFC not present for this graph"); - } else { - if (configure_mfc(mixer, device, intf_name, TAG_STREAM_MFC, - STREAM_COMPRESS, rate, channels, pcm_format_to_bits(format), miid)) { - printf("Failed to configure pspd mfc\n"); - goto mixer_exit; - } - } - - /* Note: No common metadata as of now*/ - - /* connect stream to audio intf */ - if (connect_agm_audio_intf_to_stream(mixer, device, intf_name, STREAM_COMPRESS, true)) { - printf("Failed to connect stream to audio interface\n"); - goto mixer_exit; - } - - compress = compress_open(card, device, COMPRESS_OUT, &config); - if (!compress || !is_compress_ready(compress)) { - fprintf(stderr, "Unable to open Compress device %d:%d\n", - card, device); - fprintf(stderr, "ERR: %s\n", compress_get_error(compress)); - goto mixer_exit; - }; - - if (verbose) - fprintf(finfo, "%s: Opened compress device\n", __func__); - - size = config.fragment_size; - buffer = malloc(size * config.fragments); - if (!buffer) { - fprintf(stderr, "Unable to allocate %d bytes\n", size); - goto comp_exit; - } - - fprintf(finfo, "Recording file %s On Card %u device %u, with buffer of %lu bytes\n", - name, card, device, buffer_size); - fprintf(finfo, "Codec %u Format %u Channels %u, %u Hz\n", - codec.id, codec.format, codec.ch_out, rate); - - compress_start(compress); - - if (verbose) - fprintf(finfo, "%s: Capturing audio NOW!!!\n", __func__); - - do { - read = compress_read(compress, buffer, size); - if (read < 0) { - fprintf(stderr, "Error reading sample\n"); - fprintf(stderr, "ERR: %s\n", compress_get_error(compress)); - goto buf_exit; - } - if ((unsigned int)read != size) { - fprintf(stderr, "We read %d, DSP sent %d\n", - size, read); - } - - if (read > 0) { - total_read += read; - - written = write(file, buffer, read); - if (written != (size_t)read) { - fprintf(stderr, "Error writing output file: %s\n", - strerror(errno)); - goto buf_exit; - } - if (verbose) { - print_time(compress); - fprintf(finfo, "%s: read %d\n", __func__, read); - } - } - } while (!length || total_read < length); - - ret = compress_stop(compress); - if (ret < 0) { - fprintf(stderr, "Error closing stream\n"); - fprintf(stderr, "ERR: %s\n", compress_get_error(compress)); - } - - ret = finish_record(); - if (ret < 0) { - fprintf(stderr, "Failed to finish header: %s\n", strerror(ret)); - goto buf_exit; - } - - if (verbose) - fprintf(finfo, "%s: exit success\n", __func__); - - free(buffer); - close(file); - file = 0; - - compress_close(compress); - - return; -buf_exit: - free(buffer); -comp_exit: - compress_close(compress); - connect_agm_audio_intf_to_stream(mixer, device, intf_name, STREAM_COMPRESS, false); -mixer_exit: - mixer_close(mixer); -file_exit: - close(file); - - if (verbose) - fprintf(finfo, "%s: exit failure\n", __func__); - - exit(EXIT_FAILURE); -} - -static void sig_handler(int signum __attribute__ ((unused))) -{ - finish_record(); - - if (file) - close(file); - - _exit(EXIT_FAILURE); -} - -int main(int argc, char **argv) -{ - char *file = NULL; - unsigned long buffer_size = 0; - unsigned int card = 0, device = 0, frag = 0, length = 0; - unsigned int rate = DEFAULT_RATE, channels = DEFAULT_CHANNELS; - unsigned int bits = 16; - unsigned int format = DEFAULT_FORMAT; - char* intf_name = NULL; - int ret = 0; - unsigned int devicepp_kv = DEVICEPP_TX_AUDIO_FLUENCE_SMECNS; - unsigned int stream_kv = 0; - unsigned int instance_kv = INSTANCE_1; - struct device_config config; - unsigned int device_kv = 0; - - if (signal(SIGINT, sig_handler) == SIG_ERR) { - fprintf(stderr, "Error registering signal handler\n"); - exit(EXIT_FAILURE); - } - - if (argc < 3) - usage(); - - verbose = 0; - - file = argv[1]; - /* parse command line arguments */ - argv += 2; - while (*argv) { - if (strcmp(*argv, "-d") == 0) { - argv++; - if (*argv) - device = atoi(*argv); - } else if (strcmp(*argv, "-c") == 0) { - argv++; - if (*argv) - channels = atoi(*argv); - } else if (strcmp(*argv, "-r") == 0) { - argv++; - if (*argv) - rate = atoi(*argv); - } else if (strcmp(*argv, "-b") == 0) { - argv++; - if (*argv) - bits = atoi(*argv); - } else if (strcmp(*argv, "-D") == 0) { - argv++; - if (*argv) - card = atoi(*argv); - } else if (strcmp(*argv, "-l") == 0) { - argv++; - if (*argv) - length = atoi(*argv); - } else if (strcmp(*argv, "-i") == 0) { - argv++; - if (*argv) - intf_name = *argv; - } else if (strcmp(*argv, "-dkv") == 0) { - argv++; - if (*argv) - device_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-skv") == 0) { - argv++; - if (*argv) - stream_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-ikv") == 0) { - argv++; - if (*argv) - instance_kv = atoi(*argv); - } else if (strcmp(*argv, "-dppkv") == 0) { - argv++; - if (*argv) - devicepp_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-buf") == 0) { - argv++; - if (*argv) - buffer_size = atoi(*argv); - } else if (strcmp(*argv, "-f") == 0) { - argv++; - if (*argv) - frag = atoi(*argv); - } else if (strcmp(*argv, "-v") == 0) { - argv++; - if (*argv) - verbose = atoi(*argv); - } else if (strcmp(*argv, "-help") == 0) { - usage(); - } - if (*argv) - argv++; - } - - if (intf_name == NULL) { - printf("Invalid audio interface index denoted by -i\n"); - exit(EXIT_FAILURE); - } - - ret = get_device_media_config(BACKEND_CONF_FILE, intf_name, &config); - if (ret) { - printf("Invalid input, entry not found for %s\n", intf_name); - fclose(file); - return ret; - } - - switch (bits) { - case 32: - format = SNDRV_PCM_FORMAT_S32_LE; - break; - default: - format = SNDRV_PCM_FORMAT_S16_LE; - break; - } - capture_samples(file, card, device, buffer_size, frag, length, - rate, channels, format, &config, stream_kv, device_kv, instance_kv, - devicepp_kv); - - fprintf(finfo, "Finish capturing... Close Normally\n"); - - exit(EXIT_SUCCESS); -} - diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/agmcompressplay.c b/qcom/opensource/agm/plugins/tinyalsa/test/agmcompressplay.c deleted file mode 100755 index b88ad8e8..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/agmcompressplay.c +++ /dev/null @@ -1,653 +0,0 @@ -/* - * Copyright (c) 2019, 2021, The Linux Foundation. All rights reserved. - * This code is used under the BSD license. - * - * BSD LICENSE - * - * Copyright (c) 2011-2012, Intel Corporation - * All rights reserved. - * - * Author: Vinod Koul - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * Neither the name of Intel Corporation nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - * - * LGPL LICENSE - * - * Copyright (c) 2011-2012, Intel Corporation. - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU Lesser General Public License, - * version 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public - * License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to - * the Free Software Foundation, Inc., - * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#define __force -//#define __bitwise -#define __user -#include -#include - -#include "agmmixer.h" - - -#define MP3_SYNC 0xe0ff - -const int mp3_sample_rates[3][3] = { - {44100, 48000, 32000}, /* MPEG-1 */ - {22050, 24000, 16000}, /* MPEG-2 */ - {11025, 12000, 8000}, /* MPEG-2.5 */ -}; - -const int mp3_bit_rates[3][3][15] = { - { - /* MPEG-1 */ - { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448}, /* Layer 1 */ - { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384}, /* Layer 2 */ - { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320}, /* Layer 3 */ - }, - { - /* MPEG-2 */ - { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256}, /* Layer 1 */ - { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, /* Layer 2 */ - { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, /* Layer 3 */ - }, - { - /* MPEG-2.5 */ - { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256}, /* Layer 1 */ - { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, /* Layer 2 */ - { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, /* Layer 3 */ - }, -}; - -enum mpeg_version { - MPEG1 = 0, - MPEG2 = 1, - MPEG25 = 2 -}; - -enum mp3_stereo_mode { - STEREO = 0x00, - JOINT = 0x01, - DUAL = 0x02, - MONO = 0x03 -}; - -static int verbose; - -static void usage(void) -{ - fprintf(stderr, "usage: cplay [OPTIONS] filename\n" - "-D\tcard number\n" - "-d\tdevice node\n" - "-b\tbuffer size\n" - "-f\tfragments\n\n" - "-v\tverbose mode\n" - "-help\tPrints this help list\n\n" - "-t\tcodec type\n\n" - "1 : mp3" - "2 : aac" - "-p\tpause/resume with 2 secs sleep\n\n" - " [-num_intf num of interfaces followed by interface name]\n" - " [-i intf_name] : Can be multiple if num_intf is more than 1\n" - " [-dkv device_kv] : Can be multiple if num_intf is more than 1\n" - " [-dppkv deviceppkv] : Assign 0 if no device pp in the graph\n" - " [-ikv instance_kv] : Assign 0 if no instance kv in the graph\n" - " [-skv stream_kv]"); - - exit(EXIT_FAILURE); -} - -void play_samples(char *name, unsigned int card, unsigned int device, unsigned int *device_kv, - unsigned int stream_kv, unsigned int instance_kv, unsigned int *devicepp_kv, - unsigned long buffer_size, unsigned int frag, unsigned int format, - int pause, char **intf_name, int intf_num); - -struct mp3_header { - uint16_t sync; - uint8_t format1; - uint8_t format2; -}; - -#define ADTS_SYNC 0xF0FF -#define MP3_FORMAT 1 -#define AAC_ADTS_FORMAT 2 - -struct adts_header { - uint32_t sync; - uint8_t format1; - uint8_t format2; - uint8_t format3; -}; - -uint aac_sample_rates[] = {96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350, 48000, 48000, 48000}; - -int parse_aac_header(struct adts_header *header, unsigned int *num_channels, - unsigned int *sample_rate, unsigned int *protection_absent) -{ - int profile, sample_rate_idx; - - /* check sync bits */ - if ((header->sync & 0xF0FF) != ADTS_SYNC) { - fprintf(stderr, "Error: Can't find sync word: 0x%X\n", header->sync); - return -1; - } - *protection_absent = (header->sync >> 8) & 0x01; - profile = ((header->sync >> 22) & 0x03) - 1; - sample_rate_idx = ((header->sync >> 18) & 0x0F); -// channel_idx = ((header->format1 >> 7) & 0x07); -// frame_length = ((header->format1 >> 14) & 0x1FFF); - - *num_channels = 2; - *sample_rate = aac_sample_rates[sample_rate_idx]; -// *size = frame_length - ((protection_absent == 1)? 7: 9)); - - if (verbose) - printf("%s: exit sr %d\n", __func__, *sample_rate); - return 0; -} - -int parse_mp3_header(struct mp3_header *header, unsigned int *num_channels, - unsigned int *sample_rate, unsigned int *bit_rate) -{ - int ver_idx, mp3_version, layer, bit_rate_idx, sample_rate_idx, channel_idx; - - /* check sync bits */ - if ((header->sync & MP3_SYNC) != MP3_SYNC) { - fprintf(stderr, "Error: Can't find sync word\n"); - return -1; - } - ver_idx = (header->sync >> 11) & 0x03; - mp3_version = ver_idx == 0 ? MPEG25 : ((ver_idx & 0x1) ? MPEG1 : MPEG2); - layer = 4 - ((header->sync >> 9) & 0x03); - bit_rate_idx = ((header->format1 >> 4) & 0x0f); - sample_rate_idx = ((header->format1 >> 2) & 0x03); - channel_idx = ((header->format2 >> 6) & 0x03); - - if (sample_rate_idx == 3 || layer == 4 || bit_rate_idx == 15) { - fprintf(stderr, "Error: Can't find valid header\n"); - return -1; - } - *num_channels = (channel_idx == MONO ? 1 : 2); - *sample_rate = mp3_sample_rates[mp3_version][sample_rate_idx]; - *bit_rate = (mp3_bit_rates[mp3_version][layer - 1][bit_rate_idx]) * 1000; - if (verbose) - printf("%s: exit\n", __func__); - return 0; -} - -int check_codec_format_supported(unsigned int card, unsigned int device, struct snd_codec *codec) -{ - if (is_codec_supported(card, device, COMPRESS_IN, codec) == false) { - fprintf(stderr, "Error: This codec or format is not supported by DSP\n"); - return -1; - } - return 0; -} - -static int print_time(struct compress *compress) -{ - unsigned int avail; - struct timespec tstamp; - - if (compress_get_hpointer(compress, &avail, &tstamp) != 0) { - fprintf(stderr, "Error querying timestamp\n"); - fprintf(stderr, "ERR: %s\n", compress_get_error(compress)); - return -1; - } else - fprintf(stderr, "DSP played %ld.%ld\n", tstamp.tv_sec, tstamp.tv_nsec*1000); - return 0; -} - -int main(int argc, char **argv) -{ - char *file; - unsigned long buffer_size = 0; - char **intf_name = NULL; - int ret = 0, i = 0; - unsigned int card = 0, device = 0, frag = 0, audio_format = 0, pause = 0; - int intf_num = 1; - uint32_t dkv = SPEAKER; - uint32_t dppkv = DEVICEPP_RX_AUDIO_MBDRC; - unsigned int stream_kv = 0; - unsigned int instance_kv = INSTANCE_1; - unsigned int *device_kv = (unsigned int *) malloc(intf_num * sizeof(unsigned int)); - unsigned int *devicepp_kv = (unsigned int *) malloc(intf_num * sizeof(unsigned int)); - - if (!device_kv || !devicepp_kv) { - printf(" insufficient memory\n"); - return 1; - } - - if (argc < 3) { - usage(); - return 1; - } - - device_kv[0] = dkv; - devicepp_kv[0] = dppkv; - - file = argv[1]; - /* parse command line arguments */ - argv += 2; - while (*argv) { - if (strcmp(*argv, "-d") == 0) { - argv++; - if (*argv) - device = atoi(*argv); - } else if (strcmp(*argv, "-t") == 0) { - argv++; - if (*argv) - audio_format = atoi(*argv); - } else if (strcmp(*argv, "-D") == 0) { - argv++; - if (*argv) - card = atoi(*argv); - } else if (strcmp(*argv, "-p") == 0) { - argv++; - if (*argv) - pause = atoi(*argv); - } else if (strcmp(*argv, "-f") == 0) { - argv++; - if (*argv) - frag = atoi(*argv); - } else if (strcmp(*argv, "-v") == 0) { - argv++; - if (*argv) - verbose = atoi(*argv); - } else if (strcmp(*argv, "-num_intf") == 0) { - argv++; - if (*argv) - intf_num = atoi(*argv); - } else if (strcmp(*argv, "-i") == 0) { - intf_name = (char**) malloc(intf_num * sizeof(char*)); - if (!intf_name) { - printf("insufficient memory\n"); - return 1; - } - for (i = 0; i < intf_num ; i++){ - argv++; - if (*argv) - intf_name[i] = *argv; - } - } else if (strcmp(*argv, "-dkv") == 0) { - device_kv = (unsigned int *) realloc(device_kv, intf_num * sizeof(unsigned int)); - if (!device_kv) { - printf(" insufficient memory\n"); - return 1; - } - for (i = 0; i < intf_num ; i++) { - argv++; - if (*argv) { - device_kv[i] = convert_char_to_hex(*argv); - } - } - } else if (strcmp(*argv, "-skv") == 0) { - argv++; - if (*argv) - stream_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-ikv") == 0) { - argv++; - if (*argv) { - instance_kv = atoi(*argv); - } - } else if (strcmp(*argv, "-dppkv") == 0) { - devicepp_kv = (unsigned int *) realloc(devicepp_kv, intf_num * sizeof(unsigned int)); - if (!devicepp_kv) { - printf(" insufficient memory\n"); - return 1; - } - for (i = 0; i < intf_num ; i++) { - devicepp_kv[i] = DEVICEPP_RX_AUDIO_MBDRC; - } - for (i = 0; i < intf_num ; i++) - { - argv++; - if(*argv) { - devicepp_kv[i] = convert_char_to_hex(*argv); - } - } - } else if (strcmp(*argv, "-help") == 0) { - usage(); - } - - if (*argv) - argv++; - } - - if (intf_name == NULL) - return 1; - - play_samples(file, card, device, device_kv, stream_kv, instance_kv, devicepp_kv, - buffer_size, frag, audio_format, pause, - intf_name, intf_num); - - fprintf(stderr, "Finish Playing.... Close Normally\n"); - if (device_kv) - free(device_kv); - if (devicepp_kv) - free(devicepp_kv); - if (intf_name) - free(intf_name); - exit(EXIT_SUCCESS); -} - -void play_samples(char *name, unsigned int card, unsigned int device, unsigned int *device_kv, - unsigned int stream_kv, unsigned int instance_kv, unsigned int *devicepp_kv, - unsigned long buffer_size, unsigned int frag, unsigned int format, - int pause, char **intf_name, int intf_num) -{ - struct compr_config config; - struct snd_codec codec; - struct compress *compress; - struct mp3_header header; - struct adts_header adts_header; - struct mixer *mixer; - FILE *file; - char *buffer; - int num_read, wrote; - unsigned int channels = 0, rate = 0, bits = 0; - struct device_config *dev_config = NULL; - struct group_config *grp_config = NULL; - int size, index, ret = 0; - uint32_t miid = 0; - - dev_config = (struct device_config *) malloc(intf_num * sizeof(struct device_config)); - if (!dev_config) { - printf("Failed to allocate memory for dev config"); - return; - } - grp_config = (struct group_config *) malloc(intf_num * sizeof(struct group_config)); - if (!grp_config) { - printf("Failed to allocate memory for group config"); - return; - } - - stream_kv = stream_kv ? stream_kv : COMPRESSED_OFFLOAD_PLAYBACK; - - if (verbose) - printf("%s: entry\n", __func__); - file = fopen(name, "rb"); - if (!file) { - fprintf(stderr, "Unable to open file '%s'\n", name); - exit(EXIT_FAILURE); - } - - if (format == MP3_FORMAT) { - fread(&header, sizeof(header), 1, file); - - if (parse_mp3_header(&header, &channels, &rate, &bits) == -1) { - fclose(file); - exit(EXIT_FAILURE); - } - - codec.id = SND_AUDIOCODEC_MP3; -#ifdef SND_COMPRESS_DEC_HDR - } else if (format == AAC_ADTS_FORMAT) { - uint16_t protection_absent, crc; - fread(&adts_header, sizeof(adts_header), 1, file); - if (parse_aac_header(&adts_header, &channels, &rate, (unsigned int*)&protection_absent) == -1) { - fclose(file); - exit(EXIT_FAILURE); - } - if (!protection_absent) { - fread(&crc, 2, 1, file); - } - codec.id = SND_AUDIOCODEC_AAC; - codec.format = SND_AUDIOSTREAMFORMAT_MP4ADTS; - bits = 16; - codec.options.aac_dec.audio_obj_type = 29; - codec.options.aac_dec.pce_bits_size = 0; -#endif - } else { - printf("unknown format"); - } - codec.ch_in = channels; - codec.ch_out = channels; - codec.sample_rate = rate; - if (!codec.sample_rate) { - fprintf(stderr, "invalid sample rate %d\n", rate); - fclose(file); - exit(EXIT_FAILURE); - } - codec.bit_rate = bits; - codec.rate_control = 0; - codec.profile = 0; - codec.level = 0; - codec.ch_mode = 0; - codec.format = 0; - if ((buffer_size != 0) && (frag != 0)) { - config.fragment_size = buffer_size/frag; - config.fragments = frag; - } else { - /* use driver defaults */ - config.fragment_size = 0; - config.fragments = 0; - } - config.codec = &codec; - - mixer = mixer_open(card); - if (!mixer) { - printf("Failed to open mixer\n"); - goto FILE_EXIT; - } - for (index = 0; index < intf_num; index++) { - ret = get_device_media_config(BACKEND_CONF_FILE, intf_name[index], &dev_config[index]); - if (ret) { - printf("Invalid input, entry not found for : %s\n", intf_name[index]); - fclose(file); - } - printf("Backend %s rate ch bit : %d, %d, %d\n", intf_name[index], - dev_config[index].rate, dev_config[index].ch, dev_config[index].bits); - - /* set device/audio_intf media config mixer control */ - if (set_agm_device_media_config(mixer, intf_name[index], &dev_config[index])) { - printf("Failed to set device media config\n"); - goto MIXER_EXIT; - } - - /* set audio interface metadata mixer control */ - if (set_agm_audio_intf_metadata(mixer, intf_name[index], device_kv[index], PLAYBACK, - dev_config[index].rate, dev_config[index].bits, stream_kv)) { - printf("Failed to set device metadata\n"); - goto MIXER_EXIT; - } - } - - /* set audio interface metadata mixer control */ - if (set_agm_stream_metadata(mixer, device, stream_kv, PLAYBACK, STREAM_COMPRESS, - instance_kv)) { - printf("Failed to set stream metadata\n"); - goto MIXER_EXIT; - } - - /* Note: No common metadata as of now*/ - for (index = 0; index < intf_num; index++) { - if (devicepp_kv[index] != 0) { - if (set_agm_streamdevice_metadata(mixer, device, stream_kv, PLAYBACK, STREAM_COMPRESS, intf_name[index], - devicepp_kv[index])) { - printf("Failed to set pcm metadata\n"); - goto MIXER_EXIT; - } - } - - /* connect stream to audio intf */ - if (connect_agm_audio_intf_to_stream(mixer, device, intf_name[index], STREAM_COMPRESS, true)) { - printf("Failed to connect pcm to audio interface\n"); - goto MIXER_EXIT; - } - - ret = agm_mixer_get_miid (mixer, device, intf_name[index], STREAM_PCM, PER_STREAM_PER_DEVICE_MFC, &miid); - if (ret) { - printf("MFC not present for this graph\n"); - } else { - if (configure_mfc(mixer, device, intf_name[index], PER_STREAM_PER_DEVICE_MFC, - STREAM_COMPRESS, dev_config[index].rate, dev_config[index].ch, - dev_config[index].bits, miid)) { - printf("Failed to configure pspd mfc\n"); - goto MIXER_EXIT; - } - } - - if (strstr(intf_name[index], "VIRT-")) { - if (get_group_device_info(BACKEND_CONF_FILE, intf_name[index], &grp_config[index])) - goto MIXER_EXIT; - - if (set_agm_group_device_config(mixer, intf_name[index], &grp_config[index])) { - printf("Failed to set grp device config\n"); - goto MIXER_EXIT; - } - } - } - - - compress = compress_open(card, device, COMPRESS_IN, &config); - if (!compress || !is_compress_ready(compress)) { - fprintf(stderr, "Unable to open Compress device %d:%d\n", - card, device); - fprintf(stderr, "ERR: %s\n", compress_get_error(compress)); - goto MIXER_EXIT; - }; - if (verbose) - printf("%s: Opened compress device\n", __func__); - - for (index = 0; index < intf_num; index++) { - if (strstr(intf_name[index], "VIRT-") || (device_kv[index] == SPEAKER) || (device_kv[index] == HANDSET)) { - if (set_agm_group_mux_config(mixer, device, &grp_config[index], intf_name[index], dev_config[index].ch)) { - printf("Failed to set grp device config\n"); - } - } - } - size = config.fragment_size; - buffer = malloc(size * config.fragments); - if (!buffer) { - fprintf(stderr, "Unable to allocate %d bytes\n", size); - goto COMP_EXIT; - } - - /* we will write frag fragment_size and then start */ - num_read = fread(buffer, 1, size * config.fragments, file); - if (num_read > 0) { - if (verbose) - printf("%s: Doing first buffer write of %d\n", __func__, num_read); - wrote = compress_write(compress, buffer, num_read); - if (wrote < 0) { - fprintf(stderr, "Error %d playing sample\n", wrote); - fprintf(stderr, "ERR: %s\n", compress_get_error(compress)); - goto BUF_EXIT; - } - if (wrote != num_read) { - /* TODO: Buufer pointer needs to be set here */ - fprintf(stderr, "We wrote %d, DSP accepted %d\n", num_read, wrote); - } - } - printf("Playing file %s On Card %u device %u, with buffer of %lu bytes\n", - name, card, device, buffer_size); - printf("Format %u Channels %u, %u Hz, Bit Rate %d\n", - SND_AUDIOCODEC_MP3, channels, rate, bits); - - compress_start(compress); - if (verbose) - printf("%s: You should hear audio NOW!!!\n", __func__); - - do { - num_read = fread(buffer, 1, size, file); - if (num_read > 0) { - wrote = compress_write(compress, buffer, num_read); - if (wrote < 0) { - fprintf(stderr, "Error playing sample\n"); - fprintf(stderr, "ERR: %s\n", compress_get_error(compress)); - goto BUF_EXIT; - } - if (wrote != num_read) { - /* TODO: Buffer pointer needs to be set here */ - fprintf(stderr, "We wrote %d, DSP accepted %d\n", num_read, wrote); - } - if (verbose) { - print_time(compress); - printf("%s: wrote %d\n", __func__, wrote); - } - if (pause) { - printf("%s: pause \n", __func__); - compress_pause(compress); - sleep(2); - printf("%s: resume \n", __func__); - compress_resume(compress); - } - } - } while (num_read > 0); - - if (verbose) - printf("%s: exit success\n", __func__); - /* issue drain if it supports */ - compress_drain(compress); - /* disconnect stream to audio intf */ - for(index = 0; index < intf_num; index++) { - connect_agm_audio_intf_to_stream(mixer, device, intf_name[index], STREAM_COMPRESS, false); - } - free(buffer); - fclose(file); - compress_close(compress); - return; -BUF_EXIT: - free(buffer); -COMP_EXIT: - compress_close(compress); -MIXER_EXIT: - if (dev_config) - free(dev_config); - if (grp_config) - free(grp_config); - mixer_close(mixer); -FILE_EXIT: - fclose(file); - if (verbose) - printf("%s: exit failure\n", __func__); - exit(EXIT_FAILURE); -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/agmhostless.c b/qcom/opensource/agm/plugins/tinyalsa/test/agmhostless.c deleted file mode 100755 index 7cdd1a23..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/agmhostless.c +++ /dev/null @@ -1,392 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "agmmixer.h" - -static int close_f = 0; - -void sigint_handler(int sig) -{ - close_f = 1; -} - -void play_loopback(unsigned int card, unsigned int p_device, unsigned int c_device, unsigned int channels, - unsigned int rate, enum pcm_format format, struct device_config *cap_config, - struct device_config *p_config, unsigned int period_size, - unsigned int period_count, unsigned int play_cap_time, char* capture_intf, - char* play_intf, unsigned int pdkv, unsigned int cdkv, unsigned int stream_kv, - unsigned int do_loopback); - -void usage() -{ - printf(" Usage: %s [-D card] [-P Hostless Playback device] [-C Hostless Capture device] [-p period_size]\n" - " [-n n_periods] [-c channels] [-r rate] [-b bits] [-T playback/capture time ]\n" - " [-i capture intf] [-o playback intf]\n" - " [-cdkv capture_device_kv] [-pdkv playback_device_kv] [-skv stream_kv]\n" - " Used to enable 'hostless' mode for audio devices with a DSP back-end.\n" - " Alternatively, specify '-l' for loopback mode: this program will read\n" - " from the capture device and write to the playback device.\n"); -} - -int main(int argc, char **argv) -{ - unsigned int card = 100; - unsigned int p_device = 1; - unsigned int c_device = 0; - unsigned int period_size = 1024; - unsigned int period_count = 4; - unsigned int bits = 16; - unsigned int num_channels = 2; - unsigned int sample_rate = 48000; - unsigned int play_cap_time = 10; - char* c_intf_name = NULL; - char* p_intf_name = NULL; - unsigned int do_loopback = 0; - enum pcm_format format; - struct device_config capture_config; - struct device_config play_config; - unsigned int c_device_kv = 0; - unsigned int p_device_kv = 0; - unsigned int stream_kv = 0; - unsigned int ret = 0; - - if (argc < 2) { - usage(); - return 1; - } - - /* parse command line arguments */ - argv += 1; - while (*argv) { - if (strcmp(*argv, "-P") == 0) { - argv++; - if (*argv) - p_device = atoi(*argv); - } else if (strcmp(*argv, "-C") == 0) { - argv++; - if (*argv) - c_device = atoi(*argv); - } else if (strcmp(*argv, "-p") == 0) { - argv++; - if (*argv) - period_size = atoi(*argv); - } else if (strcmp(*argv, "-n") == 0) { - argv++; - if (*argv) - period_count = atoi(*argv); - } else if (strcmp(*argv, "-c") == 0) { - argv++; - if (*argv) - num_channels = atoi(*argv); - } else if (strcmp(*argv, "-r") == 0) { - argv++; - if (*argv) - sample_rate = atoi(*argv); - } else if (strcmp(*argv, "-b") == 0) { - argv++; - if (*argv) - bits = atoi(*argv); - } else if (strcmp(*argv, "-T") == 0) { - argv++; - if (*argv) - play_cap_time = atoi(*argv); - } else if (strcmp(*argv, "-D") == 0) { - argv++; - if (*argv) - card = atoi(*argv); - } else if (strcmp(*argv, "-i") == 0) { - argv++; - if (*argv) - c_intf_name = *argv; - } else if (strcmp(*argv, "-o") == 0) { - argv++; - if (*argv) - p_intf_name = *argv; - } else if (strcmp(*argv, "-l") == 0) { - do_loopback = 1; - } else if (strcmp(*argv, "-skv") == 0) { - argv++; - if (*argv) - stream_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-cdkv") == 0) { - argv++; - if (*argv) - c_device_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-pdkv") == 0) { - argv++; - if (*argv) - p_device_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-help") == 0) { - usage(); - } - - if (*argv) - argv++; - } - - ret = get_device_media_config(BACKEND_CONF_FILE, c_intf_name, &capture_config); - if (ret) { - printf("Invalid input, assigning default values for : %s\n", c_intf_name); - capture_config.rate = sample_rate; - capture_config.bits = bits; - capture_config.ch = num_channels; - } - - ret = get_device_media_config(BACKEND_CONF_FILE, p_intf_name, &play_config); - if (ret) { - printf("Invalid input, assigning default values for : %s\n", p_intf_name); - play_config.rate = sample_rate; - play_config.bits = bits; - play_config.ch = num_channels; - } - - switch (bits) { - case 32: - format = PCM_FORMAT_S32_LE; - break; - case 24: - format = PCM_FORMAT_S24_LE; - break; - case 16: - format = PCM_FORMAT_S16_LE; - break; - default: - printf("%u bits is not supported.\n", bits); - return 1; - } - play_loopback(card, p_device, c_device, num_channels, sample_rate, format, &capture_config, &play_config, period_size, - period_count, play_cap_time, c_intf_name, p_intf_name, p_device_kv, - c_device_kv, stream_kv, do_loopback); - - return 0; -} - -void play_loopback(unsigned int card, unsigned int p_device, unsigned int c_device, unsigned int channels, - unsigned int rate, enum pcm_format format, struct device_config *cap_config, - struct device_config *p_config, unsigned int period_size, - unsigned int period_count, unsigned int play_cap_time, char* capture_intf, - char* play_intf, unsigned int pdkv, unsigned int cdkv, unsigned int stream_kv, - unsigned int do_loopback) -{ - struct pcm_config config; - struct pcm *p_pcm, *c_pcm; - struct mixer *mixer; - char *buffer = NULL; - char *p_intf_name = play_intf; - char *c_intf_name = capture_intf; - unsigned int size; - unsigned int bytes_read = 0; - unsigned int frames = 0, ret = 0, miid = 0; - struct timespec end; - struct timespec now; - struct group_config grp_config; - stream_kv = stream_kv ? stream_kv : PCM_RX_LOOPBACK; - - if (!cap_config || !p_config || !capture_intf || !play_intf) { - printf("%s: %d: Invalid arguments.\n", __func__, __LINE__); - return; - } - - memset(&config, 0, sizeof(config)); - config.channels = channels; - config.rate = rate; - config.period_size = period_size; - config.period_count = period_count; - config.format = format; - config.start_threshold = 0; - config.stop_threshold = 0; - config.silence_threshold = 0; - - mixer = mixer_open(card); - if (!mixer) { - printf("Failed to open mixer\n"); - return; - } - - /* set device/audio_intf media config mixer control */ - if (set_agm_device_media_config(mixer, p_intf_name, p_config)) { - printf("Failed to set playback device media config\n"); - goto err_close_mixer; - } - - if (set_agm_device_media_config(mixer, c_intf_name, cap_config)) { - printf("Failed to set capture device media config\n"); - goto err_close_mixer; - } - - /* set audio interface metadata mixer control */ - if (set_agm_audio_intf_metadata(mixer, c_intf_name, cdkv, CAPTURE, rate, cap_config->bits, stream_kv)) { - printf("Failed to set capture device metadata\n"); - goto err_close_mixer; - } - - if (set_agm_audio_intf_metadata(mixer, p_intf_name, pdkv, PLAYBACK, rate, p_config->bits, stream_kv)) { - printf("Failed to set playback device metadata\n"); - goto err_close_mixer; - } - - if (set_agm_stream_metadata(mixer, p_device, stream_kv, LOOPBACK, STREAM_PCM, - 0)) { - printf("Failed to capture stream metadata\n"); - goto err_close_mixer; - } - - /* Note: No common metadata as of now*/ - - /* connect pcm stream to audio intf */ - if (connect_agm_audio_intf_to_stream(mixer, p_device, p_intf_name, STREAM_PCM, true)) { - printf("Failed to connect playback pcm to audio interface\n"); - goto err_close_mixer; - } - - if (connect_agm_audio_intf_to_stream(mixer, c_device, c_intf_name, STREAM_PCM, true)) { - printf("Failed to connect capture pcm to audio interface\n"); - connect_agm_audio_intf_to_stream(mixer, p_device, p_intf_name, STREAM_PCM, false); - goto err_close_mixer; - } - - if (connect_play_pcm_to_cap_pcm(mixer, p_device, c_device)) { - printf("Failed to connect capture pcm to audio interface\n"); - goto err_disconnect; - } - - if (strstr(p_intf_name, "VIRT-")) { - if (get_group_device_info(BACKEND_CONF_FILE, p_intf_name, &grp_config)) - goto err_disconnect; - - if (set_agm_group_device_config(mixer, p_intf_name, &grp_config)) { - printf("Failed to set grp device config\n"); - goto err_disconnect; - } - } - ret = agm_mixer_get_miid (mixer, p_device, p_intf_name, STREAM_PCM, PER_STREAM_PER_DEVICE_MFC, &miid); - if (ret) { - printf("MFC not present for this graph\n"); - } else { - if (configure_mfc(mixer, p_device, p_intf_name, PER_STREAM_PER_DEVICE_MFC, - STREAM_PCM, p_config->rate, p_config->ch, - p_config->bits, miid)) { - printf("Failed to configure pspd mfc\n"); - goto err_disconnect; - } - } - - p_pcm = pcm_open(card, p_device, PCM_OUT, &config); - if (!p_pcm || !pcm_is_ready(p_pcm)) { - printf("Unable to open playback PCM device (%s)\n", - pcm_get_error(p_pcm)); - goto err_disconnect; - } - if (strstr(p_intf_name, "VIRT-") || (pdkv == SPEAKER) || (pdkv == HANDSET)) { - if (set_agm_group_mux_config(mixer, p_device, &grp_config, p_intf_name, p_config->ch)) { - printf("Failed to set mux config\n"); - goto err_close_p_pcm; - } - } - - if (pcm_start(p_pcm) < 0) { - printf("start error"); - goto err_close_p_pcm; - } - - c_pcm = pcm_open(card, c_device, PCM_IN, &config); - if (!c_pcm || !pcm_is_ready(c_pcm)) { - printf("Unable to open playback PCM device (%s)\n", - pcm_get_error(c_pcm)); - goto err_close_p_pcm; - } - - if (pcm_start(c_pcm) < 0) { - printf("start error"); - goto err_close_c_pcm; - } - - if (do_loopback) { - size = pcm_frames_to_bytes(c_pcm, pcm_get_buffer_size(c_pcm)); - buffer = malloc(size); - if (!buffer) { - printf("Unable to allocate %d bytes\n", size); - goto err_close_c_pcm; - } - } - - clock_gettime(CLOCK_MONOTONIC, &end); - end.tv_sec += play_cap_time; - while (1) { - if (close_f) - break; - if (do_loopback) { - if (pcm_read(c_pcm, buffer, size)) { - printf("Unable to read from PCM capture device %u (%s)\n", - c_device, pcm_get_error(c_pcm)); - break; - } - if (pcm_write(p_pcm, buffer, size)) { - printf("Unable to write to PCM playback device %u (%s)\n", - p_device, pcm_get_error(p_pcm)); - break; - } - } else { - usleep(100000); - } - - if (play_cap_time) { - clock_gettime(CLOCK_MONOTONIC, &now); - if (now.tv_sec > end.tv_sec || - (now.tv_sec == end.tv_sec && now.tv_nsec >= end.tv_nsec)) - break; - } - } - connect_play_pcm_to_cap_pcm(mixer, -1, c_device); -err_close_c_pcm: - pcm_close(c_pcm); -err_close_p_pcm: - if (buffer) - free(buffer); - pcm_close(p_pcm); -err_disconnect: - connect_agm_audio_intf_to_stream(mixer, p_device, p_intf_name, STREAM_PCM, false); - connect_agm_audio_intf_to_stream(mixer, c_device, c_intf_name, STREAM_PCM, false); -err_close_mixer: - mixer_close(mixer); -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/agmmixer.c b/qcom/opensource/agm/plugins/tinyalsa/test/agmmixer.c deleted file mode 100755 index ccbdf44a..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/agmmixer.c +++ /dev/null @@ -1,1625 +0,0 @@ -/* -** Copyright (c) 2019, 2021, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022-2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "agmmixer.h" - -#define EVENT_ID_DETECTION_ENGINE_GENERIC_INFO 0x0800104F - -#define PARAM_ID_DETECTION_ENGINE_GENERIC_EVENT_CFG 0x0800104E -#define PARAM_ID_MFC_OUTPUT_MEDIA_FORMAT 0x08001024 - -#define PARAM_ID_USB_AUDIO_INTF_CFG 0x080010D6 - -enum { - DEVICE = 1, - GROUP, -}; - -enum pcm_channel_map -{ - PCM_CHANNEL_L = 1, - PCM_CHANNEL_R = 2, - PCM_CHANNEL_C = 3, - PCM_CHANNEL_LS = 4, - PCM_CHANNEL_RS = 5, - PCM_CHANNEL_LFE = 6, - PCM_CHANNEL_CS = 7, - PCM_CHANNEL_CB = PCM_CHANNEL_CS, - PCM_CHANNEL_LB = 8, - PCM_CHANNEL_RB = 9, -}; -/* Payload of the PARAM_ID_MFC_OUTPUT_MEDIA_FORMAT parameter in the - Media Format Converter Module. Following this will be the variable payload for channel_map. */ -struct param_id_mfc_output_media_fmt_t -{ - int32_t sampling_rate; - int16_t bit_width; - int16_t num_channels; - uint16_t channel_type[0]; -}__attribute__((packed)); - -struct apm_module_param_data_t -{ - uint32_t module_instance_id; - uint32_t param_id; - uint32_t param_size; - uint32_t error_code; -}; - -struct param_id_usb_audio_intf_cfg_t -{ - uint32_t usb_token; - /**< @h2xmle_description {Valid token for the USB audio device} */ - uint32_t svc_interval; - /**< @h2xmle_description {USB device service interval in microseconds. Though the acceptable - values are between 125- 3276800, the actual supported values are - determined by the equation specified in USB 3.0 documentation.} - @h2xmle_range {125..3276800} - @h2xmle_default {125} - */ -}; - -struct detection_engine_generic_event_cfg { - uint32_t event_mode; -}; - - -struct gsl_module_id_info_entry { - uint32_t module_id; /**< module id */ - uint32_t module_iid; /**< globally unique module instance id */ -}; - -/** - * Structure mapping the tag_id to module info (mid and miid) - */ -struct gsl_tag_module_info_entry { - uint32_t tag_id; /**< tag id of the module */ - uint32_t num_modules; /**< number of modules matching the tag_id */ - struct gsl_module_id_info_entry module_entry[0]; /**< module list */ -}; - -struct gsl_tag_module_info { - uint32_t num_tags; /**< number of tags */ - struct gsl_tag_module_info_entry tag_module_entry[0]; - /**< variable payload of type struct gsl_tag_module_info_entry */ -}; - -unsigned int slot_mask_map[5] = { 0, SLOT_MASK1, SLOT_MASK3, SLOT_MASK7, SLOT_MASK15}; - -#define PADDING_8BYTE_ALIGN(x) ((((x) + 7) & 7) ^ 7) - -static unsigned int bits_to_sndrv_format(unsigned int bits) -{ - switch (bits) { - case 32: - return SNDRV_PCM_FORMAT_S32_LE; - case 8: - return SNDRV_PCM_FORMAT_S8; - case 24: - return SNDRV_PCM_FORMAT_S24_3LE; - default: - case 16: - return SNDRV_PCM_FORMAT_S16_LE; - }; -} - -static unsigned int alsa_to_sndrv_format(enum pcm_format fmt) -{ - switch (fmt) { - case PCM_FORMAT_S32_LE: - return SNDRV_PCM_FORMAT_S32_LE; - case PCM_FORMAT_S8: - return SNDRV_PCM_FORMAT_S8; - case PCM_FORMAT_S24_3LE: - return SNDRV_PCM_FORMAT_S24_3LE; - case PCM_FORMAT_S24_LE: - return SNDRV_PCM_FORMAT_S24_LE; - default: - case PCM_FORMAT_S16_LE: - return SNDRV_PCM_FORMAT_S16_LE; - }; -} - -static enum pcm_format get_pcm_format(char *str) -{ - if (!strncmp(str, "PCM_FORMAT_S16_LE", strlen("PCM_FORMAT_S16_LE"))) { - return PCM_FORMAT_S16_LE; - } else if (!strncmp(str, "PCM_FORMAT_S32_LE", strlen("PCM_FORMAT_S32_LE"))) { - return PCM_FORMAT_S32_LE; - } else if (!strncmp(str, "PCM_FORMAT_S8", strlen("PCM_FORMAT_S8"))) { - return PCM_FORMAT_S8; - } else if (!strncmp(str, "PCM_FORMAT_S24_LE", strlen("PCM_FORMAT_S24_LE"))) { - return PCM_FORMAT_S24_LE; - } else if (!strncmp(str, "PCM_FORMAT_S24_3LE", strlen("PCM_FORMAT_S24_3LE"))) { - return PCM_FORMAT_S24_3LE; - } else { - return PCM_FORMAT_INVALID; - } -} - -int get_pcm_bit_width(enum pcm_format fmt_id) -{ - int bit_width = 16; - - switch (fmt_id) { - case PCM_FORMAT_S24_3LE: - /* - *This api returns the number of audio data bit width specific to the format - *e.g. In S24_LE, even if the number of bytes is 4, the audio data is only in 3 bytes - *Hence we return 24 as the bit_width, whereas the bitspersample for this format would - *return 32 - */ - case PCM_FORMAT_S24_LE: - bit_width = 24; - break; - case PCM_FORMAT_S32_LE: - bit_width = 32; - break; - case PCM_FORMAT_S8: - bit_width = 8; - case PCM_FORMAT_S16_LE: - default: - break; - } - - return bit_width; -} - -void start_tag(void *userdata, const XML_Char *tag_name, const XML_Char **attr) -{ - struct device_config *config = (struct device_config *)userdata; - enum pcm_format fmt; - - if (strncmp(tag_name, "device", strlen("device")) != 0) - return; - - if (strcmp(attr[0], "name") != 0) { - printf("name not found\n"); - return; - } - - if (strcmp(attr[2], "rate") != 0) { - printf("rate not found\n"); - return; - } - - if (strcmp(attr[4], "ch") != 0) { - printf("channels not found\n"); - return; - } - - if (strcmp(attr[6], "bits") != 0) { - printf("bits not found\n"); - return; - } - - if (strncmp(config->name, attr[1], sizeof(config->name))) - return; - - if (attr[8]) { - if (strcmp(attr[8], "format") == 0) { - printf("PCM format found\n"); - fmt = get_pcm_format(attr[9]); - if (fmt != PCM_FORMAT_INVALID && fmt < PCM_FORMAT_MAX) - config->format = fmt; - } - } else { - config->format = PCM_FORMAT_INVALID; - } - - config->rate = atoi(attr[3]); - config->ch = atoi(attr[5]); - config->bits = atoi(attr[7]); -} - -void start_group_tag(void *userdata, const XML_Char *tag_name, const XML_Char **attr) -{ - struct group_config *config = (struct group_config *)userdata; - enum pcm_format fmt; - - if (strncmp(tag_name, "group_device", strlen("group_device")) != 0) - return; - - if (strcmp(attr[0], "name") != 0) { - printf("name not found\n"); - return; - } - - if (strcmp(attr[2], "rate") != 0) { - printf("rate not found\n"); - return; - } - - if (strcmp(attr[4], "ch") != 0) { - printf("channels not found\n"); - return; - } - - if (strcmp(attr[6], "bits") != 0) { - printf("bits not found\n"); - return; - } - - if (strcmp(attr[8], "slot_mask") != 0) { - printf("slot_mask not found\n"); - return; - } - - if (strncmp(config->name, attr[1], sizeof(config->name))) - return; - - if (attr[10]) { - if (strcmp(attr[10], "format") == 0) { - printf("PCM format found\n"); - fmt = get_pcm_format(attr[11]); - if (fmt != PCM_FORMAT_INVALID && fmt < PCM_FORMAT_MAX) - config->format = fmt; - } - } else { - config->format = PCM_FORMAT_INVALID; - } - config->rate = atoi(attr[3]); - config->ch = atoi(attr[5]); - config->bits = atoi(attr[7]); - config->slot_mask = atoi(attr[9]); -} - -int convert_char_to_hex(char *char_num) -{ - uint64_t hex_num = 0; - uint32_t base = 1; - int32_t len = strlen(char_num); - for (int i = len-1; i>=2; i--) { - if (char_num[i] >= '0' && char_num[i] <= '9') { - hex_num += (char_num[i] - 48) * base; - base = base << 4; - } else if (char_num[i] >= 'A' && char_num[i] <= 'F') { - hex_num += (char_num[i] - 55) * base; - base = base << 4; - } else if (char_num[i] >= 'a' && char_num[i] <= 'f') { - hex_num += (char_num[i] - 87) * base; - base = base << 4; - } - } - return (int32_t) hex_num; -} - -static int get_backend_info(char* filename, char *intf_name, void *config, int type) -{ - FILE *file = NULL; - XML_Parser parser; - int ret = 0; - int bytes_read; - void *buf = NULL; - struct device_config *dev_cfg; - struct group_config *grp_cfg; - - file = fopen(filename, "r"); - if (!file) { - ret = -EINVAL; - printf("Failed to open xml file name %s ret %d", filename, ret); - goto done; - } - - parser = XML_ParserCreate(NULL); - if (!parser) { - ret = -EINVAL; - printf("Failed to create XML ret %d", ret); - goto closeFile; - } - if (type == DEVICE) { - dev_cfg = (struct device_config *)config; - memset(dev_cfg, 0, sizeof(*dev_cfg)); - strlcpy(dev_cfg->name, intf_name, sizeof(dev_cfg->name)); - XML_SetElementHandler(parser, start_tag, NULL); - } else { - grp_cfg = (struct group_config *)config; - memset(grp_cfg, 0, sizeof(*grp_cfg)); - strlcpy(grp_cfg->name, intf_name, sizeof(grp_cfg->name)); - XML_SetElementHandler(parser, start_group_tag, NULL); - } - - XML_SetUserData(parser, config); - - while (1) { - buf = XML_GetBuffer(parser, 1024); - if (buf == NULL) { - ret = -EINVAL; - printf("XML_Getbuffer failed ret %d", ret); - goto freeParser; - } - - bytes_read = fread(buf, 1, 1024, file); - if (bytes_read < 0) { - ret = -EINVAL; - printf("fread failed ret %d", ret); - goto freeParser; - } - - if (XML_ParseBuffer(parser, bytes_read, bytes_read == 0) == XML_STATUS_ERROR) { - ret = -EINVAL; - printf("XML ParseBuffer failed for %s file ret %d", filename, ret); - goto freeParser; - } - if (bytes_read == 0 || ((struct device_config *)config)->rate != 0) - break; - } - - if (((struct device_config *)config)->rate == 0) { - ret = -EINVAL; - printf("Entry not found\n"); - } -freeParser: - XML_ParserFree(parser); -closeFile: - fclose(file); -done: - return ret; -} - -int get_device_media_config(char* filename, char *intf_name, struct device_config *config) -{ - return get_backend_info(filename, intf_name, (void *)config, DEVICE); -} - -int get_group_device_info(char* filename, char *intf_name, struct group_config *config) -{ - char *be_name = strdup(intf_name); - if (be_name == NULL) { - printf("%s(): Insufficient memory to create be_name \n", __func__); - return -ENOMEM; - } - int be_len = strlen(intf_name) - 7; - - be_name[be_len] = '\0'; - return get_backend_info(filename, be_name, (void *)config, GROUP); -} - -int set_agm_group_device_config(struct mixer *mixer, char *intf_name, struct group_config *config) -{ - char *stream = "PCM"; - char *grp_ctl = "grp config"; - char *control = "setParamTag"; - char *mixer_str = NULL; - struct mixer_ctl *ctl; - long grp_config[5]; - int ctl_len = 0, be_len; - int ret = 0; - char *be_name = strdup(intf_name); - if (be_name == NULL) { - printf("%s(): Insufficient memory to create be_name \n", __func__); - ret = -ENOMEM; - goto done; - } - - be_len = strlen(intf_name) - 7; - be_name[be_len] = '\0'; - - ctl_len = strlen(be_name) + 1 + strlen(grp_ctl) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - printf("mixer_str calloc failed\n"); - ret = -ENOMEM; - goto done; - } - snprintf(mixer_str, ctl_len, "%s %s", be_name, grp_ctl); - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - ret = ENOENT; - goto done; - } - - grp_config[0] = config->rate; - grp_config[1] = config->ch; - if (config->format == PCM_FORMAT_INVALID) - grp_config[2] = bits_to_sndrv_format(config->bits); - else - grp_config[2] = alsa_to_sndrv_format(config->format); - grp_config[3] = AGM_DATA_FORMAT_FIXED_POINT; - grp_config[4] = config->slot_mask; - - ret = mixer_ctl_set_array(ctl, &grp_config, sizeof(grp_config)/sizeof(grp_config[0])); - if (ret) { - printf("Failed to set grp media config mixer ctl\n"); - goto done; - } - -done: - if (be_name) - free(be_name); - - if (mixer_str) - free(mixer_str); - return ret; -} - -int set_agm_group_mux_config(struct mixer *mixer, unsigned int device, struct group_config *config, char *intf_name, unsigned int channels) -{ - char *stream = "PCM"; - char *control = "setParamTag"; - char *mixer_str = NULL; - struct mixer_ctl *ctl; - int ctl_len = 0, val_len; - int ret = 0; - struct agm_tag_config* tag_config = NULL; - uint32_t miid = 0; - - ret = set_agm_stream_metadata_type(mixer, device, intf_name, STREAM_PCM); - if (ret) - return 0; - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - printf("mixer_str realloc failed\n"); - goto done; - } - - val_len = sizeof(struct agm_tag_config) + sizeof(struct agm_key_value); - - tag_config = (struct agm_tag_config*)calloc(1, val_len); - if (!tag_config) - goto done; - - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - goto done; - } - tag_config->tag = TAG_DEVICE_MUX; - tag_config->num_tkvs = 1; - tag_config->kv[0].key = TAG_KEY_SLOT_MASK; - ret = agm_mixer_get_miid(mixer, device, intf_name, STREAM_PCM, TAG_DEVICE_MUX, &miid); - if (strstr(intf_name, "VIRT-")) - tag_config->kv[0].value = config->slot_mask; - else if (ret == 0) - tag_config->kv[0].value = slot_mask_map[channels]; - else { - ret = 0; - goto done; - } - - mixer_ctl_set_array(ctl, tag_config, val_len); -done: - if (mixer_str) - free(mixer_str); - if (tag_config) - free(tag_config); - return ret; -} - -int set_agm_device_media_config(struct mixer *mixer, char *intf_name, struct device_config *config) -{ - char *control = "rate ch fmt"; - char *mixer_str; - struct mixer_ctl *ctl; - long media_config[4]; - int ctl_len = 0; - int ret = 0; - - ctl_len = strlen(intf_name) + 1 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - printf("mixer_str calloc failed\n"); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s %s", intf_name, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - media_config[0] = config->rate; - media_config[1] = config->ch; - if (config->format == PCM_FORMAT_INVALID) - media_config[2] = bits_to_sndrv_format(config->bits); - else - media_config[2] = alsa_to_sndrv_format(config->format); - media_config[3] = AGM_DATA_FORMAT_FIXED_POINT; - - ret = mixer_ctl_set_array(ctl, &media_config, sizeof(media_config)/sizeof(media_config[0])); - free(mixer_str); - return ret; -} - -int set_agm_device_custom_payload(struct mixer *mixer, char *intf_name, void *payload, size_t size) -{ - char *control = "setParam"; - char *mixer_str; - struct mixer_ctl *ctl; - long media_config[4]; - int ctl_len = 0; - int ret = 0; - - ctl_len = strlen(intf_name) + 1 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - printf("mixer_str calloc failed\n"); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s %s", intf_name, control); - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - ret = mixer_ctl_set_array(ctl, payload, size); - free(mixer_str); - return ret; -} - -void get_agm_usb_audio_config_payload(uint8_t** payload, size_t* size, - uint32_t miid, struct usbAudioConfig *data) -{ - struct apm_module_param_data_t* header; - struct param_id_usb_audio_intf_cfg_t *usbConfig; - uint8_t* payloadInfo = NULL; - size_t payloadSize = 0; - - payloadSize = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_usb_audio_intf_cfg_t); - - - if (payloadSize % 8 != 0) - payloadSize = payloadSize + (8 - payloadSize % 8); - - payloadInfo = (uint8_t*) calloc(1, payloadSize); - if (!payloadInfo) { - printf("payloadInfo new failed %s \n", strerror(errno)); - return; - } - - header = (struct apm_module_param_data_t*)payloadInfo; - usbConfig = (struct param_id_usb_audio_intf_cfg_t*)(payloadInfo + - sizeof(struct apm_module_param_data_t)); - header->module_instance_id = miid; - header->param_id = PARAM_ID_USB_AUDIO_INTF_CFG; - header->error_code = 0x0; - header->param_size = payloadSize - sizeof(struct apm_module_param_data_t); - printf("header params \n IID:%x param_id:%x error_code:%d param_size:%d \n", - header->module_instance_id, header->param_id, - header->error_code, header->param_size); - - usbConfig->usb_token = data->usb_token; - usbConfig->svc_interval = data->svc_interval; - printf("customPayload address %pK and size %zu \n", payloadInfo, payloadSize); - - *size = payloadSize; - *payload = payloadInfo; - -} - -int connect_play_pcm_to_cap_pcm(struct mixer *mixer, unsigned int p_device, unsigned int c_device) -{ - char *pcm = "PCM"; - char *control = "loopback"; - char *mixer_str; - struct mixer_ctl *ctl; - int ctl_len = 0; - char *val; - int val_len = 0; - int ret = 0; - - ctl_len = strlen(pcm) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - printf("mixer_str calloc failed\n"); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s%d %s", pcm, c_device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - if (p_device < 0) { - val = "ZERO"; - } else { - val_len = strlen(pcm) + 4; - val = calloc(1, val_len); - if (!val) { - printf("val calloc failed\n"); - free(mixer_str); - return -ENOMEM; - } - snprintf(val, val_len, "%s%d", pcm, p_device); - } - - ret = mixer_ctl_set_enum_by_string(ctl, val); - free(mixer_str); - if (p_device < 0) - free(val); - - return ret; -} - -int connect_agm_audio_intf_to_stream(struct mixer *mixer, unsigned int device, char *intf_name, enum stream_type stype, bool connect) -{ - char *stream = "PCM"; - char *control; - char *mixer_str; - struct mixer_ctl *ctl; - int ctl_len = 0; - int ret = 0; - - if (connect) - control = "connect"; - else - control = "disconnect"; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - printf("mixer_str calloc failed\n"); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - ret = mixer_ctl_set_enum_by_string(ctl, intf_name); - free(mixer_str); - return ret; -} - -int agm_mixer_set_ecref_path(struct mixer *mixer, unsigned int device, enum stream_type stype, char *intf_name) -{ - char *stream = "PCM"; - char *control; - char *mixer_str; - struct mixer_ctl *ctl; - int ctl_len = 0; - int ret = 0; - - control = "echoReference"; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - printf("mixer_str calloc failed\n"); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - ret = mixer_ctl_set_enum_by_string(ctl, intf_name); - free(mixer_str); - return ret; -} - -int set_agm_audio_intf_metadata(struct mixer *mixer, char *intf_name, unsigned int dkv, - enum usecase_type usecase, int rate, int bitwidth, uint32_t val) -{ - char *control = "metadata"; - struct mixer_ctl *ctl; - char *mixer_str; - struct agm_key_value *gkv = NULL, *ckv = NULL; - struct prop_data *prop = NULL; - uint8_t *metadata = NULL; - uint32_t num_gkv = 1, num_ckv = 3, num_props = 0; - uint32_t gkv_size, ckv_size, prop_size, ckv_index = 0; - int ctl_len = 0, offset = 0; - int ret = 0; - - gkv_size = num_gkv * sizeof(struct agm_key_value); - ckv_size = num_ckv * sizeof(struct agm_key_value); - prop_size = sizeof(struct prop_data) + (num_props * sizeof(uint32_t)); - - metadata = calloc(1, sizeof(num_gkv) + sizeof(num_ckv) + gkv_size + ckv_size + prop_size); - if (!metadata) - return -ENOMEM; - - gkv = calloc(num_gkv, sizeof(struct agm_key_value)); - ckv = calloc(num_ckv, sizeof(struct agm_key_value)); - prop = calloc(1, prop_size); - if (!gkv || !ckv || !prop) { - if (ckv) - free(ckv); - if (gkv) - free(gkv); - if (prop) - free(prop); - free(metadata); - return -ENOMEM; - } - - if (usecase == PLAYBACK) { - gkv[0].key = DEVICERX; - gkv[0].value = dkv ? dkv : SPEAKER; - } else if (usecase == HAPTICS) { - gkv[0].key = DEVICERX; - gkv[0].value = HAPTICS_DEVICE; - } else if (val == VOICE_UI) { - gkv[0].key = DEVICETX; - gkv[0].value = dkv ? dkv : HANDSETMIC_VA; - } else { - gkv[0].key = DEVICETX; - gkv[0].value = dkv ? dkv : HANDSETMIC; - } - ckv[ckv_index].key = SAMPLINGRATE; - ckv[ckv_index].value = rate; - - ckv_index++; - ckv[ckv_index].key = BITWIDTH; - ckv[ckv_index].value = bitwidth; - - ckv_index++; - ckv[ckv_index].key = GAIN;; - ckv[ckv_index].value = 0; - - prop->prop_id = 0; //Update prop_id here - prop->num_values = num_props; - - memcpy(metadata, &num_gkv, sizeof(num_gkv)); - offset += sizeof(num_gkv); - memcpy(metadata + offset, gkv, gkv_size); - offset += gkv_size; - memcpy(metadata + offset, &num_ckv, sizeof(num_ckv)); - offset += sizeof(num_ckv); - memcpy(metadata + offset, ckv, ckv_size); - offset += ckv_size; - memcpy(metadata + offset, prop, prop_size); - - ctl_len = strlen(intf_name) + 1 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - free(gkv); - free(ckv); - free(prop); - free(metadata); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s %s", intf_name, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(gkv); - free(ckv); - free(prop); - free(metadata); - free(mixer_str); - return ENOENT; - } - - ret = mixer_ctl_set_array(ctl, metadata, sizeof(num_gkv) + sizeof(num_ckv) + gkv_size + ckv_size + prop_size); - - free(gkv); - free(ckv); - free(prop); - free(metadata); - free(mixer_str); - return ret; -} - -int set_agm_stream_metadata_type(struct mixer *mixer, int device, char *val, enum stream_type stype) -{ - char *stream = "PCM"; - char *control = "control"; - char *mixer_str; - struct mixer_ctl *ctl; - int ctl_len = 0,ret = 0; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - printf("mixer_str calloc failed\n"); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - ret = mixer_ctl_set_enum_by_string(ctl, val); - free(mixer_str); - return ret; -} - -void populateChannelMap(uint16_t *pcmChannel, uint8_t numChannel) -{ - if (numChannel == 1) { - pcmChannel[0] = PCM_CHANNEL_C; - } else if (numChannel == 2) { - pcmChannel[0] = PCM_CHANNEL_L; - pcmChannel[1] = PCM_CHANNEL_R; - } else if (numChannel == 3) { - pcmChannel[0] = PCM_CHANNEL_L; - pcmChannel[1] = PCM_CHANNEL_R; - pcmChannel[2] = PCM_CHANNEL_C; - } else if (numChannel == 4) { - pcmChannel[0] = PCM_CHANNEL_L; - pcmChannel[1] = PCM_CHANNEL_R; - pcmChannel[2] = PCM_CHANNEL_LB; - pcmChannel[3] = PCM_CHANNEL_RB; - } else if (numChannel == 5) { - pcmChannel[0] = PCM_CHANNEL_L; - pcmChannel[1] = PCM_CHANNEL_R; - pcmChannel[2] = PCM_CHANNEL_C; - pcmChannel[3] = PCM_CHANNEL_LB; - pcmChannel[4] = PCM_CHANNEL_RB; - } else if (numChannel == 6) { - pcmChannel[0] = PCM_CHANNEL_L; - pcmChannel[1] = PCM_CHANNEL_R; - pcmChannel[2] = PCM_CHANNEL_C; - pcmChannel[3] = PCM_CHANNEL_LFE; - pcmChannel[4] = PCM_CHANNEL_LB; - pcmChannel[5] = PCM_CHANNEL_RB; - } else if (numChannel == 7) { - pcmChannel[0] = PCM_CHANNEL_L; - pcmChannel[1] = PCM_CHANNEL_R; - pcmChannel[2] = PCM_CHANNEL_C; - pcmChannel[3] = PCM_CHANNEL_LFE; - pcmChannel[4] = PCM_CHANNEL_LB; - pcmChannel[5] = PCM_CHANNEL_RB; - pcmChannel[6] = PCM_CHANNEL_CS; - } else if (numChannel == 8) { - pcmChannel[0] = PCM_CHANNEL_L; - pcmChannel[1] = PCM_CHANNEL_R; - pcmChannel[2] = PCM_CHANNEL_C; - pcmChannel[3] = PCM_CHANNEL_LFE; - pcmChannel[4] = PCM_CHANNEL_LB; - pcmChannel[5] = PCM_CHANNEL_RB; - pcmChannel[6] = PCM_CHANNEL_LS; - pcmChannel[7] = PCM_CHANNEL_RS; - } -} - -int configure_mfc(struct mixer *mixer, int device, char *intf_name, int tag, - enum stream_type stype, unsigned int rate, - unsigned int channels, unsigned int bits, uint32_t miid) -{ - int ret = 0; - struct apm_module_param_data_t* header = NULL; - struct param_id_mfc_output_media_fmt_t *mfcConf; - uint16_t* pcmChannel = NULL; - uint8_t* payloadInfo = NULL; - size_t payloadSize = 0, padBytes = 0, size; - - payloadSize = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_mfc_output_media_fmt_t) + - sizeof(uint16_t)*channels; - - padBytes = PADDING_8BYTE_ALIGN(payloadSize); - - payloadInfo = (uint8_t*) calloc(1, payloadSize + padBytes); - if (!payloadInfo) { - return -ENOMEM; - } - - header = (struct apm_module_param_data_t*)payloadInfo; - mfcConf = (struct param_id_mfc_output_media_fmt_t*)(payloadInfo + - sizeof(struct apm_module_param_data_t)); - pcmChannel = (uint16_t*)(payloadInfo + sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_mfc_output_media_fmt_t)); - - header->module_instance_id = miid; - header->param_id = PARAM_ID_MFC_OUTPUT_MEDIA_FORMAT; - header->error_code = 0x0; - header->param_size = payloadSize - sizeof(struct apm_module_param_data_t); - - mfcConf->sampling_rate = rate; - mfcConf->bit_width = bits; - mfcConf->num_channels = channels; - populateChannelMap(pcmChannel, channels); - size = payloadSize + padBytes; - - ret = agm_mixer_set_param(mixer, device, stype, (void *)payloadInfo, (int)size); - free(payloadInfo); - return ret; -} - -int set_agm_capture_stream_metadata(struct mixer *mixer, int device, uint32_t val, enum usecase_type usecase, - enum stream_type stype, unsigned int instance_kv) -{ - char *stream = "PCM"; - char *control = "metadata"; - char *mixer_str; - struct mixer_ctl *ctl; - uint8_t *metadata = NULL; - struct agm_key_value *gkv = NULL, *ckv = NULL; - struct prop_data *prop = NULL; - uint32_t num_gkv = 1, num_ckv = 1, num_props = 0; - uint32_t gkv_size, ckv_size, prop_size, index = 0; - int ctl_len = 0, ret = 0, offset = 0; - char *type = "ZERO"; - - ret = set_agm_stream_metadata_type(mixer, device, type, stype); - if (ret) - return ret; - - if (instance_kv != 0) - num_gkv += 1; - - gkv_size = num_gkv * sizeof(struct agm_key_value); - ckv_size = num_ckv * sizeof(struct agm_key_value); - prop_size = sizeof(struct prop_data) + (num_props * sizeof(uint32_t)); - - metadata = calloc(1, sizeof(num_gkv) + sizeof(num_ckv) + gkv_size + ckv_size + prop_size); - if (!metadata) - return -ENOMEM; - - gkv = calloc(num_gkv, sizeof(struct agm_key_value)); - ckv = calloc(num_ckv, sizeof(struct agm_key_value)); - prop = calloc(1, prop_size); - if (!gkv || !ckv || !prop) { - if (ckv) - free(ckv); - if (gkv) - free(gkv); - free(metadata); - return -ENOMEM; - } - - gkv[index].key = STREAMTX; - gkv[index].value = val; - index++; - - if (instance_kv != 0) { - gkv[index].key = INSTANCE; - gkv[index].value = instance_kv; - index++; - } - - index = 0; - ckv[index].key = VOLUME; - ckv[index].value = LEVEL_0; - - prop->prop_id = 0; //Update prop_id here - prop->num_values = num_props; - - memcpy(metadata, &num_gkv, sizeof(num_gkv)); - offset += sizeof(num_gkv); - memcpy(metadata + offset, gkv, gkv_size); - offset += gkv_size; - memcpy(metadata + offset, &num_ckv, sizeof(num_ckv)); - - offset += sizeof(num_ckv); - memcpy(metadata + offset, ckv, ckv_size); - offset += ckv_size; - memcpy(metadata + offset, prop, prop_size); - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - ret = -ENOMEM; - goto done; - } - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - ret = ENOENT; - goto done; - } - - ret = mixer_ctl_set_array(ctl, metadata, sizeof(num_gkv) + sizeof(num_ckv) + gkv_size + ckv_size + prop_size); - -done: - free(gkv); - free(ckv); - free(prop); - free(metadata); - free(mixer_str); - return ret; -} - -int set_agm_streamdevice_metadata(struct mixer *mixer, int device, uint32_t val, enum usecase_type usecase, - enum stream_type stype, char *intf_name, - unsigned int devicepp_kv) -{ - char *stream = "PCM"; - char *control = "metadata"; - char *mixer_str; - struct mixer_ctl *ctl; - uint8_t *metadata = NULL; - struct agm_key_value *gkv = NULL; - uint32_t num_gkv = 2; - uint32_t gkv_size, index = 0; - int ctl_len = 0, ret = 0, offset = 0; - char *type = intf_name; - - ret = set_agm_stream_metadata_type(mixer, device, type, stype); - if (ret) - return ret; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - gkv_size = num_gkv * sizeof(struct agm_key_value); - - metadata = calloc(1, sizeof(num_gkv) + gkv_size); - if (!metadata) - return -ENOMEM; - - gkv = calloc(num_gkv, sizeof(struct agm_key_value)); - if (!gkv) { - free(metadata); - return -ENOMEM; - } - if (val == VOICE_UI) { - gkv[index].key = STREAMTX; - gkv[index].value = val; - index++; - } else if (usecase == PLAYBACK) { - gkv[index].key = STREAMRX; - gkv[index].value = val; - index++; - } else if (usecase == CAPTURE) { - gkv[index].key = STREAMTX; - gkv[index].value = val; - index++; - } - if (val == VOICE_UI) { - gkv[index].key = DEVICEPP_TX; - gkv[index].value = devicepp_kv; - index++; - } else if (usecase == PLAYBACK) { - gkv[index].key = DEVICEPP_RX; - gkv[index].value = devicepp_kv; - index++; - } else if (usecase == CAPTURE) { - gkv[index].key = DEVICEPP_TX; - gkv[index].value = devicepp_kv; - index++; - } - - memcpy(metadata, &num_gkv, sizeof(num_gkv)); - offset += sizeof(num_gkv); - memcpy(metadata + offset, gkv, gkv_size); - offset += gkv_size; - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - free(gkv); - free(metadata); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(gkv); - free(metadata); - free(mixer_str); - return ENOENT; - } - - ret = mixer_ctl_set_array(ctl, metadata, sizeof(num_gkv) + gkv_size); - - free(gkv); - free(metadata); - free(mixer_str); - return ret; -} - -int set_agm_stream_metadata(struct mixer *mixer, int device, uint32_t val, enum usecase_type usecase, - enum stream_type stype, unsigned int instance_kv) -{ - char *stream = "PCM"; - char *control = "metadata"; - char *mixer_str; - struct mixer_ctl *ctl; - uint8_t *metadata = NULL; - struct agm_key_value *gkv = NULL, *ckv = NULL; - struct prop_data *prop = NULL; - uint32_t num_gkv = 1, num_ckv = 1, num_props = 0; - uint32_t gkv_size, ckv_size, prop_size, index = 0; - int ctl_len = 0, ret = 0, offset = 0; - char *type = "ZERO"; - - ret = set_agm_stream_metadata_type(mixer, device, type, stype); - if (ret) - return ret; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - if (instance_kv != 0) - num_gkv += 1; - - if (val == VOICE_UI) { - num_gkv = 3; - } - - gkv_size = num_gkv * sizeof(struct agm_key_value); - ckv_size = num_ckv * sizeof(struct agm_key_value); - prop_size = sizeof(struct prop_data) + (num_props * sizeof(uint32_t)); - - metadata = calloc(1, sizeof(num_gkv) + sizeof(num_ckv) + gkv_size + ckv_size + prop_size); - if (!metadata) - return -ENOMEM; - - gkv = calloc(num_gkv, sizeof(struct agm_key_value)); - ckv = calloc(num_ckv, sizeof(struct agm_key_value)); - prop = calloc(1, prop_size); - if (!gkv || !ckv || !prop) { - if (ckv) - free(ckv); - if (gkv) - free(gkv); - if (prop) - free(prop); - free(metadata); - return -ENOMEM; - } - - if (val == VOICE_UI) { - gkv[index].key = STREAMTX; - gkv[index].value = val; - index++; - if (instance_kv != 0){ - gkv[index].key = INSTANCE; - gkv[index].value = instance_kv; - index++; - } - gkv[index].key = STREAM_CONFIG; - gkv[index].value = STREAM_CFG_VUI_SVA; - index++; - } else if (usecase == PLAYBACK) { - gkv[index].key = STREAMRX; - gkv[index].value = val; - - index++; - if (instance_kv != 0) { - printf("Instance key is added\n"); - gkv[index].key = INSTANCE; - gkv[index].value = instance_kv; - index++; - } - } else if (usecase == LOOPBACK) { - gkv[index].key = STREAMRX; - gkv[index].value = val; - } - - index = 0; - ckv[index].key = VOLUME; - ckv[index].value = LEVEL_0; - - prop->prop_id = 0; //Update prop_id here - prop->num_values = num_props; - - memcpy(metadata, &num_gkv, sizeof(num_gkv)); - offset += sizeof(num_gkv); - memcpy(metadata + offset, gkv, gkv_size); - offset += gkv_size; - memcpy(metadata + offset, &num_ckv, sizeof(num_ckv)); - - offset += sizeof(num_ckv); - memcpy(metadata + offset, ckv, ckv_size); - offset += ckv_size; - memcpy(metadata + offset, prop, prop_size); - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - free(gkv); - free(ckv); - free(prop); - free(metadata); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(gkv); - free(ckv); - free(prop); - free(metadata); - free(mixer_str); - return ENOENT; - } - - ret = mixer_ctl_set_array(ctl, metadata, sizeof(num_gkv) + sizeof(num_ckv) + gkv_size + ckv_size + prop_size); - - free(gkv); - free(ckv); - free(prop); - free(metadata); - free(mixer_str); - return ret; -} - -int agm_mixer_register_event(struct mixer *mixer, int device, enum stream_type stype, uint32_t miid, uint8_t is_register) -{ - char *stream = "PCM"; - char *control = "event"; - char *mixer_str; - struct mixer_ctl *ctl; - struct agm_event_reg_cfg *event_cfg; - int payload_size = 0; - int ctl_len = 0,ret = 0; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) - return -ENOMEM; - - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - ctl_len = sizeof(struct agm_event_reg_cfg) + payload_size; - event_cfg = calloc(1, ctl_len); - if (!event_cfg) { - free(mixer_str); - return -ENOMEM; - } - - event_cfg->module_instance_id = miid; - event_cfg->event_id = EVENT_ID_DETECTION_ENGINE_GENERIC_INFO; - event_cfg->event_config_payload_size = payload_size; - event_cfg->is_register = !!is_register; - - ret = mixer_ctl_set_array(ctl, event_cfg, ctl_len); - free(event_cfg); - free(mixer_str); - return ret; -} - -int agm_mixer_get_miid(struct mixer *mixer, int device, char *intf_name, - enum stream_type stype, int tag_id, uint32_t *miid) -{ - char *stream = "PCM"; - char *control = "getTaggedInfo"; - char *mixer_str; - struct mixer_ctl *ctl; - int ctl_len = 0,ret = 0, i; - void *payload; - struct gsl_tag_module_info *tag_info; - struct gsl_tag_module_info_entry *tag_entry; - int offset = 0; - - ret = set_agm_stream_metadata_type(mixer, device, intf_name, stype); - if (ret) - return ret; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) - return -ENOMEM; - - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - payload = calloc(1024, sizeof(char)); - if (!payload) { - free(mixer_str); - return -ENOMEM; - } - - ret = mixer_ctl_get_array(ctl, payload, 1024); - if (ret < 0) { - printf("Failed to mixer_ctl_get_array\n"); - free(payload); - free(mixer_str); - return ret; - } - tag_info = payload; - ret = -1; - tag_entry = &tag_info->tag_module_entry[0]; - offset = 0; - for (i = 0; i < tag_info->num_tags; i++) { - tag_entry += offset/sizeof(struct gsl_tag_module_info_entry); - - offset = sizeof(struct gsl_tag_module_info_entry) + (tag_entry->num_modules * sizeof(struct gsl_module_id_info_entry)); - if (tag_entry->tag_id == tag_id) { - struct gsl_module_id_info_entry *mod_info_entry; - - if (tag_entry->num_modules) { - mod_info_entry = &tag_entry->module_entry[0]; - *miid = mod_info_entry->module_iid; - ret = 0; - break; - } - } - } - - free(payload); - free(mixer_str); - return ret; -} - -int agm_mixer_set_param(struct mixer *mixer, int device, - enum stream_type stype, void *payload, int size) -{ - char *stream = "PCM"; - char *control = "setParam"; - char *mixer_str; - struct mixer_ctl *ctl; - int ctl_len = 0,ret = 0; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - free(payload); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - - ret = mixer_ctl_set_array(ctl, payload, size); - - free(mixer_str); - return ret; -} - -int agm_mixer_set_param_with_file(struct mixer *mixer, int device, - enum stream_type stype, char *path) -{ - FILE *fp; - int size, bytes_read; - void *payload; - char *stream = "PCM"; - char *control = "setParam"; - char *mixer_str; - struct mixer_ctl *ctl; - int ctl_len = 0,ret = 0; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - fp = fopen(path, "rb"); - if (!fp) { - printf("%s: Unable to open file '%s'\n", __func__, path); - return 1; - } - - fseek(fp, 0, SEEK_END); - size = ftell(fp); - printf("%s: size of %s file is %d bytes\n", __func__, path, size); - - payload = calloc(1, size); - if (!payload) - return -ENOMEM; - - fseek(fp, 0, SEEK_SET); - bytes_read = fread((char*)payload, 1, size , fp); - if (bytes_read != size) { - printf("%s failed to read data from file %s, bytes read = %d\n", __func__, path, bytes_read); - free(payload); - return -1; - } - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - free(payload); - fclose(fp); - return -ENOMEM; - } - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - free(payload); - fclose(fp); - return ENOENT; - } - - - ret = mixer_ctl_set_array(ctl, payload, size); - - free(mixer_str); - free(payload); - fclose(fp); - return ret; -} - -int agm_mixer_get_event_param(struct mixer *mixer, int device, enum stream_type stype, uint32_t miid) -{ - char *stream = "PCM"; - char *control = "getParam"; - char *mixer_str; - struct mixer_ctl *ctl; - int ctl_len = 0,ret = 0; - struct apm_module_param_data_t* header; - struct detection_engine_generic_event_cfg *pEventCfg; - uint8_t* payload = NULL; - size_t payloadSize = 0; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) - return -ENOMEM; - - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - - payloadSize = sizeof(struct apm_module_param_data_t) + - sizeof(struct detection_engine_generic_event_cfg); - - if (payloadSize % 8 != 0) - payloadSize = payloadSize + (8 - payloadSize % 8); - - payload = (uint8_t*)malloc((size_t)payloadSize); - if (!payload) { - printf("malloc failed\n"); - free(mixer_str); - return -ENOMEM; - } - header = (struct apm_module_param_data_t*)payload; - header->module_instance_id = miid; - header->param_id = PARAM_ID_DETECTION_ENGINE_GENERIC_EVENT_CFG; - header->error_code = 0x0; - header->param_size = payloadSize - sizeof(struct apm_module_param_data_t); - - pEventCfg = (struct detection_engine_generic_event_cfg *) - (payload + sizeof(struct apm_module_param_data_t)); - - ret = mixer_ctl_set_array(ctl, payload, payloadSize); - if (ret) { - printf("%s set failed\n", __func__); - goto exit; - } - - memset(payload, 0, payloadSize); - ret = mixer_ctl_get_array(ctl, payload, payloadSize); - if (ret) { - printf("%s set failed\n", __func__); - goto exit; - } - - printf("received payload data is 0x%x\n", pEventCfg->event_mode); -exit: - free(mixer_str); - free(payload); - return ret; -} - -int agm_mixer_get_buf_tstamp(struct mixer *mixer, int device, enum stream_type stype, uint64_t *tstamp) -{ - char *stream = "PCM"; - char *control = "bufTimestamp"; - char *mixer_str; - struct mixer_ctl *ctl; - int ctl_len = 0,ret = 0; - uint64_t ts = 0; - - if (stype == STREAM_COMPRESS) - stream = "COMPRESS"; - - ctl_len = strlen(stream) + 4 + strlen(control) + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) - return -ENOMEM; - - snprintf(mixer_str, ctl_len, "%s%d %s", stream, device, control); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - printf("Invalid mixer control: %s\n", mixer_str); - free(mixer_str); - return ENOENT; - } - - ret = mixer_ctl_get_array(ctl, &ts, sizeof(uint64_t)); - if (ret) { - printf("%s get failed\n", __func__); - goto exit; - } - - *tstamp = ts; -exit: - free(mixer_str); - return ret; -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/agmmixer.h b/qcom/opensource/agm/plugins/tinyalsa/test/agmmixer.h deleted file mode 100755 index 9d26592b..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/agmmixer.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022-2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#ifndef __AGM_COMMON_H__ -#define __AGM_COMMON_H__ - -#include -#include - -enum usecase_type{ - PLAYBACK, - CAPTURE, - LOOPBACK, - HAPTICS, -}; - -enum stream_type { - STREAM_PCM, - STREAM_COMPRESS, -}; - -struct device_config { - char name[80]; - unsigned int rate; - unsigned int ch; - unsigned int bits; - enum pcm_format format; -}; - -struct usbAudioConfig { - uint32_t usb_token; - uint32_t svc_interval; -}; - -struct group_config { - char name[80]; - unsigned int rate; - unsigned int ch; - unsigned int bits; - unsigned int slot_mask; - enum pcm_format format; -}; - -typedef enum { - SLOT_MASK1 = 1, - SLOT_MASK3 = 3, - SLOT_MASK7 = 7, - SLOT_MASK15 = 15, -}slot_mask_t; - -#if defined(__cplusplus) -extern "C" { -#endif - -int convert_char_to_hex(char *char_num); -int get_pcm_bit_width(enum pcm_format fmt_id); -int set_agm_device_media_config(struct mixer *mixer, char *intf_name, struct device_config *config); -int set_agm_device_custom_payload(struct mixer *mixer, char *intf_name, void *payload, size_t size); -void get_agm_usb_audio_config_payload(uint8_t** payload, size_t* size, uint32_t miid, struct usbAudioConfig *data); -int set_agm_group_device_config(struct mixer *mixer, char *intf_name, struct group_config *config); -int set_agm_group_mux_config(struct mixer *mixer, unsigned int device, struct group_config *config, char *intf_name, unsigned int channels); -int connect_play_pcm_to_cap_pcm(struct mixer *mixer, unsigned int p_device, unsigned int c_device); -int set_agm_audio_intf_metadata(struct mixer *mixer, char *intf_name, unsigned int dkv, enum usecase_type, int rate, int bitwidth, uint32_t val); -int set_agm_stream_metadata_type(struct mixer *mixer, int device, char *val, enum stream_type stype); -int set_agm_streamdevice_metadata(struct mixer *mixer, int device, uint32_t val, enum usecase_type usecase, enum stream_type stype, - char *intf_name, unsigned int devicepp_kv); -int set_agm_stream_metadata(struct mixer *mixer, int device, uint32_t val, enum usecase_type utype, enum stream_type stype, - unsigned int instance_kv); -int set_agm_capture_stream_metadata(struct mixer *mixer, int device, uint32_t val, enum usecase_type utype, enum stream_type stype, - unsigned int instance_kv); -int connect_agm_audio_intf_to_stream(struct mixer *mixer, unsigned int device, - char *intf_name, enum stream_type, bool connect); -int agm_mixer_register_event(struct mixer *mixer, int device, enum stream_type stype, uint32_t miid, uint8_t is_register); -int agm_mixer_get_miid(struct mixer *mixer, int device, char *intf_name, enum stream_type stype, int tag_id, uint32_t *miid); -int agm_mixer_set_param(struct mixer *mixer, int device, - enum stream_type stype, void *payload, int size); -int agm_mixer_set_param_with_file(struct mixer *mixer, int device, - enum stream_type stype, char *path); -int agm_mixer_set_ecref_path(struct mixer *mixer, unsigned int device, enum stream_type stype, char *intf_name); -int agm_mixer_get_event_param(struct mixer *mixer, int device, enum stream_type stype,uint32_t miid); -int agm_mixer_get_buf_tstamp(struct mixer *mixer, int device, enum stream_type stype, uint64_t *tstamp); -int get_device_media_config(char* filename, char *intf_name, struct device_config *config); -int get_group_device_info(char* filename, char *intf_name, struct group_config *config); -int configure_mfc(struct mixer *mixer, int device, char *intf_name, int tag, enum stream_type stype, unsigned int rate, - unsigned int channels, unsigned int bits, uint32_t miid); - -#if defined(__cplusplus) -} /* extern "C" */ -#endif - -#endif diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/agmplay.c b/qcom/opensource/agm/plugins/tinyalsa/test/agmplay.c deleted file mode 100755 index b653e6ce..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/agmplay.c +++ /dev/null @@ -1,516 +0,0 @@ -/* -** Copyright (c) 2019, 2021, The Linux Foundation. All rights reserved. -** -** Copyright 2011, The Android Open Source Project -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of The Android Open Source Project nor the names of -** its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY The Android Open Source Project ``AS IS'' AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -** ARE DISCLAIMED. IN NO EVENT SHALL The Android Open Source Project BE LIABLE -** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -** DAMAGE. -** -** Changes from Qualcomm Innovation Center, Inc. are provided under the following license: -** Copyright (c) 2022-2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "agmmixer.h" - -#define ID_RIFF 0x46464952 -#define ID_WAVE 0x45564157 -#define ID_FMT 0x20746d66 -#define ID_DATA 0x61746164 - -struct riff_wave_header { - uint32_t riff_id; - uint32_t riff_sz; - uint32_t wave_id; -}; - -struct chunk_header { - uint32_t id; - uint32_t sz; -}; - -struct chunk_fmt { - uint16_t audio_format; - uint16_t num_channels; - uint32_t sample_rate; - uint32_t byte_rate; - uint16_t block_align; - uint16_t bits_per_sample; -}; - -static int close = 0; - -void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned int usb_device, - unsigned int channels, unsigned int rate, unsigned int bits, - unsigned int *device_kv, unsigned int stream_kv, unsigned int instance_kv, - unsigned int *devicepp_kv, struct chunk_fmt fmt, bool haptics, char **intf_name, - int intf_num, bool is_24_LE); - -void stream_close(int sig) -{ - /* allow the stream to be closed gracefully */ - signal(sig, SIG_IGN); - close = 1; -} - -static void usage(void) -{ - printf(" Usage: %s file.wav [-help print usage] [-D card] [-d device]\n" - " [-c channels] [-r rate] [-b bits]\n" - " [-num_intf num of interfaces followed by interface name]\n" - " [-i intf_name] : Can be multiple if num_intf is more than 1\n" - " [-dkv device_kv] : Can be multiple if num_intf is more than 1\n" - " [-dppkv deviceppkv] : Assign 0 if no device pp in the graph\n" - " [-ikv instance_kv] : Assign 0 if no instance kv in the graph\n" - " [-skv stream_kv] [-h haptics usecase]\n" - " [is_24_LE] : [0-1] Only to be used if user wants to play S24_LE clip\n" - " [-usb_d usb device]\n" - " 0: If clip bps is 32, and format is S32_LE\n" - " 1: If clip bps is 24, and format is S24_LE\n"); -} - -int main(int argc, char **argv) -{ - FILE *file; - struct riff_wave_header riff_wave_header; - struct chunk_header chunk_header; - struct chunk_fmt chunk_fmt; - unsigned int card = 100, device = 100, i=0; - unsigned int usb_device = 1; - unsigned int channels = 2; - unsigned int rate = 48000; - unsigned int bits = 16; - int intf_num = 1; - uint32_t dkv = SPEAKER; - uint32_t dppkv = DEVICEPP_RX_AUDIO_MBDRC; - unsigned int stream_kv = 0; - unsigned int instance_kv = INSTANCE_1; - bool haptics = false; - char **intf_name = NULL; - char *filename; - int more_chunks = 1, ret = 0; - bool is_24_LE = false; - unsigned int *devicepp_kv = (unsigned int *) malloc(intf_num * sizeof(unsigned int)); - unsigned int *device_kv = (unsigned int *) malloc(intf_num * sizeof(unsigned int)); - - if (!device_kv || !devicepp_kv) { - printf(" insufficient memory\n"); - return 1; - } - - if (argc < 3) { - usage(); - return 1; - } - - device_kv[0] = dkv; - devicepp_kv[0] = dppkv; - - filename = argv[1]; - file = fopen(filename, "rb"); - if (!file) { - printf("Unable to open file '%s'\n", filename); - return 1; - } - - fread(&riff_wave_header, sizeof(riff_wave_header), 1, file); - if ((riff_wave_header.riff_id != ID_RIFF) || - (riff_wave_header.wave_id != ID_WAVE)) { - printf("Error: '%s' is not a riff/wave file\n", filename); - fclose(file); - return 1; - } - - do { - fread(&chunk_header, sizeof(chunk_header), 1, file); - - switch (chunk_header.id) { - case ID_FMT: - fread(&chunk_fmt, sizeof(chunk_fmt), 1, file); - /* If the format header is larger, skip the rest */ - if (chunk_header.sz > sizeof(chunk_fmt)) - fseek(file, chunk_header.sz - sizeof(chunk_fmt), SEEK_CUR); - break; - case ID_DATA: - /* Stop looking for chunks */ - more_chunks = 0; - break; - default: - /* Unknown chunk, skip bytes */ - fseek(file, chunk_header.sz, SEEK_CUR); - } - } while (more_chunks); - - /* parse command line arguments */ - argv += 2; - while (*argv) { - if (strcmp(*argv, "-d") == 0) { - argv++; - if (*argv) - device = atoi(*argv); - } else if (strcmp(*argv, "-c") == 0) { - argv++; - if (*argv) - channels = atoi(*argv); - } else if (strcmp(*argv, "-r") == 0) { - argv++; - if (*argv) - rate = atoi(*argv); - } else if (strcmp(*argv, "-b") == 0) { - argv++; - if (*argv) - bits = atoi(*argv); - } else if (strcmp(*argv, "-D") == 0) { - argv++; - if (*argv) - card = atoi(*argv); - } else if (strcmp(*argv, "-num_intf") == 0) { - argv++; - if (*argv) - intf_num = atoi(*argv); - } else if (strcmp(*argv, "-i") == 0) { - intf_name = (char**) malloc(intf_num * sizeof(char*)); - if (!intf_name) { - printf("insufficient memory\n"); - return 1; - } - for (i = 0; i < intf_num ; i++){ - argv++; - if (*argv) - intf_name[i] = *argv; - } - } else if (strcmp(*argv, "-h") == 0) { - argv++; - if (*argv) - haptics = *argv; - } else if (strcmp(*argv, "-dkv") == 0) { - device_kv = (unsigned int *) realloc(device_kv, intf_num * sizeof(unsigned int)); - if (!device_kv) { - printf(" insufficient memory\n"); - return 1; - } - for (i = 0; i < intf_num ; i++) { - argv++; - if (*argv) { - device_kv[i] = convert_char_to_hex(*argv); - } - } - } else if (strcmp(*argv, "-skv") == 0) { - argv++; - if (*argv) - stream_kv = convert_char_to_hex(*argv); - } else if (strcmp(*argv, "-ikv") == 0) { - argv++; - if (*argv) { - instance_kv = atoi(*argv); - } - } else if (strcmp(*argv, "-dppkv") == 0) { - devicepp_kv = (unsigned int *) realloc(devicepp_kv, intf_num * sizeof(unsigned int)); - if (!devicepp_kv) { - printf(" insufficient memory\n"); - return 1; - } - for (i = 0; i < intf_num ; i++) { - devicepp_kv[i] = DEVICEPP_RX_AUDIO_MBDRC; - } - for (i = 0; i < intf_num ; i++) - { - argv++; - if (*argv) { - devicepp_kv[i] = convert_char_to_hex(*argv); - } - } - } else if (strcmp(*argv, "-is_24_LE") == 0) { - argv++; - if (*argv) { - is_24_LE = atoi(*argv); - } - } else if (strcmp(*argv, "-usb_d") == 0) { - argv++; - if (*argv) - usb_device = atoi(*argv); - } else if (strcmp(*argv, "-help") == 0) { - usage(); - } - if (*argv) - argv++; - } - - if (intf_name == NULL) - return 1; - - play_sample(file, card, device, usb_device, channels, rate, bits, device_kv, stream_kv, - instance_kv, devicepp_kv, chunk_fmt, haptics, intf_name, intf_num, is_24_LE); - - fclose(file); - if (device_kv) - free(device_kv); - if (devicepp_kv) - free(devicepp_kv); - if (intf_name) - free(intf_name); - - return 0; -} - -void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned int usb_device, - unsigned int channels, unsigned int rate, unsigned int bits, - unsigned int *device_kv, unsigned int stream_kv, unsigned int instance_kv, - unsigned int *devicepp_kv, struct chunk_fmt fmt, bool haptics, char **intf_name, - int intf_num, bool is_24_LE) -{ - struct pcm_config config; - struct pcm *pcm; - struct mixer *mixer; - char *buffer; - int playback_path, playback_value; - int size, index, ret = 0; - int num_read; - struct group_config *grp_config = NULL; - struct device_config *dev_config = NULL; - uint32_t miid = 0; - struct usbAudioConfig cfg; - uint8_t* payload = NULL; - size_t payloadSize = 0; - - grp_config = (struct group_config *) malloc(intf_num * sizeof(struct group_config)); - if (!grp_config) { - printf("Failed to allocate memory for group config"); - return; - } - - dev_config = (struct device_config *) malloc(intf_num * sizeof(struct device_config)); - if (!dev_config) { - printf("Failed to allocate memory for dev config"); - return; - } - - memset(&config, 0, sizeof(config)); - config.channels = fmt.num_channels; - config.rate = fmt.sample_rate; - config.period_size = 1024; - config.period_count = 4; - if (fmt.bits_per_sample == 32) { - if (is_24_LE) - config.format = PCM_FORMAT_S24_LE; - else - config.format = PCM_FORMAT_S32_LE; - } else if (fmt.bits_per_sample == 24) - config.format = PCM_FORMAT_S24_3LE; - else if (fmt.bits_per_sample == 16) - config.format = PCM_FORMAT_S16_LE; - config.start_threshold = 0; - config.stop_threshold = 0; - config.silence_threshold = 0; - - mixer = mixer_open(card); - if (!mixer) { - printf("Failed to open mixer\n"); - return; - } - - if (haptics) { - playback_path = HAPTICS; - stream_kv = stream_kv ? stream_kv : HAPTICS_PLAYBACK; - } else { - playback_path = PLAYBACK; - stream_kv = stream_kv ? stream_kv : PCM_LL_PLAYBACK; - } - - for (index = 0; index < intf_num; index++) { - if(intf_name[index] != NULL && strcmp(intf_name[index], "USB_AUDIO-RX") == 0) { - dev_config[index].rate = rate; - dev_config[index].ch = channels; - dev_config[index].bits = bits; - dev_config[index].format = PCM_FORMAT_INVALID; - } else { - ret = get_device_media_config(BACKEND_CONF_FILE, intf_name[index], &dev_config[index]); - if (ret) { - printf("Invalid input, entry not found for : %s\n", intf_name[index]); - fclose(file); - } - if (dev_config[index].format != PCM_FORMAT_INVALID) { - printf("Valid format from backend_conf %d\n", dev_config[index].format); - /* Updating bitwitdh based on format to avoid mismatch between bitwidth - * and format, as device bw will be used to configure MFC. - */ - dev_config[index].bits = get_pcm_bit_width(dev_config[index].format); - } - } - printf("Backend %s rate ch bit fmt : %d, %d, %d %d\n", intf_name[index], - dev_config[index].rate, dev_config[index].ch, dev_config[index].bits, - dev_config[index].format); - - /* set device/audio_intf media config mixer control */ - if (set_agm_device_media_config(mixer, intf_name[index], &dev_config[index])) { - printf("Failed to set device media config\n"); - goto err_close_mixer; - } - - /* set audio interface metadata mixer control */ - if (set_agm_audio_intf_metadata(mixer, intf_name[index], device_kv[index], playback_path, - dev_config[index].rate, dev_config[index].bits, stream_kv)) { - printf("Failed to set device metadata\n"); - goto err_close_mixer; - } - } - - /* set audio interface metadata mixer control */ - if (set_agm_stream_metadata(mixer, device, stream_kv, PLAYBACK, STREAM_PCM, - instance_kv)) { - printf("Failed to set pcm metadata\n"); - goto err_close_mixer; - } - - /* Note: No common metadata as of now*/ - for (index = 0; index < intf_num; index++) { - if (devicepp_kv[index] != 0) { - if (set_agm_streamdevice_metadata(mixer, device, stream_kv, PLAYBACK, STREAM_PCM, intf_name[index], - devicepp_kv[index])) { - printf("Failed to set pcm metadata\n"); - goto err_close_mixer; - } - } - - if (intf_name[index] != NULL && strcmp(intf_name[index], "USB_AUDIO-RX") == 0) { - ret = agm_mixer_get_miid (mixer, device, intf_name[index], STREAM_PCM, DEVICE_HW_ENDPOINT_RX, &miid); - if (ret == 0) { - cfg.usb_token = usb_device << 16; - cfg.svc_interval = 0; - get_agm_usb_audio_config_payload(&payload, &payloadSize, miid, &cfg); - - if (payloadSize) { - ret = set_agm_device_custom_payload(mixer, intf_name[index], payload, payloadSize); - } else { - ret = -1; - printf("set_agm_device_custom_payload failed\n"); - goto err_close_mixer; - } - } else { - printf("Failed to get miid for USB_AUDIO-TX\n"); - goto err_close_mixer; - } - - } - - /* connect pcm stream to audio intf */ - if (connect_agm_audio_intf_to_stream(mixer, device, intf_name[index], STREAM_PCM, true)) { - printf("Failed to connect pcm to audio interface\n"); - goto err_close_mixer; - } - - ret = agm_mixer_get_miid (mixer, device, intf_name[index], STREAM_PCM, PER_STREAM_PER_DEVICE_MFC, &miid); - if (ret) { - printf("MFC not present for this graph\n"); - } else { - if (configure_mfc(mixer, device, intf_name[index], PER_STREAM_PER_DEVICE_MFC, - STREAM_PCM, dev_config[index].rate, dev_config[index].ch, - dev_config[index].bits, miid)) { - printf("Failed to configure pspd mfc\n"); - goto err_close_mixer; - } - } - - if (strstr(intf_name[index], "VIRT-")) { - if (get_group_device_info(BACKEND_CONF_FILE, intf_name[index], &grp_config[index])) - goto err_close_mixer; - - if (set_agm_group_device_config(mixer, intf_name[index], &grp_config[index])) { - printf("Failed to set grp device config\n"); - goto err_close_mixer; - } - } - } - - pcm = pcm_open(card, device, PCM_OUT, &config); - if (!pcm || !pcm_is_ready(pcm)) { - printf("Unable to open PCM device %u (%s)\n", - device, pcm_get_error(pcm)); - goto err_close_mixer; - } - - for (index = 0; index < intf_num; index++) { - if (strstr(intf_name[index], "VIRT-") || (device_kv[index] == SPEAKER) || (device_kv[index] == HANDSET)) { - if (set_agm_group_mux_config(mixer, device, &grp_config[index], intf_name[index], dev_config[index].ch)) { - printf("Failed to set grp device config\n"); - } - } - } - - size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm)); - buffer = malloc(size); - if (!buffer) { - printf("Unable to allocate %d bytes\n", size); - goto err_close_pcm; - } - - printf("Playing sample: %u ch, %u hz, %u bit\n", fmt.num_channels, - fmt.sample_rate, fmt.bits_per_sample); - - if (pcm_start(pcm) < 0) { - printf("start error\n"); - goto err_close_pcm; - } - - /* catch ctrl-c to shutdown cleanly */ - signal(SIGINT, stream_close); - - do { - num_read = fread(buffer, 1, size, file); - if (num_read > 0) { - if (pcm_write(pcm, buffer, num_read)) { - printf("Error playing sample\n"); - break; - } - } - } while (!close && num_read > 0); - - pcm_stop(pcm); - /* disconnect pcm stream to audio intf */ - for (index = 0; index < intf_num; index++) { - connect_agm_audio_intf_to_stream(mixer, device, intf_name[index], STREAM_PCM, false); - } - - free(buffer); -err_close_pcm: - pcm_close(pcm); -err_close_mixer: - if (payload) { - free(payload); - } - if (dev_config) - free(dev_config); - if (grp_config) - free(grp_config); - mixer_close(mixer); -} diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/agmtest.pc.in b/qcom/opensource/agm/plugins/tinyalsa/test/agmtest.pc.in deleted file mode 100755 index f7c36f81..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/agmtest.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: agmtest -Description: agm test tool -Version: @VERSION@ -Libs: -L${libdir} -Cflags: -I${includedir}/agmtest diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/backend_conf.xml b/qcom/opensource/agm/plugins/tinyalsa/test/backend_conf.xml deleted file mode 100755 index 38d64315..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/backend_conf.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/configure.ac b/qcom/opensource/agm/plugins/tinyalsa/test/configure.ac deleted file mode 100755 index 058e8add..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/configure.ac +++ /dev/null @@ -1,53 +0,0 @@ -# Requires autoconf tool later than 2.61 -AC_PREREQ(2.69) -# Initialize the agm plugin package version 1.0.0 -AC_INIT([agmtest],1.0.0) -# Does not strictly follow GNU Coding standards -AM_INIT_AUTOMAKE([foreign subdir-objects]) -# Disables auto rebuilding of configure, Makefile.ins -AM_MAINTAINER_MODE -# Verifies the --srcdir is correct by checking for the path -#AC_CONFIG_SRCDIR([test/agmplay.c]) -# defines some macros variable to be included by source -AC_CONFIG_MACRO_DIR([m4]) - -AC_PROG_CC -AM_PROG_CC_C_O -AC_PROG_CXX -AC_PROG_LIBTOOL -AC_PROG_AWK -AC_PROG_CPP -AC_PROG_INSTALL -AC_PROG_LN_S -AC_PROG_MAKE_SET -PKG_PROG_PKG_CONFIG -AC_ARG_WITH([glib], -AC_HELP_STRING([--with-glib], - [enable glib, Build against glib. Use this when building for HLOS systems which use glib])) - -if (test "x${with_glib}" = "xyes"); then - PKG_CHECK_MODULES(GTHREAD, gthread-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GThread >= 2.16 is required)) - PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GLib >= 2.16 is required)) - GLIB_CFLAGS="$GLIB_CFLAGS $GTHREAD_CFLAGS" - GLIB_LIBS="$GLIB_LIBS $GTHREAD_LIBS" - - AC_SUBST(GLIB_CFLAGS) - AC_SUBST(GLIB_LIBS) -fi - -AM_CONDITIONAL(USE_GLIB, test "x${with_glib}" = "xyes") - -# Checks for libraries -PKG_CHECK_MODULES([MMHEADERS], [mm-audio-headers]) -AC_SUBST([MMHEADERS_CFLAGS]) - -AC_ARG_WITH([openwrt], - AS_HELP_STRING([use openwrt (default is no)]), - [with_openwrt=$withval], - [with_openwrt=no]) -AM_CONDITIONAL([BUILDSYSTEM_OPENWRT], [test "x${with_openwrt}" = "xyes"]) - -AC_CONFIG_FILES([ Makefile agmtest.pc ]) -AC_OUTPUT diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/gtest/Android.mk b/qcom/opensource/agm/plugins/tinyalsa/test/gtest/Android.mk deleted file mode 100755 index 0607de11..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/gtest/Android.mk +++ /dev/null @@ -1,36 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := gtest_agm_test -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS += -Wno-unused-parameter -Wno-unused-result -LOCAL_CFLAGS += -DBACKEND_CONF_FILE=\"/vendor/etc/backend_conf.xml\" -LOCAL_SRC_FILES := gtest_agm_test.cpp \ -../AgmPlayer.cpp \ -../RiffWaveParser.cpp \ -../ChunkParser.cpp \ -../PlaybackCommand.cpp \ -../PlaybackCommandParser.cpp - -LOCAL_HEADER_LIBRARIES := \ - libagm_headers \ - libacdb_headers - -#if android version is R, refer to qtitinyxx otherwise use upstream ones -#This assumes we would be using AR code only for Android R and subsequent versions. -ifneq ($(filter 11 R, $(PLATFORM_VERSION)),) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa -else -LOCAL_SHARED_LIBRARIES += libtinyalsa -endif - -LOCAL_SHARED_LIBRARIES += \ - libagmmixer liblog libcutils libutils - -LOCAL_STATIC_LIBRARIES := libgmock libgtest libgtest_main - -include $(BUILD_EXECUTABLE) diff --git a/qcom/opensource/agm/plugins/tinyalsa/test/gtest/gtest_agm_test.cpp b/qcom/opensource/agm/plugins/tinyalsa/test/gtest/gtest_agm_test.cpp deleted file mode 100755 index 88a57ed8..00000000 --- a/qcom/opensource/agm/plugins/tinyalsa/test/gtest/gtest_agm_test.cpp +++ /dev/null @@ -1,669 +0,0 @@ -/* -** Copyright (c) 2024, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include -#include - -#include -#include "../AgmPlayer.h" -#include "../PlaybackCommandParser.h" -#include "../MockAgmMixerWrapper.h" -#include "../MockAgmPcmWrapper.h" - -class ParserTest : public ::testing::Test { -protected: - void SetUp() override { - riffWaveParser = new RiffWaveParser(); - chunkParser = new ChunkParser(); - } - - void TearDown() override { - delete riffWaveParser; - delete chunkParser; - } - - std::ifstream file; - HeaderParser* riffWaveParser; - HeaderParser* chunkParser; -}; - -TEST_F(ParserTest, RiffWavParserIsValidFail) { - file.open("/sdcard/sample.m4a", std::ios::binary); - if (!file) { - std::cout << "please, push the sample.m4a file in /sdcard/ folder" << std::endl; - exit(1); - } - riffWaveParser->parseHeader(file); - EXPECT_FALSE(riffWaveParser->isValid()); - file.close(); -} - -TEST_F(ParserTest, RiffWavParserIsValidSuccess) { - file.open("/sdcard/sample.wav", std::ios::binary); - if (!file) { - std::cout << "please, push the sample.wav file in /sdcard/ folder" << std::endl; - exit(1); - } - riffWaveParser->parseHeader(file); - EXPECT_TRUE(riffWaveParser->isValid()); - file.close(); -} - -TEST_F(ParserTest, ChunkParserParseHeaderSuccess) { - ChunkFormat chunkFormat; - - file.open("/sdcard/sample.wav", std::ios::binary); - if (!file) { - std::cout << "please, push the sample.wav file in /sdcard/ folder" << std::endl; - exit(1); - } - riffWaveParser->parseHeader(file); - EXPECT_EQ(true, riffWaveParser->isValid()); - - chunkParser->parseHeader(file); - chunkFormat = chunkParser->getFormat(); - EXPECT_EQ(1, chunkFormat.audio_format); - EXPECT_EQ(2, chunkFormat.num_channels); - EXPECT_EQ(48000, chunkFormat.sample_rate); - EXPECT_EQ(192000, chunkFormat.byte_rate); - EXPECT_EQ(4, chunkFormat.block_align); - EXPECT_EQ(16, chunkFormat.bits_per_sample); - file.close(); -} - -class PlaybackCommandParserTest : public ::testing::Test { -protected: - void SetUp() override { - command = new char*[30]; - } - - void TearDown() override { - if (command) { - delete[] command; - command = nullptr; - } - } - - void makeTestCommand() { - memset(command, 0, sizeof(command)); - command[0] = "agmplay"; - command[1] = "/sdcard/48.wav"; - command[2] = "-d"; - command[3] = "100"; - command[4] = "-D"; - command[5] = "100"; - command[6] = "-num_intf"; - command[7] = "1"; - command[8] = "-i"; - command[9] = "TDM-LPAIF-RX-PRIMARY"; - command[10] = "-h"; - command[11] = "false"; - command[12] = "-dkv"; - command[13] = "0xA2000001"; - command[14] = "-skv"; - command[15] = "0"; - command[16] = "-ikv"; - command[17] = "1"; - command[18] = "-dppkv"; - command[19] = "0xAC000002"; - command[20] = "-is_24_LE"; - command[21] = "false"; - command[22] = "-c"; - command[23] = "2"; - command[24] = "-r"; - command[25] = "48000"; - command[26] = "-b"; - command[27] = "16"; - command[28] = "-usb_d"; - command[29] = "1"; - } - - PlaybackCommandParser parser; - char** command = nullptr; - char **interfaceName = nullptr; - unsigned int *device_kv = nullptr; - unsigned int *devicepp_kv = nullptr; -}; - -TEST_F(PlaybackCommandParserTest, TestParseCommandLine) { - makeTestCommand(); - parser.parseCommandLine(command); - - device_kv = parser.getPlaybackCommand().getDeviceKeyVector(); - devicepp_kv = parser.getPlaybackCommand().getDeviceppKeyVector(); - interfaceName = parser.getPlaybackCommand().getInterfaceName(); - - EXPECT_EQ(100, parser.getPlaybackCommand().getCard()); - EXPECT_EQ(100, parser.getPlaybackCommand().getDevice()); - EXPECT_EQ(1, parser.getPlaybackCommand().getInterfaceNumber()); - EXPECT_STREQ("TDM-LPAIF-RX-PRIMARY", interfaceName[0]); - EXPECT_FALSE(parser.getPlaybackCommand().getHaptics() ); - EXPECT_EQ(0xA2000001, *device_kv); - EXPECT_EQ(0, parser.getPlaybackCommand().getStreamKeyVector()); - EXPECT_EQ(1, parser.getPlaybackCommand().getInstanceKeyVector()); - EXPECT_EQ(0xAC000002, *devicepp_kv); - EXPECT_FALSE(parser.getPlaybackCommand().is24LE()); - EXPECT_EQ(2, parser.getPlaybackCommand().getChannel()); - EXPECT_EQ(48000, parser.getPlaybackCommand().getSampleRate()); - EXPECT_EQ(16, parser.getPlaybackCommand().getBitWidth()); - EXPECT_EQ(1, parser.getPlaybackCommand().getUsbDevice()); -} - -class AgmPlayTestFixture : public ::testing::Test { -protected: - void SetUp() override { - riffWaveParser = new RiffWaveParser(); - chunkParser = new ChunkParser(); - command = new char*[30]; - - file.open("/sdcard/sample.wav", std::ios::binary); - if (!file) { - std::cout << "please, push the sample.wav file in /sdcard/ folder" << std::endl; - exit(1); - } - riffWaveParser->parseHeader(file); - if (!riffWaveParser->isValid()) { - std::cout << "It is not a riff/wave file" << std::endl; - file.close(); - exit(1); - } - chunkParser->parseHeader(file); - makeTestCommand(); - parser.parseCommandLine(command); - agmPlayer = new AgmPlayer(&mockAgmMixer, &mockAgmPcm); - } - - void TearDown() override { - delete agmPlayer; - delete riffWaveParser; - delete chunkParser; - if (command) { - delete[] command; - command == nullptr; - } - file.close(); - } - - void makeTestCommand() { - memset(command, 0, sizeof(command)); - command[0] = "agmplay"; - command[1] = "/sdcard/48.wav"; - command[2] = "-d"; - command[3] = "100"; - command[4] = "-D"; - command[5] = "100"; - command[6] = "-i"; - command[7] = "TDM-LPAIF-RX-PRIMARY"; - command[8] = "-dkv"; - command[9] = "0xA2000001"; - } - - char** command = nullptr; - std::ifstream file; - HeaderParser* riffWaveParser; - HeaderParser* chunkParser; - PlaybackCommandParser parser; - AgmPlayer *agmPlayer; - MockAgmMixerWrapper mockAgmMixer; - MockAgmPcmWrapper mockAgmPcm; -}; - -TEST_F(AgmPlayTestFixture, openMixerFail) { - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, setDeviceMediaConfigFail) { - struct device_config deviceConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, setAudioInterfaceMetadataFail) { - struct device_config deviceConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, setStreamConfigFail) { - struct device_config deviceConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, setStreamDeviceMetadataFail) { - struct device_config deviceConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamDeviceMetadata(testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, connectAudioInterfaceToStreamFail) { - struct device_config deviceConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamDeviceMetadata(testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, connectAudioInterfaceToStream(testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, configureMFCFail) { - struct device_config deviceConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamDeviceMetadata(testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, connectAudioInterfaceToStream(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, configureMFC(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, setGroupConfigFail) { - struct device_config deviceConfig; - struct group_config groupConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamDeviceMetadata(testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, connectAudioInterfaceToStream(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, configureMFC(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getGroupConfig(testing::_)) - .WillOnce(testing::Return(groupConfig)); - EXPECT_CALL(mockAgmMixer, setGroupConfig(testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, pcmOpenFail) { - struct device_config deviceConfig; - struct group_config groupConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamDeviceMetadata(testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, connectAudioInterfaceToStream(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, configureMFC(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getGroupConfig(testing::_)) - .WillOnce(testing::Return(groupConfig)); - EXPECT_CALL(mockAgmMixer, setGroupConfig(testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmOpen(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, pcmStartFail) { - struct device_config deviceConfig; - struct group_config groupConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamDeviceMetadata(testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, connectAudioInterfaceToStream(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, configureMFC(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getGroupConfig(testing::_)) - .WillOnce(testing::Return(groupConfig)); - EXPECT_CALL(mockAgmMixer, setGroupConfig(testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmOpen(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmFramesToBytes()) - .WillOnce(testing::Return(16384)); - EXPECT_CALL(mockAgmPcm, pcmStart()) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, pcmWriteFail) { - struct device_config deviceConfig; - struct group_config groupConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamDeviceMetadata(testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, connectAudioInterfaceToStream(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, configureMFC(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getGroupConfig(testing::_)) - .WillOnce(testing::Return(groupConfig)); - EXPECT_CALL(mockAgmMixer, setGroupConfig(testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmOpen(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmFramesToBytes()) - .WillOnce(testing::Return(16384)); - EXPECT_CALL(mockAgmPcm, pcmStart()) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmWrite(testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayTestFixture, playSampleSuccess) { - struct device_config deviceConfig; - struct group_config groupConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(deviceConfig)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamDeviceMetadata(testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, connectAudioInterfaceToStream(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, configureMFC(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, getGroupConfig(testing::_)) - .WillOnce(testing::Return(groupConfig)); - EXPECT_CALL(mockAgmMixer, setGroupConfig(testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmOpen(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmFramesToBytes()) - .WillOnce(testing::Return(16384)); - EXPECT_CALL(mockAgmPcm, pcmStart()) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmWrite(testing::_, testing::_)) - .WillRepeatedly(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmStop()) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, disconnectAudioInterfaceToStream(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmPcm, pcmClose()) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(0, agmPlayer->playSample(file, format, command)); -} - -class AgmPlayUSBTestFixture : public ::testing::Test { -protected: - void SetUp() override { - riffWaveParser = new RiffWaveParser(); - chunkParser = new ChunkParser(); - command = new char*[30]; - - file.open("/sdcard/sample.wav", std::ios::binary); - if (!file) { - std::cout << "please, push the sample.wav file in /sdcard/ folder" << std::endl; - exit(1); - } - riffWaveParser->parseHeader(file); - if (!riffWaveParser->isValid()) { - std::cout << "It is not a riff/wave file" << std::endl; - file.close(); - exit(1); - } - chunkParser->parseHeader(file); - - makeTestCommand(); - parser.parseCommandLine(command); - - agmPlayer = new AgmPlayer(&mockAgmMixer, &mockAgmPcm); - } - - void TearDown() override { - delete agmPlayer; - delete riffWaveParser; - delete chunkParser; - if (command) { - delete[] command; - command == nullptr; - } - file.close(); - } - - void makeTestCommand() { - memset(command, 0, sizeof(command)); - command[0] = "agmplay"; - command[1] = "/sdcard/48.wav"; - command[2] = "-d"; - command[3] = "100"; - command[4] = "-D"; - command[5] = "100"; - command[6] = "-i"; - command[7] = "USB_AUDIO-RX"; - command[8] = "-dkv"; - command[9] = "0xA2000001"; - } - - char** command = nullptr; - std::ifstream file; - HeaderParser* riffWaveParser; - HeaderParser* chunkParser; - PlaybackCommandParser parser; - AgmPlayer *agmPlayer; - MockAgmMixerWrapper mockAgmMixer; - MockAgmPcmWrapper mockAgmPcm; -}; - -TEST_F(AgmPlayUSBTestFixture, setUSBDeviceMediaConfigFail) { - struct device_config deviceConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} - -TEST_F(AgmPlayUSBTestFixture, setDeviceCustomPayloadFail) { - struct device_config deviceConfig; - ChunkFormat format = chunkParser->getFormat(); - PlaybackCommand command = parser.getPlaybackCommand(); - - EXPECT_CALL(mockAgmMixer, mixerOpen(testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setDeviceMediaConfig(testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setAudioInterfaceMetadata(testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamMetadata(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setStreamDeviceMetadata(testing::_, testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(0)); - EXPECT_CALL(mockAgmMixer, setDeviceCustomPayload(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(-1)); - EXPECT_CALL(mockAgmMixer, mixerClose()) - .WillOnce(testing::Return(0)); - - EXPECT_EQ(-1 , agmPlayer->playSample(file, format, command)); -} diff --git a/qcom/opensource/agm/service/Android.mk b/qcom/opensource/agm/service/Android.mk deleted file mode 100755 index 37ba429f..00000000 --- a/qcom/opensource/agm/service/Android.mk +++ /dev/null @@ -1,79 +0,0 @@ -LOCAL_PATH := $(call my-dir) -# Build libagm_headers -include $(CLEAR_VARS) -LOCAL_MODULE := libagm_headers -LOCAL_VENDOR_MODULE := true -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/inc/public -include $(BUILD_HEADER_LIBRARY) - -# Build libagm -include $(CLEAR_VARS) - -LOCAL_MODULE := libagm -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -# { SEC_AUDIO_COMMON -# if you need to print metadata, add -DAGM_DEBUG_METADATA -# LOCAL_CFLAGS := -D_ANDROID_ -DAGM_DEBUG_METADATA -# } SEC_AUDIO_COMMON -LOCAL_CFLAGS := -D_ANDROID_ -DAGM_USE_CUTILS -LOCAL_CFLAGS += -Wno-tautological-compare -Wno-macro-redefined -Wall -LOCAL_CFLAGS += -D_GNU_SOURCE -DACDB_PATH=\"/vendor/etc/acdbdata/\" -LOCAL_CFLAGS += -DACDB_DELTA_FILE_PATH="/data/vendor/audio/acdbdata/delta" - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/inc/public -LOCAL_C_INCLUDES += $(LOCAL_PATH)/inc/private - -# { SEC_AUDIO_COMMON -LOCAL_C_INCLUDES += $(TOP)/system/media/audio/include -# } SEC_AUDIO_COMMON - -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/inc/public - -LOCAL_SRC_FILES := \ - src/agm.c\ - src/graph.c\ - src/graph_module.c\ - src/metadata.c\ - src/session_obj.c\ - src/device.c \ - src/utils.c \ - src/device_hw_ep.c \ - src/agm_memlogger.c - -LOCAL_HEADER_LIBRARIES := \ - libspf-headers \ - libutils_headers \ - libacdb_headers \ - libarmemlog_headers - -LOCAL_SHARED_LIBRARIES := \ - libar-gsl \ - liblog \ - liblx-osal \ - libaudioroute \ - libats \ - libarmemlog \ - libcutils - -#if android version is R, use qtitinyalsa lib otherwise use upstream ones -#This assumes we would be using AR code only for Android R and subsequent versions. -ifneq ($(filter R 11,$(PLATFORM_VERSION)),) -LOCAL_SHARED_LIBRARIES += libqti-tinyalsa -else -LOCAL_SHARED_LIBRARIES += libtinyalsa -endif - - -ifeq ($(strip $(AUDIO_FEATURE_ENABLED_DYNAMIC_LOG)), true) -LOCAL_CFLAGS += -DDYNAMIC_LOG_ENABLED -LOCAL_C_INCLUDES += $(TOP)/external/expat/lib/expat.h -LOCAL_SHARED_LIBRARIES += libaudio_log_utils -LOCAL_SHARED_LIBRARIES += libexpat -LOCAL_HEADER_LIBRARIES += libaudiologutils_headers -endif - -include $(BUILD_SHARED_LIBRARY) - diff --git a/qcom/opensource/agm/service/Makefile.am b/qcom/opensource/agm/service/Makefile.am deleted file mode 100755 index 1e7458a8..00000000 --- a/qcom/opensource/agm/service/Makefile.am +++ /dev/null @@ -1,68 +0,0 @@ -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = agm.pc -EXTRA_DIST = $(pkgconfig_DATA) - -if BUILDSYSTEM_OPENWRT -h_sources = ./inc/agm_api.h \ - ./inc/agm_list.h \ - ./inc/utils.h - -AM_CFLAGS = -I ./inc \ - -I $(top_builddir)/src/system/core/include/log/ - -library_include_HEADERS = $(h_sources) -library_includedir = $(includedir)/agm - -agm_sources = ./src/graph.c \ - ./src/graph_module.c \ - ./src/device.c \ - ./src/device_hw_ep.c \ - ./src/metadata.c \ - ./src/session_obj.c \ - ./src/utils.c \ - ./src/agm.c - -else -h_sources = ${top_srcdir}/inc/public/agm/agm_api.h \ - ${top_srcdir}/inc/public/agm/agm_list.h \ - ${top_srcdir}/inc/public/agm/utils.h \ - ${top_srcdir}/inc/private/agm/metadata.h \ - ${top_srcdir}/inc/private/agm/graph.h \ - ${top_srcdir}/inc/private/agm/session_obj.h \ - ${top_srcdir}/inc/private/agm/device.h - -AM_CFLAGS = @SPF_CFLAGS@ -AM_CFLAGS += -I ${top_srcdir}/inc/public -AM_CFLAGS += -I ${top_srcdir}/inc/private -AM_CFLAGS += @MMHEADERS_CFLAGS@ -AM_CFLAGS += -DDYNAMIC_LOG_ENABLED - -library_include_HEADERS = $(h_sources) -library_includedir = $(includedir)/agm - -agm_sources = ${top_srcdir}/src/graph.c \ - ${top_srcdir}/src/graph_module.c \ - ${top_srcdir}/src/device.c \ - ${top_srcdir}/src/device_hw_ep.c \ - ${top_srcdir}/src/metadata.c \ - ${top_srcdir}/src/session_obj.c \ - ${top_srcdir}/src/agm.c \ - ${top_srcdir}/src/utils.c - -endif - -lib_LTLIBRARIES = libagm.la -libagm_la_SOURCES = $(agm_sources) -libagm_la_LIBADD = -ltinyalsa -lar_osal -lar_gsl -lats -laudio_log_utils - -if !BUILDSYSTEM_OPENWRT -libagm_la_LIBADD += -laudio_log_utils -endif - -libagm_la_CFLAGS := $(AM_CFLAGS) -DACDB_PATH=\"/etc/acdbdata/\" -DACDB_DELTA_FILE_PATH="/data/audio/delta" -if BUILDSYSTEM_OPENWRT -libagm_la_LIBADD += -lglib-2.0 -endif -libagm_la_CFLAGS += -D__unused=__attribute__\(\(__unused__\)\) -libagm_la_CFLAGS += @GLIB_CFLAGS@ -Dstrlcpy=g_strlcpy -Dstrlcat=g_strlcat -include glib.h -libagm_la_LDFLAGS = -module -shared -avoid-version diff --git a/qcom/opensource/agm/service/README.md b/qcom/opensource/agm/service/README.md deleted file mode 100755 index 3e19e3f2..00000000 --- a/qcom/opensource/agm/service/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# agm -Audio Graph Manager diff --git a/qcom/opensource/agm/service/agm.pc.in b/qcom/opensource/agm/service/agm.pc.in deleted file mode 100755 index eeded6db..00000000 --- a/qcom/opensource/agm/service/agm.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: agm -Description: agm library -Version: @VERSION@ -Libs: -L${libdir} -Cflags: -I${includedir}/agm diff --git a/qcom/opensource/agm/service/configure.ac b/qcom/opensource/agm/service/configure.ac deleted file mode 100755 index 921f0259..00000000 --- a/qcom/opensource/agm/service/configure.ac +++ /dev/null @@ -1,56 +0,0 @@ -# -*- Autoconf -*- -# configure.ac -- Autoconf script for agm -# - -# Process this file with autoconf to produce a configure script - -# Requires autoconf tool later than 2.61 -AC_PREREQ(2.69) -# Initialize the audio-ms12-noship package version 1.0.0 -AC_INIT([agm],1.0.1) -# Does not strictly follow GNU Coding standards -AM_INIT_AUTOMAKE([foreign subdir-objects]) - -AC_PROG_CC -AM_PROG_CC_C_O -AC_PROG_CXX -AC_PROG_LIBTOOL -AC_PROG_AWK -AC_PROG_CPP -AC_PROG_INSTALL -AC_PROG_LN_S -AC_PROG_MAKE_SET -PKG_PROG_PKG_CONFIG -AC_ARG_WITH([glib], -AC_HELP_STRING([--with-glib], - [enable glib, Build against glib. Use this when building for HLOS systems which use glib])) - -if (test "x${with_glib}" = "xyes"); then - PKG_CHECK_MODULES(GTHREAD, gthread-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GThread >= 2.16 is required)) - PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GLib >= 2.16 is required)) - GLIB_CFLAGS="$GLIB_CFLAGS $GTHREAD_CFLAGS" - GLIB_LIBS="$GLIB_LIBS $GTHREAD_LIBS" - - AC_SUBST(GLIB_CFLAGS) - AC_SUBST(GLIB_LIBS) -fi - -AM_CONDITIONAL(USE_GLIB, test "x${with_glib}" = "xyes") - -# Checks for libraries -PKG_CHECK_MODULES([SPF], [spf]) -AC_SUBST([SPF_CFLAGS]) - -PKG_CHECK_MODULES([MMHEADERS], [mm-audio-headers]) -AC_SUBST([MMHEADERS_CFLAGS]) - -AC_ARG_WITH([openwrt], - AS_HELP_STRING([use openwrt (default is no)]), - [with_openwrt=$withval], - [with_openwrt=no]) -AM_CONDITIONAL([BUILDSYSTEM_OPENWRT], [test "x${with_openwrt}" = "xyes"]) - -AC_CONFIG_FILES([ Makefile agm.pc ]) -AC_OUTPUT diff --git a/qcom/opensource/agm/service/inc/private/agm/agm_memlogger.h b/qcom/opensource/agm/service/inc/private/agm/agm_memlogger.h deleted file mode 100755 index 44b2bb41..00000000 --- a/qcom/opensource/agm/service/inc/private/agm/agm_memlogger.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef AGM_MEMLOGGER_H -#define AGM_MEMLOGGER_H -/* -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include "mem_logger.h" -#include "graph_queue.h" -#include "spf_reset_queue.h" -#include "gsl_intf.h" - -/// @brief Initializes all memlog queues tracking AGM memory states -void agm_memlog_init(); - -/// @brief Deinitializes all memlog queues tracking AGM memory states -void agm_memlog_deinit(); - -/// @brief Enqueues data to graph memory queue & static buffer -/// @param qState the current graph state (open, close, start, etc) -/// @param qResult the success or failure of the call -/// @param qHandle the graph handle of the graph object -void agm_memlog_graph_enqueue(graph_queue_state qState, int qResult, void *qHandle); -/**/ - -/// @brief Enqueues data to SPF reset memory queue & static buffer -/// @param qState the state of the SPF reset, down or up -void agm_memlog_spf_reset_enqueue(spf_reset_state qState); - -/// @brief Callback function that registers new instances of SPF notifications going down or back up -/// @param events_id the ID of the event registered -/// @param event_payload the payload of the event registered -/// @param event_payload_sz the size of the event payload -/// @param client_data the data the client passes -/// @return an error code representing status -uint32_t agm_memlog_spf_reset_cb(enum gsl_global_event_ids event_id, void *event_payload, size_t event_payload_sz, void *client_data); - -#endif \ No newline at end of file diff --git a/qcom/opensource/agm/service/inc/private/agm/agm_priv.h b/qcom/opensource/agm/service/inc/private/agm/agm_priv.h deleted file mode 100755 index df7046b6..00000000 --- a/qcom/opensource/agm/service/inc/private/agm/agm_priv.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2019, 2021 The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _AGM_PRIV_H_ -#define _AGM_PRIV_H_ - -#include - -/** - * Key Vector - */ -struct agm_key_vector_gsl { - size_t num_kvs; /**< number of key value pairs */ - struct agm_key_value *kv; /**< array of key value pairs */ -}; -struct sg_prop { - uint32_t prop_id; - uint32_t num_values; - uint32_t *values; -}; - -/** - * Metadata Key Vectors - */ -struct agm_meta_data_gsl { - /** - * Used to lookup the calibration data - */ - struct agm_key_vector_gsl gkv; - - /** - * Used to lookup the calibration data - */ - struct agm_key_vector_gsl ckv; - /** - * Used to lookup the property ids - */ - struct sg_prop sg_props; -}; - -struct agm_tag_config_gsl { - uint32_t tag_id; /**< tag id */ - struct agm_key_vector_gsl tkv; -}; - - -#endif /* _AGM_PRIV_H_ */ diff --git a/qcom/opensource/agm/service/inc/private/agm/device.h b/qcom/opensource/agm/service/inc/private/agm/device.h deleted file mode 100755 index 9bd6a088..00000000 --- a/qcom/opensource/agm/service/inc/private/agm/device.h +++ /dev/null @@ -1,246 +0,0 @@ -/* -** Copyright (c) 2019-2021 The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted (subject to the limitations in the -** disclaimer below) provided that the following conditions are met: -** -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** -** * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE -** GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT -** HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -** IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -** IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#ifndef __AGM_DEVICE_H__ -#define __AGM_DEVICE_H__ - -#include -#include -#include -#ifdef DEVICE_USES_ALSALIB -#include -#endif - -#define MAX_DEV_NAME_LEN 80 - -#define PCM_INTF_IDX_PRIMARY 0x0 -#define PCM_INTF_IDX_SECONDARY 0x1 -#define PCM_INTF_IDX_TERTIARY 0x2 -#define PCM_INTF_IDX_QUATERNARY 0x3 -#define PCM_INTF_IDX_QUINARY 0x4 -#define PCM_INTF_IDX_SENARY 0x5 - -#define CODEC_DMA 0x0 -#define MI2S 0x1 -#define TDM 0x2 -#define AUXPCM 0x3 -#define SLIMBUS 0x4 -#define DISPLAY_PORT 0x5 -#define USB_AUDIO 0x6 -#define PCM_RT_PROXY 0x7 -#define AUDIOSS_DMA 0x8 -#define PCM_DUMMY 0x9 -#define BTFM_PROXY 0xa - -#define AUDIO_OUTPUT 0x1 /**< playback usecases*/ -#define AUDIO_INPUT 0x2 /**< capture/voice activation usecases*/ - -struct device_obj; - -struct refcount { - int open; - int prepare; - int start; -}; - -enum device_state { - DEV_CLOSED, - DEV_OPENED, - DEV_PREPARED, - DEV_STARTED, - DEV_STOPPED, -}; - -struct hw_ep_cdc_dma_i2s_tdm_config { - /* lpaif type e.g. LPAIF, LPAIF_WSA, LPAIF_RX_TX*/ - uint32_t lpaif_type; - /* Interface ID e.g. Primary, Secondary, Tertiary ….*/ - uint32_t intf_idx; -}; - -struct hw_ep_slimbus_config { - /* Slimbus device id : Expected values : - * DEV1 : 0 - * DEV2 : 1 - */ - uint32_t dev_id; -}; - -struct hw_ep_pcm_rt_proxy_config { - /* RT proxy device id */ - uint32_t dev_id; -}; - -struct hw_ep_audioss_dma_config { - /* lpaid type e.g LPAIF_VA */ - uint32_t lpaif_type; - /* AudioSS DMA device id */ - uint32_t dev_id; -}; - -struct hw_ep_pcm_dummy_config { - /* PCM dummy device id */ - uint32_t dev_id; -}; - -union hw_ep_config { - struct hw_ep_cdc_dma_i2s_tdm_config cdc_dma_i2s_tdm_config; - struct hw_ep_slimbus_config slim_config; - struct hw_ep_pcm_rt_proxy_config pcm_rt_proxy_config; - struct hw_ep_audioss_dma_config audioss_dma_config; - struct hw_ep_pcm_dummy_config pcm_dummy_config; -}; - -typedef struct hw_ep_info -{ - /* interface e.g. CODEC_DMA, I2S, AUX_PCM, SLIM, DISPLAY_PORT */ - uint32_t intf; - /* Direction of the interface RX or TX (Sink or Source)*/ - uint32_t dir; - - union hw_ep_config ep_config; -}hw_ep_info_t; - -struct device_group_data { - char name[MAX_DEV_NAME_LEN]; - bool has_multiple_dai_link; - struct refcount refcnt; - struct agm_group_media_config media_config; - struct listnode list_node; -}; - -struct device_obj { - /* - * name of the device object populated from /proc/asound/pcm - * --- - * --- - * e.g. - * TDM-LPAIF_WSA-RX-SECONDARY - * SLIM-DEVICE_1-TX-0 - */ - char name[MAX_DEV_NAME_LEN]; - - struct listnode list_node; - pthread_mutex_t lock; - /* pcm device info associated with the device object */ - uint32_t card_id; - hw_ep_info_t hw_ep_info; - uint32_t pcm_id; -#ifdef DEVICE_USES_ALSALIB - snd_pcm_t *pcm; -#else - struct pcm *pcm; -#endif - struct agm_media_config media_config; - struct agm_meta_data_gsl metadata; - struct refcount refcnt; - int state; - void *params; - size_t params_size; - - bool is_virtual_device; - int num_virtual_child; - struct device_obj *parent_dev; - struct device_group_data *group_data; -}; - -/* Initializes device_obj, enumerate and fill device related information */ -int device_init(); -void device_deinit(); -/* Returns list of supported devices */ -int device_get_aif_info_list(struct aif_info *aif_list, size_t *audio_intfs); -/* returns device_obj associated with device_id */ -int device_get_obj(uint32_t device_idx, struct device_obj **dev_obj); -int device_get_hw_ep_info(struct device_obj *dev_obj, - struct hw_ep_info *hw_ep_info_); -int populate_device_hw_ep_info(struct device_obj *dev_obj); -struct device_obj* populate_virtual_device_hw_ep_info(struct device_obj *dev_obj, int num); -int device_open(struct device_obj *dev_obj); -int device_prepare(struct device_obj *dev_obj); -int device_start(struct device_obj *dev_obj); -int device_stop(struct device_obj *dev_obj); -int device_close(struct device_obj *dev_obj); - -enum device_state device_current_state(struct device_obj *obj); -/* api to set device media config */ -int device_set_media_config(struct device_obj *obj, - struct agm_media_config *device_media_config); -/* api to set device meta graph keys + cal keys */ -int device_set_metadata(struct device_obj *obj, uint32_t size, - uint8_t *payload); -/* api to set device setparam payload */ -int device_set_params(struct device_obj *obj, void *payload, size_t size); - -int populate_device_hw_ep_info(struct device_obj *dev_obj); - -int device_get_snd_card_id(); -int device_get_channel_map(struct device_obj *dev_obj, uint32_t **chmap); - -int device_group_set_media_config(struct device_group_data *grp_data, - struct agm_group_media_config *device_media_config); -int device_get_group_data(uint32_t group_id , struct device_group_data **grp_data); -int device_get_group_list(struct aif_info *aif_list, size_t *num_groups); - -int device_get_start_refcnt(struct device_obj *dev_obj); -int device_get_state(struct device_obj *dev_obj); -bool get_file_path_extn(char* file_path_extn, char* file_path_extn_wo_variant); -#endif diff --git a/qcom/opensource/agm/service/inc/private/agm/graph.h b/qcom/opensource/agm/service/inc/private/agm/graph.h deleted file mode 100755 index 896f877e..00000000 --- a/qcom/opensource/agm/service/inc/private/agm/graph.h +++ /dev/null @@ -1,439 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef GPH_OBJ_H -#define GPH_OBJ_H - -#include -#include -#include -#include - -#define ATTRIBUTES_DATA_MODE_MASK 0x3 -#define DATA_MODE_FLAG_SHMEM 0x0 /**< shared memory mode */ -#define DATA_MODE_FLAG_BLOCKING 0x1 /**< heap memory mode blocking */ -#define DATA_MODE_FLAG_NON_BLOCKING 0x2 /**< heap memory mode non-blocking */ - -typedef enum state -{ - CLOSED = 0x0, - OPENED = 0x01, - PREPARED = 0x10, - STARTED = 0x100, - STOPPED = 0x1000, -} graph_state_t; - - -/** - * \brief Callback function signature for events to client - * - * \param[in] event_params: holds all event related info - * \param[in] client_data: client data that was provided during cb registration - */ -typedef void (*event_cb)(struct agm_event_cb_params *event_params, - void *client_data); - -struct graph_obj; - -/** - *\brief Initialize graph handling module, this in turn initializes - * GSL with correct ACDB data file. This should be triggered only once - * during the lifetime of the service. - * - * retuns AR_EOK on success and error code on failure. - */ -int graph_init(); - -/** - *\brief De initialize graph handling module, - * this in turn deinitializes GSL. - * - * retuns AR_EOK on success and error code on failure. - */ -int graph_deinit(); - -/** - *graph object specfici APIs - */ - -/** - *\brief Opens graph based on the shared gkvs and ckvs - * All other subsequent operations on the graph are valid - * only after a successfull open call. It is expected that - * session and device objects should not go away till the - * associated graph object is present. - * The order in which the objects should be created is - * session, device in any order then the last object to be - * created is graph. Similary when closing the session, the - * first object to be closed is the graph object and then - * the session/device objects. - *\param [in] meta_data_kv: composite graph and calibration - * key vectors needed to setup the complete graph. - *\param [in] session_obj: session obj - *\param [in] device_obj: Device to which the session is - * connected to.In case of SSMD/MSMD usecases, the - * second device would be added to the graph using - * graph_add api. - *\param [in/out] graph_obj: Graph object created based on - * session and device objects. - * - * return AR_EOK on success or error code otherwise. - */ -int graph_open(struct agm_meta_data_gsl *meta_data_kv, - struct session_obj *ses_obj, - struct device_obj *dev_obj, - struct graph_obj **gph_obj); - -/** - *\brief prepare modules in the graph. - *\param [in] graph_obj: associated graph obj - *\param [in] cb: pointer to callback function implemented by - * the client - * - * return AR_EOK on success or error code otherwise. - */ -int graph_register_cb(struct graph_obj *gph_obj, event_cb cb, - void *client_data); - -/** - * \brief Register for events from Modules. Not needed for data path events. - * - * \param[in] graph_obj - Valid graph_obj - * \param[out] evt_reg_info - event specific configuration. - * - * \return 0 on success, error code otherwise - */ -int graph_register_for_events(struct graph_obj *gph_obj, - struct agm_event_reg_cfg *evt_reg_cfg); - - -/** - *\brief Set a custom config on the graph - * the config is a self sustained payload which is passed as is - * to GSL. Client is expected to ensure to form correct payload. - * Client should ensure that custom configs and the state requirement - * to configure modules with this custom config is adhered to. - * Graph object wont be able to force this policy. - *\param [in] graph_obj: associated graph obj - *\param [in] config: payload to pass to SPF via GSL. - * - * return AR_EOK on success, or error code otherwise. - */ -int graph_set_config(struct graph_obj *gph_obj, void *payload, - size_t payload_size); - -/** - *\brief issue a prepare command to modules in the graph. - *\param [in] graph_obj: associated graph obj - * - * return AR_EOK on sucess or error code otherwise. - */ -int graph_prepare(struct graph_obj *gph_obj); - -/** - *\brief Issue start command to modules in the graph. - *\param [in] graph_obj: associated graph obj - * - * return AR_EOK on success or error code otherwise. - */ -int graph_start(struct graph_obj *gph_obj); - -/** - *\brief Read audio data captured by the graph. - *\param [in] graph_obj: associated graph obj - *\param [in/out] size: size of data to be read. - *\param [in/out] buffer: buffer where data is copied/filled to. - * - * return num of bytes read on success or error code on failure. - */ -int graph_read(struct graph_obj *gph_obj, struct agm_buff *buffer, size_t *size); - -/** - *\brief write audio data to be rendered - *\param [in] graph_obj: associated graph obj - *\param [in/out] size: size of data to be written - *\param [in/out] buffer: buffer from where data is copied - * - * return zero on success or error code on failure. - */ -int graph_write(struct graph_obj *gph_obj, struct agm_buff *buffer, size_t *size); - -/** - *\brief pause an existing graph. - *\param [in] graph_obj: associated graph obj - * - * return AR_EOK on success or error code otherwise. - */ -int graph_pause(struct graph_obj *gph_obj); - -/** - *\brief flush an existing graph. - *\param [in] graph_obj: associated graph obj - * - * return AR_EOK on success or error code otherwise. - */ -int graph_flush(struct graph_obj *gph_obj); - -/** - *\brief resume an existing graph. - *\param [in] graph_obj: associated graph obj - * - * return AR_EOK on success or error code otherwise. - */ -int graph_resume(struct graph_obj *gph_obj); - -/** - *\brief suspend an existing graph. - *\param [in] graph_obj: associated graph obj - * - * return AR_EOK on success or error code otherwise. - */ -int graph_suspend(struct graph_obj *gph_obj); - -/** - *\brief add a new audio path (graph/subgraph) to an exisitng graph. - * Assumption here is only the device leg would always be updated, - * as a part of the passed GKV. - *\param [in] graph_obj: associated graph obj - *\param [in] meta_data_kv: composite graph and calibration key vector - * which describe only the new graph. In case of SSSD to SSMD - * transition, this argument would only represent the new device and - * stream connection.e.g S1D1 is moving to S1D1D2, then graph_add - * meta data would only have S1D2 related key vectors. - *\param [in] dev_obj: This is an optional argument, pass the device obj - * if a new device is getting added to the current graph - * e.g. in case of SSSD to SSMD usecase transition. In cases - * such as EC_Ref or SideTone, graph_add would just add a new - * processing path into an existing graph and hence device object - * in such cases wont be needed. - * - * return AR_EOK on success or error code otherwise. - */ -int graph_add(struct graph_obj *gph_obj, - struct agm_meta_data_gsl *meta_data_kv, - struct device_obj *dev_obj); - -/** - *\brief change an exisitng graph. - *\param [in] graph_obj: associated graph obj - *\param [in] meta_data_kv: composite graph and calibration key vector - * which describes the new complete graph (new updated graph). - * Expectation here is that only the device leg of the graph - * gets updated/replaced. Session related gkv remains the same. - *\param [in] dev_obj: Pass the device obj - * e.g. in case of device switch - * - * return AR_EOK on success or error code otherwise. - */ -int graph_change(struct graph_obj *gph_obj, - struct agm_meta_data_gsl *meta_data_kv, - struct device_obj *dev_obj); - - -/** - *\brief remove certain graph modules from an exisitng graph. - *\param [in] graph_obj: associated graph obj - *\param [in] gkv: graph key vector - * which describes part of graph(subgraph) to be removed - * from the current graph - * - * return AR_EOK on success or error code otherwise. - */ -int graph_remove(struct graph_obj *gph_obj, - struct agm_meta_data_gsl *meta_data_kv); - -/** - *\brief Issue stop to the associated graph - *\param [in] graph_obj: associated graph obj - *\param [in] gkv: graph key vector - * which describes part of graph(subgraph) to be removed - * from the current graph - * - * return AR_EOK on success or error code otherwise. - */ -int graph_stop(struct graph_obj *gph_obj, - struct agm_meta_data_gsl *meta_data); - -/** - *\brief close the graph, clears the graph object related - * memory. - *\param [in] graph_obj: associated graph obj - * - * return AR_EOK on success or error code otherwise. - */ -int graph_close(struct graph_obj *gph_obj); - -/** - *\brief return the no of buffers consumed/captured by the HW(SPF). - * memory. - *\param [in] graph_obj: associated graph obj - *\param [in] dir : specifies the path for which information is requested - * e.g. RX/TX. - * returns no of buffers consumed/captured. - */ -size_t graph_get_hw_processed_buff_cnt(struct graph_obj *gph_obj, - enum direction dir); - -int graph_get_tags_with_module_info(struct agm_key_vector_gsl *gkv, - void *payload, size_t *size); - -int graph_set_config_with_tag(struct graph_obj *gph_obj, - struct agm_key_vector_gsl *gkv, - struct agm_tag_config_gsl *tag_config); - -int graph_get_config(struct graph_obj *graph_obj, void *payload, - size_t payload_size); - -int graph_set_cal(struct graph_obj *gph_obj, - struct agm_meta_data_gsl *meta_data); - -int graph_rw_acdb_param(void *payload, bool is_param_write); - -/** - *\brief Issue eos to the associated graph - *\param [in] graph_obj: associated graph obj - * - * return AR_EOK on success or error code otherwise. - */ -int graph_eos(struct graph_obj *gph_obj); - -/** - *\brief Get timestamp of the associated running graph - *\param [in] graph_obj: associated graph obj - *\param [out] timestamp: updated the timestamp value if success - * - * return AR_EOK on success or error code otherwise. - */ -int graph_get_session_time(struct graph_obj *gph_obj, uint64_t *timestamp); - -/** - *\brief Get timestamp of the last read buffer - *\param [in] graph_obj: associated graph obj - *\param [out] timestamp: updated timestamp value if success - * - * return AR_EOK on success or error code otherwise. - */ -int graph_get_buffer_timestamp(struct graph_obj *gph_obj, uint64_t *timestamp); - -/** - *\brief Get buffer shared memory info - *\param [in] graph_obj: associated graph obj - *\param [out] buf_info: agm_buf_info containing dma_buf info - *\param [in] flag: either DATA_BUF or POS_BUF or both - * - * return CASA_EOK on success or error code otherwise. - */ -int graph_get_buf_info(struct graph_obj *gph_obj, - struct agm_buf_info *buf_info, uint32_t flag); - -/** - *\brief Set gapless metadata of the associated running graph - *\param [in] graph_obj: associated graph obj - *\param [in] type: Silence Type (Initial/Trailing) - *\param [in] trailing_silence: Initial/Trailing silence samples to remove - * - * return CASA_EOK on success or error code otherwise. - */ -int graph_set_gapless_metadata(struct graph_obj *graph_obj, - enum agm_gapless_silence_type type, - uint32_t silence); - -/** - *\brief Set tagged parameter to acdb - *\param [in] graph_key_vect: graph key vector list - *\param [in] tag_id: tag for the module - *\param [in] tag_key_vect: tag key vector list - *\param [in] payload: parameter data - *\param [in] payload_size: size of the payload - * - * return CASA_EOK on success or error code otherwise. - */ -int graph_set_tag_data_to_acdb( - struct agm_key_vector_gsl *graph_key_vect, uint32_t tag_id, - struct agm_key_vector_gsl *tag_key_vect, uint8_t *payload, - uint32_t payload_size); - -/** - *\brief Set tagged parameter to acdb - *\param [in] graph_key_vect: graph key vector list - *\param [in] calibration_key_vect: calibration key vector list - *\param [in] payload: parameter data - *\param [in] payload_size: size of the payload - * - * return CASA_EOK on success or error code otherwise. - */ - -int graph_set_cal_data_to_acdb( - struct agm_key_vector_gsl *graph_key_vect, - struct agm_key_vector_gsl *cal_key_vect, uint8_t *payload, - uint32_t payload_size); - -/** - *\brief Get tagged parameter to acdb - *\param [in] graph_key_vect: graph key vector list - *\param [in] tag_id: tag for the module - *\param [in] tag_key_vect: tag key vector list - *\param [in/out] payload: query buffer for in and return buffer for out - *\param [in/out] payload_size: size of the payload for query buffer at in and - * return buffer at out - * - * return CASA_EOK on success or error code otherwise. - */ - -int graph_get_tagged_data(const struct agm_key_vector_gsl *graph_key_vect, - uint32_t tag, struct agm_key_vector_gsl *tag_key_vect, uint8_t *payload, - size_t *payload_size); - -/** - *\brief Get TKV or CKV parameter from acdb - *\param [in] graph_key_vect: graph key vector list - *\param [in] tag: tag for the module. use 0 for CKV. - *\param [in] tag_key_vect: tag key vector list - *\param [in/out] payload: query buffer for in and return buffer for out - *\param [in/out] payload_size: size of the payload for query buffer at in and - * return buffer at out - * - * return CASA_EOK on success or error code otherwise. - */ -int graph_get_tckv_data_from_acdb( - const struct agm_key_vector_gsl *graph_key_vect, uint32_t tag, - struct agm_key_vector_gsl *tag_key_vect, uint8_t *payload, - size_t *payload_size); - -/** - *\ brief Enable persistence on acdb - *\ param [in] enable_flag: enable or disable - * - * return CASA_EOK on success or error code otherwise. - */ - -int32_t graph_enable_acdb_persistence(uint8_t enable_flag); - -int graph_set_media_config_datapath(struct graph_obj *gph_obj); -#endif /*GPH_OBJ_H*/ diff --git a/qcom/opensource/agm/service/inc/private/agm/graph_module.h b/qcom/opensource/agm/service/inc/private/agm/graph_module.h deleted file mode 100755 index 9d0060d2..00000000 --- a/qcom/opensource/agm/service/inc/private/agm/graph_module.h +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - * - */ -#ifndef GPH_MODULE_H -#define GPH_MODULE_H - -#include -#include - -/*Platfrom Key Value file, defines tag keys and their values*/ -#include "kvh2xml.h" - -/*Module specific header files used.*/ -#include "apm_api.h" -#include "module_cmn_api.h" -#include "wr_sh_mem_ep_api.h" -#include "rd_sh_mem_ep_api.h" -#include "common_enc_dec_api.h" -#include "hw_intf_cmn_api.h" -#include "codec_dma_api.h" -#include "i2s_api.h" -#include "pcm_tdm_api.h" -#include "slimbus_api.h" -#include "spr_api.h" -#include "gapless_api.h" -#include "pcm_encoder_api.h" -#include "aac_encoder_api.h" - -/* - *Internal enum to identify different modules - *Graph object only should have basic modules which - *would be implicitly configured by it. - *For all other modules the client is supposed to form the - *payload and pass it as an blob, which is then sent to - *SPF via gsl. - *NOTE:Ensure that the hw_ep_info.intf in device object - *also uses the same enum values to define a hw - *interface. -*/ - -#define TAG_STREAM_SPR 0xC0000013 -#define ALIGN_PAYLOAD(x,a) x = (((x) + (size_t)(a-1)) & ~(size_t)(a-1)) -#define PARAM_VAL_NATIVE -1 - -typedef enum module -{ - MODULE_STREAM_START = 0, - MODULE_PCM_ENCODER = MODULE_STREAM_START, - MODULE_PCM_DECODER, - MODULE_PCM_CONVERTER, - MODULE_WR_SHARED_MEM, - MODULE_PLACEHOLDER_ENCODER, - MODULE_PLACEHOLDER_DECODER, - MODULE_STREAM_PAUSE, - MODULE_STREAM_SPR, - MODULE_STREAM_GAPLESS, - MODULE_RD_SHARED_MEM, - /* - *Ensure that whenever a new stream module is added it - *is added in the end of stream module list and the end - *is updated with the same entry. - */ - MODULE_STREAM_END = MODULE_RD_SHARED_MEM, - MODULE_DEVICE_START = 0, - MODULE_HW_EP_RX = MODULE_DEVICE_START, - MODULE_HW_EP_TX, - /* - *Ensure that whenever a new device module is added it - *is added in the end of device module list and the end - *is updated with the same entry. - */ - MODULE_DEVICE_END = MODULE_HW_EP_RX, -}module_t; - - -enum channel_num{ - CHANNEL_1 = 1, - CHANNEL_2, - CHANNEL_3, - CHANNEL_4, - CHANNEL_5, - CHANNEL_6, - CHANNEL_7, - CHANNEL_8, -}; - -struct module_info { - struct listnode list; - /*local enum based module identification*/ - module_t module; - /*module tag defined in the platform header file exported to ACDB*/ - uint32_t tag; - /*module id querried from ACDB*/ - uint32_t mid; - /*module instance id querried from ACDB*/ - uint32_t miid; - /*indicates if this module instance was configured*/ - bool is_configured; - /*Device object if this module is associated with an hardware end point*/ - struct device_obj *dev_obj; - /*GKV which contains/describes this module*/ - struct agm_key_vector_gsl *gkv; - /* - *Every module defines its configuration api, which in turn - *then is used by graph object to configure the module using - *gsl_set_config/gsl_set_custom_config api's. - */ - int (*configure)(struct module_info *mod, struct graph_obj *gph_obj); -}; - -typedef struct module_info module_info_t; - -struct graph_buf_info { - /* timestamp updated in struct gsl_buff on gsl_read */ - uint64_t timestamp; -}; - -struct graph_obj { - pthread_mutex_t lock; - pthread_mutex_t gph_open_thread_lock; - pthread_t gph_open_thread; - pthread_cond_t gph_opened; - bool gph_open_thread_created; - graph_state_t state; - gsl_handle_t graph_handle; - struct listnode tagged_mod_list; - struct gsl_cmd_configure_read_write_params buf_config; - event_cb cb; - void *client_data; - struct session_obj *sess_obj; - uint32_t spr_miid; - struct graph_buf_info buf_info; - bool is_config_buf_params_done; -}; - -void get_stream_module_list_array(module_info_t **info, size_t *size); -void get_hw_ep_module_list_array(module_info_t **info, size_t *size); - -#endif /*GPH_MODULE_H*/ diff --git a/qcom/opensource/agm/service/inc/private/agm/metadata.h b/qcom/opensource/agm/service/inc/private/agm/metadata.h deleted file mode 100755 index ab8a6361..00000000 --- a/qcom/opensource/agm/service/inc/private/agm/metadata.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2019, 2021 The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _METADATA_H_ -#define _METADATA_H_ - -#include -#include - -struct agm_meta_data_gsl* metadata_merge(int num, ...); -int metadata_copy(struct agm_meta_data_gsl *dest, uint32_t size, uint8_t *payload); -void metadata_free(struct agm_meta_data_gsl *metadata); -void metadata_update_cal(struct agm_meta_data_gsl *meta_data, - struct agm_key_vector_gsl *ckv); -void metadata_print(struct agm_meta_data_gsl* metadata); - -#endif //METADATA_H diff --git a/qcom/opensource/agm/service/inc/private/agm/session_obj.h b/qcom/opensource/agm/service/inc/private/agm/session_obj.h deleted file mode 100755 index b6969d0d..00000000 --- a/qcom/opensource/agm/service/inc/private/agm/session_obj.h +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _SESSION_OBJ_H_ -#define _SESSION_OBJ_H_ - -#include -#include -#include -#include -#include -#include -#include -#include - -enum aif_state { - AIF_CLOSED, - AIF_CLOSE, - AIF_OPEN, - AIF_OPENED, - AIF_STOPPED, - AIF_PREPARED, - AIF_STARTED, -}; - -struct aif { - struct listnode node; - uint32_t aif_id; - struct device_obj *dev_obj; - enum aif_state state; - struct agm_meta_data_gsl sess_aif_meta; - void *params; - size_t params_size; - struct agm_tag_config *tag_config; -}; - -enum session_state { - SESSION_CLOSED, - SESSION_OPENED, - SESSION_PREPARED, - SESSION_STARTED, - SESSION_STOPPED, -}; - -struct session_cb { - struct listnode node; - agm_event_cb cb; - enum event_type evt_type; - void *client_data; -}; - -struct session_obj { - struct listnode node; - uint32_t sess_id; - enum session_state state; - struct agm_meta_data_gsl sess_meta; - struct listnode aif_pool; - struct listnode cb_pool; - struct graph_obj *graph; - struct agm_session_config stream_config; - struct agm_media_config in_media_config; - struct agm_media_config out_media_config; - struct agm_buffer_config in_buffer_config; - struct agm_buffer_config out_buffer_config; - void *params; - size_t params_size; - uint32_t loopback_sess_id; - bool loopback_state; - uint32_t ec_ref_aif_id; - bool ec_ref_state; - uint32_t rx_metadata_sz; - uint32_t tx_metadata_sz; - pthread_mutex_t lock; - pthread_mutex_t cb_pool_lock; -}; - -struct session_pool { - struct listnode session_list; - pthread_mutex_t lock; -}; - -struct session_pool *sess_pool; - -int session_obj_init(); -int session_obj_deinit(); -int session_obj_valid_check(uint64_t hndl); -int session_obj_get(int session_id, struct session_obj **sess_obj); -struct session_obj *session_obj_retrieve_from_pool(uint32_t session_id); -int session_obj_open(uint32_t session_id, - enum agm_session_mode sess_mode, - struct session_obj **sess_obj); -int session_obj_set_config(struct session_obj *session, - struct agm_session_config *stream_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config); -int session_obj_prepare(struct session_obj *sess_obj); -int session_obj_start(struct session_obj *sess_obj); -int session_obj_stop(struct session_obj *sess_obj); -int session_obj_close(struct session_obj *sess_obj); -int session_obj_pause(struct session_obj *sess_obj); -int session_obj_flush(struct session_obj *sess_obj); -int session_obj_resume(struct session_obj *sess_obj); -int session_obj_suspend(struct session_obj *sess_obj); -int session_obj_read(struct session_obj *sess_obj, void *buff, size_t *count); -int session_obj_write(struct session_obj *sess_obj, void *buff, size_t *count); -int session_obj_sess_aif_connect(struct session_obj *sess_obj, - uint32_t audio_intf, bool state); -int session_obj_set_sess_metadata(struct session_obj *sess_obj, uint32_t size, - uint8_t *metadata); -int session_obj_set_sess_aif_metadata(struct session_obj *sess_obj, - uint32_t audio_intf, uint32_t size, - uint8_t *metadata); -int session_obj_set_sess_params(struct session_obj *sess_obj, - void* payload, size_t size); -int session_obj_set_sess_aif_params(struct session_obj *sess_obj, - uint32_t audio_intf, - void *payload, size_t size); -int session_obj_get_sess_params(struct session_obj *sess_obj, - void *payload, size_t size); -int session_obj_set_sess_aif_params_with_tag(struct session_obj *sess_obj, - uint32_t aif_id, - struct agm_tag_config *tag_config); -int session_obj_rw_acdb_params_with_tag(struct session_obj *sess_obj, - uint32_t aif_id, struct agm_acdb_param *acdb_param, - bool is_param_set); -int session_obj_set_sess_aif_cal(struct session_obj *sess_obj, - uint32_t aif_id, - struct agm_cal_config *cal_config); -int session_obj_get_tag_with_module_info(struct session_obj *sess_obj, - uint32_t audio_intf, void *payload, size_t *size); -int session_dummy_get_tag_with_module_info( - struct agm_key_vector_gsl *gkv, - void *payload, size_t *size); -int session_dummy_rw_acdb_tunnel( - void *payload, bool is_param_set); -size_t session_obj_hw_processed_buff_cnt(struct session_obj *sess_obj, - enum direction dir); -int session_obj_set_loopback(struct session_obj *sess_obj, - uint32_t playback_sess_id, bool state); -int session_obj_set_ec_ref(struct session_obj *sess_obj, - uint32_t aif_id, bool state); -int session_obj_register_cb(struct session_obj *sess_obj, agm_event_cb cb, - enum event_type evt_type, void *client_data); -int session_obj_register_for_events(struct session_obj *sess_obj, - struct agm_event_reg_cfg *evt_reg_cfg); -int session_obj_set_ec_ref(struct session_obj *sess_obj, uint32_t aif_id, - bool state); -int session_obj_eos(struct session_obj *sess_obj); -int session_obj_get_timestamp(struct session_obj *sess_obj, - uint64_t *timestamp); -int session_obj_buffer_timestamp(struct session_obj *sess_obj, - uint64_t *timestamp); -int session_obj_get_sess_buf_info(struct session_obj *sess_obj, - struct agm_buf_info *buf_info, uint32_t flag); -int session_obj_set_gapless_metadata(struct session_obj *sess_obj, - enum agm_gapless_silence_type type, - uint32_t silence); -int session_obj_write_with_metadata(struct session_obj *sess_obj, - struct agm_buff *buff, - size_t *consumed_size); -int session_obj_read_with_metadata(struct session_obj *sess_obj, - struct agm_buff *buff, - uint32_t *captured_size); -int session_obj_set_non_tunnel_mode_config(struct session_obj *sess_obj, - struct agm_session_config *session_config, - struct agm_media_config *in_media_config, - struct agm_media_config *out_media_config, - struct agm_buffer_config *rx_buffer_config, - struct agm_buffer_config *tx_buffer_config); - -#endif diff --git a/qcom/opensource/agm/service/inc/public/agm/agm_api.h b/qcom/opensource/agm/service/inc/public/agm/agm_api.h deleted file mode 100755 index 7f1f23d6..00000000 --- a/qcom/opensource/agm/service/inc/public/agm/agm_api.h +++ /dev/null @@ -1,1224 +0,0 @@ -/* - * Copyright (c) 2019, 2021 The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2022-2023, Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - * - */ - -#ifndef _AGM_INTF_H_ -#define _AGM_INTF_H_ -/** - *============================================================================= - * \file agm_api.h - * - * \brief - * Defines public APIs for Audio Graph Manager (AGM) - *============================================================================= - */ -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include -#include - -struct session_obj; - -/**< - * used to indicate a given buffer is the final buffer, client will get - * notified once the buffer has been rendered - */ -#define AGM_BUFF_FLAG_EOS 0x1 - -/**< true if buffer has a valid timestamp */ -#define AGM_BUFF_FLAG_TS_VALID 0x2 - -/**< true if buffer is marked as EOF */ -#define AGM_BUFF_FLAG_EOF 0x4 - -/**< true if buffer contains media format */ -#define AGM_BUFF_FLAG_MEDIA_FORMAT 0x8 - -/*Enables SRCM event in metadata on the read path*/ -#define AGM_SESSION_FLAG_INBAND_SRCM 0x1 - -/** - * A single entry of a Key Vector - */ -struct agm_key_value { - uint32_t key; /**< key */ - uint32_t value; /**< value */ -}; - -struct prop_data { - uint32_t prop_id; - uint32_t num_values; -uint32_t values[]; -}; - -/** - * Bit formats - */ -enum agm_media_format -{ - AGM_FORMAT_INVALID, - AGM_FORMAT_PCM_S8, /**< 8-bit signed */ - AGM_FORMAT_PCM_S16_LE, /**< 16-bit signed */ - AGM_FORMAT_PCM_S24_LE, /**< 24-bits in 4-bytes */ - AGM_FORMAT_PCM_S24_3LE, /**< 24-bits in 3-bytes */ - AGM_FORMAT_PCM_S32_LE, /**< 32-bit signed */ - AGM_FORMAT_MP3, /**< MP3 codec */ - AGM_FORMAT_AAC, /**< AAC codec */ - AGM_FORMAT_FLAC, /**< FLAC codec */ - AGM_FORMAT_ALAC, /**< ALAC codec */ - AGM_FORMAT_APE, /**< APE codec */ - AGM_FORMAT_WMASTD, /**< WMA codec */ - AGM_FORMAT_WMAPRO, /**< WMA pro codec */ - AGM_FORMAT_VORBIS, /**< Vorbis codec */ - AGM_FORMAT_AMR_NB, /**< AMR NB codec */ - AGM_FORMAT_AMR_WB, /**< AMR WB codec */ - AGM_FORMAT_AMR_WB_PLUS, /**< AMR WB Plus codec */ - AGM_FORMAT_EVRC, /**< EVRC codec */ - AGM_FORMAT_G711, /**< G711 codec */ - AGM_FORMAT_QCELP, /**< G711 codec */ - AGM_FORMAT_OPUS, /**< OPUS codec */ - AGM_FORMAT_MAX, -}; - -/** - * Data format - * MUST stay in sync with media_fmt_api.h - */ -enum agm_data_format -{ - AGM_DATA_FORMAT_INVALID, - AGM_DATA_FORMAT_FIXED_POINT, /**< fixed point */ - AGM_DATA_FORMAT_IEC61937_PACKETIZED, /**< IEC61937 packetized stream */ - AGM_DATA_FORMAT_IEC60958_PACKETIZED, /**< IEC60958 packetized stream for PCM only */ - AGM_DATA_FORMAT_DSD_OVER_PCM, /**< DSD over PCM stream */ - AGM_DATA_FORMAT_GENERIC_COMPRESSED, /**< generic compressed stream */ - AGM_DATA_FORMAT_RAW_COMPRESSED, /**< raw compressed stream */ - AGM_DATA_FORMAT_COMPR_OVER_PCM_PACKETIZED, /**< Compressed bitstreams packetized */ - AGM_DATA_FORMAT_IEC60958_PACKETIZED_NON_LINEAR, /**< IEC60958 packetized stream for compressed streams */ -}; - -/** - * AGM data modes - */ -enum agm_data_mode -{ - AGM_DATA_INVALID, - AGM_DATA_BLOCKING, /**< Blocking mode */ - AGM_DATA_NON_BLOCKING, /**< Non blocking mode */ - AGM_DATA_PUSH_PULL, /**< Push Pull mode */ - AGM_DATA_EXTERN_MEM, /**< Push Pull mode */ - AGM_DATA_MODE_MAX, -}; - -/** - *AGM session modes - */ -enum agm_session_mode -{ - AGM_SESSION_DEFAULT, /**< Normal agm tunnel session*/ - AGM_SESSION_NO_HOST, /**< Hostless mode */ - AGM_SESSION_NON_TUNNEL, /**< Non tunnel mode */ - AGM_SESSION_NO_CONFIG, /**< No Config mode*/ - AGM_SESSION_COMPRESS, /**< Compress mode*/ -}; - -struct agm_extern_alloc_buff_info{ - int alloc_handle;/**< unique handle identifying extern mem allocation */ - uint32_t alloc_size; /**< size of external allocation */ - uint32_t offset; /**< offset of buffer within extern allocation */ -}; - -struct agm_buff { - uint64_t timestamp; /**< timestamp in micro-secs */ - uint32_t flags; /**< bitmasked flags for e.g. AGM_BUFF_FLAG_EOS */ - uint32_t size; /**< size of buffer in bytes */ - uint8_t *addr; /**< data buffer */ - uint32_t metadata_size; /**< size of metadata blob */ - uint8_t *metadata; /**< Blob for metadata */ - struct agm_extern_alloc_buff_info alloc_info; /**< holds info for extern buff */ -}; - -/** - *Gapless playback Silence type - */ -enum agm_gapless_silence_type -{ - INITIAL_SILENCE, /**< Initial silence sample to be removed*/ - TRAILING_SILENCE, /**< Trailing silence sample to be removed*/ -}; - -/** - * AAC decoder parameters - */ -struct agm_session_aac_dec { - uint16_t aac_fmt_flag; /**< AAC format flag */ - uint16_t audio_obj_type; /**< AAC obj type */ - uint16_t num_channels; /**< AAC obj type */ - uint16_t total_size_of_PCE_bits;/**< PCE bits size */ - uint32_t sample_rate; /**< Sample rate */ -}; - -/** - * AAC encoder parameters - */ -struct agm_session_aac_enc_cfg { - uint16_t aac_enc_mode; /**< AAC encoder mode */ - uint16_t aac_fmt_flag; /**< AAC format flag */ -}; - -struct agm_session_aac_enc { - uint32_t aac_bit_rate; - uint32_t global_cutoff_freq; - struct agm_session_aac_enc_cfg enc_cfg; -}; - -/** - * FLAC decoder parameters - */ -struct agm_session_flac_dec { - uint16_t num_channels; /**< Number of channels */ - uint16_t sample_size; /**< Sample size */ - uint16_t min_blk_size; /**< Minimum block size */ - uint16_t max_blk_size; /**< Maximum block size */ - uint32_t sample_rate; /**< Sample rate */ - uint32_t min_frame_size; /**< Minimum frame size */ - uint32_t max_frame_size; /**< Maximum frame size */ -}; - -/** - * ALAC decoder parameters - */ -struct agm_session_alac_dec { - uint32_t frame_length; /**< Frame length */ - uint8_t compatible_version; /**< Version */ - uint8_t bit_depth; /**< bit depth */ - uint8_t pb; /**< tuning parameters */ - uint8_t mb; /**< tuning parameters */ - uint8_t kb; /**< tuning parameters */ - uint8_t num_channels; /**< Number of channels */ - uint16_t max_run; /**< Max run */ - uint32_t max_frame_bytes; /**< Max Frame bytes */ - uint32_t avg_bit_rate; /**< avg bit rate */ - uint32_t sample_rate; /**< sample rate */ - uint32_t channel_layout_tag; /**< Channel layout tag */ -}; - -/** - * APE decoder parameters - */ -struct agm_session_ape_dec { - uint16_t compatible_version; /**< Version */ - uint16_t compression_level; /**< Compression Level */ - uint32_t format_flags; /**< Format flags */ - uint32_t blocks_per_frame; /**< Blocks per frame */ - uint32_t final_frame_blocks; /**< Final frame blocks */ - uint32_t total_frames; /**< Total frames */ - uint16_t bit_width; /**< Bit width */ - uint16_t num_channels; /**< Number of channels */ - uint32_t sample_rate; /**< Sample rate */ - uint32_t seek_table_present; /**< Seek table present */ -}; - -/** - * WMA decoder parameters - */ -struct agm_session_wma_dec { - uint16_t fmt_tag; /**< Format Tag */ - uint16_t num_channels; /**< Number of channels */ - uint32_t sample_rate; /**< Sample rate */ - uint32_t avg_bytes_per_sec; /**< Avg bytes per sec */ - uint16_t blk_align; /**< Block align */ - uint16_t bits_per_sample; /**< Bits per sample */ - uint32_t channel_mask; /**< Channel mask */ - uint16_t enc_options; /**< Encoder options */ - uint16_t reserved; /**< reserved */ -}; - -/** - * WMA Pro decoder parameters - */ -struct agm_session_wmapro_dec { - uint16_t fmt_tag; /**< Format Tag */ - uint16_t num_channels; /**< Number of channels */ - uint32_t sample_rate; /**< Sample rate */ - uint32_t avg_bytes_per_sec; /**< Avg bytes per sec */ - uint16_t blk_align; /**< Block align */ - uint16_t bits_per_sample; /**< Bits per sample */ - uint32_t channel_mask; /**< Channel mask */ - uint16_t enc_options; /**< Encoder options */ - uint16_t advanced_enc_option; /**< Adv encoder options */ - uint32_t advanced_enc_option2; /**< Adv encoder options2 */ -}; - -/** - * OPUS decoder parameters - */ -struct agm_session_opus_dec { - uint16_t bitstream_format; - uint16_t payload_type; - uint8_t version; - uint8_t num_channels; - uint16_t pre_skip; - uint32_t sample_rate; - uint16_t output_gain; - uint8_t mapping_family; - uint8_t stream_count; - uint8_t coupled_count; - uint8_t channel_map[8]; - uint8_t reserved[3]; -}; - -/** - * Session encoder/decoder parameters - */ -union agm_session_codec -{ - struct agm_session_aac_dec aac_dec; /**< AAC decoder config */ - struct agm_session_aac_enc aac_enc; /**< AAC encoder config */ - struct agm_session_flac_dec flac_dec; /**< Flac decoder config */ - struct agm_session_alac_dec alac_dec; /**< Alac decoder config */ - struct agm_session_ape_dec ape_dec; /**< APE decoder config */ - struct agm_session_wma_dec wma_dec; /**< WMA decoder config */ - struct agm_session_wmapro_dec wmapro_dec; /**< WMAPro decoder config */ - struct agm_session_opus_dec opus_dec; /**< OPUS decoder config */ -}; - -/** - * Flag to determine data buf or postion buf. - * One bit is used for each type. - */ -enum buf_flag { - DATA_BUF = 0x1, - POS_BUF = 0x2, -}; - -/** - * Shared memory buffer info 211 - */ -struct agm_buf_info { - int32_t data_buf_fd; - int32_t data_buf_size; - int32_t pos_buf_fd; - int32_t pos_buf_size; -}; - -/** - * Media Config - */ -struct agm_media_config { - uint32_t rate; /**< sample rate */ - uint32_t channels; /**< number of channels */ - enum agm_media_format format; /**< format */ - uint32_t data_format; /**< data format */ -}; - -struct agm_group_media_config { - struct agm_media_config config; - uint32_t slot_mask; /**< slot_mask for TDM*/ -}; - -/** - * Session Direction - */ -enum direction { - RX = 1, /**< RX */ - TX, /**< TX */ -}; - -/** - * MAX length of the AIF Name - */ -#define AIF_NAME_MAX_LEN 32 - -/** - * AIF Info - */ -struct aif_info { - char aif_name[AIF_NAME_MAX_LEN]; /**< AIF name */ - enum direction dir; /**< direction */ -}; - -/** - * Session Config - */ -struct agm_session_config { - enum direction dir; /**< TX or RX */ - enum agm_session_mode sess_mode; /**< indicates mode of agm sesison, non-tunnel, or hostless */ - uint32_t start_threshold; /**< start_threshold: number of buffers * buffer size */ - uint32_t stop_threshold; /**< stop_th6reshold: number of buffers * buffer size */ - union agm_session_codec codec; /**< codec configuration */ - enum agm_data_mode data_mode; /**< compress format ID */ - uint32_t sess_flags; /**< pass session specific flags e.g enable inband SRCM event*/ -}; - -/** - * Buffer Config - */ -struct agm_buffer_config { - uint32_t count; /**< number of buffers */ - size_t size; /**< size of each buffer */ - size_t max_metadata_size; /**< max metadata size a client attaches to a buffer */ -}; - -/** - * Maps the modules instance id to module id for a single module - */ -struct agm_module_id_iid_map { - uint32_t module_id; /**< module id */ - uint32_t module_iid; /**< globally unique module instance id */ -}; - -/** - * Structure which holds tag and corresponding modules tagged with tag id - */ -struct agm_tag_info { - uint32_t tag_id; /**< tag id */ - uint32_t num_modules; /**< number of modules matching the tag_id */ - struct agm_module_id_iid_map mid_iid_list[0]; /**< agm_module_id_iid_map list */ -}; - -/** - * Structure which holds tag info of a given graph. - */ -struct agm_tag_module_info_list { - uint32_t num_tags; /**< number of tags */ - uint8_t tag_info_list[];/**< variable payload of type struct agm_tag_module_info */ -}; - -/** - * Structure which holds tag config for setparams - */ -struct agm_tag_config { - uint32_t tag; /**< tag id */ - uint32_t num_tkvs; /**< num of tag key values*/ - struct agm_key_value kv[]; /**< tag key vector*/ -}; - -struct agm_cal_config { - uint32_t num_ckvs; /**< num of tag key values*/ - struct agm_key_value kv[]; /**< tag key vector*/ -}; - -struct agm_acdb_param { - bool isTKV; - uint32_t tag; - uint32_t num_kvs; /**< number of ckv or tkv*/ - uint32_t blob_size; /**< kv size + payload size*/ - uint8_t blob[]; /**< kv + payload */ -}; - -struct agm_acdb_tunnel_param { - bool isTKV; - uint32_t tag; - uint32_t num_gkvs; /**< number of gkv*/ - uint32_t num_kvs; /**< number of ckv or tkv*/ - uint32_t blob_size; /**< gkv size + t/ckv size + payload size*/ - uint8_t blob[]; /**< gkv + t/ckv + payload */ -}; - -/** - * Event types - */ -enum event_type -{ - AGM_EVENT_DATA_PATH = 1,/**< Events on the Data path, READ_DONE or WRITE_DONE */ - AGM_EVENT_MODULE, /**< Events raised by modules */ -}; - -struct agm_event_read_write_done_payload { - uint32_t tag; /**< tag that was used to read/write this buffer */ - uint32_t status; /**< data buffer status as defined in ar_osal_error.h */ - uint32_t md_status; /**< meta-data status as defined in ar_osal_error.h */ - struct agm_buff buff; /**< buffer that was passed to agm_read/agm_write */ -}; - -/** - * Event registration structure. - */ -struct agm_event_reg_cfg { - /** Valid instance ID of module */ - uint32_t module_instance_id; - - /** Valid event ID of the module */ - uint32_t event_id; - - /** - * Size of the event config data based upon the module_instance_id/event_id - * combination. @values > 0 bytes, in multiples of 4 bytes atleast - */ - uint32_t event_config_payload_size; - - /** - * 1 - to register the event - * 0 - to de-register the event - */ - uint8_t is_register; - - /** - * module specifc event registration payload - */ - uint8_t event_config_payload[]; -}; - -/** Data Events that will be notified to client from AGM */ -enum agm_event_id { - /** - * Indicates EOS rendered event - */ - AGM_EVENT_EOS_RENDERED = 0x0, - - /** - * Indicates buffer provided as part of read call has been filled. - */ - - AGM_EVENT_READ_DONE = 0x1, - /** - * Indicates buffer provided as part of write has been consumed - */ - - AGM_EVENT_WRITE_DONE = 0x2, - /** - * Indicates early EOS event flagged internally by AGM in case - * flush - */ - - AGM_EVENT_EARLY_EOS_INTERNAL = 0x5, - /** - * Indicates early EOS event - */ - - AGM_EVENT_EARLY_EOS = 0x08001126, - - AGM_EVENT_ID_MAX -}; - -/** data that will be passed to client in the event callback */ -struct agm_event_cb_params { -/**< identifies the module which generated event */ - uint32_t source_module_id; - -/**< identifies the event */ - uint32_t event_id; - -/**< size of payload below */ - uint32_t event_payload_size; - -/**< payload associated with the event if any */ - uint8_t event_payload[]; -}; - -/** Data passed by the client when requesting dump */ -struct agm_dump_info { - /**< identifies the signal received by client */ - int32_t signal; - /**< identifies client pid */ - uint32_t pid; - /**< identifies client uid */ - uint32_t uid; -}; - -/** - * \brief Callback function signature for events to client - * - * \param[in] session_id - Valid audio session id - * \param[in] event_params - holds all event related info - * \param[in] client_data - client data set during callback registration. - */ -typedef void (*agm_event_cb)(uint32_t session_id, - struct agm_event_cb_params *event_params, void *client_data); - -/** - * \brief Callback function signature for crash notification to clients - * - * \param[in] cookie - cookie set during callback registration - */ -typedef void (*agm_service_crash_cb)(uint64_t cookie); - -/** - * \brief Initialize agm. - * - * \return 0 on success, error code on failure. - */ -int agm_init( ); - -/** - * \brief De-Initialize agm. - * - * \return 0 on success, error code on failure. - */ -int agm_deinit(); - - /** - * \brief Set media configuration for an audio interface. - * - * \param[in] aif_id - Valid audio interface id - * \param[in] media_config - valid media configuration for the - * audio interafce. - * - * \return 0 on success, error code on failure. - * If the audio interface is already in use and the - * new media_config is different from previous, api will return - * failure. - */ -int agm_aif_set_media_config(uint32_t aif_id, - struct agm_media_config *media_config); - - - /** - * \brief Set metadata for an audio interface. - * - * \param[in] aif_id - Valid audio interface id - * \param[in] size - size of metadata in bytes - * \param[in] metadata - valid metadata for the audio - * interface. - * - * \return 0 on success, error code on failure. - * If the audio interface is already in use and the - * new meta data is set, api will return - * failure. - */ -int agm_aif_set_metadata(uint32_t aif_id, - uint32_t size, uint8_t *metadata); - -/** - * \brief Set metadata for the session. - * - * \param[in] session_id - Valid audio session id - * \param[in] size - size of metadata in bytes - * \param[in] metadata - valid metadata for the session. - * - * \return 0 on success, error code on failure. - * If the session is already opened and the new - * meta data is set, api will return failure. - */ -int agm_session_set_metadata(uint32_t session_id, - uint32_t size, uint8_t *metadata); - - /** - * \brief Set metadata for the session, audio intf pair. - * - * \param[in] session_id - Valid session id - * \param[in] aif_id - Valid audio interface id - * \param[in] size - size of metadata in bytes - * \param[in] metadata - valid metadata for the session and - * audio_intf. - * - * \return 0 on success, error code on failure. - * If the session is already opened and the new - * meta data is set, api will return failure. - */ -int agm_session_aif_set_metadata(uint32_t session_id, - uint32_t aif_id, - uint32_t size, uint8_t *metadata); - -/** - * \brief Set metadata for the session, audio intf pair. - * - * \param[in] session_id - Valid audio session id - * \param[in] aif_id - Valid audio interface id - * \param[in] state - Connect or Disconnect AIF to Session - * - * \return 0 on success, error code on failure. - * If the session is already opened and the new - * meta data is set, api will return failure. - */ -int agm_session_aif_connect(uint32_t session_id, - uint32_t aif_id, - bool state); - -/** - * \brief Set metadata for the session, audio intf pair. - * - * \param[in] session_id - Valid audio session id - * \param[in] aif_id - Valid audio interface id - * \param[in] payload - payload containing tag module info list in the graph. - * The memory for this pointer is allocated by client. - * \param [in,out] size: size of the payload. - * if the value of size is zero, AGM will update required module - * info list of a given graph. - * if size equal or greater than the required size, - * AGM will copy the module info. - * - * \return 0 on success, error code on failure. - */ -int agm_session_aif_get_tag_module_info(uint32_t session_id, - uint32_t aif_id, void *payload, - size_t *size); - -/** - * \brief Set parameters for modules in audio interface - * - * \param[in] aif_id - Valid audio interface id - * \param[in] payload - payload - * \param[in] size - payload size in bytes - * - * \return 0 on success, error code on failure. - */ -int agm_aif_set_params(uint32_t aif_id, - void* payload, size_t size); - -/** - * \brief Set parameters for modules in b/w stream and audio interface - * - * \param[in] session_id - Valid audio session id - * \param[in] aif_id - Valid audio interface id - * \param[in] payload - payload - * \param[in] size - payload size in bytes - * - * \return 0 on success, error code on failure. - * If the session is already opened and the new - * meta data is set, api will return failure. - */ -int agm_session_aif_set_params(uint32_t session_id, - uint32_t aif_id, - void* payload, size_t size); - -/** - * \brief Set calibration for modules in b/w stream and audio interface - * - * \param[in] session_id - Valid audio session id - * \param[in] aif_id - Valid audio interface id - * \param[in] cal_config - calibration key vector - * - * \return 0 on success, error code on failure. - */ -int agm_session_aif_set_cal(uint32_t session_id, - uint32_t aif_id, - struct agm_cal_config *cal_config); - -/** - * \brief Set parameters for modules in stream - * - * \param[in] session_id - Valid audio session id - * \param[in] payload - payload - * \param[in] size - payload size in bytes - * - * \return 0 on success, error code on failure. - * If the session is already opened and the new - * meta data is set, api will return failure. - */ -int agm_session_set_params(uint32_t session_id, - void* payload, size_t size); - -/** - * \brief Get parameters of the modules of a given session - * - * \param[in] session_id - Valid audio session id - * \param[in] payload - payload - * \param[in] size - payload size in bytes - * - * \return 0 on success, error code on failure. - * If the session is not opened, - * api will return failure. - */ -int agm_session_get_params(uint32_t session_id, - void* payload, size_t size); - -/** - * \brief Get parameters for modules at acdb without session - * - - * \param[in] payload - payload with tag and calibration date - * \param[in] size - size of payload - * - * \return 0 on success, error code on failure. - */ -int agm_get_params_from_acdb_tunnel(void *payload, size_t *size); - -/** - * \brief Set parameters for modules in b/w stream and audio interface - * - * \param[in] session_id - Valid audio session id - * \param[in] aif_id - valid audio interface id - * \param[in] tag_config - tag config structure with tag id and tag key vector - * - * \return 0 on success, error code on failure. - * If the session is already opened and the new - * meta data is set, api will return failure. - */ - -int agm_set_params_with_tag(uint32_t session_id, uint32_t aif_id, - struct agm_tag_config *tag_config); - -/** - * \brief Set parameters for modules in b/w stream and audio interface - * - * \param[in] session_id - Valid audio session id - * \param[in] aif_id - valid audio interface id - * \param[in] payload - payload with tag and calibration date - * \param[in] size - size of payload - * - * \return 0 on success, error code on failure. - * If the session is already opened and the new - * meta data is set, api will return failure. - */ - -int agm_set_params_with_tag_to_acdb(uint32_t session_id, uint32_t aif_id, - void *payload, size_t size); - -/** - * \brief Set parameters for modules at acdb without session - * - - * \param[in] payload - payload with tag and calibration date - * \param[in] size - size of payload - * - * \return 0 on success, error code on failure. - */ - -int agm_set_params_to_acdb_tunnel(void *payload, size_t size); - -/** - * \brief Open the session with specified session id. - * - * \param[in] session_id - Valid audio session id - * \param[in] cb - callback function to be invoked when an event occurs. - * \param[in] evt_type - event type that - * \param[in] client_data - client data. - * - * \return 0 on success, error code otherwise - */ - -int agm_session_register_cb(uint32_t session_id, agm_event_cb cb, - enum event_type evt_type, void *client_data); - -/** - * \brief Register for events from Modules. Not needed for data path events. - * - * \param[in] session_id - Valid audio session id - * \param[out] evt_reg_info - event specific configuration. - * - * \return 0 on success, error code otherwise - */ -int agm_session_register_for_events(uint32_t session_id, - struct agm_event_reg_cfg *evt_reg_cfg); - -/** - * \brief Open the session with specified session id. - * - * \param[in] session_id - Valid audio session id - * \param[in] sess_mode - Mode in which this agm session is to be opened - * \param[out] handle - updated with valid session - * handle if the operation is successful. - * - * \return 0 on success, error code otherwise - */ -int agm_session_open(uint32_t session_id, - enum agm_session_mode sess_mode, - uint64_t *handle); - -/** - * \brief Set Session config - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * \param[in] session_config - valid stream configuration of the - * sessions - * \param[in] media_config - valid media configuration of the - * session. - * \param[in] buffer_config - buffer configuration for the - * session. Null if hostless - * - * \return 0 on success, error code otherwise - */ -int agm_session_set_config(uint64_t hndl, - struct agm_session_config *session_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config); - -/** - * \brief Close the session. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * - * \return 0 on success, error code otherwise - */ -int agm_session_close(uint64_t hndl); - -/** - * \brief prepare the session. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * - * \return 0 on success, error code otherwise - */ -int agm_session_prepare(uint64_t hndl); - -/** - * \brief Start the session. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * - * \return 0 on success, error code otherwise - */ - -int agm_session_start(uint64_t hndl); - -/** - * \brief Stop the session. session must be in started/paused - * state before stopping. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * - * \return 0 on success, error code otherwise - */ -int agm_session_stop(uint64_t hndl); - -/** - * \brief Pause the session. session must be in started state - * before resuming. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * - * \return 0 on success, error code otherwise - */ -int agm_session_pause(uint64_t hndl); - -/** - * \brief flush the session. session must be in pause state - * before flushing. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * - * \return 0 on success, error code otherwise - */ -int agm_session_flush(uint64_t hndl); - -/** - * \brief flush the session. session must be in pause state - * before flushing. - * - * \param[in] session_id - Valid audio session id - * - * \return 0 on success, error code otherwise - */ -int agm_sessionid_flush(uint32_t session_id); - -/** - * \brief Resume the session. session must be in paused state - * before resuming. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * - * \return 0 on success, error code otherwise - */ -int agm_session_resume(uint64_t hndl); - -/** - * \brief suspend the session. session must be in started state - * before suspending. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * - * \return 0 on success, error code otherwise - */ -int agm_session_suspend(uint64_t hndl); - -/** - * \brief Read data buffers.from session - * - * \param[in] handle: session handle returned from - * agm_session_open - * \param[in,out] buff: buffer where data will be copied to - * \param[in,out] count: number of bytes requested to fill into - * the buffer. AGM will update the count with actual - * number of bytes filled. - * - * \return 0 on success, error code otherwise - */ -int agm_session_read(uint64_t handle, void *buff, size_t *count); - -/** - * \brief Write data buffers.to session - * - * \param[in] handle: session handle returned from - * agm_session_open - * \param[in] buff: buffer where data will be copied from - * \param[in] count: actual number of bytes in the buffer. AGM - * will update the count with number of bytes - * consumed/written. - * - * \return 0 on success, error code otherwise - */ -int agm_session_write(uint64_t hndl, void *buff, size_t *count); - -/** - * \brief Get count of Buffer processed by h/w - * - * \param[in] handle: session handle returned from - * agm_session_open - * \param[in] dir: indicates whether to return the write or - * read buffer count - * - * \return: An increasing count of buffers, value wraps back to zero - * once it reaches SIZE_MAX - */ -size_t agm_get_hw_processed_buff_cnt(uint64_t hndl, enum direction dir); - -/** - * \brief Get list of AIF info objects. - * - * \param [in] aif_list: list of aif_info objects - * \param [in,out] num_aif_info: number of aif info items in the list. - * if num_aif_info value is listed as zero, AGM will update num_aif_info with - * the number of aif info items in AGM. - * if num_aif_info is greater than zero, - * AGM will copy client specified num_aif_info of items into aif_list. - * - * \return: 0 on success, error code otherwise - */ -int agm_get_aif_info_list(struct aif_info *aif_list, size_t *num_aif_info); - -/** - * \brief Set loopback between capture and playback sessions - * - * \param[in] capture_session_id : a non zero capture session id - * \param[in] playback_session_id: playback session id. - * \param[in] state : flag to indicate to enable(true) or disable(false) loopback - * - * \return: 0 on success, error code otherwise - */ -int agm_session_set_loopback(uint32_t capture_session_id, - uint32_t playback_session_id, bool state); - -/** - * \brief Set ec reference on capture session - * - * \param[in] capture_session_id : a non zero capture session id - * \param[in] aif_id: aif_id on RX path. - * \param[in] state : flag to indicate to enable(true) or disable(false) ec_ref - * - * \return: 0 on success, error code otherwise - */ -int agm_session_set_ec_ref(uint32_t capture_session_id, uint32_t aif_id, - bool state); - -/** - * \brief send eos of the session. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * - * \return 0 on success, error code otherwise - */ -int agm_session_eos(uint64_t handle); - -/** - * \brief get timestamp of the session. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * \param[out] timestamp - updated with valid timestamp if the - * operation is successful. - * - * \return 0 on success, error code otherwise - */ -int agm_get_session_time(uint64_t handle, uint64_t *timestamp); - -/** - * \brief get timestamp of last read buffer. - * - * \param[in] session_id - Valid audio session id - * \param[out] timestamp - updated with valid timestamp if the - * operation is successful. - * - * \return 0 on success, error code otherwise - */ -int agm_get_buffer_timestamp(uint32_t session_id, uint64_t *timestamp); - -/** - * \brief Get shared memory buf_info of a given session - * - * \param[in] session_id - Valid audio session id - * \param[out] buf_info - agm_buf_info structure with dma_buf_fd - * \param[in] buf_info - flag to determine data buf/pos buf - * - * \return 0 on success, error code on failure. - * If the session is not opened, - * api will return failure. - */ -int agm_session_get_buf_info(uint32_t session_id, struct agm_buf_info *buf_info, uint32_t flag); - -/** - * \brief This api is a no-op if agm runs in clients context. - * In scenarios where AGM runs in its own process context - * and clients talk to AGM over IPC, this api could be used - * by clients to register a callback with the agm client wrapper - * implentation, which is then responsible to trigger this callback - * when the agm service crashes. Once the callback is invoked clients - * then can decide on the approach they want to take with respect to - * clean up of the agm sesisons - - * \param[in] agm_service_crash_cb - Callback passed by clients - * \param[in] cookie - Cookie that client expect to be passed during the invocation - * of the callback. - * - * \return 0 on success, error code otherwise - */ - -int agm_register_service_crash_callback(agm_service_crash_cb cb, - uint64_t cookie); - -/** - * \brief set gapless metadata of the session. - * - * \param[in] handle - Valid session handle obtained - * from agm_session_open - * \param[in] type - Silence Type (Initial or Trailing) - * \param[in] silence - Initial/Trailing silence samples to be - * removed - * - * \return 0 on success, error code otherwise - */ -int agm_set_gapless_session_metadata(uint64_t handle, enum agm_gapless_silence_type type, - uint32_t silence); - -/** - * \brief Write data buffers with metadata to session - * - * \param[in] handle: session handle returned from - * agm_session_open - * \param[in] buff: agm_buffer where data will be copied from - * \param[in] consumed size: Actual number of bytes that were consumed by AGM - * - * \return 0 on success, error code otherwise - */ -int agm_session_write_with_metadata(uint64_t hndl, struct agm_buff *buff, - size_t *consumed_size); - -/** - * \brief Read data buffers with metadata to session - * - * \param[in] handle: session handle returned from - * agm_session_open - * \param[in] buff: agm_buffer where data will be copied to - * \param[in] captured_size: Actual number of bytes that were captured - * - * \return 0 on success, error code otherwise - */ -int agm_session_read_with_metadata(uint64_t hndl, struct agm_buff *buff, - uint32_t *captured_size); - -/** - * \brief Helps set config for non tunnel mode (rx and tx path) - * - * \param[in] handle: session handle returned from - * agm_session_open - * \param[in] session_config - valid stream configuration of the - * sessions - * \param[in] in_media_config - valid media configuration of the - * input data. - * \param[in] in_buffer_config - buffer configuration for the - * input data path. - * \param[in] out_media_config - valid media configuration of the - * output data. - * \param[in] out_buffer_config - buffer configuration for the - * output data path. - * - * \return 0 on success, error code otherwise - */ -int agm_session_set_non_tunnel_mode_config(uint64_t hndl, - struct agm_session_config *session_config, - struct agm_media_config *in_media_config, - struct agm_media_config *out_media_config, - struct agm_buffer_config *in_buffer_config, - struct agm_buffer_config *out_buffer_config); - - -/** - * \brief Get list of group AIF objects. - * - * \param [in] aif_list: list of group aif_info objects - * \param [in,out] num_groups: number of group aif items in the list. - * if num_groups value is listed as zero, AGM will update num_groups with - * the number of group aif items in AGM. - * if num_groups is greater than zero, - * AGM will copy client specified num_groups of items into aif_list. - * - * \return: 0 on success, error code otherwise - */ -int agm_get_group_aif_info_list(struct aif_info *aif_list, size_t *num_groups); - - /** - * \brief Set media configuration for a group AIF. - * - * \param[in] aif_group_id - Valid group id - * \param[in] media_config - valid media configuration for the - * audio interafce. - * - * \return 0 on success, error code on failure. - * If the audio interface is already in use and the - * new media_config is different from previous, api will return - * failure. - */ -int agm_aif_group_set_media_config(uint32_t aif_group_id, - struct agm_group_media_config *media_config); - -/** - * \brief Write buffers containing codec params to session on datapath - * - * \param[in] session_id - Valid audio session id - * \param[in] buff: agm_buffer where data will be copied from - * - * \return 0 on success, error code otherwise - */ -int agm_session_write_datapath_params(uint32_t session_id, struct agm_buff *buff); - -/** - * \brief Dump AGM information based on client - * - * \param[in] dump_info - dump information populated by - * the client to facilitate dump - * - * \return 0 on success, error code on failure. - */ -int agm_dump(struct agm_dump_info *dump_info); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* _AGM_INTF_H_ */ diff --git a/qcom/opensource/agm/service/inc/public/agm/agm_list.h b/qcom/opensource/agm/service/inc/public/agm/agm_list.h deleted file mode 100755 index 2b89c857..00000000 --- a/qcom/opensource/agm/service/inc/public/agm/agm_list.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2008-2013 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 __LIST_H_ -#define __LIST_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -struct listnode { - struct listnode *next; - struct listnode *prev; -}; - -#define node_to_item(node, container, member) \ - (container *) (((char*) (node)) - offsetof(container, member)) - -#define list_declare(name) \ - struct listnode name = { \ - .next = &name, \ - .prev = &name, \ - } - -#define list_for_each(node, list) \ - for (node = (list)->next; node != (list); node = node->next) - -#define list_for_each_reverse(node, list) \ - for (node = (list)->prev; node != (list); node = node->prev) - -#define list_for_each_safe(node, n, list) \ - for (node = (list)->next, n = node->next; \ - node != (list); \ - node = n, n = node->next) - -static inline void list_init(struct listnode *node) -{ - node->next = node; - node->prev = node; -} - -static inline void list_add_tail(struct listnode *head, struct listnode *item) -{ - item->next = head; - item->prev = head->prev; - head->prev->next = item; - head->prev = item; -} - -static inline void list_add_head(struct listnode *head, struct listnode *item) -{ - item->next = head->next; - item->prev = head; - head->next->prev = item; - head->next = item; -} - -static inline void list_remove(struct listnode *item) -{ - item->next->prev = item->prev; - item->prev->next = item->next; -} - -#define list_empty(list) ((list) == (list)->next) -#define list_head(list) ((list)->next) -#define list_tail(list) ((list)->prev) - -#ifdef __cplusplus -}; -#endif /* __cplusplus */ - -#endif diff --git a/qcom/opensource/agm/service/inc/public/agm/utils.h b/qcom/opensource/agm/service/inc/public/agm/utils.h deleted file mode 100755 index 1a76635a..00000000 --- a/qcom/opensource/agm/service/inc/public/agm/utils.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -** Copyright (c) 2019-2020, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#ifndef __UTILS_H__ -#include "ar_osal_error.h" - -#ifdef FEATURE_IPQ_OPENWRT -#include -#else -#include -#endif - -#define AGM_LOGE(arg,...) ALOGE("%s: %d " arg, __func__, __LINE__, ##__VA_ARGS__) -#define AGM_LOGD(arg,...) ALOGD("%s: %d " arg, __func__, __LINE__, ##__VA_ARGS__) -#define AGM_LOGI(arg,...) ALOGI("%s: %d " arg, __func__, __LINE__, ##__VA_ARGS__) -#define AGM_LOGV(arg,...) ALOGV("%s: %d " arg, __func__, __LINE__, ##__VA_ARGS__) - -/*convert osal error codes to lnx error codes*/ -int ar_err_get_lnx_err_code(uint32_t error); -/*helper to print errors in string form*/ -char *ar_err_get_err_str(uint32_t error); - -#endif /*__UTILS_H*/ diff --git a/qcom/opensource/agm/service/src/agm.c b/qcom/opensource/agm/service/src/agm.c deleted file mode 100755 index 363c6374..00000000 --- a/qcom/opensource/agm/service/src/agm.c +++ /dev/null @@ -1,1113 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2022-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -#define LOG_TAG "AGM: API" -#include -#include -#include -#include -#include -#include "ats.h" -#include -#include -#include -#include - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_AGM_SRC -#include -#endif - -// { SEC_AUDIO_COMMON -#include -#include -// } SEC_AUDIO_COMMON - -#define RETRY_INTERVAL_US 500 * 1000 -static bool agm_initialized = 0; -static pthread_t ats_thread; -static const int MAX_RETRIES = 120; - -static void *ats_init_thread(void *obj __unused) -{ - int ret = 0; - int retry = 0; - - while(retry++ < MAX_RETRIES) { - ret = ats_init(); - if (0 != ret) { - AGM_LOGE("ats_init failed retry %d err %d", retry, ret); - usleep(RETRY_INTERVAL_US); - } else { - AGM_LOGD("ATS initialized"); - break; - } - } - return NULL; -} - -int agm_init() -{ -#ifdef SEC_AUDIO_BOOT_ON_ERR - AGM_LOGD("Enter. agm_initialized %d ", agm_initialized); -#endif - - int ret = 0; - -#ifdef SEC_FACTORY_INTERPOSER - AGM_LOGE("use default primary hal on secondary bin(not support audio)"); - property_set("vendor.audio.use.primary.default", "true"); - goto exit; -#endif -#ifdef SEC_AUDIO_BOOT_ON_ERR - if (property_get_bool("vendor.audio.use.primary.default", false)) { - AGM_LOGE("fail to init agm, sndcard is not active"); - goto exit; - } -#endif - - if (agm_initialized) - goto exit; - - pthread_attr_t tattr; - struct sched_param param; - -#ifdef DYNAMIC_LOG_ENABLED - register_for_dynamic_logging("agm"); - log_utils_init(); -#endif - - agm_memlog_init(); - pthread_attr_init (&tattr); - pthread_attr_getschedparam (&tattr, ¶m); - param.sched_priority = SCHED_FIFO; - pthread_attr_setschedparam (&tattr, ¶m); - - ret = session_obj_init(); - if (0 != ret) { - AGM_LOGE("Session_obj_init failed with %d", ret); - -#ifdef SEC_AUDIO_BOOT_ON_ERR - if (ret == -EAGAIN || ret == -EIO) { - property_set("vendor.audio.use.primary.default", "true"); - AGM_LOGE("sound card err, vendor.audio.use.primary.default as true"); - ret = 0; - } -#endif - - goto exit; - } - - agm_initialized = 1; - - ret = pthread_create(&ats_thread, (const pthread_attr_t *) &tattr, - ats_init_thread, NULL); - if (ret) - AGM_LOGE(" ats init thread creation failed\n"); - -exit: -#ifdef SEC_AUDIO_BOOT_ON_ERR - AGM_LOGD("Exit. agm_initialized %d ", agm_initialized); -#endif - return ret; -} - -int agm_deinit() -{ - //close all sessions first - if (agm_initialized) { - AGM_LOGD("Deinitializing ATS..."); - ats_deinit(); - session_obj_deinit(); - agm_memlog_deinit(); - agm_initialized = 0; - } - - return 0; -} - -int agm_get_aif_info_list(struct aif_info *aif_list, size_t *num_aif_info) -{ - if (!num_aif_info || ((*num_aif_info != 0) && !aif_list)) { - AGM_LOGE("Error Invalid params\n"); - return -EINVAL; - } - - return device_get_aif_info_list(aif_list, num_aif_info); -} - -int agm_get_group_aif_info_list(struct aif_info *aif_list, size_t *num_groups) -{ - if (!num_groups || ((*num_groups != 0) && !aif_list)) { - AGM_LOGE("Error Invalid params\n"); - return -EINVAL; - } - - return device_get_group_list(aif_list, num_groups); -} - -int agm_aif_set_metadata(uint32_t aif_id, uint32_t size, uint8_t *metadata) -{ - struct device_obj *obj = NULL; - int32_t ret = 0; - - ret = device_get_obj(aif_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving device obj with audio_intf id=%d\n", - ret, aif_id); - goto done; - } - - ret = device_set_metadata(obj, size, metadata); - if (ret) { - AGM_LOGE("Error:%d setting metadata device obj with" - "audio_intf id=%d\n", ret, aif_id); - goto done; - } - -done: - return ret; -} - -int agm_aif_set_media_config(uint32_t aif_id, - struct agm_media_config *media_config) -{ - struct device_obj *obj = NULL; - int ret = 0; - - ret = device_get_obj(aif_id, &obj); - if (ret) { - AGM_LOGE("Error:%d, retrieving device obj with audio_intf id=%d\n", - ret, aif_id); - goto done; - } - - ret = device_set_media_config(obj, media_config); - if (ret) { - AGM_LOGE("Error:%d setting mediaconfig device obj \ - with audio_intf id=%d\n", ret, aif_id); - goto done; - } - -done: - return ret; -} - -int agm_aif_group_set_media_config(uint32_t aif_group_id, - struct agm_group_media_config *media_config) -{ - struct device_group_data *grp_data = NULL; - int ret = 0; - - ret = device_get_group_data(aif_group_id, &grp_data); - if (ret) { - AGM_LOGE("Error:%d, retrieving device obj with audio_intf id=%d\n", - ret, aif_group_id); - goto done; - } - - ret = device_group_set_media_config(grp_data, media_config); - if (ret) { - AGM_LOGE("Error:%d setting mediaconfig for device group \ - with group id=%d\n", ret, aif_group_id); - goto done; - } - -done: - return ret; -} - -int agm_session_set_metadata(uint32_t session_id, - uint32_t size, uint8_t *metadata) -{ - - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_set_sess_metadata(obj, size, metadata); - if (ret) { - AGM_LOGE("Error:%d setting metadata for session obj with \ - session id=%d\n", ret, session_id); - goto done; - } - -done: - return ret; -} - -int agm_session_aif_set_metadata(uint32_t session_id, - uint32_t aif_id, - uint32_t size, uint8_t *metadata) -{ - - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_set_sess_aif_metadata(obj, aif_id, size, metadata); - if (ret) { - AGM_LOGE("Error:%d setting metadata for session obj \ - with session id=%d, aif_id=%d\n", ret, session_id, aif_id); - goto done; - } - -done: - return ret; -} - -int agm_session_aif_get_tag_module_info(uint32_t session_id, - uint32_t aif_id, void *payload, size_t *size) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_get_tag_with_module_info(obj, aif_id, payload, size); - if (ret) { - AGM_LOGE("Error:%d setting parameters for session obj with \ - session id=%d, aif_id=%d\n", - ret, session_id, aif_id); - goto done; - } - -done: - return ret; -} - -int agm_get_params_from_acdb_tunnel(void *payload, size_t *size) -{ - int ret = 0; - struct agm_acdb_tunnel_param *payloadACDBTunnelInfo = NULL; - uint32_t k = 0; - uint32_t *ptr = NULL; - uint32_t tag = 0; - struct agm_key_vector_gsl gkv = {0, NULL}; - - AGM_LOGD("enter\n"); - - if (!payload) { - AGM_LOGE("payload is nullptr"); - return -EINVAL; - } - - payloadACDBTunnelInfo = (struct agm_acdb_tunnel_param *)payload; - AGM_LOGD("payload size is 0x%x", *size); - AGM_LOGD("tag=%x istkv=%x num_gkvs=0x%x num_kvs=0x%x blob_size=0x%x", - payloadACDBTunnelInfo->tag, - payloadACDBTunnelInfo->isTKV, - payloadACDBTunnelInfo->num_gkvs, - payloadACDBTunnelInfo->num_kvs, - payloadACDBTunnelInfo->blob_size); - - ptr = payloadACDBTunnelInfo->blob; - for (k = 0; k < payloadACDBTunnelInfo->blob_size / 4; k++) { - AGM_LOGV("%d data = 0x%x", k, *ptr++); - } - - ptr = payloadACDBTunnelInfo->blob + sizeof(struct agm_key_value) * - (payloadACDBTunnelInfo->num_gkvs + payloadACDBTunnelInfo->num_kvs); - // tag is stored at miid. Convertion happens next. - AGM_LOGI("tag = 0x%x", *ptr); - - gkv.num_kvs = payloadACDBTunnelInfo->num_gkvs; - gkv.kv = payloadACDBTunnelInfo->blob; - - ret = session_dummy_rw_acdb_tunnel(payload, FALSE); - if (ret) { - AGM_LOGE("Error get tag list"); - goto error; - } - -error: - return ret; -} - -int agm_session_aif_set_cal(uint32_t session_id, - uint32_t aif_id, - struct agm_cal_config *cal_config) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_set_sess_aif_cal(obj, aif_id, cal_config); - if (ret) { - AGM_LOGE("Error:%d setting calibration for session obj \ - with session id=%d, aif_id=%d\n", - ret, session_id, aif_id); -goto done; -} - -done: -return ret; -} - -/* This does not support runtime update of device param payload */ -int agm_aif_set_params(uint32_t aif_id, - void* payload, size_t size) -{ - struct device_obj *obj = NULL; - int32_t ret = 0; - - ret = device_get_obj(aif_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving device obj with audio_intf id=%d\n", - ret, aif_id); - goto done; - } - - ret = device_set_params(obj, payload, size); - if (ret) { - AGM_LOGE("Error:%d set params for aif_id=%d\n", - ret, aif_id); - goto done; - } - -done: - return ret; -} - -int agm_session_aif_set_params(uint32_t session_id, - uint32_t aif_id, - void* payload, size_t size) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with \ - session id=%d\n", ret, session_id); - goto done; - } - - ret = session_obj_set_sess_aif_params(obj, aif_id, payload, size); - if (ret) { - AGM_LOGE("Error:%d setting parameters for session obj with \ - session id=%d, aif_id=%d\n", - ret, session_id, aif_id); - goto done; - } - -done: - return ret; -} - -int agm_session_get_params(uint32_t session_id, - void* payload, size_t size) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_get_sess_params(obj, payload, size); - if (ret) { - AGM_LOGE("Error:%d getting parameters for session obj with" - "session id=%d\n",ret, session_id); - goto done; - } - -done: - return ret; -} - -int agm_session_set_params(uint32_t session_id, - void* payload, size_t size) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_set_sess_params(obj, payload, size); - if (ret) { - AGM_LOGE("Error:%d setting parameters for session obj with \ - session id=%d\n", ret, session_id); - goto done; -} - -done: - return ret; -} - -int agm_set_params_with_tag(uint32_t session_id, uint32_t aif_id, - struct agm_tag_config *tag_config) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_set_sess_aif_params_with_tag(obj, aif_id, tag_config); - if (ret) { - AGM_LOGE("Error:%d setting parameters for session obj with \ - session id=%d\n", ret, session_id); - goto done; - } - -done: - return ret; -} - -int agm_set_params_with_tag_to_acdb(uint32_t session_id, uint32_t aif_id, - void *payload, size_t size) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_rw_acdb_params_with_tag(obj, aif_id, - (struct agm_acdb_param *)payload, true); - if (ret) { - AGM_LOGE("Error:%d setting parameters for session obj with \ - session id=%d\n", ret, session_id); - goto done; - } - -done: - return ret; -} - -int agm_set_params_to_acdb_tunnel(void *payload, size_t size) -{ - int ret = 0; - struct agm_acdb_tunnel_param *payloadACDBTunnelInfo = NULL; - uint32_t k = 0; - uint32_t *ptr = NULL; - uint32_t tag = 0; - - AGM_LOGD("enter\n"); - - if (!payload) { - AGM_LOGE("payload is nullptr"); - return -EINVAL; - } - - payloadACDBTunnelInfo = (struct agm_acdb_tunnel_param *)payload; - AGM_LOGD("payload size is 0x%x", size); - AGM_LOGD("tag=%x istkv=%x num_gkvs=0x%x num_kvs=0x%x blob_size=0x%x", - payloadACDBTunnelInfo->tag, - payloadACDBTunnelInfo->isTKV, - payloadACDBTunnelInfo->num_gkvs, - payloadACDBTunnelInfo->num_kvs, - payloadACDBTunnelInfo->blob_size); - - ptr = payloadACDBTunnelInfo->blob; - for (k = 0; k < payloadACDBTunnelInfo->blob_size / 4; k++) { - AGM_LOGV("%d data = 0x%x", k, *ptr++); - } - - ptr = payloadACDBTunnelInfo->blob + sizeof(struct agm_key_value) * - (payloadACDBTunnelInfo->num_gkvs + payloadACDBTunnelInfo->num_kvs); - // tag is stored at miid. Convertion happens next. - AGM_LOGI("tag = 0x%x", *ptr); - - ret = session_dummy_rw_acdb_tunnel(payload, TRUE); - if (ret) { - AGM_LOGE("Error get tag list"); - goto error; - } - -error: - return ret; -} - -int agm_session_register_cb(uint32_t session_id, agm_event_cb cb, - enum event_type evt_type, void *client_data) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_register_cb(obj, cb, evt_type, client_data); - if (ret) { - AGM_LOGE("Error:%d registering callback for session obj with \ - session id=%d\n", ret, session_id); - goto done; - } - -done: - return ret; -} - -int agm_session_register_for_events(uint32_t session_id, - struct agm_event_reg_cfg *evt_reg_cfg) -{ - struct session_obj *obj = NULL; - int ret = 0; - - if (!evt_reg_cfg) { - AGM_LOGE("Invalid ev_reg_cfg for session id=%d\n", - session_id); - ret = -EINVAL; - goto done; - } - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_register_for_events(obj, evt_reg_cfg); - if (ret) { - AGM_LOGE("Error:%d registering event for session obj with \ - session id=%d\n", ret, session_id); - goto done; - } - -done: - return ret; -} - -int agm_session_aif_connect(uint32_t session_id, - uint32_t aif_id, - bool state) -{ - - struct session_obj *obj = NULL; - int ret = 0; - - AGM_LOGI("%sconnecting aifid:%d with session id=%d\n", - (state ? "": "dis"), aif_id, session_id); - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_sess_aif_connect(obj, aif_id, state); - if (ret) { - AGM_LOGE("Error:%d Connecting aifid:%d with session id=%d\n", - ret, aif_id, session_id); - goto done; - } - -done: -return ret; -} - -int agm_session_open(uint32_t session_id, - enum agm_session_mode sess_mode, - uint64_t *hndl) -{ - - struct session_obj **handle = (struct session_obj**) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_open(session_id, sess_mode, handle); -} - -int agm_session_set_config(uint64_t hndl, - struct agm_session_config *stream_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config) -{ - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - return session_obj_set_config(handle, stream_config, media_config, - buffer_config); -} - -int agm_session_prepare(uint64_t hndl) -{ - - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_prepare(handle); -} - -int agm_session_start(uint64_t hndl) -{ - - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_start(handle); -} - -int agm_session_stop(uint64_t hndl) -{ - - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_stop(handle); -} - -int agm_session_close(uint64_t hndl) -{ - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_close(handle); -} - -int agm_session_pause(uint64_t hndl) -{ - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_pause(handle); -} - -int agm_session_flush(uint64_t hndl) -{ - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_flush(handle); -} - -int agm_sessionid_flush(uint32_t session_id) -{ - struct session_obj *handle = NULL; - int ret = 0; - - handle = session_obj_retrieve_from_pool(session_id); - if (!handle) { - AGM_LOGE("Incorrect session_id:%d, doesn't match sess_obj from pool", - session_id); - return -EINVAL; - } - return session_obj_flush(handle); -} - -int agm_session_resume(uint64_t hndl) -{ - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_resume(handle); -} - -int agm_session_suspend(uint64_t hndl) -{ - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_suspend(handle); -} - -int agm_session_write(uint64_t hndl, void *buff, size_t *count) -{ - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_write(handle, buff, count); -} - -int agm_session_read(uint64_t hndl, void *buff, size_t *count) -{ - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_read(handle, buff, count); -} - -size_t agm_get_hw_processed_buff_cnt(uint64_t hndl, enum direction dir) -{ - struct session_obj *handle = (struct session_obj *) hndl; - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(hndl)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_hw_processed_buff_cnt(handle, dir); -} - -int agm_session_set_loopback(uint32_t capture_session_id, - uint32_t playback_session_id, bool state) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(capture_session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, capture_session_id); - goto done; - } - - ret = session_obj_set_loopback(obj, playback_session_id, state); - if (ret) { - AGM_LOGE("Error:%d setting loopback for session obj with \ - session id=%d\n", ret, capture_session_id); - goto done; - } - -done: - return ret; -} - - -int agm_session_set_ec_ref(uint32_t capture_session_id, uint32_t aif_id, - bool state) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(capture_session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, capture_session_id); - goto done; - } - - ret = session_obj_set_ec_ref(obj, aif_id, state); - if (ret) { - AGM_LOGE("Error:%d setting ec_ref for session obj with \ - session id=%d\n", ret, capture_session_id); - goto done; - } - -done: - return ret; -} - -int agm_session_eos(uint64_t handle) -{ - if (!handle) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(handle)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_eos((struct session_obj *) handle); -} - -int agm_get_session_time(uint64_t handle, uint64_t *timestamp) -{ - if (!handle || !timestamp) { - AGM_LOGE("Invalid handle or timestamp pointer\n"); - return -EINVAL; - } - - if (!session_obj_valid_check(handle)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_get_timestamp((struct session_obj *) handle, timestamp); -} - -int agm_get_buffer_timestamp(uint32_t session_id, uint64_t *timestamp) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - return ret; - } - - if (!timestamp) { - AGM_LOGE("Invalid timestamp pointer\n"); - return -EINVAL; - } - - return session_obj_buffer_timestamp(obj, timestamp); -} - -int agm_session_get_buf_info(uint32_t session_id, struct agm_buf_info *buf_info, uint32_t flag) -{ - struct session_obj *obj = NULL; - int ret = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - memset(buf_info, 0, sizeof(struct agm_buf_info)); - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - goto done; - } - - ret = session_obj_get_sess_buf_info(obj, buf_info, flag); - if (ret) { - memset(buf_info, 0, sizeof(struct agm_buf_info)); - AGM_LOGE("Error:%d getting buf_info for session id=%d, flag = %d\n", - ret, session_id, flag); - } - -done: - return ret; -} - -int agm_register_service_crash_callback(agm_service_crash_cb cb __unused, - uint64_t cookie __unused) -{ - - AGM_LOGE("client directly communicating with agm need not call this api"); - return -ENOSYS; -} - -int agm_set_gapless_session_metadata(uint64_t handle, - enum agm_gapless_silence_type type, - uint32_t silence) -{ - if (!handle) { - AGM_LOGE("%s Invalid handle\n", __func__); - return -EINVAL; - } - - if (!session_obj_valid_check(handle)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_set_gapless_metadata((struct session_obj *) handle, type, - silence); -} - -int agm_session_write_with_metadata(uint64_t handle, struct agm_buff *buff, - size_t *consumed_size) -{ - if (!handle) { - AGM_LOGE("%s Invalid handle\n", __func__); - return -EINVAL; - } - - if (!session_obj_valid_check(handle)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_write_with_metadata((struct session_obj *) handle, buff, - consumed_size); -} - -int agm_session_read_with_metadata(uint64_t handle, struct agm_buff *buff, - uint32_t *captured_size ) -{ - if (!handle) { - AGM_LOGE("%s Invalid handle\n", __func__); - return -EINVAL; - } - - if (!session_obj_valid_check(handle)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_read_with_metadata((struct session_obj *) handle, buff, - captured_size); -} - -int agm_session_set_non_tunnel_mode_config(uint64_t handle, - struct agm_session_config *session_config, - struct agm_media_config *in_media_config, - struct agm_media_config *out_media_config, - struct agm_buffer_config *in_buffer_config, - struct agm_buffer_config *out_buffer_config) -{ - if (!handle) { - AGM_LOGE("%s Invalid handle\n", __func__); - return -EINVAL; - } - - if (!session_obj_valid_check(handle)) { - AGM_LOGE("Invalid handle\n"); - return -EINVAL; - } - return session_obj_set_non_tunnel_mode_config((struct session_obj *) handle, - session_config, - in_media_config, - out_media_config, - in_buffer_config, - out_buffer_config); -} - -int agm_session_write_datapath_params(uint32_t session_id, struct agm_buff *buff) -{ - struct session_obj *obj = NULL; - int ret = 0; - size_t consumed_size = 0; - - ret = session_obj_get(session_id, &obj); - if (ret) { - AGM_LOGE("Error:%d retrieving session obj with session id=%d\n", - ret, session_id); - return ret; - } - - return session_obj_write_with_metadata(obj, buff, &consumed_size); -} - -int agm_dump(struct agm_dump_info *dump_info __unused) -{ - // Placeholder for future enhancements - return 0; -} diff --git a/qcom/opensource/agm/service/src/agm_memlogger.c b/qcom/opensource/agm/service/src/agm_memlogger.c deleted file mode 100755 index 78e32ff2..00000000 --- a/qcom/opensource/agm/service/src/agm_memlogger.c +++ /dev/null @@ -1,79 +0,0 @@ -/* -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#include -#include - -void agm_memlog_init() -{ - int ret = 0; - ret = memLoggerInitQ(GRAPH_Q, MEMLOG_CFG_FILE); //initializes the queue for the debug logger - if (ret) { - AGM_LOGE("error in initializing memory queue %d", ret); - } - ret = memLoggerInitStatbuf(GRAPH_STATBUF, MEMLOG_CFG_FILE); - if (ret) { - AGM_LOGE("error in initializing graph static buffer %d", ret); - } - - ret = memLoggerInitQ(SPF_RESET_Q, MEMLOG_CFG_FILE); //initializes the queue for the debug logger - if (ret) { - AGM_LOGE("error in initializing SPF Reset queue %d", ret); - } - ret = memLoggerInitStatbuf(SPF_RESET_STATBUF, MEMLOG_CFG_FILE); - if (ret) { - AGM_LOGE("error in initializing SPF reset static buffer %d", ret); - } - ret = gsl_register_global_event_cb(agm_memlog_spf_reset_cb, NULL); - if (ret) { - AGM_LOGE("error in initializing SPF reset callback %d", ret); - } -} - -void agm_memlog_deinit() -{ - memLoggerDeinitQ(GRAPH_Q); - memLoggerDeinitStatbuf(GRAPH_STATBUF); -} - -void agm_memlog_graph_enqueue(graph_queue_state qState, int qResult, void *qHandle) -{ - struct graph_queue que; - - que.timestamp = memLoggerFetchTimestamp(); - que.state = qState; - que.result = qResult; - que.stream_handle = qHandle; - - memLoggerEnqueue(GRAPH_Q, (void*) &que); - if (qResult != 0) - { - memLoggerIncrementStatbuf(GRAPH_STATBUF, qState); - } -} - -void agm_memlog_spf_reset_enqueue(spf_reset_state qState) -{ - struct ssr_pdr_queue que; - - que.timestamp = memLoggerFetchTimestamp(); - que.state = qState; - - memLoggerEnqueue(SPF_RESET_Q, (void*) &que); - memLoggerIncrementStatbuf(SPF_RESET_STATBUF, qState); -} - -uint32_t agm_memlog_spf_reset_cb(enum gsl_global_event_ids event_id, void *event_payload, size_t event_payload_sz, void *client_data) -{ - if (event_id == GSL_GLOBAL_EVENT_AUDIO_SVC_DN) - { - agm_memlog_spf_reset_enqueue(SPF_RESET_DOWN); - } - else if (event_id == GSL_GLOBAL_EVENT_AUDIO_SVC_UP) - { - agm_memlog_spf_reset_enqueue(SPF_RESET_UP); - } - return 0; -} diff --git a/qcom/opensource/agm/service/src/device.c b/qcom/opensource/agm/service/src/device.c deleted file mode 100755 index 1c6323a0..00000000 --- a/qcom/opensource/agm/service/src/device.c +++ /dev/null @@ -1,1303 +0,0 @@ -/* -** Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved. -** SPDX-License-Identifier: BSD-3-Clause-Clear -**/ - -#define LOG_TAG "AGM: device" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef DEVICE_USES_ALSALIB -#include -#else -#include -#endif - -#define SNDCARD_PATH "/sys/kernel/snd_card/card_state" -#define PCM_DEVICE_FILE "/proc/asound/pcm" - -// { SEC_AUDIO_BOOT_ON_ERR // 100s -> 60s -#define MAX_RETRY 60 /*Device will try these many times before return an error*/ -// } SEC_AUDIO_BOOT_ON_ERR -#define RETRY_INTERVAL 1 /*Retry interval in seconds*/ - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_DEVICE -#include -#endif - -#define TRUE 1 -#define FALSE 0 - -#define BUF_SIZE 1024 -#define FILE_PATH_EXTN_MAX_SIZE 80 -#define MAX_RETRY_CNT 20 -#define SND_CARD_DEVICE_FILE "/proc/asound/cards" - -/* Global list to store supported devices */ -static struct listnode device_list; -static struct listnode device_group_data_list; -static uint32_t num_audio_intfs; -static uint32_t num_group_devices; - -#ifdef DEVICE_USES_ALSALIB -static snd_ctl_t *mixer; -#else -static struct mixer *mixer = NULL; -#endif - -#define MAX_BUF_SIZE 2048 -/** - * The maximum period bytes for dummy dai is 8192 bytes. - * Hard coding of period size to 960 frames was leading - * to bigger period bytes for multi channels. - * So, now based on frame size, Period size is being calculated. - * 1 frame = bytes_per_sample * channels - * period size = 8192/(bytes_per_sample * channels) - */ -#define MAX_PERIOD_BUFFER 8192 -#define DEFAULT_PERIOD_COUNT 2 - -#define MAX_USR_INPUT 9 - -#define AGM_PCM_RATE_5512 (5512) -#define AGM_PCM_RATE_8000 (8000) -#define AGM_PCM_RATE_11025 (11025) -#define AGM_PCM_RATE_16000 (16000) -#define AGM_PCM_RATE_22050 (2205) -#define AGM_PCM_RATE_32000 (32000) -#define AGM_PCM_RATE_44100 (44100) -#define AGM_PCM_RATE_48000 (48000) -#define AGM_PCM_RATE_64000 (64000) -#define AGM_PCM_RATE_88200 (88200) -#define AGM_PCM_RATE_96000 (96000) -#define AGM_PCM_RATE_176400 (176400) -#define AGM_PCM_RATE_192000 (192000) -#define AGM_PCM_RATE_352800 (352800) -#define AGM_PCM_RATE_384000 (384000) - -#define AGM_DEFAULT_PCM_RATE (AGM_PCM_RATE_48000) - -/** Sound card state */ -typedef enum snd_card_status_t { - SND_CARD_STATUS_OFFLINE = 0, - SND_CARD_STATUS_ONLINE, - SND_CARD_STATUS_NONE, -} snd_card_status_t; - -int get_pcm_bits_per_sample(enum agm_media_format fmt_id) -{ - int bits_per_sample = 16; - - switch(fmt_id) { - case AGM_FORMAT_PCM_S8: /**< 8-bit signed */ - bits_per_sample = 8; - break; - case AGM_FORMAT_PCM_S24_LE: /**< 24-bits in 4-bytes, 8_24 form*/ - bits_per_sample = 32; - break; - case AGM_FORMAT_PCM_S24_3LE: /**< 24-bits in 3-bytes */ - bits_per_sample = 24; - break; - case AGM_FORMAT_PCM_S32_LE: /**< 32-bit signed */ - bits_per_sample = 32; - break; - case AGM_FORMAT_PCM_S16_LE: /**< 16-bit signed */ - default: - bits_per_sample = 16; - break; - } - return bits_per_sample; -} - -int device_get_snd_card_id() -{ - struct device_obj *dev_obj = node_to_item(list_head(&device_list), - struct device_obj, list_node); - - if (dev_obj == NULL) { - AGM_LOGE("%s: Invalid device object\n", __func__); - return -EINVAL; - } - return dev_obj->card_id; -} - -static struct device_obj *device_get_pcm_obj(struct device_obj *dev_obj) -{ - if (dev_obj->parent_dev) - return dev_obj->parent_dev; - else - return dev_obj; -} - -#ifdef DEVICE_USES_ALSALIB -snd_pcm_format_t agm_to_alsa_format(enum agm_media_format format) -{ - switch (format) { - case AGM_FORMAT_PCM_S32_LE: - return SND_PCM_FORMAT_S32_LE; - case AGM_FORMAT_PCM_S8: - return SND_PCM_FORMAT_S8; - case AGM_FORMAT_PCM_S24_3LE: - return SND_PCM_FORMAT_S24_3LE; - case AGM_FORMAT_PCM_S24_LE: - return SND_PCM_FORMAT_S24_LE; - default: - case AGM_FORMAT_PCM_S16_LE: - return SND_PCM_FORMAT_S16_LE; - }; -} - - -int device_open(struct device_obj *dev_obj) -{ - int ret = 0; - snd_pcm_t *pcm; - char pcm_name[80]; - snd_pcm_stream_t stream; - snd_pcm_hw_params_t *hwparams; - snd_pcm_format_t format; - snd_pcm_uframes_t period_size; - unsigned int rate, channels, period_count; - struct device_group_data *grp_data = NULL; - struct agm_media_config *media_config = NULL; - struct device_obj *obj = NULL; - - if (dev_obj == NULL) { - AGM_LOGE("%s: Invalid device object\n", __func__); - return -EINVAL; - } - - obj = device_get_pcm_obj(dev_obj); - - snprintf(pcm_name, sizeof(pcm_name), "hw:%u,%u", obj->card_id, obj->pcm_id); - - stream = (obj->hw_ep_info.dir == AUDIO_OUTPUT) ? - SND_PCM_STREAM_PLAYBACK : SND_PCM_STREAM_CAPTURE; - - pthread_mutex_lock(&obj->lock); - - if (obj->group_data) - grp_data = obj->group_data; - - if (obj->refcnt.open) { - AGM_LOGE("%s: PCM device %u already opened\n", - __func__, obj->pcm_id); - obj->refcnt.open++; - if (grp_data) - grp_data->refcnt.open++; - goto done; - } - - if (grp_data && !grp_data->has_multiple_dai_link) - media_config = &grp_data->media_config.config; - else - media_config = &dev_obj->media_config; - - channels = media_config->channels; - rate = media_config->rate; - format = agm_to_alsa_format(media_config->format); - period_size = (MAX_PERIOD_BUFFER)/(channels * - (get_pcm_bits_per_sample(media_config->format)/8)); - period_count = DEFAULT_PERIOD_COUNT; - - ret = snd_pcm_open(&pcm, pcm_name, stream, 0); - if (ret < 0) { - AGM_LOGE("%s: Unable to open PCM device %s", __func__, pcm_name); - goto done; - } - - snd_pcm_hw_params_alloca(&hwparams); - - ret = snd_pcm_hw_params_any(pcm, hwparams); - if (ret < 0) { - AGM_LOGE("Default config not available for %s, exiting", pcm_name); - goto done; - } - snd_pcm_hw_params_set_access(pcm, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED); - snd_pcm_hw_params_set_format(pcm, hwparams, format); - snd_pcm_hw_params_set_channels(pcm, hwparams, channels); - snd_pcm_hw_params_set_rate(pcm, hwparams, rate, 0); - snd_pcm_hw_params_set_period_size(pcm, hwparams, period_size, 0); - snd_pcm_hw_params_set_periods(pcm, hwparams, period_count, 0); - - ret = snd_pcm_hw_params(pcm, hwparams); - if (ret < 0) { - AGM_LOGE("%s unable to set hw params for %s, rate[%u], ch[%u], fmt[%u]", - __func__, pcm_name, rate, channels, format); - goto done; - } - obj->pcm = pcm; - obj->state = DEV_OPENED; - obj->refcnt.open++; - if (grp_data) - grp_data->refcnt.open++; -done: - pthread_mutex_unlock(&obj->lock); - return ret; -} -#else -enum pcm_format agm_to_pcm_format(enum agm_media_format format) -{ - switch (format) { - case AGM_FORMAT_PCM_S32_LE: - return PCM_FORMAT_S32_LE; - case AGM_FORMAT_PCM_S8: - return PCM_FORMAT_S8; - case AGM_FORMAT_PCM_S24_3LE: - return PCM_FORMAT_S24_3LE; - case AGM_FORMAT_PCM_S24_LE: - return PCM_FORMAT_S24_LE; - default: - case AGM_FORMAT_PCM_S16_LE: - return PCM_FORMAT_S16_LE; - }; -} - -bool device_pcm_is_rate_supported(unsigned int rate) -{ - switch(rate) { - case AGM_PCM_RATE_5512: - case AGM_PCM_RATE_8000: - case AGM_PCM_RATE_11025: - case AGM_PCM_RATE_16000: - case AGM_PCM_RATE_22050: - case AGM_PCM_RATE_32000: - case AGM_PCM_RATE_44100: - case AGM_PCM_RATE_48000: - case AGM_PCM_RATE_64000: - case AGM_PCM_RATE_88200: - case AGM_PCM_RATE_96000: - case AGM_PCM_RATE_176400: - case AGM_PCM_RATE_192000: - case AGM_PCM_RATE_352800: - case AGM_PCM_RATE_384000: - return true; - default: - return false; - }; -} - -int device_open(struct device_obj *dev_obj) -{ - int ret = 0; - struct pcm *pcm = NULL; - struct pcm_config config; - uint32_t pcm_flags; - struct device_group_data *grp_data = NULL; - struct agm_media_config *media_config = NULL; - struct device_obj *obj = NULL; - - if (dev_obj == NULL) { - AGM_LOGE("Invalid device object\n"); - return -EINVAL; - } - - obj = device_get_pcm_obj(dev_obj); - pthread_mutex_lock(&obj->lock); - - if (obj->group_data) - grp_data = obj->group_data; - - if (obj->refcnt.open) { - AGM_LOGI("PCM device %u already opened\n", - obj->pcm_id); - obj->refcnt.open++; - if (grp_data) - grp_data->refcnt.open++; - goto done; - } - - memset(&config, 0, sizeof(struct pcm_config)); - if (grp_data && !grp_data->has_multiple_dai_link) - media_config = &grp_data->media_config.config; - else - media_config = &dev_obj->media_config; - - config.channels = media_config->channels; - config.rate = media_config->rate; - if (!device_pcm_is_rate_supported(config.rate)) { - AGM_LOGD("Unsupported PCM rate %d changing to default rate %d\n", - config.rate, AGM_DEFAULT_PCM_RATE); - config.rate = AGM_DEFAULT_PCM_RATE; - } - - config.format = agm_to_pcm_format(media_config->format); - config.period_size = (MAX_PERIOD_BUFFER)/(config.channels * - (get_pcm_bits_per_sample(media_config->format)/8)); - - config.period_count = DEFAULT_PERIOD_COUNT; - config.start_threshold = config.period_size / 4; - config.stop_threshold = INT_MAX; - - pcm_flags = (obj->hw_ep_info.dir == AUDIO_OUTPUT) ? PCM_OUT : PCM_IN; - pcm = pcm_open(obj->card_id, obj->pcm_id, pcm_flags, - &config); - if (!pcm || !pcm_is_ready(pcm)) { - AGM_LOGE("Unable to open PCM device %u (%s) rate %u ch %d fmt %u", - obj->pcm_id, pcm_get_error(pcm), config.rate, - config.channels, config.format); - AGM_LOGE("Period Size %d \n", config.period_size); - ret = -EIO; - goto done; - } - obj->pcm = pcm; - obj->state = DEV_OPENED; - obj->refcnt.open++; - if (grp_data) - grp_data->refcnt.open++; -done: - pthread_mutex_unlock(&obj->lock); - return ret; -} -#endif - -int device_prepare(struct device_obj *dev_obj) -{ - int ret = 0; - struct device_group_data *grp_data = NULL; - struct device_obj *obj = NULL; - - if (dev_obj == NULL) { - AGM_LOGE("Invalid device object\n"); - return -EINVAL; - } - - obj = device_get_pcm_obj(dev_obj); - - pthread_mutex_lock(&obj->lock); - - if (obj->group_data) - grp_data = obj->group_data; - - if (obj->refcnt.prepare) { - AGM_LOGD("PCM device %u already in prepare state\n", - obj->pcm_id); - obj->refcnt.prepare++; - if (grp_data) - grp_data->refcnt.prepare++; - pthread_mutex_unlock(&obj->lock); - return ret; - } -#ifdef DEVICE_USES_ALSALIB - ret = snd_pcm_prepare(obj->pcm); -#else - ret = pcm_prepare(obj->pcm); -#endif - if (ret) { - AGM_LOGE("PCM device %u prepare failed, ret = %d\n", - obj->pcm_id, ret); - goto done; - } - - obj->state = DEV_PREPARED; - obj->refcnt.prepare++; - -done: - pthread_mutex_unlock(&obj->lock); - return ret; -} - -int device_start(struct device_obj *dev_obj) -{ - int ret = 0; - struct device_group_data *grp_data = NULL; - struct device_obj *obj = NULL; - - if (dev_obj == NULL) { - AGM_LOGE("Invalid device object\n"); - return -EINVAL; - } - - obj = device_get_pcm_obj(dev_obj); - - pthread_mutex_lock(&obj->lock); - if (obj->state < DEV_PREPARED) { - AGM_LOGE("PCM device %u not yet prepared, exiting\n", - obj->pcm_id); - ret = -1; - goto done; - } - - if (obj->group_data) - grp_data = obj->group_data; - - if (obj->refcnt.start) { - AGM_LOGI("PCM device %u already in start state\n", - obj->pcm_id); - obj->refcnt.start++; - if (grp_data) - grp_data->refcnt.start++; - goto done; - } - - obj->state = DEV_STARTED; - obj->refcnt.start++; - if (grp_data) - grp_data->refcnt.start++; - -done: - pthread_mutex_unlock(&obj->lock); - return ret; -} - -int device_stop(struct device_obj *dev_obj) -{ - int ret = 0; - struct device_group_data *grp_data = NULL; - struct device_obj *obj = NULL; - - if(dev_obj == NULL) { - AGM_LOGE("Invalid device object\n"); - return -EINVAL; - } - - obj = device_get_pcm_obj(dev_obj); - - pthread_mutex_lock(&obj->lock); - if (!obj->refcnt.start) { - AGM_LOGE("PCM device %u already stopped\n", - obj->pcm_id); - goto done; - } - - if (obj->group_data) { - grp_data = obj->group_data; - grp_data->refcnt.start--; - } - - obj->refcnt.start--; - if (obj->refcnt.start == 0) { -#ifdef DEVICE_USES_ALSALIB - ret = snd_pcm_drop(obj->pcm); -#else - ret = pcm_stop(obj->pcm); -#endif - if (ret) { - AGM_LOGE("PCM device %u stop failed, ret = %d\n", - obj->pcm_id, ret); - } - obj->state = DEV_STOPPED; - } - -done: - pthread_mutex_unlock(&obj->lock); - return ret; -} - -int device_close(struct device_obj *dev_obj) -{ - int ret = 0; - struct device_group_data *grp_data = NULL; - struct device_obj *obj = NULL; - - if (dev_obj == NULL) { - AGM_LOGE("Invalid device object\n"); - return -EINVAL; - } - - obj = device_get_pcm_obj(dev_obj); - - pthread_mutex_lock(&obj->lock); - if (!obj->refcnt.open) { - AGM_LOGE("PCM device %u already closed\n", - obj->pcm_id); - goto done; - } - - if (obj->group_data) { - grp_data = obj->group_data; - if (--grp_data->refcnt.open == 0) { - grp_data->refcnt.prepare = 0; - grp_data->refcnt.start = 0; - } - } - - if (--obj->refcnt.open == 0) { -#ifdef DEVICE_USES_ALSALIB - ret = snd_pcm_close(obj->pcm); -#else - ret = pcm_close(obj->pcm); -#endif - if (ret) { - AGM_LOGE("PCM device %u close failed, ret = %d\n", - obj->pcm_id, ret); - } -// { SEC_AUDIO_ADD_FOR_DEBUG - else { - AGM_LOGI("PCM device %u closed\n", obj->pcm_id); - } -// } SEC_AUDIO_ADD_FOR_DEBUG - - obj->state = DEV_CLOSED; - obj->refcnt.prepare = 0; - obj->refcnt.start = 0; - } - -done: - pthread_mutex_unlock(&obj->lock); - return ret; -} - -enum device_state device_current_state(struct device_obj *dev_obj) -{ - return dev_obj->state; -} - -int device_get_aif_info_list(struct aif_info *aif_list, size_t *audio_intfs) -{ - struct device_obj *dev_obj; - uint32_t copied = 0; - uint32_t requested = *audio_intfs; - struct listnode *dev_node, *temp; - - if (*audio_intfs == 0){ - *audio_intfs = num_audio_intfs; - } else { - list_for_each_safe(dev_node, temp, &device_list) { - dev_obj = node_to_item(dev_node, struct device_obj, list_node); - strlcpy(aif_list[copied].aif_name, dev_obj->name, - AIF_NAME_MAX_LEN); - aif_list[copied].dir = dev_obj->hw_ep_info.dir; - copied++; - if (copied == requested) - break; - } - *audio_intfs = copied; - } - return 0; -} - -int device_get_group_list(struct aif_info *aif_list, size_t *num_groups) -{ - struct device_group_data *grp_data; - uint32_t copied = 0; - uint32_t requested = *num_groups; - struct listnode *grp_node, *temp; - - if (*num_groups == 0){ - *num_groups = num_group_devices; - } else { - list_for_each_safe(grp_node, temp, &device_group_data_list) { - grp_data = node_to_item(grp_node, struct device_group_data, list_node); - strlcpy(aif_list[copied].aif_name, grp_data->name, - AIF_NAME_MAX_LEN); - copied++; - if (copied == requested) - break; - } - *num_groups = copied; - } - return 0; -} - -int device_get_obj(uint32_t device_idx, struct device_obj **dev_obj) -{ - int i = 0; - struct listnode *dev_node, *temp; - struct device_obj *obj; - - if (device_idx > num_audio_intfs) { - AGM_LOGE("Invalid device_id %u, max_supported device id: %d\n", - device_idx, num_audio_intfs); - return -EINVAL; - } - - list_for_each_safe(dev_node, temp, &device_list) { - if (i++ == device_idx) { - obj = node_to_item(dev_node, struct device_obj, list_node); - *dev_obj = obj; - return 0; - } - } - return -EINVAL; -} - -int device_get_group_data(uint32_t group_id , struct device_group_data **grp_data) -{ - int i = 0; - struct listnode *group_node, *temp; - struct device_group_data *data; - - if (group_id >= num_group_devices) { - AGM_LOGE("Invalid group_id %u, max_supported device id: %d\n", - group_id, num_group_devices); - return -EINVAL; - } - - list_for_each_safe(group_node, temp, &device_group_data_list) { - if (i++ == group_id) { - data = node_to_item(group_node, struct device_group_data, list_node); - *grp_data = data; - return 0; - } - } - return -EINVAL; -} - -int device_set_media_config(struct device_obj *dev_obj, - struct agm_media_config *device_media_config) -{ - if (dev_obj == NULL || device_media_config == NULL) { - AGM_LOGE("Invalid device object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&dev_obj->lock); - dev_obj->media_config.channels = device_media_config->channels; - dev_obj->media_config.rate = device_media_config->rate; - dev_obj->media_config.format = device_media_config->format; - dev_obj->media_config.data_format = device_media_config->data_format; - pthread_mutex_unlock(&dev_obj->lock); - - return 0; -} - -int device_group_set_media_config(struct device_group_data *grp_data, - struct agm_group_media_config *media_config) -{ - if (grp_data == NULL || media_config == NULL) { - AGM_LOGE("Invalid input\n"); - return -EINVAL; - } - memcpy(&grp_data->media_config, media_config, sizeof(*media_config)); - - return 0; -} - -int device_set_metadata(struct device_obj *dev_obj, uint32_t size, - uint8_t *metadata) -{ - int ret = 0; - - pthread_mutex_lock(&dev_obj->lock); - metadata_free(&dev_obj->metadata); - ret = metadata_copy(&(dev_obj->metadata), size, metadata); -#ifdef AGM_DEBUG_METADATA - AGM_LOGI("Setting device metadata for %s\n", dev_obj->name); - metadata_print(&(dev_obj->metadata)); -#endif - pthread_mutex_unlock(&dev_obj->lock); - - return ret; -} - -int device_set_params(struct device_obj *dev_obj, - void *payload, size_t size) -{ - int ret = 0; - - pthread_mutex_lock(&dev_obj->lock); - - if (dev_obj->params) { - free(dev_obj->params); - dev_obj->params = NULL; - dev_obj->params_size = 0; - } - - dev_obj->params = calloc(1, size); - if (!dev_obj->params) { - AGM_LOGE("No memory for dev params on dev_id:%d\n", - dev_obj->pcm_id); - ret = -EINVAL; - goto done; - } - - memcpy(dev_obj->params, payload, size); - dev_obj->params_size = size; - -done: - pthread_mutex_unlock(&dev_obj->lock); - return ret; -} - -#ifdef DEVICE_USES_ALSALIB -int device_get_channel_map(struct device_obj *dev_obj, uint32_t **chmap) -{ - snd_ctl_elem_id_t *id; - snd_ctl_elem_info_t *info; - snd_ctl_elem_value_t *control; - char *mixer_str = NULL; - int i, ctl_len = 0, ret = 0, card_id; - uint8_t *payload = NULL; - char card[16]; - char *dev_name = NULL; - - if (mixer == NULL) { - card_id = device_get_snd_card_id(); - if (card_id < 0) { - AGM_LOGE("%s: failed to get card_id", __func__); - return -EINVAL; - } - - snprintf(card, 16, "hw:%u", card_id); - if ((ret = snd_ctl_open(&mixer, card, 0)) < 0) { - AGM_LOGE("Control device %s open error: %s", card, snd_strerror(ret)); - return ret; - } - - } - - if (dev_obj->parent_dev) - dev_name = dev_obj->parent_dev->name; - else - dev_name = dev_obj->name; - - ctl_len = strlen(dev_name) + 1 + strlen("Channel Map") + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - AGM_LOGE("%s: Failed to allocate memory for mixer_str", __func__); - return -ENOMEM; - } - - payload = calloc(16, sizeof(uint32_t)); - if (!payload) { - AGM_LOGE("%s: Failed to allocate memory for payload", __func__); - ret = -ENOMEM; - goto done; - } - - snprintf(mixer_str, ctl_len, "%s %s", dev_name, "Channel Map"); - - snd_ctl_elem_id_alloca(&id); - snd_ctl_elem_info_alloca(&info); - snd_ctl_elem_value_alloca(&control); - - snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER); - snd_ctl_elem_id_set_name(id, (const char *)mixer_str); - - snd_ctl_elem_info_set_id(info, id); - ret = snd_ctl_elem_info(mixer, info); - if (ret < 0) { - AGM_LOGE("Cannot get element info for %s\n", mixer_str); - goto done; - } - snd_ctl_elem_info_get_id(info, id); - - snd_ctl_elem_value_set_id(control, id); - ret = snd_ctl_elem_read(mixer, control); - if (ret < 0) { - AGM_LOGE("Failed to mixer_ctl_get_array\n"); - goto err_get_ctl; - } - - for (i = 0; i < 16 * sizeof(uint32_t); i++) - payload[i] = snd_ctl_elem_value_get_byte(control, i); - - *chmap = payload; - goto done; - -err_get_ctl: -done: - free(mixer_str); - return ret; -} -#else -int device_get_channel_map(struct device_obj *dev_obj, uint32_t **chmap) -{ - struct mixer_ctl *ctl = NULL; - char *mixer_str = NULL; - int ctl_len = 0, ret = 0, card_id; - void *payload = NULL; - char *dev_name = NULL; - - if (mixer == NULL) { - card_id = device_get_snd_card_id(); - if (card_id < 0) { - AGM_LOGE("failed to get card_id"); - return -EINVAL; - } - - mixer = mixer_open(card_id); - if (!mixer) { - AGM_LOGE("failed to get mixer handle"); - return -EINVAL; - } - } - - if (dev_obj->parent_dev) - dev_name = dev_obj->parent_dev->name; - else - dev_name = dev_obj->name; - - ctl_len = strlen(dev_name) + 1 + strlen("Channel Map") + 1; - mixer_str = calloc(1, ctl_len); - if (!mixer_str) { - AGM_LOGE("Failed to allocate memory for mixer_str"); - return -ENOMEM; - } - - payload = calloc(16, sizeof(uint32_t)); - if (!payload) { - AGM_LOGE("Failed to allocate memory for payload"); - ret = -ENOMEM; - goto done; - } - - snprintf(mixer_str, ctl_len, "%s %s", dev_name, "Channel Map"); - - ctl = mixer_get_ctl_by_name(mixer, mixer_str); - if (!ctl) { - AGM_LOGE("Invalid mixer control: %s\n", mixer_str); - ret = -ENOENT; - goto err_get_ctl; - } - - ret = mixer_ctl_get_array(ctl, payload, 16 * sizeof(uint32_t)); - if (ret < 0) { - AGM_LOGE("Failed to mixer_ctl_get_array\n"); - goto err_get_ctl; - } - *chmap = payload; - goto done; - -err_get_ctl: - free(payload); -done: - free(mixer_str); - return ret; -} -#endif - -int device_get_start_refcnt(struct device_obj *dev_obj) -{ - if (dev_obj == NULL) { - AGM_LOGE("Invalid device object\n"); - return 0; - } - - if (dev_obj->group_data) - return dev_obj->group_data->refcnt.start; - else - return dev_obj->refcnt.start; - -} - -int device_get_state(struct device_obj *dev_obj) -{ - if (dev_obj == NULL) { - AGM_LOGE("Invalid device object\n"); - return DEV_CLOSED; - } - - if (dev_obj->parent_dev) - return dev_obj->parent_dev->state; - else - return dev_obj->state; -} - -static struct device_group_data* device_get_group_data_by_name(char *dev_name) -{ - struct device_group_data *grp_data = NULL; - char group_name[MAX_DEV_NAME_LEN]; - char *ptr = NULL; - int pos = 0; - struct listnode *grp_node, *temp; - - memset(group_name, 0, MAX_DEV_NAME_LEN); - - ptr = strstr(dev_name, "-VIRT"); - pos = ptr - dev_name + 1; - strlcpy(group_name, dev_name, pos); - - list_for_each_safe(grp_node, temp, &device_group_data_list) { - grp_data = node_to_item(grp_node, struct device_group_data, list_node); - if (!strncmp(group_name, grp_data->name, MAX_DEV_NAME_LEN)) { - grp_data->has_multiple_dai_link = true; - goto done; - } - } - - grp_data = calloc(1, sizeof(struct device_group_data)); - if (grp_data == NULL) { - AGM_LOGE("memory allocation for group_data failed\n"); - return NULL; - } - - strlcpy(grp_data->name, group_name, pos); - list_add_tail(&device_group_data_list, &grp_data->list_node); - num_group_devices++; - -done: - return grp_data; -} - -int parse_snd_card() -{ - char buffer[MAX_BUF_SIZE]; - unsigned int count = 0, i = 0; - FILE *fp; - int ret = 0; - struct listnode *dev_node, *temp; - struct device_obj *dev_obj = NULL; - - fp = fopen(PCM_DEVICE_FILE, "r"); - if (!fp) { - AGM_LOGE("ERROR. %s file open failed\n", - PCM_DEVICE_FILE); - return -ENODEV; - } - - list_init(&device_list); - list_init(&device_group_data_list); - num_group_devices = 0; - while (fgets(buffer, MAX_BUF_SIZE - 1, fp) != NULL) - { - dev_obj = calloc(1, sizeof(struct device_obj)); - - if (!dev_obj) { - AGM_LOGE("failed to allocate device_obj mem\n"); - ret = -ENOMEM; - goto free_device; - } - - AGM_LOGV("buffer: %s\n", buffer); - /* For Non-DPCM Dai-links, it is in the format of: - * -: idname> : name> : - 1 - * Here, pcm->idname is in the form of "stream_name> - -" - */ - sscanf(buffer, "%02u-%02u: %79s", &dev_obj->card_id, - &dev_obj->pcm_id, dev_obj->name); - AGM_LOGD("%d:%d:%s\n", dev_obj->card_id, dev_obj->pcm_id, dev_obj->name); - - /* populate the hw_ep_info for all the available pcm-id's*/ - ret = populate_device_hw_ep_info(dev_obj); - if (ret) { - AGM_LOGE("hw_ep_info parsing failed %s\n", - dev_obj->name); - free(dev_obj); - ret = 0; - continue; - } - - pthread_mutex_init(&dev_obj->lock, (const pthread_mutexattr_t *) NULL); - list_add_tail(&device_list, &dev_obj->list_node); - count++; - if (dev_obj->num_virtual_child) { - dev_obj->group_data = device_get_group_data_by_name(dev_obj->name); - - /* Enumerate virtual backends */ - for (int i = 0; i < dev_obj->num_virtual_child; i++) { - struct device_obj *child_dev_obj = populate_virtual_device_hw_ep_info(dev_obj, i); - if (child_dev_obj) { - list_add_tail(&device_list, &child_dev_obj->list_node); - count++; - } - child_dev_obj = NULL; - } - } - - dev_obj = NULL; - } - /* - * count 0 indicates that expected sound card was not registered - * inform the upper layers to try again after sometime. - */ - if (count == 0) { - ret = -EAGAIN; - goto free_device; - } - - num_audio_intfs = count; - goto close_file; - -free_device: - list_for_each_safe(dev_node, temp, &device_list) { - dev_obj = node_to_item(dev_node, struct device_obj, list_node); - list_remove(dev_node); - free(dev_obj); - dev_obj = NULL; - } - - list_remove(&device_group_data_list); - list_remove(&device_list); -close_file: - fclose(fp); - return ret; -} - -static int wait_for_snd_card_to_online() -{ - int ret = 0; - uint32_t retries = MAX_RETRY; - int fd = -1; - char buf[12]; - snd_card_status_t card_status = SND_CARD_STATUS_NONE; - - /* wait here till snd card is registered */ - /* maximum wait period = (MAX_RETRY * RETRY_INTERVAL_US) micro-seconds */ - do { - if ((fd = open(SNDCARD_PATH, O_RDWR)) < 0) { - AGM_LOGE("Failed to open snd sysfs node, will retry for %d times ...", (retries - 1)); - } else { - memset(buf , 0 ,sizeof(buf)); - lseek(fd,0L,SEEK_SET); - read(fd, buf, 1); - close(fd); - fd = -1; - - buf[sizeof(buf) - 1] = '\0'; - card_status = SND_CARD_STATUS_NONE; - sscanf(buf , "%d", &card_status); - - if (card_status == SND_CARD_STATUS_ONLINE) { - AGM_LOGV("snd sysfs node open successful"); - break; - } - } - retries--; - sleep(RETRY_INTERVAL); - } while ( retries > 0); - - if (0 == retries) { - AGM_LOGE("Failed to open snd sysfs node, exiting ... "); - ret = -EIO; - } - - return ret; -} - -int device_init() -{ - int ret = 0; - - ret = wait_for_snd_card_to_online(); - if (ret) { - AGM_LOGE("Not found any SND card online\n"); - return ret; - } - - ret = parse_snd_card(); - if (ret) - AGM_LOGE("no valid snd device found\n"); - - return ret; -} - -void device_deinit() -{ - unsigned int list_count = 0; - struct device_obj *dev_obj = NULL; - struct device_group_data *grp_data = NULL; - struct listnode *dev_node, *grp_node, *temp; - - AGM_LOGE("device deinit called\n"); - list_for_each_safe(dev_node, temp, &device_list) { - dev_obj = node_to_item(dev_node, struct device_obj, list_node); - list_remove(dev_node); - - metadata_free(&dev_obj->metadata); - - if (dev_obj->params) - free(dev_obj->params); - - free(dev_obj); - dev_obj = NULL; - } - - list_for_each_safe(grp_node, temp, &device_group_data_list) { - grp_data = node_to_item(grp_node, struct device_group_data, list_node); - list_remove(grp_node); - free(grp_data); - grp_data = NULL; - } - - list_remove(&device_group_data_list); - list_remove(&device_list); - -#ifdef DEVICE_USES_ALSALIB - if (mixer) - snd_ctl_close(mixer); -#else - if (mixer) - mixer_close(mixer); -#endif -} - -static void split_snd_card_name(const char * in_snd_card_name, char* file_path_extn, - char* file_path_extn_wo_variant) -{ - /* Sound card name follows below mentioned convention: - -
--snd-card. - */ - char *snd_card_name = NULL; - char *tmp = NULL; - char *card_sub_str = NULL; - - snd_card_name = strdup(in_snd_card_name); - if (snd_card_name == NULL) { - goto done; - } - - card_sub_str = strtok_r(snd_card_name, "-", &tmp); - if (card_sub_str == NULL) { - AGM_LOGE("called on invalid snd card name(%s)", in_snd_card_name); - goto done; - } - strlcat(file_path_extn, card_sub_str, FILE_PATH_EXTN_MAX_SIZE); - - while ((card_sub_str = strtok_r(NULL, "-", &tmp))) { - if (strncmp(card_sub_str, "snd", strlen("snd"))) { - strlcpy(file_path_extn_wo_variant, file_path_extn, FILE_PATH_EXTN_MAX_SIZE); - strlcat(file_path_extn, "_", FILE_PATH_EXTN_MAX_SIZE); - strlcat(file_path_extn, card_sub_str, FILE_PATH_EXTN_MAX_SIZE); - } - else - break; - } - -done: - if (snd_card_name) - free(snd_card_name); -} - -static bool check_and_update_snd_card(char *in_snd_card_str) -{ - char *str = NULL, *tmp = NULL; - int card = 0, card_id = -1; - bool is_updated = false; - char *snd_card_str = strdup(in_snd_card_str); - - if (snd_card_str == NULL) { - return is_updated; - } - - card = device_get_snd_card_id(); - if (card < 0) { - goto done; - } - - str = strtok_r(snd_card_str, "[:] ", &tmp); - if (str == NULL) { - goto done; - } - card_id = atoi(str); - - str = strtok_r(NULL, "[:] ", &tmp); - if (str == NULL) { - goto done; - } - - if (card_id == card) { - is_updated = true; - } - -done: - if (snd_card_str) - free(snd_card_str); - return is_updated; -} - -static bool update_snd_card_info(char snd_card_name[]) -{ - bool is_updated = false; - char line1[BUF_SIZE] = {0}, line2[BUF_SIZE] = {0}; - FILE *file = NULL; - int len = 0, retries = MAX_RETRY; - char *card_name = NULL, *tmp = NULL; - - if (access(SND_CARD_DEVICE_FILE, F_OK) != -1) { - file = fopen(SND_CARD_DEVICE_FILE, "r"); - if (file == NULL) { - AGM_LOGE("open %s: failed\n", SND_CARD_DEVICE_FILE); - goto done; - } - } else { - AGM_LOGE("Unable to access %s\n", SND_CARD_DEVICE_FILE); - goto done; - } - - /* Look for only default codec sound card */ - /* Ignore USB sound card if detected */ - /* Example of data read from /proc/asound/cards: */ - /* card-id [dummyidpsndcard]: dummy-idp-variant-snd- - dummy-idp-variant-snd-card */ - /* dummy-idp-variant-snd-card */ - do { - if (!fgets(line1, BUF_SIZE - 1, file)) { - break; - } - len = strnlen(line1, BUF_SIZE); - line1[len - 1] = '\0'; - - if (!fgets(line2, BUF_SIZE - 1, file)) { - break; - } - len = strnlen(line2, BUF_SIZE); - line2[len - 1] = '\0'; - - if (check_and_update_snd_card(line1)) { - card_name = strtok_r(line2, "[:] ", &tmp); - if (card_name != NULL) { - strlcpy(snd_card_name, card_name, FILE_PATH_EXTN_MAX_SIZE); - is_updated = true; - } - } - } while(!is_updated && --retries); - -done: - if (file) - fclose(file); - return is_updated; -} - -bool get_file_path_extn(char* file_path_extn, char* file_path_extn_wo_variant) -{ - int snd_card_found = false, retry = 0; - char snd_card_name[FILE_PATH_EXTN_MAX_SIZE]; - - do { - snd_card_found = update_snd_card_info(snd_card_name); - - if (snd_card_found) { - split_snd_card_name(snd_card_name, file_path_extn, file_path_extn_wo_variant); - AGM_LOGV("Found Codec sound card"); - break; - } else { - AGM_LOGI("Sound card not found, retry %d", retry++); - sleep(1); - } - } while (!snd_card_found && retry <= MAX_RETRY_CNT); - - return snd_card_found; -} diff --git a/qcom/opensource/agm/service/src/device_hw_ep.c b/qcom/opensource/agm/service/src/device_hw_ep.c deleted file mode 100755 index 58911f15..00000000 --- a/qcom/opensource/agm/service/src/device_hw_ep.c +++ /dev/null @@ -1,427 +0,0 @@ -/* -** Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted (subject to the limitations in the -** disclaimer below) provided that the following conditions are met: -** -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** -** * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE -** GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT -** HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -** IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -** IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#define LOG_TAG "AGM: device" - -#include - -#include -#include -#include -#include -#include - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_DEVICE_HW_EP -#include -#endif - -#define DEV_ARG_SIZE 21 -#define DEV_VALUE_SIZE 61 - -#define CODEC_RX0 1 -#define CODEC_TX0 1 -#define CODEC_RX1 2 -#define CODEC_TX1 2 -#define CODEC_RX2 3 -#define CODEC_TX2 3 -#define CODEC_RX3 4 -#define CODEC_TX3 4 -#define CODEC_RX4 5 -#define CODEC_TX4 5 -#define CODEC_RX5 6 -#define CODEC_TX5 6 -#define CODEC_RX6 7 -#define CODEC_RX7 8 - -#define SLIMBUS_DEVICE_1 0 -#define SLIMBUS_DEVICE_2 1 - -#define MAX_VIRTUAL_CHILDS 8 - -static int populate_hw_ep_intf_idx(hw_ep_info_t *hw_ep_info, char *intf_idx) -{ - struct hw_ep_cdc_dma_i2s_tdm_config *cdc_dma_i2s_tdm_config; - - cdc_dma_i2s_tdm_config = &hw_ep_info->ep_config.cdc_dma_i2s_tdm_config; - - switch(hw_ep_info->intf) { - case CODEC_DMA: - if (!strcmp(intf_idx, "0")) - cdc_dma_i2s_tdm_config->intf_idx = CODEC_RX0; - else if (!strcmp(intf_idx, "1")) - cdc_dma_i2s_tdm_config->intf_idx = CODEC_RX1; - else if (!strcmp(intf_idx, "2")) - cdc_dma_i2s_tdm_config->intf_idx = CODEC_RX2; - else if (!strcmp(intf_idx, "3")) - cdc_dma_i2s_tdm_config->intf_idx = CODEC_RX3; - else if (!strcmp(intf_idx, "4")) - cdc_dma_i2s_tdm_config->intf_idx = CODEC_RX4; - else if (!strcmp(intf_idx, "5")) - cdc_dma_i2s_tdm_config->intf_idx = CODEC_RX5; - else if (!strcmp(intf_idx, "6")) - cdc_dma_i2s_tdm_config->intf_idx = CODEC_RX6; - else if (!strcmp(intf_idx, "7")) - cdc_dma_i2s_tdm_config->intf_idx = CODEC_RX7; - else { - AGM_LOGE("No matching intf_idx found\n"); - return -EINVAL; - } - break; - case MI2S: - case TDM: - case AUXPCM: - if (!strcmp(intf_idx, "PRIMARY")) - cdc_dma_i2s_tdm_config->intf_idx = PCM_INTF_IDX_PRIMARY; - else if (!strcmp(intf_idx, "SECONDARY")) - cdc_dma_i2s_tdm_config->intf_idx = PCM_INTF_IDX_SECONDARY; - else if (!strcmp(intf_idx, "TERTIARY")) - cdc_dma_i2s_tdm_config->intf_idx = PCM_INTF_IDX_TERTIARY; - else if (!strcmp(intf_idx, "QUATERNARY")) - cdc_dma_i2s_tdm_config->intf_idx = PCM_INTF_IDX_QUATERNARY; - else if(!strcmp(intf_idx, "QUINARY")) - cdc_dma_i2s_tdm_config->intf_idx = PCM_INTF_IDX_QUINARY; - else if(!strcmp(intf_idx, "SENARY")) - cdc_dma_i2s_tdm_config->intf_idx = PCM_INTF_IDX_SENARY; - else { - AGM_LOGE("No matching intf_idx found\n"); - return -EINVAL; - } - break; - default: - AGM_LOGE("Unsupported HW endpoint %d\n", hw_ep_info->intf); - return -EINVAL; - } - - return 0; -} - -static int populate_hw_ep_intf(hw_ep_info_t *hw_ep_info, char *intf) -{ - if (!strcmp(intf, "SLIM")) - hw_ep_info->intf = SLIMBUS; - else if (!strcmp(intf, "DISPLAY_PORT")) - hw_ep_info->intf = DISPLAY_PORT; - else if (!strcmp(intf, "USB_AUDIO")) - hw_ep_info->intf = USB_AUDIO; - else if (!strcmp(intf, "CODEC_DMA")) - hw_ep_info->intf = CODEC_DMA; - else if (!strcmp(intf, "MI2S")) - hw_ep_info->intf = MI2S; - else if (!strcmp(intf, "TDM")) - hw_ep_info->intf = TDM; - else if (!strcmp(intf, "AUXPCM")) - hw_ep_info->intf = AUXPCM; - else if (!strcmp(intf, "PCM_RT_PROXY")) - hw_ep_info->intf = PCM_RT_PROXY; - else if (!strcmp(intf, "AUDIOSS_DMA")) - hw_ep_info->intf = AUDIOSS_DMA; - else if (!strcmp(intf, "PCM_DUMMY")) - hw_ep_info->intf = PCM_DUMMY; - else if (!strcmp(intf, "BTFM_PROXY")) - hw_ep_info->intf = BTFM_PROXY; - else { - AGM_LOGE("No matching intf found\n"); - return -EINVAL; - } - return 0; -} - -static int populate_hw_ep_direction(hw_ep_info_t *hw_ep_info, char *dir) -{ - if (!strcmp(dir, "RX")) - hw_ep_info->dir = AUDIO_OUTPUT; - else if (!strcmp(dir, "TX")) - hw_ep_info->dir = AUDIO_INPUT; - else { - AGM_LOGE("No matching dir found\n"); - return -EINVAL; - } - return 0; -} - -static int populate_audioss_dma_ep_info(hw_ep_info_t *hw_ep_info, char *value) -{ - char lpaif_type[DEV_ARG_SIZE]; - char arg[DEV_ARG_SIZE] = {0}; - - struct hw_ep_audioss_dma_config *audioss_dma_config; - int ret = 0; - - audioss_dma_config = &hw_ep_info->ep_config.audioss_dma_config; - - sscanf(value, "%20[^-]-%60s", arg, value); - strlcpy(lpaif_type, arg, strlen(arg)+1); - sscanf(value, "%20[^-]-%60s", arg, value); - - if (!strcmp(lpaif_type, "LPAIF_VA")) { - audioss_dma_config->lpaif_type = LPAIF_VA; - } else { - AGM_LOGE("No matching lpaif_type found\n"); - return -EINVAL; - } - - ret = populate_hw_ep_direction(hw_ep_info, arg); - if (ret) { - AGM_LOGE("failed to parse direction\n"); - return ret; - } - - sscanf(value, "%20[^-]-%60s", arg, value); - audioss_dma_config->dev_id = atoi(arg); - - return ret; - -} - -static int populate_btfm_rt_proxy_ep_info(hw_ep_info_t *hw_ep_info, char *value) -{ - char arg[DEV_ARG_SIZE] = {0}; - struct hw_ep_pcm_rt_proxy_config *pcm_rt_proxy_config; - int ret = 0; - - sscanf(value, "%20[^-]-%60s", arg, value); - ret = populate_hw_ep_direction(hw_ep_info, arg); - if (ret) { - AGM_LOGE("failed to parse direction\n"); - return ret; - } - - pcm_rt_proxy_config = &hw_ep_info->ep_config.pcm_rt_proxy_config; - sscanf(value, "%20[^-]-%60s", arg, value); - pcm_rt_proxy_config->dev_id = atoi(arg); - - return ret; -} - -static int populate_pcm_dummy_ep_info(hw_ep_info_t *hw_ep_info, char *value) -{ - char arg[DEV_ARG_SIZE] = {0}; - struct hw_ep_pcm_dummy_config *pcm_dummy_config; - int ret = 0; - - sscanf(value, "%20[^-]-%60s", arg, value); - ret = populate_hw_ep_direction(hw_ep_info, arg); - if (ret) { - AGM_LOGE("failed to parse direction\n"); - return ret; - } - - pcm_dummy_config = &hw_ep_info->ep_config.pcm_dummy_config; - sscanf(value, "%20[^-]-%60s", arg, value); - pcm_dummy_config->dev_id = atoi(arg); - - return ret; -} - -static int populate_slim_dp_usb_ep_info(hw_ep_info_t *hw_ep_info, char *value) -{ - char dir[DEV_ARG_SIZE], arg[DEV_ARG_SIZE] = {0}; - char dev_id[DEV_ARG_SIZE] = {0}; - struct hw_ep_slimbus_config *slim_config; - - if (hw_ep_info->intf == SLIMBUS) {/* read_dev_id for SLIMBUS */ - slim_config = &hw_ep_info->ep_config.slim_config; - sscanf(value, "%20[^-]-%60s", arg, value); - strlcpy(dev_id, arg, strlen(arg)+1); - if (!strcmp(dev_id, "DEV1")) - slim_config->dev_id = SLIMBUS_DEVICE_1; - else if (!strcmp(dev_id, "DEV2")) - slim_config->dev_id = SLIMBUS_DEVICE_2; - else { - return -EINVAL; - } - - } - sscanf(value, "%20[^-]-%60s", arg, value); - strlcpy(dir, arg, strlen(arg)+1); - - return populate_hw_ep_direction(hw_ep_info, dir); -} - -static int populate_cdc_dma_i2s_tdm_pcm_ep_info(hw_ep_info_t *hw_ep_info, char *value, int *num_virt_child) -{ - char lpaif_type[DEV_ARG_SIZE]; - char intf_idx[DEV_ARG_SIZE], dir[DEV_ARG_SIZE]; - char arg[DEV_ARG_SIZE] = {0}; - - struct hw_ep_cdc_dma_i2s_tdm_config *cdc_dma_i2s_tdm_config; - int ret = 0; - - cdc_dma_i2s_tdm_config = &hw_ep_info->ep_config.cdc_dma_i2s_tdm_config; - - sscanf(value, "%20[^-]-%60s", arg, value); - strlcpy(lpaif_type, arg, strlen(arg)+1); - sscanf(value, "%20[^-]-%60s", arg, value); - strlcpy(dir, arg, strlen(arg)+1); - sscanf(value, "%20[^-]-%60s", arg, value); - strlcpy(intf_idx, arg, strlen(arg)+1); - - if(strstr(value, "VIRT-")) { - /* with below statement, arg = VIRT, value = "x-codec" */ - sscanf(value, "%20[^-]-%60s", arg, value); - /* with below statement, arg = x, value = "codec" */ - sscanf(value, "%20[^-]-%60s", arg, value); - *num_virt_child = atoi(arg); - if (*num_virt_child > MAX_VIRTUAL_CHILDS) - *num_virt_child = MAX_VIRTUAL_CHILDS; - } - - if (!strcmp(lpaif_type, "LPAIF")) - cdc_dma_i2s_tdm_config->lpaif_type = LPAIF; - else if (!strcmp(lpaif_type, "LPAIF_RXTX")) - cdc_dma_i2s_tdm_config->lpaif_type = LPAIF_RXTX; - else if (!strcmp(lpaif_type, "LPAIF_WSA")) - cdc_dma_i2s_tdm_config->lpaif_type = LPAIF_WSA; - else if (!strcmp(lpaif_type, "LPAIF_VA")) - cdc_dma_i2s_tdm_config->lpaif_type = LPAIF_VA; - else if (!strcmp(lpaif_type, "LPAIF_AXI")) - cdc_dma_i2s_tdm_config->lpaif_type = LPAIF_AXI; - else if (!strcmp(lpaif_type, "LPAIF_AUD")) - cdc_dma_i2s_tdm_config->lpaif_type = LPAIF_AUD; - else if (!strcmp(lpaif_type, "LPAIF_SDR")) - cdc_dma_i2s_tdm_config->lpaif_type = LPAIF_SDR; - else if (!strcmp(lpaif_type, "LPAIF_WSA2")) - cdc_dma_i2s_tdm_config->lpaif_type = LPAIF_WSA2; - else { - AGM_LOGE("No matching lpaif_type found\n"); - return -EINVAL; - } - - ret = populate_hw_ep_direction(hw_ep_info, dir); - if (ret) - return ret; - - return populate_hw_ep_intf_idx(hw_ep_info, intf_idx); -} - -static void update_virtual_device_name(struct device_obj *dev_obj, int num) -{ - char *ptr = NULL; - int pos = 0; - - ptr = strstr(dev_obj->name, "VIRT-"); - pos = ptr - dev_obj->name; - pos += strlen("VIRT-"); - ptr += strlen("VIRT-") + 1; - snprintf(&dev_obj->name[pos], DEV_ARG_SIZE, "%d%s", num, ptr); -} - -struct device_obj* populate_virtual_device_hw_ep_info(struct device_obj *parent_dev_obj, int num) -{ - struct device_obj *dev_obj = calloc(1, sizeof(struct device_obj)); - - if (!dev_obj) - return NULL; - - memcpy(dev_obj, parent_dev_obj, sizeof(struct device_obj)); - update_virtual_device_name(dev_obj, num); - dev_obj->num_virtual_child = 0; - dev_obj->is_virtual_device = true; - dev_obj->parent_dev = parent_dev_obj; - - return dev_obj; -} - -int populate_device_hw_ep_info(struct device_obj *dev_obj) -{ - char intf[DEV_ARG_SIZE]; - char arg[DEV_ARG_SIZE] = {0}; - char value[DEV_VALUE_SIZE] = {0}; - int ret = 0; - - if (dev_obj == NULL) { - AGM_LOGE("Invalid device object\n"); - return -EINVAL; - } - - sscanf(dev_obj->name, "%20[^-]-%60s", arg, value); - strlcpy(intf, arg, strlen(arg)+1); - - ret = populate_hw_ep_intf(&dev_obj->hw_ep_info, intf); - if (ret) - return ret; - - switch(dev_obj->hw_ep_info.intf) { - case CODEC_DMA: - case MI2S: - case TDM: - case AUXPCM: - return populate_cdc_dma_i2s_tdm_pcm_ep_info(&dev_obj->hw_ep_info, value, - &dev_obj->num_virtual_child); - case SLIMBUS: - case DISPLAY_PORT: - case USB_AUDIO: - return populate_slim_dp_usb_ep_info(&dev_obj->hw_ep_info, value); - case PCM_RT_PROXY: - case BTFM_PROXY: - return populate_btfm_rt_proxy_ep_info(&dev_obj->hw_ep_info, value); - case AUDIOSS_DMA: - return populate_audioss_dma_ep_info(&dev_obj->hw_ep_info, value); - case PCM_DUMMY: - return populate_pcm_dummy_ep_info(&dev_obj->hw_ep_info, value); - default: - AGM_LOGE("Unsupported interface name %s\n", __func__, dev_obj->name); - return -EINVAL; - } -} diff --git a/qcom/opensource/agm/service/src/graph.c b/qcom/opensource/agm/service/src/graph.c deleted file mode 100755 index f6a6a557..00000000 --- a/qcom/opensource/agm/service/src/graph.c +++ /dev/null @@ -1,2381 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * -** Changes from Qualcomm Innovation Center are provided under the following license: -** Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted (subject to the limitations in the -** disclaimer below) provided that the following conditions are met: -** -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** -** * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE -** GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT -** HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -** IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -** IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#define LOG_TAG "AGM: graph" - -#include -#include -#include -#include -#include -#include -#include -#include -#include "gsl_intf.h" -#include -#include -#include -#include -#include - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_GRAPH -#include -#endif - -// { SEC_AUDIO_COMMON -#include -// } SEC_AUDIO_COMMON - -#define DEVICE_RX 0 -#define DEVICE_TX 1 -#define FILE_PATH_EXTN_MAX_SIZE 80 -#define ACDB_PATH_MAX_LENGTH 50 - -#define TAGGED_MOD_SIZE_BYTES 1024 - -enum { - MIID_IDX, - NUM_OF_PARAM_IDX, - PARAM_ID_IDX, - PARAM_LIST_MAX_IDX, -}; - -/* TODO: remove this later after including in spf header files */ -#define PARAM_ID_SOFT_PAUSE_START 0x800102e -#define PARAM_ID_SOFT_PAUSE_RESUME 0x800102f - -#define CONVX(x) #x -#define CONV_TO_STRING(x) CONVX(x) - -#define ADD_MODULE(x, y) \ - ({ \ - module_info_t *add_mod = NULL;\ - add_mod = calloc(1, sizeof(module_info_t));\ - if (add_mod != NULL) {\ - *add_mod = x;\ - if (y != NULL) add_mod->dev_obj = y; \ - list_add_tail(&graph_obj->tagged_mod_list, &add_mod->list);\ - } \ - add_mod;\ - }) - -typedef struct module_info_link_list { - module_info_t *data; - struct listnode tagged_list; -}module_info_link_list_t; - -static char acdb_path[ACDB_PATH_MAX_LENGTH]; -static void print_graph_alias(const struct agm_meta_data_gsl *meta_data_kv); - -static int get_acdb_files_from_directory(const char* acdb_files_path, - struct gsl_acdb_data_files *data_files) -{ - int result = 0; - int ret = 0; - int i = 0; - DIR *dir_fp = NULL; - struct dirent *dentry; - - dir_fp = opendir(acdb_files_path); - if (dir_fp == NULL) { - AGM_LOGE("cannot open acdb path %s\n", acdb_files_path); - ret = EINVAL; - goto done; - } - - /* search directory for .acdb files */ - while ((dentry = readdir(dir_fp)) != NULL) { - if ((strstr(dentry->d_name, ".acdb") != NULL) || - (strstr(dentry->d_name, ".qwsp") != NULL)) { - if (data_files->num_files >= GSL_MAX_NUM_OF_ACDB_FILES) { - AGM_LOGE("Reached max num of files, %d!\n", i); - break; - } - result = snprintf( - data_files->acdbFiles[i].fileName, - sizeof(data_files->acdbFiles[i].fileName), - "%s/%s", acdb_files_path, dentry->d_name); - if ((result < 0) || - (result >= (int)sizeof(data_files->acdbFiles[i].fileName))) { - AGM_LOGE("snprintf failed: %s/%s, err %d\n", - acdb_files_path, - data_files->acdbFiles[i].fileName, - result); - ret = -EINVAL; - break; - } - data_files->acdbFiles[i].fileNameLen = - (uint32_t)strlen(data_files->acdbFiles[i].fileName); - AGM_LOGI("Load file: %s\n", data_files->acdbFiles[i].fileName); - i++; - } - } - - if (i == 0) - AGM_LOGE("No .acdb files found in %s!\n", acdb_files_path); - - data_files->num_files = i; - - closedir(dir_fp); -done: - return ret; -} - -#define PULL_PUSH_SHMEM_ENDPOINT SHMEM_ENDPOINT /** Temp: till pull mode keys are defined */ -int configure_buffer_params(struct graph_obj *gph_obj, - struct session_obj *sess_obj) -{ - struct gsl_cmd_configure_read_write_params buf_config = {0}; - int ret = 0; - size_t size = 0; - enum gsl_cmd_id cmd_id; - enum agm_data_mode mode = sess_obj->stream_config.data_mode; - struct agm_buffer_config buffer_config = {0}; - - if (gph_obj == NULL){ - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - if (gph_obj->is_config_buf_params_done) { - AGM_LOGD("configure buf params already done"); - return 0; - } - - AGM_LOGD("Enter"); - /* - *In case of non-tunnel mode we configure - *read and write buffer params together - */ - if ((sess_obj->stream_config.sess_mode == AGM_SESSION_NON_TUNNEL) && - (sess_obj->stream_config.dir == (RX | TX))) { - - /*configure read params*/ - AGM_LOGD("read params: mode %d sess buf_sz %zu num_bufs %d metadata %d \n", - mode, sess_obj->in_buffer_config.size, - sess_obj->in_buffer_config.count, - sess_obj->in_buffer_config.max_metadata_size); - - buf_config.start_threshold = sess_obj->stream_config.start_threshold; - buf_config.stop_threshold = sess_obj->stream_config.stop_threshold; - buf_config.buff_size = (uint32_t)sess_obj->in_buffer_config.size; - buf_config.num_buffs = sess_obj->in_buffer_config.count; - buf_config.max_metadata_size = sess_obj->in_buffer_config.max_metadata_size; - if (mode == AGM_DATA_BLOCKING) - buf_config.attributes = GSL_DATA_MODE_BLOCKING; - else if (mode == AGM_DATA_EXTERN_MEM) - buf_config.attributes = GSL_DATA_MODE_EXTERN_MEM; - else if (mode == AGM_DATA_NON_BLOCKING) - buf_config.attributes = GSL_DATA_MODE_NON_BLOCKING; - else { - AGM_LOGE("Unsupported buffer mode : %d, Default to Blocking\n", mode); - buf_config.attributes = GSL_DATA_MODE_BLOCKING; - } - buf_config.shmem_ep_tag = RD_SHMEM_ENDPOINT; - - size = sizeof(struct gsl_cmd_configure_read_write_params); - - cmd_id = GSL_CMD_CONFIGURE_READ_PARAMS; - - ret = gsl_ioctl(gph_obj->graph_handle, cmd_id, &buf_config, size); - if (ret != 0) - goto done; - - /*configure write params, note that only few parameters change for read and write params - * e.g, attributes, start_threshold, stop_threshold are same for both. - */ - AGM_LOGD("write params: mode %d sess buf_sz %zu num_bufs %d metadata %d \n", - mode, sess_obj->out_buffer_config.size, - sess_obj->out_buffer_config.count, - sess_obj->out_buffer_config.max_metadata_size); - - buf_config.buff_size = (uint32_t)sess_obj->out_buffer_config.size; - buf_config.num_buffs = sess_obj->out_buffer_config.count; - buf_config.max_metadata_size = sess_obj->out_buffer_config.max_metadata_size; - buf_config.shmem_ep_tag = WR_SHMEM_ENDPOINT; - cmd_id = GSL_CMD_CONFIGURE_WRITE_PARAMS; - - ret = gsl_ioctl(gph_obj->graph_handle, cmd_id, &buf_config, size); - - } else { - if (sess_obj->stream_config.dir == TX) - buffer_config = sess_obj->in_buffer_config; - else - buffer_config = sess_obj->out_buffer_config; - - AGM_LOGD("%s sess buf_sz %zu num_bufs %d\n", sess_obj->stream_config.dir == RX? - "Playback":"Capture", buffer_config.size, - buffer_config.count); - - if (mode == AGM_DATA_PUSH_PULL) { - buf_config.buff_size = buffer_config.count * - buffer_config.size; - buf_config.num_buffs = 1; - } else { - buf_config.buff_size = (uint32_t)buffer_config.size; - buf_config.num_buffs = buffer_config.count; - } - buf_config.start_threshold = sess_obj->stream_config.start_threshold; - buf_config.stop_threshold = sess_obj->stream_config.stop_threshold; - - if (mode == AGM_DATA_PUSH_PULL) - buf_config.shmem_ep_tag = PULL_PUSH_SHMEM_ENDPOINT; - else if ((sess_obj->stream_config.sess_mode == AGM_SESSION_COMPRESS) && - (sess_obj->stream_config.dir == TX)) - buf_config.shmem_ep_tag = RD_SHMEM_ENDPOINT; - else - buf_config.shmem_ep_tag = SHMEM_ENDPOINT; - /** - *TODO:expose a flag to chose between different data passing modes - *BLOCKING/NON-BLOCKING/SHARED_MEM. - */ - if (mode == AGM_DATA_BLOCKING) - buf_config.attributes = GSL_DATA_MODE_BLOCKING; - else if (mode == AGM_DATA_EXTERN_MEM) - buf_config.attributes = GSL_DATA_MODE_EXTERN_MEM; - else if (mode == AGM_DATA_NON_BLOCKING) - buf_config.attributes = GSL_DATA_MODE_NON_BLOCKING; - else if (mode == AGM_DATA_PUSH_PULL) - buf_config.attributes = GSL_DATA_MODE_PUSH_PULL; - else { -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - AGM_LOGI("Unsupported buffer mode : %d, Default to Blocking\n", mode); -#else - AGM_LOGE("Unsupported buffer mode : %d, Default to Blocking\n", mode); -#endif - buf_config.attributes = GSL_DATA_MODE_BLOCKING; - } - - size = sizeof(struct gsl_cmd_configure_read_write_params); - - if (sess_obj->stream_config.dir == RX) - cmd_id = GSL_CMD_CONFIGURE_WRITE_PARAMS; - else - cmd_id = GSL_CMD_CONFIGURE_READ_PARAMS; - - ret = gsl_ioctl(gph_obj->graph_handle, cmd_id, &buf_config, size); - } -done: - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("Buffer configuration failed error %d\n", ret); - } else - gph_obj->is_config_buf_params_done = true; - - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -static int get_acdb_path(void) -{ - int ret = 0; - - ret = snprintf(acdb_path, ACDB_PATH_MAX_LENGTH, - "%s", "/vendor/etc/audconf/OPEN"); - if (ret < 0) { - AGM_LOGE("default snprintf failed: err %d\n", ret); - ret = -EINVAL; - goto err; - } - -err: - return ret; -} - -int graph_init() -{ - uint32_t ret = 0; - struct gsl_acdb_data_files acdb_files; - struct gsl_acdb_file delta_file; - struct gsl_init_data init_data; - const char *delta_file_path; - char file_path_extn[FILE_PATH_EXTN_MAX_SIZE] = {0}; - char file_path_extn_wo_variant[FILE_PATH_EXTN_MAX_SIZE] = {0}; - bool snd_card_found = false; - -#ifndef ACDB_PATH -# error "Define -DACDB_PATH="PATH" in the makefile to compile" -#endif - /*Populate acdbfiles from the shared file path*/ - acdb_files.num_files = 0; - - snd_card_found = get_file_path_extn(file_path_extn, file_path_extn_wo_variant); - if (snd_card_found) { - snprintf(acdb_path, ACDB_PATH_MAX_LENGTH, "%s%s", ACDB_PATH, file_path_extn); - } else { - ret = -ENOENT; - goto err; - } - AGM_LOGI("acdb file path: %s\n", acdb_path); - - ret = get_acdb_path(); - if (ret < 0) { - AGM_LOGE("failed to get the acdb path(%d)", ret); - goto err; - } - - ret = get_acdb_files_from_directory(acdb_path, &acdb_files); - if (ret) { - /* if acdb_path is not found, try without variant */ - snprintf(acdb_path, ACDB_PATH_MAX_LENGTH, "%s%s", ACDB_PATH, - file_path_extn_wo_variant); - AGM_LOGI("trying - acdb file path: %s\n", acdb_path); - ret = get_acdb_files_from_directory(acdb_path, &acdb_files); - if (ret) - goto err; - } - -#ifdef ACDB_DELTA_FILE_PATH - delta_file_path = CONV_TO_STRING(ACDB_DELTA_FILE_PATH); - if ((strlen(delta_file_path) + 1) > sizeof(delta_file.fileName)) { - AGM_LOGE("path is big than what gsl handles"); - ret = -EINVAL; - goto err; - } - delta_file.fileNameLen = strlen(delta_file_path) + 1; - ret = strlcpy(delta_file.fileName, delta_file_path, delta_file.fileNameLen); -#else -# error "Define -DACDB_DELTA_FILE_PATH="PATH" in the makefile to compile" -#endif - - init_data.acdb_files = &acdb_files; - init_data.acdb_delta_file = &delta_file; - init_data.acdb_addr = 0x0; - init_data.max_num_ready_checks = 1; - init_data.ready_check_interval_ms = 1000; - ret = gsl_init(&init_data); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("gsl_init failed error %d \n", ret); - } - -err: - return ret; -} - -int graph_deinit() -{ - - gsl_deinit(); - return 0; -} - -void gsl_callback_func(struct gsl_event_cb_params *event_params, - void *client_data) -{ - struct graph_obj *graph_obj = (struct graph_obj *) client_data; - struct agm_event_cb_params *ev; - struct gsl_event_read_write_done_payload *rw_done_payload; - - if (graph_obj == NULL) { - AGM_LOGE("Invalid graph object"); - goto done; - } - if (event_params == NULL) { - AGM_LOGE("event params NULL"); - goto done; - } - - ev = calloc(1, sizeof(struct agm_event_cb_params) + event_params->event_payload_size); - if (!ev) { - AGM_LOGE("Not enough memory for payload\n"); - goto done; - } - - ev->source_module_id = event_params->source_module_id; - ev->event_id = event_params->event_id; - ev->event_payload_size = event_params->event_payload_size; - memcpy(ev->event_payload, event_params->event_payload, event_params->event_payload_size); - - if (graph_obj->sess_obj && - graph_obj->sess_obj->stream_config.data_mode == AGM_DATA_EXTERN_MEM) { - if ((ev->event_payload_size > 0) && ((ev->event_id == AGM_EVENT_READ_DONE) || - (ev->event_id == AGM_EVENT_WRITE_DONE))) { - rw_done_payload = (struct gsl_event_read_write_done_payload *)ev->event_payload; - rw_done_payload->md_status = ar_err_get_lnx_err_code(rw_done_payload->md_status); - rw_done_payload->status = ar_err_get_lnx_err_code(rw_done_payload->status); - } - } - - if (graph_obj->cb) - graph_obj->cb(ev, - graph_obj->client_data); - free(ev); -done: - return; -} - -int graph_get_tags_with_module_info(struct agm_key_vector_gsl *gkv, - void *payload, size_t *size) -{ - int ret; - ret = gsl_get_tags_with_module_info((struct gsl_key_vector *) gkv, - payload, size); - return ar_err_get_lnx_err_code(ret); -} - -static int get_tags_with_module_info(struct agm_key_vector_gsl *gkv, - void **payload, size_t *size) -{ - int ret = 0; - void *new_payload = NULL; - - // start with TAGGED_MOD_SIZE_BYTES - *size = TAGGED_MOD_SIZE_BYTES; - *payload = calloc(1, *size); - if (NULL == *payload) { - AGM_LOGE("Not enough memory for payload\n"); - ret = -ENOMEM; - goto error; - } - - ret = gsl_get_tags_with_module_info((struct gsl_key_vector *)gkv, *payload, - size); - ret = ar_err_get_lnx_err_code(ret); - if (ret != 0) { - if (ret == -ENODATA) { - // default TAGGED_MOD_SIZE_BYTES was not sufficient, alloc new size - new_payload = realloc(*payload, *size); - if (!new_payload) { - AGM_LOGE("Not enough memory for payload\n"); - ret = -ENOMEM; - free(*payload); - goto error; - } - - *payload = new_payload; - ret = gsl_get_tags_with_module_info((struct gsl_key_vector *)gkv, - *payload, size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("Failed to get tags info with error no %d\n",ret); - free(*payload); - goto error; - } - goto done; - } else { - AGM_LOGE("Failed to get tags info with error no %d\n",ret); - free(*payload); - goto error; - } - } - - goto done; - -error: - *payload = NULL; - *size = 0; - -done: - return ret; -} - -static int add_to_list(uint32_t module_list_count, module_info_t *info, struct listnode *node) -{ - uint32_t count = 0; - int ret = 0; - module_info_link_list_t *mod_list = NULL; - - for (count = 0; count < module_list_count; count++) { - mod_list = calloc(1, sizeof(module_info_link_list_t)); - if (!mod_list) { - AGM_LOGE("Not enough memory for payload\n"); - ret = -ENOMEM; - goto done; - } - mod_list->data = info + count; - list_add_tail(node, &mod_list->tagged_list); - } -done: - return ret; -} - -int graph_open(struct agm_meta_data_gsl *meta_data_kv, - struct session_obj *sess_obj, struct device_obj *dev_obj, - struct graph_obj **gph_obj) -{ - struct graph_obj *graph_obj = NULL; - int ret = 0; - struct listnode *temp_node, *node = NULL, *node_list = NULL; - - struct gsl_tag_module_info *tag_module_info = NULL; - size_t tag_module_info_size; - struct gsl_tag_module_info_entry *gsl_tag_entry = NULL; - struct agm_key_vector_gsl *gkv; - int i = 0; - size_t module_list_count = 0; - module_info_t *mod, *temp_mod = NULL; - module_info_link_list_t *mod_list = NULL; - size_t arraysize = 0; - module_info_t *stream_module_list = NULL; - module_info_t *hw_ep_module = NULL; - module_info_t *add_module = NULL; - - list_declare(node_sess); - list_init(&node_sess); - list_declare(node_hw); - list_init(&node_hw); - - - AGM_LOGD("entry\n"); - if (meta_data_kv == NULL || gph_obj == NULL || sess_obj == NULL) { - AGM_LOGE("Invalid input\n"); - ret = -EINVAL; - goto done; - } - - graph_obj = calloc (1, sizeof(struct graph_obj)); - if (graph_obj == NULL) { - AGM_LOGE("failed to allocate graph object\n"); - ret = -ENOMEM; - goto done; - } - - metadata_print(meta_data_kv); - print_graph_alias(meta_data_kv); - - list_init(&graph_obj->tagged_mod_list); - pthread_mutex_init(&graph_obj->lock, (const pthread_mutexattr_t *)NULL); - if (sess_obj->stream_config.sess_mode == AGM_SESSION_NO_CONFIG) - goto no_config; - - /** - *TODO:In the current config parameters we dont have a - *way to know if a hostless session (loopback) - *is session loopback or device loopback - *We assume now that if it is a hostless - *session then it is device loopback always. - *And hence we configure pcm decoder/encoder/convertor - *only in case of a no hostless session. - */ - - /*Get all the tags info of the graph and store it tag_module_info structure*/ - ret = get_tags_with_module_info(&meta_data_kv->gkv, - (void**) &tag_module_info, &tag_module_info_size); - if (ret != 0 || !tag_module_info) - goto free_graph_obj; - - gsl_tag_entry = (struct gsl_tag_module_info_entry *)(tag_module_info->tag_module_entry); - - /* Add all default stream_module to node_sess list */ - get_stream_module_list_array(&stream_module_list, &arraysize); - module_list_count = arraysize /sizeof(struct module_info); - ret = add_to_list(module_list_count, stream_module_list, &node_sess); - if (ret != 0) - goto free_graph_obj; - - /* Add all default hw_ep_module to node_hw list */ - get_hw_ep_module_list_array(&hw_ep_module, &arraysize); - module_list_count = arraysize /sizeof(struct module_info); - ret = add_to_list(module_list_count, hw_ep_module, &node_hw); - if (ret != 0) - goto free_graph_obj; - - for (i = 0; i < tag_module_info->num_tags; i++) { - if (sess_obj != NULL) { - /** - * Compare each stream_module present in node_sess list with - * gsl_tag_entry and if match found we are adding it to the graph - * module_list using ADD_MODULE . And remove this module from - * node_sess list . So that in next iterationit will not compare the - * same module with gsl_tag_entry again. - */ - list_for_each(node_list, &node_sess) { - mod_list = node_to_item(node_list, module_info_link_list_t, tagged_list); - if (gsl_tag_entry->tag_id == mod_list->data->tag) { - if (gsl_tag_entry->num_modules > 1) { - AGM_LOGE("modules num is invalid"); - goto free_graph_obj; - } - mod = mod_list->data; - add_module = ADD_MODULE(*mod, NULL); - if (!add_module) { - AGM_LOGE("no memory to allocate add_module"); - ret = -ENOMEM; - goto free_graph_obj; - } - add_module->miid = gsl_tag_entry->module_entry[0].module_iid; - add_module->mid = gsl_tag_entry->module_entry[0].module_id; - add_module->gkv = NULL; - AGM_LOGD("miid %x mid %x tag %x", add_module->miid, add_module->mid, add_module->tag); - goto tag_list; - } - } - } - - if (dev_obj != NULL) { - /** - * Compare each hw_ep_module present in node_hw list with - * gsl_tag_entry and if match found we are adding it to the graph - * module_list using ADD_MODULE . And remove this module from - * node_hw list.So that in next iteration it will not compare the - * same module with gsl_tag_entry again. - */ - list_for_each(node_list, &node_hw) { - mod_list = node_to_item(node_list, module_info_link_list_t, tagged_list); - if (gsl_tag_entry->tag_id == mod_list->data->tag) { - if (gsl_tag_entry->num_modules > 1) { - AGM_LOGE("modules num is invalid"); - goto free_graph_obj; - } - mod = mod_list->data; - add_module = ADD_MODULE(*mod, dev_obj); - if (!add_module) { - AGM_LOGE("no memory to allocate add_module"); - ret = -ENOMEM; - goto free_graph_obj; - } - add_module->miid = gsl_tag_entry->module_entry[0].module_iid; - add_module->mid = gsl_tag_entry->module_entry[0].module_id; - /*store GKV which describes/contains this module*/ - gkv = calloc(1, sizeof(struct agm_key_vector_gsl)); - if (!gkv) { - AGM_LOGE("No memory to create merged metadata\n"); - ret = -ENOMEM; - goto free_graph_obj; - } - gkv->num_kvs = meta_data_kv->gkv.num_kvs; - gkv->kv = calloc(gkv->num_kvs, sizeof(struct agm_key_value)); - if (!gkv->kv) { - AGM_LOGE("No memory to create merged metadata gkv\n"); - free(gkv); - ret = -ENOMEM; - goto free_graph_obj; - } - memcpy(gkv->kv, meta_data_kv->gkv.kv, - gkv->num_kvs * sizeof(struct agm_key_value)); - add_module->gkv = gkv; - AGM_LOGD("miid %x mid %x tag %x", add_module->miid, add_module->mid, add_module->tag); - goto tag_list; - } - } - } -tag_list: - gsl_tag_entry = (struct gsl_tag_module_info_entry *) ((char *)gsl_tag_entry + sizeof(struct gsl_tag_module_info_entry) + - (sizeof(struct gsl_module_id_info_entry) * - gsl_tag_entry->num_modules)); - } -no_config: - graph_obj->sess_obj = sess_obj; - - ret = gsl_open((struct gsl_key_vector *)&meta_data_kv->gkv, - (struct gsl_key_vector *)&meta_data_kv->ckv, - &graph_obj->graph_handle); - agm_memlog_graph_enqueue(GRAPH_OPEN, ret, graph_obj->graph_handle); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("Failed to open the graph with error %d\n", ret); - goto free_graph_obj; - } - - ret = gsl_register_event_cb(graph_obj->graph_handle, - gsl_callback_func, graph_obj); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("failed to register callback\n"); - goto close_graph; - } - graph_obj->state = OPENED; - *gph_obj = graph_obj; - AGM_LOGD("graph_handle %p\n", graph_obj->graph_handle); - - goto done; - -close_graph: - gsl_close(graph_obj->graph_handle); -free_graph_obj: - /*free the list of modules associated with this graph_object*/ - list_for_each_safe(node, temp_node, &graph_obj->tagged_mod_list) { - list_remove(node); - temp_mod = node_to_item(node, module_info_t, list); - if (temp_mod->gkv) { - if (temp_mod->gkv->kv) - free(temp_mod->gkv->kv); - free(temp_mod->gkv); - } - free(temp_mod); - } - pthread_mutex_destroy(&graph_obj->lock); - free(graph_obj); -done: - // free memory allocated in node sess/hw - list_for_each_safe(node, temp_node, &node_sess) { - list_remove(node); - mod_list = node_to_item(node, module_info_link_list_t, tagged_list); - if (mod_list) - free(mod_list); - } - - list_for_each_safe(node, temp_node, &node_hw) { - list_remove(node); - mod_list = node_to_item(node, module_info_link_list_t, tagged_list); - if (mod_list) - free(mod_list); - } - - AGM_LOGD("exit, ret %d", ret); - if (tag_module_info) - free(tag_module_info); - return ret; -} - -int graph_close(struct graph_obj *graph_obj) -{ - int ret = 0; - struct listnode *temp_node,*node = NULL; - module_info_t *temp_mod = NULL; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGD("entry handle %p", graph_obj->graph_handle); - - ret = gsl_close(graph_obj->graph_handle); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("gsl close failed error %d\n", ret); - } - agm_memlog_graph_enqueue(GRAPH_CLOSE, ret, graph_obj->graph_handle); - /*free the list of modules associated with this graph_object*/ - list_for_each_safe(node, temp_node, &graph_obj->tagged_mod_list) { - list_remove(node); - temp_mod = node_to_item(node, module_info_t, list); - if (temp_mod->gkv) { - free(temp_mod->gkv->kv); - free(temp_mod->gkv); - } - free(temp_mod); - } - pthread_mutex_unlock(&graph_obj->lock); - pthread_mutex_destroy(&graph_obj->lock); - free(graph_obj); - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int graph_prepare(struct graph_obj *graph_obj) -{ - int ret = 0; - struct listnode *node = NULL; - module_info_t *mod = NULL; - struct session_obj *sess_obj = NULL; - struct agm_session_config stream_config; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - sess_obj = graph_obj->sess_obj; - - if (sess_obj == NULL) { - AGM_LOGE("invalid sess object\n"); - return -EINVAL; - } - stream_config = sess_obj->stream_config; - - AGM_LOGD("entry graph_handle %p", graph_obj->graph_handle); - pthread_mutex_lock(&graph_obj->lock); - if (graph_obj->state == PREPARED) { - AGM_LOGD("Graph already prepared"); - goto done; - } - /** - *Iterate over mod list to configure each module - *present in the graph. Also validate if the module list - *matches the configuration passed by the client. - */ - list_for_each(node, &graph_obj->tagged_mod_list) { - mod = node_to_item(node, module_info_t, list); - if (mod->is_configured) { - if ((mod->tag == DEVICE_HW_ENDPOINT_RX) || (mod->tag == DEVICE_HW_ENDPOINT_TX)) - goto force_configure; - else - continue; - } - if ((mod->tag == STREAM_INPUT_MEDIA_FORMAT) && - (stream_config.sess_mode == AGM_SESSION_NO_HOST)) { - AGM_LOGE("Shared mem mod present for a hostless session error out\n"); - ret = -EINVAL; - goto done; - } - - if (((mod->tag == STREAM_PCM_DECODER) && - (stream_config.dir == TX)) || - ((mod->tag == STREAM_PCM_ENCODER) && - (stream_config.dir == RX))) { - AGM_LOGE("Session cfg (dir = %d) does not match session module %x\n", - stream_config.dir, mod->module); - ret = -EINVAL; - goto done; - } - -force_configure: - if (mod->configure) { - if ((mod->dev_obj != NULL) && - ((mod->tag == DEVICE_HW_ENDPOINT_RX)|| (mod->tag == DEVICE_HW_ENDPOINT_TX)) && - (device_get_start_refcnt(mod->dev_obj) > 0)) { -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - AGM_LOGI("device obj:%s in started state, start ref_cnt:%d miid %x mid %x tag %x\n", - mod->dev_obj->name, device_get_start_refcnt(mod->dev_obj), mod->miid, mod->mid, mod->tag); -#else - AGM_LOGE("device obj:%s in started state, start ref_cnt:%d miid %x mid %x tag %x\n", - mod->dev_obj->name, device_get_start_refcnt(mod->dev_obj), mod->miid, mod->mid, mod->tag); -#endif - mod->is_configured = true; - continue; - } else { - ret = mod->configure(mod, graph_obj); - if (ret != 0) { - AGM_LOGE("Module configuration for miid %x, mid %x, tag %x, failed:%d\n", - mod->miid, mod->mid, mod->tag, ret); - goto done; - } - mod->is_configured = true; - } - - } - } - - /*Configure buffers only if it is not a hostless session*/ - if ((sess_obj != NULL) && - (stream_config.sess_mode != AGM_SESSION_NO_HOST) && - sess_obj->stream_config.sess_mode != AGM_SESSION_NO_CONFIG) { - ret = configure_buffer_params(graph_obj, sess_obj); - if (ret != 0) { - AGM_LOGE("buffer configuration failed \n"); - goto done; - } - } - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_PREPARE, NULL, 0); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_prepare failed %d\n", ret); - goto done; - } - graph_obj->state = PREPARED; - -done: - pthread_mutex_unlock(&graph_obj->lock); - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int graph_start(struct graph_obj *graph_obj) -{ - int ret = 0; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGD("entry graph_handle %p", graph_obj->graph_handle); - - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_START, NULL, 0); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_start failed %d\n", ret); - goto done; - } - graph_obj->state = STARTED; - -done: - agm_memlog_graph_enqueue(GRAPH_START, ret, graph_obj->graph_handle); - pthread_mutex_unlock(&graph_obj->lock); - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int graph_stop(struct graph_obj *graph_obj, - struct agm_meta_data_gsl *meta_data) -{ - int ret = 0; - struct gsl_cmd_properties gsl_cmd_prop = {0}; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGD("entry graph_handle %p\n", graph_obj->graph_handle); - if ((graph_obj->state & (CLOSED))) { - AGM_LOGE("graph object is not in correct state, current state %d\n", - graph_obj->state); - ret = -EINVAL; - goto done; - } - - if (meta_data) { -#ifdef AGM_DEBUG_METADATA - metadata_print(meta_data); -#endif - memcpy (&(gsl_cmd_prop.gkv), &(meta_data->gkv), - sizeof(struct gsl_key_vector)); - gsl_cmd_prop.property_id = meta_data->sg_props.prop_id; - gsl_cmd_prop.num_property_values = meta_data->sg_props.num_values; - gsl_cmd_prop.property_values = meta_data->sg_props.values; - - if (graph_obj->state & (STARTED)) { - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_STOP, - &gsl_cmd_prop, sizeof(struct gsl_cmd_properties)); - /* Continue to close graph even stop fails */ - if (ret !=0) - AGM_LOGE("graph stop with prop failed %d\n", ret); - } - - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_CLOSE_WITH_PROPS, - &gsl_cmd_prop, sizeof(struct gsl_cmd_properties)); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph close with prop failed %d\n", ret); - } - } else { - if (graph_obj->state & (STOPPED)) { - AGM_LOGE("graph object is already in STOP state\n"); - goto done; - } - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_STOP, NULL, 0); - graph_obj->state = STOPPED; - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph stop failed %d\n", ret); - } - } - -done: - agm_memlog_graph_enqueue(GRAPH_STOP, ret, graph_obj->graph_handle); - pthread_mutex_unlock(&graph_obj->lock); - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int graph_pause_resume(struct graph_obj *graph_obj, bool pause) -{ - int ret = 0; - struct listnode *node = NULL; - module_info_t *mod; - struct apm_module_param_data_t *header; - size_t payload_size = 0; - uint8_t *payload = NULL; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - /* Pause module info is retrived and added to list in graph_open */ - list_for_each(node, &graph_obj->tagged_mod_list) { - mod = node_to_item(node, module_info_t, list); - if (mod->tag == TAG_PAUSE) { - AGM_LOGD("Soft Pause module IID 0x%x, Pause: %d\n", mod->miid, pause); - - payload_size = sizeof(struct apm_module_param_data_t); - ALIGN_PAYLOAD(payload_size, 8); - - payload = calloc(1, (size_t)payload_size); - if (!payload) { - AGM_LOGE("No memory to allocate for payload\n"); - ret = -ENOMEM; - goto done; - } - - header = (struct apm_module_param_data_t*)payload; - header->module_instance_id = mod->miid; - if (pause) - header->param_id = PARAM_ID_SOFT_PAUSE_START; - else - header->param_id = PARAM_ID_SOFT_PAUSE_RESUME; - - header->error_code = 0x0; - header->param_size = 0x0; - - pthread_mutex_lock(&graph_obj->lock); - ret = gsl_set_custom_config(graph_obj->graph_handle, - payload, payload_size); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_set_custom_config failed %d\n", ret); - } - pthread_mutex_unlock(&graph_obj->lock); - free(payload); - break; - } - } - -done: - agm_memlog_graph_enqueue(pause ? GRAPH_PAUSE : GRAPH_RESUME, ret, graph_obj->graph_handle); - return ret; -} - - -int graph_pause(struct graph_obj *graph_obj) -{ - return graph_pause_resume(graph_obj, true); -} - -int graph_flush(struct graph_obj *graph_obj) -{ - int ret = 0; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGD("entry graph_handle %p\n", graph_obj->graph_handle); - - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_FLUSH, NULL, 0); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_flush failed %d\n", ret); - goto done; - } - -done: - pthread_mutex_unlock(&graph_obj->lock); - AGM_LOGD("exit, ret %d", ret); - return ret; -} - - -int graph_resume(struct graph_obj *graph_obj) -{ - return graph_pause_resume(graph_obj, false); -} - -int graph_suspend(struct graph_obj *graph_obj) -{ - int ret = 0; - - AGM_LOGD("Enter"); - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGD("entry graph_handle %p\n", graph_obj->graph_handle); - - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_SUSPEND, NULL, 0); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_suspend failed %d\n", ret); - goto done; - } - -done: - pthread_mutex_unlock(&graph_obj->lock); - AGM_LOGD("exit ret: %d", ret); - return ret; -} - -int graph_set_config(struct graph_obj *graph_obj, void *payload, - size_t payload_size) -{ - int ret = 0; - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGD("entry graph_handle %p", graph_obj->graph_handle); - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_set_config failed %d\n", ret); - } - - pthread_mutex_unlock(&graph_obj->lock); - AGM_LOGD("exit, graph handle %p, ret %d", graph_obj->graph_handle, ret); - return ret; -} - -int graph_get_config(struct graph_obj *graph_obj, void *payload, - size_t payload_size) -{ - int ret = 0; - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGV("entry graph_handle %p", graph_obj->graph_handle); - ret = gsl_get_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_get_config failed %d", ret); - } - pthread_mutex_unlock(&graph_obj->lock); - - return ret; -} - -int graph_set_config_with_tag(struct graph_obj *graph_obj, - struct agm_key_vector_gsl *gkv, - struct agm_tag_config_gsl *tag_config) -{ - int ret = 0; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - ret = gsl_set_config(graph_obj->graph_handle, (struct gsl_key_vector *)gkv, - tag_config->tag_id, - (struct gsl_key_vector *)&tag_config->tkv); - if (ret) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_set_config failed %d\n", ret); - } - - pthread_mutex_unlock(&graph_obj->lock); - - return ret; -} - -int graph_set_cal(struct graph_obj *graph_obj, - struct agm_meta_data_gsl *metadata) -{ - int ret = 0; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - ret = gsl_set_cal(graph_obj->graph_handle, - (struct gsl_key_vector *)&metadata->gkv, - (struct gsl_key_vector *)&metadata->ckv); - if (ret) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_set_cal failed %d\n", ret); - } - - pthread_mutex_unlock(&graph_obj->lock); - - return ret; -} - -int graph_rw_acdb_param(void *payload, bool is_param_write) -{ - int ret = 0; - struct agm_acdb_tunnel_param *payloadACDBTunnelInfo = NULL; - uint32_t i = 0; - uint32_t *ptr = NULL; - uint8_t *ptr_to_param = NULL; - size_t actual_size = 0; - uint32_t tag = 0; - uint32_t miid = 0; - struct agm_key_vector_gsl gkv = {0, NULL}; - struct agm_key_vector_gsl kv = {0, NULL}; - struct apm_module_param_data_t* header; - size_t size = 0; - struct gsl_tag_module_info *tag_info; - struct gsl_tag_module_info_entry *tag_entry; - uint32_t offset = 0, temp_sum = 0; - uint32_t total_parsed_size = 0; - uint8_t tag_pool[TAGGED_MOD_SIZE_BYTES] = { 0 }; - - AGM_LOGD("enter"); - - if (!payload) { - AGM_LOGE("payload is nullptr"); - return -EINVAL; - } - - payloadACDBTunnelInfo = (struct agm_acdb_tunnel_param *)payload; - AGM_LOGD("istkv=%x num_gkvs=0x%x num_kvs=0x%x blob_size=0x%x", - payloadACDBTunnelInfo->isTKV, - payloadACDBTunnelInfo->num_gkvs, - payloadACDBTunnelInfo->num_kvs, - payloadACDBTunnelInfo->blob_size); - - ptr = payloadACDBTunnelInfo->blob; - for (i = 0; i < payloadACDBTunnelInfo->blob_size / 4; i++) { - AGM_LOGV("%d data = 0x%x", i, *ptr++); - } - - ptr = payloadACDBTunnelInfo->blob + sizeof(struct agm_key_value) * - (payloadACDBTunnelInfo->num_gkvs + payloadACDBTunnelInfo->num_kvs); - header = (struct apm_module_param_data_t *)ptr; - ptr_to_param = header; - - // tag is stored at miid. Convertion happens next. - tag = *ptr; - AGM_LOGD("tag to be translated is 0x%x", tag); - - gkv.num_kvs = payloadACDBTunnelInfo->num_gkvs; - gkv.kv = payloadACDBTunnelInfo->blob; - - ret = gsl_get_tags_with_module_info(&gkv, NULL, &size); - if (ret) { - AGM_LOGE("failed to get tag info size = %d size=0x%x", ret, size); - return ret; - } - - ret = gsl_get_tags_with_module_info(&gkv, tag_pool, &size); - if (ret) { - AGM_LOGE("failed to get tag pool ret = %d size=0x%x", ret, size); - return ret; - } - - tag_info = (struct gsl_tag_module_info *)tag_pool; - AGM_LOGD("num of tags is %d\n", tag_info->num_tags); - ret = -1; - tag_entry = (struct gsl_tag_module_info_entry *)(&tag_info->tag_module_entry[0]); - - offset = 0; - for (i = 0; i < tag_info->num_tags; i++) { - tag_entry += offset/sizeof(struct gsl_tag_module_info_entry); - - AGM_LOGD("tag id[%d] = 0x%x, num_modules = 0x%x\n", i, - tag_entry->tag_id, tag_entry->num_modules); - offset = sizeof(struct gsl_tag_module_info_entry) + - (tag_entry->num_modules * - sizeof(struct gsl_module_id_info_entry)); - if (tag_entry->tag_id == tag) { - struct gsl_module_id_info_entry *mod_info_entry; - - if (tag_entry->num_modules) { - mod_info_entry = &tag_entry->module_entry[0]; - miid = mod_info_entry->module_iid; - AGM_LOGI("MIID is 0x%x\n", miid); - ret = 0; - break; - } - } - } - - AGM_LOGI("originally tag = 0x%x", header->module_instance_id); - header->module_instance_id = miid; - AGM_LOGI("translated miid is = 0x%x", header->module_instance_id); - kv.num_kvs = payloadACDBTunnelInfo->num_kvs; - kv.kv = payloadACDBTunnelInfo->blob + - payloadACDBTunnelInfo->num_gkvs * sizeof(struct agm_key_value); - - AGM_LOGD("blob size = %d", payloadACDBTunnelInfo->blob_size); - __builtin_add_overflow(payloadACDBTunnelInfo->num_gkvs * sizeof(struct agm_key_value), - payloadACDBTunnelInfo->num_kvs * sizeof(struct agm_key_value), - &temp_sum); - __builtin_sub_overflow(payloadACDBTunnelInfo->blob_size, temp_sum, &actual_size); - AGM_LOGD("actual size = 0x%x", actual_size); - AGM_LOGI("num kvs = %d", kv.num_kvs); - ptr = kv.kv; - for (i = 0; i < kv.num_kvs; i++) { - AGM_LOGI("kv %d %x", i, *ptr++); - AGM_LOGI("kv %d %x", i, *ptr++); - } - - // for multiple param, we have to fill the miid in each line item. - offset = sizeof(struct apm_module_param_data_t) + header->param_size; - ALIGN_PAYLOAD(offset, 8); - total_parsed_size = offset; - while (total_parsed_size < actual_size) { - AGM_LOGI("multiple param: offset=0x%x", offset); - header = (struct apm_module_param_data_t*)((uint8_t *)header + offset); - header->module_instance_id = miid; - offset = sizeof(struct apm_module_param_data_t) + header->param_size; - ALIGN_PAYLOAD(offset, 8); - total_parsed_size += offset; - AGM_LOGI("total parsed size=0x%x param_size=0x%x offset=0x%x", - total_parsed_size, header->param_size, offset); - } - - ptr = ptr_to_param; - for (i = 0; i < actual_size / 4; i++) { - AGM_LOGV("%d data to acdb = 0x%x", i, *ptr++); - } - - if (is_param_write) { - if (payloadACDBTunnelInfo->isTKV) - ret = gsl_set_tag_data_to_acdb(&gkv, tag, &kv, ptr_to_param, actual_size); - else - ret = gsl_set_cal_data_to_acdb(&gkv, &kv, ptr_to_param, actual_size); - } else { - if (payloadACDBTunnelInfo->isTKV) - ret = graph_get_tckv_data_from_acdb(&gkv, tag, &kv, ptr_to_param, &actual_size); - else - ret = graph_get_tckv_data_from_acdb(&gkv, 0, &kv, ptr_to_param, &actual_size); - } - - return ar_err_get_lnx_err_code(ret); -} - -int graph_write(struct graph_obj *graph_obj, struct agm_buff *buffer, size_t *size) -{ - int ret = 0; - struct gsl_buff gsl_buff = {0}; - uint32_t size_written = 0; - uint32_t write_mod_tag = SHMEM_ENDPOINT; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - /* - *In case of non-tunnel mode session we have two shared memory endpoints - *One for read from the graph and other for writing into the graph - */ - if ((graph_obj->sess_obj->stream_config.sess_mode == AGM_SESSION_NON_TUNNEL) && - (graph_obj->sess_obj->stream_config.dir == (RX | TX))) - write_mod_tag = WR_SHMEM_ENDPOINT; - - gsl_buff.timestamp = buffer->timestamp; - gsl_buff.flags = buffer->flags; - gsl_buff.size = buffer->size; - gsl_buff.addr = buffer->addr; - gsl_buff.metadata_size = buffer->metadata_size; - gsl_buff.metadata = buffer->metadata; - gsl_buff.alloc_info.alloc_handle = buffer->alloc_info.alloc_handle; - gsl_buff.alloc_info.alloc_size = buffer->alloc_info.alloc_size; - gsl_buff.alloc_info.offset = buffer->alloc_info.offset; - - ret = gsl_write(graph_obj->graph_handle, - write_mod_tag, &gsl_buff, &size_written); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("gsl_write for size %zu failed with error %d\n", *size, ret); - goto done; - } - *size = (size_t)size_written; -done: - return ret; -} - -int graph_read(struct graph_obj *graph_obj, struct agm_buff *buffer, size_t *size) -{ - int ret = 0; - struct gsl_buff gsl_buff = {0}; - int size_read = 0; - uint32_t read_mod_tag = SHMEM_ENDPOINT; - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - /* - *In case of non-tunnel mode session we have two shared memory endpoints - *in a single graph, one to read from the graph and other for writing into - *the graph - */ - if ((graph_obj->sess_obj->stream_config.sess_mode == AGM_SESSION_NON_TUNNEL) && - (graph_obj->sess_obj->stream_config.dir == (RX | TX))) - read_mod_tag = RD_SHMEM_ENDPOINT; - else if ((graph_obj->sess_obj->stream_config.sess_mode == - AGM_SESSION_COMPRESS) && - (graph_obj->sess_obj->stream_config.dir == TX)) - read_mod_tag = RD_SHMEM_ENDPOINT; - - gsl_buff.timestamp = buffer->timestamp; - gsl_buff.flags = buffer->flags; - gsl_buff.size = buffer->size; - gsl_buff.addr = buffer->addr; - gsl_buff.metadata_size = buffer->metadata_size; - gsl_buff.metadata = buffer->metadata; - gsl_buff.alloc_info.alloc_handle = buffer->alloc_info.alloc_handle; - gsl_buff.alloc_info.alloc_size = buffer->alloc_info.alloc_size; - gsl_buff.alloc_info.offset = buffer->alloc_info.offset; - - ret = gsl_read(graph_obj->graph_handle, - read_mod_tag, &gsl_buff, (uint32_t *)&size_read); - if ((ret != 0) || - ((size_read == 0) && - (graph_obj->sess_obj->stream_config.sess_mode != AGM_SESSION_NON_TUNNEL))) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("size_requested %zu size_read %d error %d\n", - *size, size_read, ret); - } - *size = size_read; - graph_obj->buf_info.timestamp = gsl_buff.timestamp; - - return ret; -} - -int graph_add(struct graph_obj *graph_obj, - struct agm_meta_data_gsl *meta_data_kv, - struct device_obj *dev_obj) -{ - int ret = 0; - - struct gsl_cmd_graph_select add_graph; - module_info_t *mod = NULL; - struct agm_key_vector_gsl *gkv; - struct listnode *node = NULL; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGD("entry graph_handle %p\n", graph_obj->graph_handle); - - if (graph_obj->state < OPENED) { - AGM_LOGE("Cannot add a graph in %d state\n", graph_obj->state); - ret = -EINVAL; - goto done; - } - /** - *This api is used to add a new device leg ( is device object is - *present in the argument or to add an already exisiting graph. - *Hence we need not add any new session (stream) related modules - */ - - /*Add the new GKV to the current graph*/ - add_graph.graph_key_vector.num_kvps = meta_data_kv->gkv.num_kvs; - add_graph.graph_key_vector.kvp = (struct gsl_key_value_pair *) - meta_data_kv->gkv.kv; - add_graph.cal_key_vect.num_kvps = meta_data_kv->ckv.num_kvs; - add_graph.cal_key_vect.kvp = (struct gsl_key_value_pair *) - meta_data_kv->ckv.kv; - metadata_print(meta_data_kv); - print_graph_alias(meta_data_kv); - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_ADD_GRAPH, &add_graph, - sizeof(struct gsl_cmd_graph_select)); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph add failed with error %d\n", ret); - goto done; - } - if (dev_obj != NULL) { - module_info_t *temp_mod = NULL; - size_t module_info_size; - struct gsl_module_id_info *module_info; - bool mod_present = false; - size_t arraysize; - module_info_t *hw_ep_module = NULL; - module_info_t *add_module = NULL; - - get_hw_ep_module_list_array(&hw_ep_module, &arraysize); - if (dev_obj->hw_ep_info.dir == AUDIO_OUTPUT) - mod = &hw_ep_module[0]; - else - mod = &hw_ep_module[1]; - - ret = gsl_get_tagged_module_info((struct gsl_key_vector *) - &meta_data_kv->gkv, - mod->tag, - &module_info, (uint32_t*) &module_info_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("cannot get tagged module info for module %x\n", - mod->tag); - goto done; - } - /** - *Check if this is the same device object as was passed for graph open - *or a new one.We do this by comparing the module_iid of the module - *present in the graph object with the one returned from the above api. - *if it is a new module we add it to the list and configure it. - */ - list_for_each(node, &graph_obj->tagged_mod_list) { - temp_mod = node_to_item(node, module_info_t, list); - if (temp_mod->miid == module_info->module_entry[0].module_iid) { - mod_present = true; - /** - * Module might have configured previously as we don't reset in - * graph_remove() API. Reset is_configured flag here. - * Ex: back to back device switch scenario. - */ - temp_mod->is_configured = false; - break; - } - } - if (!mod_present) { - /** - *This is a new device object, add this module to the list and - */ - /*Make a local copy of gkv and use when we query gsl - for tagged data*/ - add_module = ADD_MODULE(*mod, dev_obj); - if (!add_module) { - AGM_LOGE("no memory to allocate add_module"); - ret = -ENOMEM; - goto done; - } - add_module->miid = module_info->module_entry[0].module_iid; - add_module->mid = module_info->module_entry[0].module_id; - gkv = calloc(1, sizeof(struct agm_key_vector_gsl)); - if (!gkv) { - AGM_LOGE("No memory to allocate for gkv\n"); - ret = -ENOMEM; - goto done; - } - gkv->num_kvs = meta_data_kv->gkv.num_kvs; - gkv->kv = calloc(gkv->num_kvs, sizeof(struct agm_key_value)); - if (!gkv->kv) { - AGM_LOGE("No memory to allocate for kv\n"); - free(gkv); - ret = -ENOMEM; - goto done; - } - memcpy(gkv->kv, meta_data_kv->gkv.kv, - gkv->num_kvs * sizeof(struct agm_key_value)); - add_module->gkv = gkv; - gkv = NULL; - AGM_LOGD("Adding the new module tag %x mid %x miid %x\n", - add_module->tag, add_module->mid, add_module->miid); - } - } - /* Configure the newly added modules only if graph is in start state, - * in all other states, graph_prepare will take care of configuring - * modules. - */ - if (graph_obj->state & (STARTED|PREPARED)) { - list_for_each(node, &graph_obj->tagged_mod_list) { - mod = node_to_item(node, module_info_t, list); - /* Need to configure SPR module again for the new device */ - if (mod->is_configured && !(mod->tag == TAG_STREAM_SPR)) - continue; - - if ((mod->dev_obj != NULL) && - ((mod->tag == DEVICE_HW_ENDPOINT_RX) || - (mod->tag == DEVICE_HW_ENDPOINT_TX)) && - (device_get_start_refcnt(mod->dev_obj) > 0)) { - AGM_LOGE("device obj:%s in started state, start ref_cnt:%d\n", - mod->dev_obj->name, device_get_start_refcnt(mod->dev_obj)); - mod->is_configured = true; - continue; - } - - if (mod->configure) { - ret = mod->configure(mod, graph_obj); - if (ret != 0) - goto done; - mod->is_configured = true; - } - } - } - -done: - pthread_mutex_unlock(&graph_obj->lock); - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int graph_change(struct graph_obj *graph_obj, - struct agm_meta_data_gsl *meta_data_kv, - struct device_obj *dev_obj) -{ - int ret = 0; - - struct gsl_cmd_graph_select change_graph; - module_info_t *mod = NULL; - struct agm_key_vector_gsl *gkv; - struct listnode *node, *temp_node = NULL; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGD("entry graph_handle %p", graph_obj->graph_handle); - metadata_print(meta_data_kv); - - if (dev_obj != NULL) { - mod = NULL; - module_info_t *add_module, *temp_mod = NULL; - size_t module_info_size; - struct gsl_module_id_info *module_info; - bool mod_present = false; - size_t arraysize; - module_info_t *hw_ep_module = NULL; - get_hw_ep_module_list_array(&hw_ep_module, &arraysize); - if (dev_obj->hw_ep_info.dir == AUDIO_OUTPUT) - mod = &hw_ep_module[0]; - else - mod = &hw_ep_module[1]; - - ret = gsl_get_tagged_module_info((struct gsl_key_vector *) - &meta_data_kv->gkv, - mod->tag, - &module_info, (uint32_t*) &module_info_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("cannot get tagged module info for module %x\n", - mod->tag); - goto done; - } - /** - *Check if this is the same device object as was passed for graph open - *or a new one.We do this by comparing the module_iid of the module - *present in the graph object with the one returned from the above api. - *If this is a new module, we delete the older device tagged module - *as it is not part of the graph anymore (would have been removed as a - *part of graph_remove). - */ - list_for_each(node, &graph_obj->tagged_mod_list) { - temp_mod = node_to_item(node, module_info_t, list); - if (temp_mod->miid == module_info->module_entry[0].module_iid) { - AGM_LOGV("info for module %x, config flag = %d\n", temp_mod->tag, temp_mod->is_configured); - mod_present = true; - temp_mod->is_configured = false; - break; - } - } - /* Delete the current hw_ep(Device module) from the list */ - list_for_each_safe(node, temp_node, &graph_obj->tagged_mod_list) { - temp_mod = node_to_item(node, module_info_t, list); - if (((temp_mod->tag == DEVICE_HW_ENDPOINT_TX) || - (temp_mod->tag == DEVICE_HW_ENDPOINT_RX)) && - (temp_mod->miid != module_info->module_entry[0].module_iid)) { - list_remove(node); - if (temp_mod->gkv) { - free(temp_mod->gkv->kv); - free(temp_mod->gkv); - } - free(temp_mod); - temp_mod = NULL; - } - } - if (!mod_present) { - /*This is a new device object, add this module to the list */ - add_module = ADD_MODULE(*mod, dev_obj); - if (!add_module) { - AGM_LOGE("No memory to allocate for add_module\n"); - ret = -ENOMEM; - goto done; - } - add_module->miid = module_info->module_entry[0].module_iid; - add_module->mid = module_info->module_entry[0].module_id; - /*Make a local copy of gkv and use when we query gsl - for tagged data*/ - gkv = calloc(1, sizeof(struct agm_key_vector_gsl)); - if (!gkv) { - AGM_LOGE("No memory to allocate for gkv\n"); - ret = -ENOMEM; - goto done; - } - gkv->num_kvs = meta_data_kv->gkv.num_kvs; - gkv->kv = calloc(gkv->num_kvs, sizeof(struct agm_key_value)); - if (!gkv->kv) { - AGM_LOGE("No memory to allocate for kv\n"); - free(gkv); - ret = -ENOMEM; - goto done; - } - memcpy(gkv->kv, meta_data_kv->gkv.kv, - gkv->num_kvs * sizeof(struct agm_key_value)); - add_module->gkv = gkv; - gkv = NULL; - } - } - /*Send the new GKV for CHANGE_GRAPH*/ - change_graph.graph_key_vector.num_kvps = meta_data_kv->gkv.num_kvs; - change_graph.graph_key_vector.kvp = (struct gsl_key_value_pair *) - meta_data_kv->gkv.kv; - change_graph.cal_key_vect.num_kvps = meta_data_kv->ckv.num_kvs; - change_graph.cal_key_vect.kvp = (struct gsl_key_value_pair *) - meta_data_kv->ckv.kv; - print_graph_alias(meta_data_kv); - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_CHANGE_GRAPH, &change_graph, - sizeof(struct gsl_cmd_graph_select)); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph add failed with error %d\n", ret); - goto done; - } - /*configure modules again*/ - list_for_each(node, &graph_obj->tagged_mod_list) { - mod = node_to_item(node, module_info_t, list); - if (mod->configure && !mod->is_configured && - (mod->dev_obj != NULL && device_get_start_refcnt(mod->dev_obj) == 0)) { - ret = mod->configure(mod, graph_obj); - if (ret != 0) - goto done; - mod->is_configured = true; - } - } -done: - pthread_mutex_unlock(&graph_obj->lock); - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int graph_remove(struct graph_obj *graph_obj, - struct agm_meta_data_gsl *meta_data_kv) -{ - int ret = 0; - struct gsl_cmd_remove_graph rm_graph; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - pthread_mutex_lock(&graph_obj->lock); - AGM_LOGD("entry graph_handle %p\n", graph_obj->graph_handle); - - /** - *graph_remove would only pass the graph which needs to be removed. - *to GSL. Once graph remove is done, sesison obj will have to issue - *graph_change/graph_add if reconfiguration of modules is needed, otherwise - *graph_start will suffice.graph remove wont reconfigure the modules. - */ - rm_graph.graph_key_vector.num_kvps = meta_data_kv->gkv.num_kvs; - rm_graph.graph_key_vector.kvp = (struct gsl_key_value_pair *) - meta_data_kv->gkv.kv; - metadata_print(meta_data_kv); - print_graph_alias(meta_data_kv); - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_REMOVE_GRAPH, &rm_graph, - sizeof(struct gsl_cmd_remove_graph)); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph add failed with error %d\n", ret); - } - - pthread_mutex_unlock(&graph_obj->lock); - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int graph_register_cb(struct graph_obj *gph_obj, event_cb cb, - void *client_data) -{ - - if (gph_obj == NULL){ - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - - if (cb == NULL) { - AGM_LOGE("No callback to register\n"); - return -EINVAL; - } - - pthread_mutex_lock(&gph_obj->lock); - gph_obj->cb = cb; - gph_obj->client_data = client_data; - pthread_mutex_unlock(&gph_obj->lock); - - return 0; -} - -int graph_register_for_events(struct graph_obj *gph_obj, - struct agm_event_reg_cfg *evt_reg_cfg) -{ - int ret = 0; - struct gsl_cmd_register_custom_event *reg_ev_payload = NULL; - size_t payload_size = 0; - - if (gph_obj == NULL){ - AGM_LOGE("invalid graph object\n"); - ret = -EINVAL; - goto done; - } - - if (evt_reg_cfg == NULL) { - AGM_LOGE("No event register payload passed\n"); - ret = -EINVAL; - goto done; - } - pthread_mutex_lock(&gph_obj->lock); - - if (gph_obj->graph_handle == NULL) { - pthread_mutex_unlock(&gph_obj->lock); - AGM_LOGE("invalid graph handle\n"); - ret = -EINVAL; - goto done; - } - payload_size = sizeof(struct gsl_cmd_register_custom_event) + - evt_reg_cfg->event_config_payload_size; - - reg_ev_payload = calloc(1, payload_size); - if (reg_ev_payload == NULL) { - pthread_mutex_unlock(&gph_obj->lock); - AGM_LOGE("calloc failed for reg_ev_payload\n"); - ret = -ENOMEM; - goto done; - } - - reg_ev_payload->event_id = evt_reg_cfg->event_id; - reg_ev_payload->module_instance_id = evt_reg_cfg->module_instance_id; - reg_ev_payload->event_config_payload_size = - evt_reg_cfg->event_config_payload_size; - reg_ev_payload->is_register = evt_reg_cfg->is_register; - - memcpy((uint8_t *)reg_ev_payload + sizeof(struct gsl_cmd_register_custom_event), - evt_reg_cfg->event_config_payload, - evt_reg_cfg->event_config_payload_size); - - ret = gsl_ioctl(gph_obj->graph_handle, GSL_CMD_REGISTER_CUSTOM_EVENT, - reg_ev_payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("event registration failed with error %d\n", ret); - } - free(reg_ev_payload); - pthread_mutex_unlock(&gph_obj->lock); - - gph_obj->buf_info.timestamp = 0; -done: - return ret; -} - -size_t graph_get_hw_processed_buff_cnt(struct graph_obj *graph_obj, - enum direction dir __unused) -{ - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object or null callback\n"); - return 0; - } - /*TODO: Uncomment that call once platform moves to latest GSL release*/ - return 2 /*gsl_get_processed_buff_cnt(graph_obj->graph_handle, dir)*/; - -} - -int graph_eos(struct graph_obj *graph_obj) -{ - int ret = 0; - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - AGM_LOGI("enter"); - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_EOS, NULL, 0); - AGM_LOGI("exit, ret %d", ret); -#else - AGM_LOGE("enter"); - ret = gsl_ioctl(graph_obj->graph_handle, GSL_CMD_EOS, NULL, 0); - AGM_LOGE("exit, ret %d", ret); -#endif - return ar_err_get_lnx_err_code(ret); -} - -int graph_get_session_time(struct graph_obj *graph_obj, uint64_t *tstamp) -{ - int ret = 0; - uint8_t *payload = NULL; - struct apm_module_param_data_t *header; - struct param_id_spr_session_time_t *sess_time; - size_t payload_size = 0; - uint64_t timestamp; - - if (graph_obj == NULL || tstamp == NULL) { - AGM_LOGE("Invalid Input Params\n"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - if (!(graph_obj->state & (STARTED))) { - AGM_LOGV("graph object is not in correct state, current state %d\n", - graph_obj->state); - ret = 0; - goto done; - } - if (graph_obj->spr_miid == 0) { - AGM_LOGE("Invalid SPR module IID to query timestamp\n"); - goto done; - } - AGM_LOGV("SPR module IID: %x\n", graph_obj->spr_miid); - - payload_size = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_spr_session_time_t); - /*ensure that the payloadsize is byte multiple */ - ALIGN_PAYLOAD(payload_size, 8); - - payload = calloc(1, (size_t)payload_size); - if (!payload) - goto done; - - header = (struct apm_module_param_data_t*)payload; - sess_time = (struct param_id_spr_session_time_t *) - (payload + sizeof(struct apm_module_param_data_t)); - - header->module_instance_id = graph_obj->spr_miid; - header->param_id = PARAM_ID_SPR_SESSION_TIME; - header->error_code = 0x0; - header->param_size = (uint32_t)sizeof(struct param_id_spr_session_time_t); - - ret = gsl_get_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("gsl_get_custom_config command failed with error %d\n", ret); - goto get_fail; - } - AGM_LOGV("session_time: msw[%u], lsw[%u], at: msw[%u], \ - lsw[%u] ts: msw[%u], lsw[%u]\n", - sess_time->session_time.value_msw, - sess_time->session_time.value_lsw, - sess_time->absolute_time.value_msw, - sess_time->absolute_time.value_lsw, - sess_time->timestamp.value_msw, - sess_time->timestamp.value_lsw); - - timestamp = (uint64_t)sess_time->session_time.value_msw; - timestamp = timestamp << 32 | sess_time->session_time.value_lsw; - *tstamp = timestamp; - -get_fail: - free(payload); -done: - pthread_mutex_unlock(&graph_obj->lock); - return ret; -} - -int graph_get_buffer_timestamp(struct graph_obj *graph_obj, uint64_t *tstamp) -{ - int ret = 0; - - if (graph_obj == NULL || tstamp == NULL) { - AGM_LOGE("Invalid Input Params"); - return -EINVAL; - } - - pthread_mutex_lock(&graph_obj->lock); - if (!(graph_obj->state & (STARTED))) { - AGM_LOGE("graph object is not in correct state, current state %d", - graph_obj->state); - ret = -EINVAL; - goto done; - } - - *tstamp = graph_obj->buf_info.timestamp; - -done: - pthread_mutex_unlock(&graph_obj->lock); - return ret; -} - -/* TODO expose this header file from osal */ -struct ar_shmem_handle { - /*ion fd created on ion memory allocation*/ - int32_t ion_mem_fd; -}; - -static int graph_fill_buf_info(struct graph_obj *gph_obj, - struct agm_buf_info *buf_info, enum gsl_cmd_id cmd_id, enum buf_flag flag) -{ - struct gsl_cmd_get_shmem_buf_info *shmem_buf_info = NULL; - struct ar_shmem_handle *shmem_handle; - int ret = -1; - - if (gph_obj == NULL){ - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - shmem_buf_info = calloc(1, sizeof(struct gsl_cmd_get_shmem_buf_info)); - if (!shmem_buf_info) { - AGM_LOGE("shmem_buf_info allocation failed\n"); - return -ENOMEM; - } - - shmem_buf_info->num_buffs = 1; - shmem_buf_info->buffs = calloc(shmem_buf_info->num_buffs, sizeof(struct gsl_shmem_buf)); - if (!shmem_buf_info->buffs) { - AGM_LOGE("buf allocation failed\n"); - ret = -ENOMEM; - goto free_shbuf_info; - } - - ret = gsl_ioctl(gph_obj->graph_handle, cmd_id, shmem_buf_info, - sizeof(struct gsl_cmd_get_shmem_buf_info) + sizeof(struct gsl_shmem_buf)); - if (ret != 0) { - AGM_LOGE("Buffer info get failed error %d", ret); - goto free_buffs; - } - - AGM_LOGD("metadata %llx\n", (unsigned long long) shmem_buf_info->buffs[0].metadata); - AGM_LOGD("shmem_buf_info size %d - addr %p\n", shmem_buf_info->size, shmem_buf_info->buffs[0].addr); - - shmem_handle = (struct ar_shmem_handle *)shmem_buf_info->buffs[0].metadata; - if (shmem_handle) { - if (flag == DATA_BUF) { - buf_info->data_buf_fd = shmem_handle->ion_mem_fd; - buf_info->data_buf_size = shmem_buf_info->size; - } - else { - buf_info->pos_buf_fd = shmem_handle->ion_mem_fd; - buf_info->pos_buf_size = shmem_buf_info->size; - } - } - -free_buffs: - free(shmem_buf_info->buffs); -free_shbuf_info: - free(shmem_buf_info); - return ret; -} - -int graph_get_buf_info(struct graph_obj *graph_obj, struct agm_buf_info *buf_info, uint32_t flag) -{ - struct session_obj *sess_obj = NULL; - enum gsl_cmd_id cmd_id; - int ret = -EINVAL; - struct agm_buffer_config buffer_config = {0}; - - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object"); - return -EINVAL; - } - - sess_obj = graph_obj->sess_obj; - if (sess_obj == NULL) { - AGM_LOGE("invalid sess object"); - return -EINVAL; - } - if (sess_obj->stream_config.dir == TX) - buffer_config = sess_obj->in_buffer_config; - else - buffer_config = sess_obj->out_buffer_config; - - if ((buffer_config.count == 0) || - (buffer_config.size == 0)) { - AGM_LOGE("invalid buffer count or size"); - return -EINVAL; - } - - configure_buffer_params(graph_obj, sess_obj); - if (flag & DATA_BUF) { - if (sess_obj->stream_config.dir == RX) - cmd_id = GSL_CMD_GET_WRITE_BUFF_INFO; - else - cmd_id = GSL_CMD_GET_READ_BUFF_INFO; - - ret = graph_fill_buf_info(graph_obj, buf_info, cmd_id, DATA_BUF); - } - - if (flag & POS_BUF) { - if (sess_obj->stream_config.dir == RX) - cmd_id = GSL_CMD_GET_WRITE_POS_BUFF_INFO; - else - cmd_id = GSL_CMD_GET_READ_POS_BUFF_INFO; - - ret = graph_fill_buf_info(graph_obj, buf_info, cmd_id, POS_BUF); - } - return ret; -} - -int graph_set_gapless_metadata(struct graph_obj *graph_obj, - enum agm_gapless_silence_type type, - uint32_t silence) -{ - int ret = 0; - struct listnode *node = NULL; - struct module_info *mod; - struct apm_module_param_data_t *header; - struct param_id_remove_initial_silence_t *pid_is; - struct param_id_remove_trailing_silence_t *pid_ts; - uint8_t *payload = NULL; - size_t payload_size = 0; - uint32_t decoder_miid = 0; - - if (graph_obj == NULL){ - AGM_LOGE("invalid graph object\n"); - return -EINVAL; - } - pthread_mutex_lock(&graph_obj->lock); - - list_for_each(node, &graph_obj->tagged_mod_list) { - mod = node_to_item(node, module_info_t, list); - if (mod->tag == TAG_STREAM_PLACEHOLDER_DECODER) { - AGM_LOGD("Decoder module IID %x", mod->miid); - decoder_miid = mod->miid; - break; - } - } - if (decoder_miid == 0) { - AGM_LOGE("Decoder MIID not found"); - ret = -EINVAL; - goto done; - } - /* Send initial/trailing silence information */ - payload_size = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_remove_initial_silence_t); - if (payload_size % 8 != 0) - payload_size = payload_size + (8 - payload_size % 8); - - payload = calloc(1, (size_t)payload_size); - if (!payload) { - AGM_LOGE("No memory to allocate for payload"); - ret = -ENOMEM; - goto done; - } - header = (struct apm_module_param_data_t*)payload; - pid_is = (struct param_id_remove_initial_silence_t *)(payload - + sizeof(struct apm_module_param_data_t)); - header->error_code = 0x0; - header->param_size = payload_size; - header->module_instance_id = decoder_miid; - if (type == INITIAL_SILENCE) { - header->param_id = PARAM_ID_REMOVE_INITIAL_SILENCE; - } else if (type == TRAILING_SILENCE) { - header->param_id = PARAM_ID_REMOVE_TRAILING_SILENCE; - } else { - AGM_LOGE("Invalid gapless silence type %d", type); - goto error; - } - pid_is->samples_per_ch_to_remove = silence; - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret !=0) - AGM_LOGE("failed to set %d type silence with ret = %d", type, ret); - -error: - free(payload); -done: - pthread_mutex_unlock(&graph_obj->lock); - return ret; -} - -int graph_set_tag_data_to_acdb( - struct agm_key_vector_gsl *graph_key_vect, uint32_t tag_id, - struct agm_key_vector_gsl *tag_key_vect, uint8_t *payload, - uint32_t payload_size) -{ - return gsl_set_tag_data_to_acdb((struct gsl_key_vector *)graph_key_vect, - tag_id, (struct gsl_key_vector *)tag_key_vect, - payload, payload_size); -} - -int graph_set_cal_data_to_acdb( - struct agm_key_vector_gsl *graph_key_vect, - struct agm_key_vector_gsl *cal_key_vect, uint8_t *payload, - uint32_t payload_size) -{ - return gsl_set_cal_data_to_acdb((struct gsl_key_vector *)graph_key_vect, - (struct gsl_key_vector *)cal_key_vect, - payload, payload_size); -} - -int graph_get_tagged_data( - const struct agm_key_vector_gsl *graph_key_vect, uint32_t tag, - struct agm_key_vector_gsl *tag_key_vect, uint8_t *payload, - size_t *payload_size) -{ - return gsl_get_tagged_data((struct gsl_key_vector *)graph_key_vect, - tag, (struct gsl_key_vector *)tag_key_vect, - payload, payload_size); -} - -int graph_get_tckv_data_from_acdb( - const struct agm_key_vector_gsl *graph_key_vect, uint32_t tag, - struct agm_key_vector_gsl *tag_key_vect, uint8_t *payload, - size_t *payload_size) -{ - int ret = 0; - uint32_t *ptr = NULL; - size_t query_payload_size = *payload_size; - struct apm_module_param_data_t *param = (apm_module_param_data_t *)payload; - uint32_t *param_list; - - if (!payload) { - return -EINVAL; - } - - //payload: instance_id, param_id, size, error_code, data, padding if possible - ptr = (uint32_t *)payload; - param_list = calloc(1, PARAM_LIST_MAX_IDX * sizeof(uint32_t)); - if (!param_list) - return -ENOMEM; - - param_list[MIID_IDX] = ptr[0]; - param_list[NUM_OF_PARAM_IDX] = 1; - param_list[PARAM_ID_IDX] = param->param_id; - - AGM_LOGI("miid=0x%x param_id=0x%x", - param_list[MIID_IDX], param_list[PARAM_ID_IDX]); - - if (tag) { - AGM_LOGI("Tag for tkv is 0x%x", tag); - ret = gsl_get_tag_data_from_acdb((struct gsl_key_vector *)graph_key_vect, - tag, (struct gsl_key_vector *)tag_key_vect, 1, param_list, - NULL, payload_size); - } else { - AGM_LOGI("This is ckv"); - ret = gsl_get_cal_data_from_acdb((struct gsl_key_vector *)graph_key_vect, - (struct gsl_key_vector *)tag_key_vect, 1, param_list, - NULL, payload_size); - } - - if (ret) { - AGM_LOGE("failed to get tagged data size"); - ret = -EINVAL; - goto end; - } - - AGM_LOGI("expected size = %d query_size= %d", - *payload_size, query_payload_size); - if (*payload_size > query_payload_size) { - AGM_LOGE("payload size is too small to hold result."); - ret = -ENOMEM; - goto end; - } - - uint8_t *get_payload = calloc(1, *payload_size); - if (!get_payload) { - ret = -ENOMEM; - goto end; - } - - if (tag) { - AGM_LOGE("This is tag data."); - ret = gsl_get_tag_data_from_acdb((struct gsl_key_vector *)graph_key_vect, - tag, (struct gsl_key_vector *)tag_key_vect, 1, param_list, - get_payload, payload_size); - } else { - AGM_LOGE("This is ckv data."); - ret = gsl_get_cal_data_from_acdb((struct gsl_key_vector *)graph_key_vect, - (struct gsl_key_vector *)tag_key_vect, 1, param_list, - get_payload, payload_size); - } - - if (ret) { - AGM_LOGE("failed to get tagged data"); - ret = -EINVAL; - goto error; - } - - memcpy(payload, get_payload, *payload_size); - -error: - free(get_payload); - -end: - free(param_list); - return ret; -} - -int graph_enable_acdb_persistence(uint8_t enable_flag) -{ - return gsl_enable_acdb_persistence(enable_flag); -} - -static bool is_media_config_needed_on_datapath(enum agm_media_format format) -{ - bool ret = false; - - switch (format) { - case AGM_FORMAT_MP3: - case AGM_FORMAT_AAC: - case AGM_FORMAT_FLAC: - case AGM_FORMAT_ALAC: - case AGM_FORMAT_APE: - case AGM_FORMAT_WMASTD: - case AGM_FORMAT_WMAPRO: - ret = true; - break; - default: - AGM_LOGE("Entered default, format %d", format); - break; - } - return ret; -} - -int graph_set_media_config_datapath(struct graph_obj *graph_obj) -{ - int ret = 0; - struct listnode *node = NULL; - module_info_t *mod = NULL; - struct session_obj *sess_obj = graph_obj->sess_obj; - - if (is_media_config_needed_on_datapath(sess_obj->out_media_config.format)) { - list_for_each(node, &graph_obj->tagged_mod_list) { - mod = node_to_item(node, module_info_t, list); - if (mod->tag == STREAM_INPUT_MEDIA_FORMAT) { - ret = mod->configure(mod, graph_obj); - if (ret != 0) { - AGM_LOGE("Module configuration for miid %x, mid %x, tag %x, failed:%d\n", - mod->miid, mod->mid, mod->tag, ret); - } - } - } - } else { - AGM_LOGD("Media configuration on dataptah is not needed for format %d", - sess_obj->out_media_config.format); - } - return ret; -} - -static void print_graph_alias(const struct agm_meta_data_gsl *meta_data_kv) -{ - uint32_t acdb_string_len = 255; - char acdb_string [255] = {0}; - int ret = AR_EOK; - - if (meta_data_kv->gkv.num_kvs == 0) { - AGM_LOGD("print_graph_alias: No GKV pairs in meta_data"); - return; - } - - ret = gsl_get_graph_alias(&meta_data_kv->gkv, acdb_string, &acdb_string_len); - if (ret) { - AGM_LOGD("gsl_get_graph_alias failed: ret = %d\n", ret); - return; - } - -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - AGM_LOGI("GKV Alias %s\n", acdb_string); -#else - AGM_LOGD("GKV Alias %s\n", acdb_string); -#endif -} diff --git a/qcom/opensource/agm/service/src/graph_module.c b/qcom/opensource/agm/service/src/graph_module.c deleted file mode 100755 index 7487a225..00000000 --- a/qcom/opensource/agm/service/src/graph_module.c +++ /dev/null @@ -1,2070 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2022-2023, Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AGM: graph_module" - -#include -#include -#include "gsl_intf.h" -#include -#include -#include -#include - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_GRAPH_MODULE -#include -#endif - -#define MONO 1 -#define GET_BITS_PER_SAMPLE(format, bit_width) \ - (format == AGM_FORMAT_PCM_S24_LE? 32 : bit_width) - -/*qfactor should be set to 23 only for 24_3LE and 24_LE formats*/ -#define GET_Q_FACTOR(format, bit_width) (bit_width - 1) - -static void get_default_channel_map(uint8_t *channel_map, int channels) -{ - switch (channels) { - case CHANNEL_1: - channel_map[0] = PCM_CHANNEL_C; - break; - case CHANNEL_2: - channel_map[0] = PCM_CHANNEL_L; - channel_map[1] = PCM_CHANNEL_R; - break; - case CHANNEL_3: - channel_map[0] = PCM_CHANNEL_L; - channel_map[1] = PCM_CHANNEL_R; - channel_map[2] = PCM_CHANNEL_C; - break; - case CHANNEL_4: - channel_map[0] = PCM_CHANNEL_L; - channel_map[1] = PCM_CHANNEL_R; - channel_map[2] = PCM_CHANNEL_LB; - channel_map[3] = PCM_CHANNEL_RB; - break; - case CHANNEL_5: - channel_map[0] = PCM_CHANNEL_L; - channel_map[1] = PCM_CHANNEL_R; - channel_map[2] = PCM_CHANNEL_C; - channel_map[3] = PCM_CHANNEL_LB; - channel_map[4] = PCM_CHANNEL_RB; - break; - case CHANNEL_6: - channel_map[0] = PCM_CHANNEL_L; - channel_map[1] = PCM_CHANNEL_R; - channel_map[2] = PCM_CHANNEL_C; - channel_map[3] = PCM_CHANNEL_LFE; - channel_map[4] = PCM_CHANNEL_LB; - channel_map[5] = PCM_CHANNEL_RB; - break; - case CHANNEL_7: - /* - * Configured for 5.1 channel mapping + 1 channel for debug - * Can be customized based on DSP. - */ - channel_map[0] = PCM_CHANNEL_L; - channel_map[1] = PCM_CHANNEL_R; - channel_map[2] = PCM_CHANNEL_C; - channel_map[3] = PCM_CHANNEL_LFE; - channel_map[4] = PCM_CHANNEL_LB; - channel_map[5] = PCM_CHANNEL_RB; - channel_map[6] = PCM_CHANNEL_CS; - break; - case CHANNEL_8: - channel_map[0] = PCM_CHANNEL_L; - channel_map[1] = PCM_CHANNEL_R; - channel_map[2] = PCM_CHANNEL_C; - channel_map[3] = PCM_CHANNEL_LFE; - channel_map[4] = PCM_CHANNEL_LB; - channel_map[5] = PCM_CHANNEL_RB; - channel_map[6] = PCM_CHANNEL_LS; - channel_map[7] = PCM_CHANNEL_RS; - } -} - -static bool is_format_pcm(enum agm_media_format fmt_id) -{ - if (fmt_id >= AGM_FORMAT_PCM_S8 && fmt_id <= AGM_FORMAT_PCM_S32_LE) - return true; - - return false; -} - -static bool is_format_bypassed(enum agm_media_format fmt_id) -{ - if (fmt_id == AGM_FORMAT_VORBIS) { - return true; - } - - return false; -} - -int get_pcm_bit_width(enum agm_media_format fmt_id) -{ - int bit_width = 16; - - switch (fmt_id) { - case AGM_FORMAT_PCM_S24_3LE: - /* - *This api returns the number of audio data bit width specific to the format - *e.g. In S24_LE, even if the number of bytes is 4, the audio data is only in 3 bytes - *Hence we return 24 as the bit_width, whereas the bitspersample for this format would - *return 32 - */ - case AGM_FORMAT_PCM_S24_LE: - bit_width = 24; - break; - case AGM_FORMAT_PCM_S32_LE: - bit_width = 32; - break; - case AGM_FORMAT_PCM_S16_LE: - default: - break; - } - - return bit_width; -} - -static int get_media_bit_width(struct session_obj *sess_obj, - struct agm_media_config *media_config) -{ - int bit_width = 16; - - if (is_format_pcm(media_config->format)) - return get_pcm_bit_width(media_config->format); - - switch (media_config->format) { - case AGM_FORMAT_FLAC: - bit_width = sess_obj->stream_config.codec.flac_dec.sample_size; - break; - case AGM_FORMAT_ALAC: - bit_width = sess_obj->stream_config.codec.alac_dec.bit_depth; - break; - case AGM_FORMAT_APE: - bit_width = sess_obj->stream_config.codec.ape_dec.bit_width; - break; - case AGM_FORMAT_WMASTD: - bit_width = sess_obj->stream_config.codec.wma_dec.bits_per_sample; - break; - case AGM_FORMAT_WMAPRO: - bit_width = sess_obj->stream_config.codec.wmapro_dec.bits_per_sample; - break; - case AGM_FORMAT_MP3: - case AGM_FORMAT_AAC: - case AGM_FORMAT_OPUS: - default: - break; - } - AGM_LOGD("%s: bit width: %d", __func__, bit_width); - - return bit_width; -} - -static int configure_codec_dma_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct device_obj *dev_obj = mod->dev_obj; - hw_ep_info_t hw_ep_info = dev_obj->hw_ep_info; - struct apm_module_param_data_t *header; - struct param_id_codec_dma_intf_cfg_t* codec_config; - size_t payload_sz; - uint8_t *payload = NULL; - uint32_t *chmap = NULL; - struct agm_media_config media_config = (dev_obj->group_data) ? - dev_obj->group_data->media_config.config :dev_obj->media_config; - - AGM_LOGV("entry mod tag %x miid %x mid %x\n", mod->tag, mod->miid, mod->mid); - - payload_sz = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_codec_dma_intf_cfg_t); - - ALIGN_PAYLOAD(payload_sz, 8); - payload = (uint8_t*)calloc(1, (size_t)payload_sz); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto done; - } - - header = (struct apm_module_param_data_t*)payload; - codec_config = (struct param_id_codec_dma_intf_cfg_t*) - (payload + sizeof(struct apm_module_param_data_t)); - - ret = device_get_channel_map(dev_obj, &chmap); - if (ret || chmap == NULL) { - AGM_LOGE("get channel map failed"); - goto done; - } - - if (chmap[0] < media_config.channels) { - AGM_LOGE("Mismatch in num channels, expected %d, received %d", - media_config.channels, chmap[0]); - ret = -EINVAL; - goto done; - } - - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_CODEC_DMA_INTF_CFG; - header->error_code = 0x0; - header->param_size = sizeof(struct param_id_codec_dma_intf_cfg_t); - - codec_config->lpaif_type = hw_ep_info.ep_config.cdc_dma_i2s_tdm_config.lpaif_type; - codec_config->intf_indx = hw_ep_info.ep_config.cdc_dma_i2s_tdm_config.intf_idx; - /* chmap[0] contains num_ch and chmap[1] contains channelmap */ - codec_config->active_channels_mask = chmap[1]; - - AGM_LOGD("cdc_dma intf cfg lpaif %d indx %d ch_msk %x", - codec_config->lpaif_type, codec_config->intf_indx, - codec_config->active_channels_mask); - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_sz); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config for module %d failed with error %d", - mod->tag, ret); - } -done: - if (chmap) - free(chmap); - - if (payload) - free(payload); - - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -static int configure_i2s_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct device_obj *dev_obj = mod->dev_obj; - hw_ep_info_t hw_ep_info = dev_obj->hw_ep_info; - struct gsl_key_vector tag_key_vect; - struct apm_module_param_data_t *header; - struct param_id_i2s_intf_cfg_t* i2s_config; - size_t payload_sz, ret_payload_sz = 0; - uint8_t *payload = NULL; - struct agm_media_config media_config = (dev_obj->group_data) ? - dev_obj->group_data->media_config.config :dev_obj->media_config; - - AGM_LOGV("entry mod tag %x miid %x mid %x", mod->tag, mod->miid, mod->mid); - - payload_sz = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_i2s_intf_cfg_t); - - ALIGN_PAYLOAD(payload_sz, 8); - ret_payload_sz = payload_sz; - payload = (uint8_t*)calloc(1, (size_t)payload_sz); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto done; - } - - header = (struct apm_module_param_data_t*)payload; - i2s_config = (struct param_id_i2s_intf_cfg_t*) - (payload + sizeof(struct apm_module_param_data_t)); - - /* - * For Codec dma we need to configure the following tags - * 1.Channels - Channels are reused to derive the active channel mask - */ - tag_key_vect.num_kvps = 1; - tag_key_vect.kvp = calloc(tag_key_vect.num_kvps, - sizeof(struct gsl_key_value_pair)); - - if (!tag_key_vect.kvp) { - AGM_LOGE("Not enough memory for KVP"); - ret = -ENOMEM; - goto free_payload; - } - - tag_key_vect.kvp[0].key = CHANNELS; - tag_key_vect.kvp[0].value = media_config.channels; - - ret = gsl_get_tagged_data((struct gsl_key_vector *)mod->gkv, - mod->tag, &tag_key_vect, (uint8_t *)payload, - &ret_payload_sz); - - if (ret != 0) { - if (ret == AR_ENEEDMORE) - AGM_LOGE("payload buffer sz %zu smaller than expected size %zu", - payload_sz, ret_payload_sz); - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGD("get_tagged_data for module %d failed with error %d", - mod->tag, ret); - goto free_kvp; - } - - AGM_LOGV("hdr mid %x pid %x er_cd %x param_sz %d", - header->module_instance_id, header->param_id, header->error_code, - header->param_size); - - i2s_config->lpaif_type = hw_ep_info.ep_config.cdc_dma_i2s_tdm_config.lpaif_type; - i2s_config->intf_idx = hw_ep_info.ep_config.cdc_dma_i2s_tdm_config.intf_idx; - - AGM_LOGV("i2s intf cfg lpaif %d indx %d sd_ln_idx %x ws_src %d", - i2s_config->lpaif_type, i2s_config->intf_idx, - i2s_config->sd_line_idx, i2s_config->ws_src); - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_sz); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config for module %d failed with error %d", - mod->tag, ret); - } -free_kvp: - free(tag_key_vect.kvp); -free_payload: - free(payload); -done: - AGM_LOGD("exit, ret %d", ret); - return ret; -} - - -static int configure_tdm_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct device_obj *dev_obj = mod->dev_obj; - hw_ep_info_t hw_ep_info = dev_obj->hw_ep_info; - struct gsl_key_vector tag_key_vect; - struct apm_module_param_data_t *header; - struct param_id_tdm_intf_cfg_t* tdm_config; - size_t payload_sz, ret_payload_sz = 0; - uint8_t *payload = NULL; - struct agm_media_config media_config = (dev_obj->group_data) ? - dev_obj->group_data->media_config.config :dev_obj->media_config; - - AGM_LOGV("entry mod tag %x miid %x mid %x", mod->tag, mod->miid, mod->mid); - - payload_sz = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_tdm_intf_cfg_t); - - ALIGN_PAYLOAD(payload_sz, 8); - ret_payload_sz = payload_sz; - payload = (uint8_t*)calloc(1, (size_t)payload_sz); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto done; - } - - header = (struct apm_module_param_data_t*)payload; - tdm_config = (struct param_id_tdm_intf_cfg_t*) - (payload + sizeof(struct apm_module_param_data_t)); - - /* - * For Codec dma we need to configure the following tags - * 1.Channels - Channels are reused to derive the active channel mask - */ - tag_key_vect.num_kvps = 1; - tag_key_vect.kvp = calloc(tag_key_vect.num_kvps, - sizeof(struct gsl_key_value_pair)); - - if (!tag_key_vect.kvp) { - AGM_LOGE("Not enough memory for KVP"); - ret = -ENOMEM; - goto free_payload; - } - - tag_key_vect.kvp[0].key = CHANNELS; - tag_key_vect.kvp[0].value = media_config.channels; - - ret = gsl_get_tagged_data((struct gsl_key_vector *)mod->gkv, - mod->tag, &tag_key_vect, (uint8_t *)payload, - &ret_payload_sz); - - if (ret != 0) { - if (ret == AR_ENEEDMORE) - AGM_LOGE("payload buffer sz %zu smaller than expected size %zu", - payload_sz, ret_payload_sz); - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGD("get_tagged_data for module %d failed with error %d", - mod->tag, ret); - goto free_kvp; - } - - tdm_config->lpaif_type = hw_ep_info.ep_config.cdc_dma_i2s_tdm_config.lpaif_type; - tdm_config->intf_idx = hw_ep_info.ep_config.cdc_dma_i2s_tdm_config.intf_idx; - - /* Update slot_mask from AGM only in case of group TDM */ - if (dev_obj->group_data) - tdm_config->slot_mask = dev_obj->group_data->media_config.slot_mask; - - AGM_LOGV("tdm intf cfg lpaif %d idx %d sync_src %d ctrl_dt_ot_enb %d", - tdm_config->lpaif_type, tdm_config->intf_idx, tdm_config->sync_src, - tdm_config->ctrl_data_out_enable); - AGM_LOGV("slt_msk %x nslts_per_frm %x slt_wdth %d sync_mode %d", - tdm_config->slot_mask, tdm_config->nslots_per_frame, - tdm_config->slot_width, tdm_config->sync_mode); - AGM_LOGV("inv_sync_pulse %d sync_data_delay %d", - tdm_config->ctrl_invert_sync_pulse, tdm_config->ctrl_sync_data_delay); - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_sz); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config for module %d failed with error %d", - mod->tag, ret); - } -free_kvp: - free(tag_key_vect.kvp); -free_payload: - free(payload); -done: - AGM_LOGD("exit, ret %d", ret); - return ret; -} - - -static int configure_aux_pcm_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct device_obj *dev_obj = mod->dev_obj; - hw_ep_info_t hw_ep_info = dev_obj->hw_ep_info; - struct gsl_key_vector tag_key_vect; - struct apm_module_param_data_t *header; - - struct param_id_hw_pcm_intf_cfg_t* aux_pcm_cfg; - size_t payload_sz ,ret_payload_sz = 0; - uint8_t *payload = NULL; - - AGM_LOGV("entry mod tag %x miid %x mid %x", mod->tag, mod->miid, mod->mid); - - payload_sz = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_hw_pcm_intf_cfg_t); - - ALIGN_PAYLOAD(payload_sz, 8); - ret_payload_sz = payload_sz; - payload = (uint8_t*)calloc(1, (size_t)payload_sz); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto done; - } - - header = (struct apm_module_param_data_t*)payload; - aux_pcm_cfg = (struct param_id_hw_pcm_intf_cfg_t*) - (payload + sizeof(struct apm_module_param_data_t)); - - /* - * For Codec dma we need to configure the following tags - * 1.Channels - Channels are reused to derive the active channel mask - */ - tag_key_vect.num_kvps = 1; - tag_key_vect.kvp = calloc(tag_key_vect.num_kvps, - sizeof(struct gsl_key_value_pair)); - - if (!tag_key_vect.kvp) { - AGM_LOGE("Not enough memory for KVP"); - ret = -ENOMEM; - goto free_payload; - } - - tag_key_vect.kvp[0].key = CHANNELS; - tag_key_vect.kvp[0].value = dev_obj->media_config.channels; - - ret = gsl_get_tagged_data((struct gsl_key_vector *)mod->gkv, - mod->tag, &tag_key_vect, (uint8_t *)payload, - &ret_payload_sz); - - if (ret != 0) { - if (ret == AR_ENEEDMORE) - AGM_LOGE("payload buffer sz %zu smaller than expected size %zu", - payload_sz, ret_payload_sz); - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGD("get_tagged_data for module %d failed with error %d", - mod->tag, ret); - goto free_kvp; - } - - aux_pcm_cfg->lpaif_type = hw_ep_info.ep_config.cdc_dma_i2s_tdm_config.lpaif_type; - aux_pcm_cfg->intf_idx = hw_ep_info.ep_config.cdc_dma_i2s_tdm_config.intf_idx; - - AGM_LOGV("aux intf cfg lpaif %d idx %d sync_src %d ctrl_dt_ot_enb %d", - aux_pcm_cfg->lpaif_type, aux_pcm_cfg->intf_idx, aux_pcm_cfg->sync_src, - aux_pcm_cfg->ctrl_data_out_enable); - AGM_LOGV("slt_msk %x frm_setting %x aux_mode %d", - aux_pcm_cfg->slot_mask, aux_pcm_cfg->frame_setting, - aux_pcm_cfg->aux_mode); - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_sz); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config for module %d failed with error %d", - mod->tag, ret); - } -free_kvp: - free(tag_key_vect.kvp); -free_payload: - free(payload); -done: - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -static int configure_slimbus_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct device_obj *dev_obj = mod->dev_obj; - hw_ep_info_t hw_ep_info = dev_obj->hw_ep_info; - struct apm_module_param_data_t *header; - struct param_id_slimbus_cfg_t* slimbus_cfg; - size_t payload_sz; - uint8_t *payload = NULL; - int i = 0; - uint32_t *chmap = NULL; - - AGM_LOGD("entry mod tag %x miid %x mid %x", mod->tag, mod->miid, mod->mid); - - if (dev_obj->media_config.channels > SB_MAX_CHAN_CNT) { - AGM_LOGE("device channels %d exceed max supported ch %d for Slimbus", - dev_obj->media_config.channels, SB_MAX_CHAN_CNT); - ret = -EINVAL; - goto done; - } - - payload_sz = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_slimbus_cfg_t); - - ALIGN_PAYLOAD(payload_sz, 8); - payload = (uint8_t*)calloc(1, (size_t)payload_sz); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto done; - } - - header = (struct apm_module_param_data_t*)payload; - slimbus_cfg = (struct param_id_slimbus_cfg_t*) - (payload + sizeof(struct apm_module_param_data_t)); - - ret = device_get_channel_map(dev_obj, &chmap); - if (ret || chmap == NULL) { - AGM_LOGE("get channel map failed"); - goto done; - } - - if (chmap[0] < dev_obj->media_config.channels) { - AGM_LOGE("Mismatch in num channels, expected %d, received %d", - dev_obj->media_config.channels, chmap[0]); - ret = -EINVAL; - goto done; - } - - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_SLIMBUS_CONFIG; - header->error_code = 0x0; - header->param_size = sizeof(struct param_id_slimbus_cfg_t); - slimbus_cfg->slimbus_dev_id = hw_ep_info.ep_config.slim_config.dev_id; - - AGM_LOGD("slimbus intf cfg dev id %d ch %d", slimbus_cfg->slimbus_dev_id, - dev_obj->media_config.channels); - for (i = 0; i < dev_obj->media_config.channels; i++) { - slimbus_cfg->shared_channel_mapping[i] = chmap[i + 1]; - AGM_LOGV("shared_chnl_mapping[%d] = 0x%x\n", i, slimbus_cfg->shared_channel_mapping[i]); - } - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_sz); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config for module %d failed with error %d", - mod->tag, ret); - } -done: - if (payload) - free(payload); - - if (chmap) - free(chmap); - - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int configure_hw_ep_media_config(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - uint8_t *payload = NULL; - size_t payload_size = 0; - struct device_obj *dev_obj = mod->dev_obj; - struct apm_module_param_data_t* header; - struct param_id_hw_ep_mf_t* hw_ep_media_conf; - struct agm_media_config media_config = (dev_obj->group_data) ? - dev_obj->group_data->media_config.config :dev_obj->media_config; - - AGM_LOGD("entry mod tag %x miid %x mid %x",mod->tag, mod->miid, mod->mid); - payload_size = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_hw_ep_mf_t); - - /*ensure that the payloadszie is byte multiple atleast*/ - ALIGN_PAYLOAD(payload_size, 8); - payload = calloc(1, (size_t)payload_size); - if (!payload) { - AGM_LOGE("No memory to allocate for payload"); - ret = -ENOMEM; - goto done; - } - - header = (struct apm_module_param_data_t*)payload; - hw_ep_media_conf = (struct param_id_hw_ep_mf_t*) - (payload + sizeof(struct apm_module_param_data_t)); - - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_HW_EP_MF_CFG; - header->error_code = 0x0; - header->param_size = sizeof(struct param_id_hw_ep_mf_t); - - hw_ep_media_conf->sample_rate = media_config.rate; - hw_ep_media_conf->bit_width = get_pcm_bit_width(media_config.format); - - hw_ep_media_conf->num_channels = media_config.channels; - hw_ep_media_conf->data_format = media_config.data_format; - - AGM_LOGD("rate %d bw %d ch %d, data_fmt %d", media_config.rate, - hw_ep_media_conf->bit_width, media_config.channels, - media_config.data_format); - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config command for module %d failed with error %d", - mod->tag, ret); - } - free(payload); -done: - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int configure_hw_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct device_obj *dev_obj = mod->dev_obj; - - if ((dev_obj->hw_ep_info.intf == PCM_RT_PROXY) || - (dev_obj->hw_ep_info.intf == PCM_DUMMY) || - (dev_obj->hw_ep_info.intf == BTFM_PROXY)) { - AGM_LOGD("no ep media config for %d\n", dev_obj->hw_ep_info.intf); - } else { - ret = configure_hw_ep_media_config(mod, graph_obj); - if (ret) { - AGM_LOGE("hw_ep_media_config failed %d", ret); - return ret; - } - } - switch (dev_obj->hw_ep_info.intf) { - case CODEC_DMA: - ret = configure_codec_dma_ep(mod, graph_obj); - break; - case MI2S: - ret = configure_i2s_ep(mod, graph_obj); - break; - case AUXPCM: - ret = configure_aux_pcm_ep(mod, graph_obj); - break; - case TDM: - ret = configure_tdm_ep(mod, graph_obj); - break; - case SLIMBUS: - ret = configure_slimbus_ep(mod, graph_obj); - break; - case DISPLAY_PORT: - case USB_AUDIO: - case PCM_RT_PROXY: - case AUDIOSS_DMA: - case PCM_DUMMY: - case BTFM_PROXY: - AGM_LOGD("no ep configuration for %d\n", dev_obj->hw_ep_info.intf); - break; - default: - AGM_LOGE("hw intf %d not enabled yet", dev_obj->hw_ep_info.intf); - ret = -EINVAL; - break; - } - return ret; -} - -/** - *PCM DECODER/ENCODER and PCM CONVERTER are configured with the - *same PCM_FORMAT_CFG hence reuse the implementation -*/ -int configure_output_media_format(struct module_info *mod, - struct graph_obj *graph_obj) -{ - struct session_obj *sess_obj = graph_obj->sess_obj; - struct media_format_t *media_fmt_hdr; - struct payload_pcm_output_format_cfg_t *pcm_output_fmt_payload; - struct apm_module_param_data_t *header; - uint8_t *payload = NULL; - size_t payload_size = 0; - uint8_t *channel_map; - int ret = 0; - int num_channels = MONO; - struct agm_media_config media_config = {0}; - - /*We use in_media_config for Record usecases or - *if it is NON_TUNNEL_MODE decode usecase otherwise - *out_media_config is used to configure PCM_Convertor - */ - if ((sess_obj->stream_config.dir == TX) || - ((sess_obj->stream_config.sess_mode == AGM_SESSION_NON_TUNNEL) && - (is_format_pcm(sess_obj->in_media_config.format)))) { - media_config = sess_obj->in_media_config; - } - else - media_config = sess_obj->out_media_config; - - AGM_LOGD("entry mod tag %x miid %x mid %x",mod->tag, mod->miid, mod->mid); - num_channels = media_config.channels; - - payload_size = sizeof(struct apm_module_param_data_t) + - sizeof(struct media_format_t) + - sizeof(struct payload_pcm_output_format_cfg_t) + - sizeof(uint8_t)*num_channels; - - /*ensure that the payloadszie is byte multiple atleast*/ - ALIGN_PAYLOAD(payload_size, 8); - - payload = calloc(1, (size_t)payload_size); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto done; - } - - - header = (struct apm_module_param_data_t*)payload; - - media_fmt_hdr = (struct media_format_t*)(payload + - sizeof(struct apm_module_param_data_t)); - pcm_output_fmt_payload = (struct payload_pcm_output_format_cfg_t*)(payload + - sizeof(struct apm_module_param_data_t) + - sizeof(struct media_format_t)); - - channel_map = (uint8_t*)(payload + sizeof(struct apm_module_param_data_t) + - sizeof(struct media_format_t) + - sizeof(struct payload_pcm_output_format_cfg_t)); - - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_PCM_OUTPUT_FORMAT_CFG; - header->error_code = 0x0; - header->param_size = sizeof(struct media_format_t) + - sizeof(struct payload_pcm_output_format_cfg_t) + - sizeof(uint8_t)*num_channels; - - media_fmt_hdr->data_format = AGM_DATA_FORMAT_FIXED_POINT; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_PCM; - media_fmt_hdr->payload_size = - (uint32_t)(sizeof(payload_pcm_output_format_cfg_t) + - sizeof(uint8_t) * num_channels); - - pcm_output_fmt_payload->endianness = PCM_LITTLE_ENDIAN; - - pcm_output_fmt_payload->bit_width = get_media_bit_width(sess_obj, &media_config); - - /** - *alignment field is referred to only in case where bit width is - *24 and bits per sample is 32, tiny alsa only supports 24 bit - *in 32 word size in LSB aligned mode(AGM_FORMAT_PCM_S24_LE). - *Hence we hardcode this to PCM_LSB_ALIGNED; - */ - pcm_output_fmt_payload->alignment = PCM_LSB_ALIGNED; - pcm_output_fmt_payload->num_channels = num_channels; - - if (((sess_obj->stream_config.dir == TX) || - ((sess_obj->stream_config.sess_mode == AGM_SESSION_NON_TUNNEL) && mod->module == MODULE_PCM_CONVERTER)) && - is_format_pcm(media_config.format)) { - /*for PCM capture usecase, we want native data to be captured hence - *configure pcm convertor accordingly - *Also in case of Non Tunnel Mode decode, we configure PCM_CONVERTOR with - *media config same as what is configured by client on the read path. - *We have added the module check above to ensure that the decoder - *PCM_OUTPUT_FORMAT_CFG is configured in the else part. - */ - pcm_output_fmt_payload->bits_per_sample = - GET_BITS_PER_SAMPLE(media_config.format, - pcm_output_fmt_payload->bit_width); - - pcm_output_fmt_payload->q_factor = - GET_Q_FACTOR(media_config.format, - pcm_output_fmt_payload->bit_width); - if (sess_obj->stream_config.sess_mode == AGM_SESSION_NON_TUNNEL) - /* - * Setting num channels to native mode for PCM convetter - * so that channels always match upstream decoder module - * channel configuration - */ - pcm_output_fmt_payload->num_channels = PARAM_VAL_NATIVE; - } else { - switch (pcm_output_fmt_payload->bit_width) { - case 16: - case 32: - pcm_output_fmt_payload->bits_per_sample = - pcm_output_fmt_payload->bit_width; - pcm_output_fmt_payload->q_factor = - pcm_output_fmt_payload->bit_width - 1; - break; - case 24: - /* - *modules after pcm convertor only work on 16 or 32bit samples hence - *even for 24 bit input data configure pcm convertor output with - *32 bits per sample also to accomodate post processing, SPF - *tean recommends to set the q_factor as 27 even for 24_LE/24_3LE formats - *This is to be done only for pcm_convertor on the playback path - */ - pcm_output_fmt_payload->bits_per_sample = 32; - pcm_output_fmt_payload->q_factor = 27; - break; - default: - AGM_LOGE("wrong bitwidth %d", pcm_output_fmt_payload->bit_width); - ret = -EINVAL; - goto done; - } - } - - if (sess_obj->stream_config.dir == RX) - pcm_output_fmt_payload->interleaved = PCM_DEINTERLEAVED_UNPACKED; - else - pcm_output_fmt_payload->interleaved = PCM_INTERLEAVED; - - /** - *#TODO:As of now channel_map is not part of media_config - *ADD channel map part as part of the session/device media config - *structure and use that channel map if set by client otherwise - * use the default channel map - */ - get_default_channel_map(channel_map, num_channels); - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config command for module %d failed with error %d", - mod->tag, ret); - } -done: - if (payload) { - free(payload); - } - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -static int configure_pcm_encoder_frame_size(struct module_info *mod, - struct graph_obj *graph_obj, - uint32_t frame_size_samples) -{ - struct apm_module_param_data_t *header; - struct param_id_pcm_encoder_frame_size_t *frame_size_payload; - uint8_t *payload = NULL; - size_t payload_size = 0; - int ret = 0; - - payload_size = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_pcm_encoder_frame_size_t); - payload = calloc(1, (size_t)payload_size); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - return -ENOMEM; - } - header = (struct apm_module_param_data_t*)payload; - frame_size_payload = (struct param_id_pcm_encoder_frame_size_t*)(payload + - sizeof(struct apm_module_param_data_t)); - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_PCM_ENCODER_FRAME_SIZE; - header->error_code = 0x0; - header->param_size = sizeof(struct param_id_pcm_encoder_frame_size_t); - - frame_size_payload->frame_size_type = 1; /* frame_size_in_samples */ - frame_size_payload->frame_size_in_samples = frame_size_samples; - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("pcm encoder frame size config for module %d failed with error %d", - mod->tag, ret); - } - free(payload); - return ret; -} - -int configure_pcm_encoder_params(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct session_obj *sess_obj = graph_obj->sess_obj; - uint32_t samples_per_msec = 0, frame_size = 0; - uint32_t channels = MONO, bits = 16; - - /* configure output media format */ - ret = configure_output_media_format(mod, graph_obj); - if (ret) - return ret; - - /* configure pcm encoder frame size */ - if (sess_obj->stream_config.sess_mode != AGM_SESSION_NON_TUNNEL) { - samples_per_msec = sess_obj->in_media_config.rate/1000; - channels = sess_obj->in_media_config.channels; - bits = get_pcm_bit_width(sess_obj->in_media_config.format); - bits = GET_BITS_PER_SAMPLE(sess_obj->in_media_config.format, bits); - channels = (channels == 0) ? MONO : channels; - frame_size = (sess_obj->in_buffer_config.size * 8) / - (channels * bits); - - if (samples_per_msec && - (((frame_size * 1000) % sess_obj->in_media_config.rate) != 0)) { - AGM_LOGD("pcm encoder: frame_size %d\n", frame_size); - ret = configure_pcm_encoder_frame_size(mod, graph_obj, frame_size); - } - } - - return ret; -} - -static int get_media_fmt_id_and_size(enum agm_media_format fmt_id, - size_t *payload_size, size_t *real_fmt_id) -{ - int ret = 0; - size_t format_size = 0; - - if (is_format_pcm(fmt_id)) { - format_size = sizeof(struct payload_media_fmt_pcm_t);; - *real_fmt_id = MEDIA_FMT_PCM; - goto pl_size; - } - - switch (fmt_id) { - case AGM_FORMAT_MP3: - format_size = 0; - *real_fmt_id = MEDIA_FMT_MP3; - break; - case AGM_FORMAT_AAC: - format_size = sizeof(struct payload_media_fmt_aac_t); - *real_fmt_id = MEDIA_FMT_AAC; - break; - case AGM_FORMAT_FLAC: - format_size = sizeof(struct payload_media_fmt_flac_t); - *real_fmt_id = MEDIA_FMT_FLAC; - break; - case AGM_FORMAT_ALAC: - format_size = sizeof(struct payload_media_fmt_alac_t); - *real_fmt_id = MEDIA_FMT_ALAC; - break; - case AGM_FORMAT_APE: - format_size = sizeof(struct payload_media_fmt_ape_t); - *real_fmt_id = MEDIA_FMT_APE; - break; - case AGM_FORMAT_WMASTD: - format_size = sizeof(struct payload_media_fmt_wmastd_t); - *real_fmt_id = MEDIA_FMT_WMASTD; - break; - case AGM_FORMAT_WMAPRO: - format_size = sizeof(struct payload_media_fmt_wmapro_t); - *real_fmt_id = MEDIA_FMT_WMAPRO; - break; - case AGM_FORMAT_OPUS: - format_size = sizeof(struct payload_media_fmt_opus_t); - *real_fmt_id = MEDIA_FMT_OPUS; - break; - case AGM_FORMAT_VORBIS: - format_size = 0; - *real_fmt_id = MEDIA_FMT_VORBIS; - break; - case AGM_FORMAT_AMR_NB: - format_size = 0; - *real_fmt_id = MEDIA_FMT_AMRNB; - break; - case AGM_FORMAT_AMR_WB: - format_size = 0; - *real_fmt_id = MEDIA_FMT_AMRWB; - break; - case AGM_FORMAT_AMR_WB_PLUS: - format_size = 0; - *real_fmt_id = MEDIA_FMT_AMRWBPLUS; - break; - case AGM_FORMAT_EVRC: - format_size = 0; - *real_fmt_id = MEDIA_FMT_EVRC; - break; - case AGM_FORMAT_G711: - format_size = 0; - *real_fmt_id = MEDIA_FMT_G711; - break; - case AGM_FORMAT_QCELP: - format_size = 0; - *real_fmt_id = MEDIA_FMT_QCELP; - break; - default: - ret = -EINVAL; - break; - } - -pl_size: - *payload_size = sizeof(struct apm_module_param_data_t) + - sizeof(struct media_format_t) + format_size; - - return ret; -} - - -int set_compressed_media_format(enum agm_media_format fmt_id, - struct media_format_t *media_fmt_hdr, - struct session_obj *sess_obj) -{ - int ret = 0; - size_t fmt_size = 0; - - switch (fmt_id) { - case AGM_FORMAT_MP3: - { - media_fmt_hdr->data_format = AGM_DATA_FORMAT_RAW_COMPRESSED ; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_MP3; - media_fmt_hdr->payload_size = 0; - break; - } - case AGM_FORMAT_AAC: - { - struct payload_media_fmt_aac_t *fmt_pl; - fmt_size = sizeof(struct payload_media_fmt_aac_t); - media_fmt_hdr->data_format = AGM_DATA_FORMAT_RAW_COMPRESSED ; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_AAC; - media_fmt_hdr->payload_size = fmt_size; - - fmt_pl = - (struct payload_media_fmt_aac_t*)(((uint8_t*)media_fmt_hdr) + - sizeof(struct media_format_t)); - - memcpy(fmt_pl, &sess_obj->stream_config.codec.aac_dec, - fmt_size); - AGM_LOGD("AAC payload: fmt:%d, Obj_type:%d, ch:%d, SR:%d", - fmt_pl->aac_fmt_flag, fmt_pl->audio_obj_type, - fmt_pl->num_channels, fmt_pl->sample_rate); - break; - } - case AGM_FORMAT_FLAC: - { - struct payload_media_fmt_flac_t *fmt_pl; - fmt_size = sizeof(struct payload_media_fmt_flac_t); - media_fmt_hdr->data_format = AGM_DATA_FORMAT_RAW_COMPRESSED ; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_FLAC; - media_fmt_hdr->payload_size = fmt_size; - - fmt_pl = (struct payload_media_fmt_flac_t*)(((uint8_t*)media_fmt_hdr) + - sizeof(struct media_format_t)); - memcpy(fmt_pl, &sess_obj->stream_config.codec.flac_dec, - fmt_size); - AGM_LOGD("FLAC payload: ch:%d, sample_size:%d, SR:%d", - fmt_pl->num_channels, fmt_pl->sample_size, fmt_pl->sample_rate); - break; - } - case AGM_FORMAT_ALAC: - { - struct payload_media_fmt_alac_t *fmt_pl; - fmt_size = sizeof(struct payload_media_fmt_alac_t); - media_fmt_hdr->data_format = AGM_DATA_FORMAT_RAW_COMPRESSED ; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_ALAC; - media_fmt_hdr->payload_size = fmt_size; - - fmt_pl = (struct payload_media_fmt_alac_t*)(((uint8_t*)media_fmt_hdr) + - sizeof(struct media_format_t)); - memcpy(fmt_pl, &sess_obj->stream_config.codec.alac_dec, - fmt_size); - AGM_LOGD("ALAC payload: bit_depth:%d, ch:%d, SR:%d", - fmt_pl->bit_depth, fmt_pl->num_channels, - fmt_pl->sample_rate); - break; - } - case AGM_FORMAT_APE: - { - struct payload_media_fmt_ape_t *fmt_pl; - fmt_size = sizeof(struct payload_media_fmt_ape_t); - media_fmt_hdr->data_format = AGM_DATA_FORMAT_RAW_COMPRESSED ; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_APE; - media_fmt_hdr->payload_size = fmt_size; - - fmt_pl = (struct payload_media_fmt_ape_t*)(((uint8_t*)media_fmt_hdr) + - sizeof(struct media_format_t)); - memcpy(fmt_pl, &sess_obj->stream_config.codec.ape_dec, - fmt_size); - AGM_LOGD("APE payload: bit_width:%d, ch:%d, SR:%d", - fmt_pl->bit_width, fmt_pl->num_channels, - fmt_pl->sample_rate); - break; - } - case AGM_FORMAT_WMASTD: - { - struct payload_media_fmt_wmastd_t *fmt_pl; - fmt_size = sizeof(struct payload_media_fmt_wmastd_t); - media_fmt_hdr->data_format = AGM_DATA_FORMAT_RAW_COMPRESSED ; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_WMASTD; - media_fmt_hdr->payload_size = fmt_size; - - fmt_pl = (struct payload_media_fmt_wmastd_t*)(((uint8_t*)media_fmt_hdr) + - sizeof(struct media_format_t)); - memcpy(fmt_pl, &sess_obj->stream_config.codec.wma_dec, - fmt_size); - AGM_LOGD("WMA payload: fmt:%d, ch:%d, SR:%d, bit_width:%d", - fmt_pl->fmt_tag, fmt_pl->num_channels, - fmt_pl->sample_rate, fmt_pl->bits_per_sample); - break; - } - case AGM_FORMAT_WMAPRO: - { - struct payload_media_fmt_wmapro_t *fmt_pl; - fmt_size = sizeof(struct payload_media_fmt_wmapro_t); - media_fmt_hdr->data_format = AGM_DATA_FORMAT_RAW_COMPRESSED ; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_WMAPRO; - media_fmt_hdr->payload_size = fmt_size; - - fmt_pl = (struct payload_media_fmt_wmapro_t*)(((uint8_t*)media_fmt_hdr) + - sizeof(struct media_format_t)); - memcpy(fmt_pl, &sess_obj->stream_config.codec.wmapro_dec, - fmt_size); - AGM_LOGD("WMAPro payload: fmt:%d, ch:%d, SR:%d, bit_width:%d", - fmt_pl->fmt_tag, fmt_pl->num_channels, - fmt_pl->sample_rate, fmt_pl->bits_per_sample); - break; - } - case AGM_FORMAT_OPUS: - { - struct payload_media_fmt_opus_t *fmt_pl; - fmt_size = sizeof(struct payload_media_fmt_opus_t); - media_fmt_hdr->data_format = AGM_DATA_FORMAT_RAW_COMPRESSED; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_OPUS; - media_fmt_hdr->payload_size = fmt_size; - - fmt_pl = (struct payload_media_fmt_opus_t*)(((uint8_t*)media_fmt_hdr) + - sizeof(struct media_format_t)); - memcpy(fmt_pl, &sess_obj->stream_config.codec.opus_dec, - fmt_size); - AGM_LOGD("OPUS payload: bitstream_format:%d payload_type:%d version:%d, ch:%d, " - "pre_skip:%d, SR:%d, output_gain:%d, mapping_family:%d, stream_count:%d, " - "coupled_count:%d", - fmt_pl->bitstream_format, fmt_pl->payload_type, fmt_pl->version, - fmt_pl->num_channels, fmt_pl->pre_skip, - fmt_pl->sample_rate, fmt_pl->output_gain, - fmt_pl->mapping_family, fmt_pl->stream_count, - fmt_pl->coupled_count); - AGM_LOGD("channel map:"); - for (int i = 0; i < fmt_pl->num_channels; i++) { - AGM_LOGD("%d", fmt_pl->channel_map[i]); - } - break; - } - default: - return -EINVAL; - } - - return ret; -} - -/** - *Configure placeholder decoder -*/ -int configure_placeholder_dec(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct gsl_key_vector tkv; - struct session_obj *sess_obj = NULL; - size_t payload_size = 0, real_fmt_id = 0; - -// { SEC_AUDIO_ADD_FOR_DEBUG - AGM_LOGI("enter"); -// } SEC_AUDIO_ADD_FOR_DEBUG - memset(&tkv, 0, sizeof(struct gsl_key_vector)); - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object"); - goto done; - } - sess_obj = graph_obj->sess_obj; - /* 1. Configure placeholder decoder with Real ID */ - ret = get_media_fmt_id_and_size(sess_obj->out_media_config.format, - &payload_size, &real_fmt_id); - if (ret) { - AGM_LOGD("module is not configured for format: %d\n", - sess_obj->out_media_config.format); - /* If ret is non-zero then placeholder module would be - * configured by client so return from here. - */ - ret = 0; - goto done; - } - - tkv.num_kvps = 1; - tkv.kvp = calloc(tkv.num_kvps, sizeof(struct gsl_key_value_pair)); - if (!tkv.kvp) { - AGM_LOGE("Not enough memory for tkv.kvp\n"); - ret = -ENOMEM; - goto done; - } - tkv.kvp->key = MEDIA_FMT_ID; - tkv.kvp->value = real_fmt_id; - - AGM_LOGD("Placeholder mod TKV key:%0x value: %0x", tkv.kvp->key, - tkv.kvp->value); - ret = gsl_set_config(graph_obj->graph_handle, (struct gsl_key_vector *)mod->gkv, - TAG_STREAM_PLACEHOLDER_DECODER, &tkv); - - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("set_config command failed with error: %d", ret); - goto done; - } - - /* 2. Set output media format cfg for placeholder decoder */ - ret = configure_output_media_format(mod, graph_obj); - if (ret != 0) - AGM_LOGE("output_media_format cfg failed: %d", ret); - -done: - if (tkv.kvp) - free(tkv.kvp); -// { SEC_AUDIO_ADD_FOR_DEBUG - AGM_LOGI("exit, ret %d", ret); -// } SEC_AUDIO_ADD_FOR_DEBUG - return ret; -} - -int configure_aac_encoder(struct module_info *mod, - struct graph_obj *graph_obj){ - int ret = 0; - struct session_obj *sess_obj = graph_obj->sess_obj; - struct apm_module_param_data_t *header; - struct param_id_aac_enc_cutoff_freq_config_t *cut_off_frequency; - uint8_t *payload = NULL; - size_t payload_size = 0; - size_t size_apm_module = sizeof(struct apm_module_param_data_t); - size_t size_cutoff_freq_config = - sizeof(struct param_id_aac_enc_cutoff_freq_config_t); - size_t size_apm_and_size_cutoff_freq = - size_apm_module + size_cutoff_freq_config; - - if (sess_obj->stream_config.codec.aac_enc.global_cutoff_freq <= 0){ - AGM_LOGD("AAC cutoff frequency ignored or not configured"); - return 0; - } - - /** - * For Encoder module, PARAM_ID_AAC_CUTOFF_FREQ_CONFIG - * configuration: optional - * */ - payload_size = size_apm_and_size_cutoff_freq; - /*ensure that the payloadszie is byte multiple atleast*/ - ALIGN_PAYLOAD(payload_size, 8); - payload = (uint8_t *)calloc(1, payload_size); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto exit; - } - header = (struct apm_module_param_data_t *)(payload); - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_AAC_CUTOFF_FREQ_CONFIG; - header->error_code = 0x0; - header->param_size = size_cutoff_freq_config; - cut_off_frequency = - (struct param_id_aac_enc_cutoff_freq_config_t *)(payload + - size_apm_module); - cut_off_frequency->freq_cutoff_mode = 1; // global cutoff frquency - cut_off_frequency->global_cutoff_freq = - sess_obj->stream_config.codec.aac_enc.global_cutoff_freq; - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE( - "custom_config command for module %d with " - "PARAM_ID_AAC_CUTOFF_FREQ_CONFIG failed with error %d", - mod->tag, ret); - goto exit; - } else { - AGM_LOGD("AAC cutoff frequency requested: %d", - cut_off_frequency->global_cutoff_freq); - free(payload); - payload = NULL; - } - -exit: - if (payload) { - free(payload); - payload = NULL; - } - AGM_LOGV("Exit: %d", ret); - return ret; -} - -/** - * codec specific encoder config only for TX type - */ -int configure_encoder_output_media_format(struct module_info *mod, - struct graph_obj *graph_obj) { - int ret = 0; - struct session_obj *sess_obj = graph_obj->sess_obj; - struct apm_module_param_data_t *header; - uint8_t *payload = NULL; - size_t payload_size = 0; - size_t size_apm_module = sizeof(struct apm_module_param_data_t); - size_t size_encoder_config = - sizeof(struct param_id_encoder_output_config_t); - size_t size_apm_and_encoder_config = size_apm_module + size_encoder_config; - AGM_LOGV("Enter"); - - /** - * For Encoder module, PARAM_ID_ENCODER_OUTPUT_CONFIG - * */ - - /** - * only TX session, hence in media config - * */ - switch (sess_obj->in_media_config.format) { - case AGM_FORMAT_AAC: { - size_t size_aac_cfg = sizeof(struct aac_enc_cfg_t); - payload_size = size_apm_and_encoder_config + size_aac_cfg; - - /*ensure that the payloadszie is byte multiple atleast*/ - ALIGN_PAYLOAD(payload_size, 8); - payload = (uint8_t *)calloc(1, payload_size); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto err; - } - - struct param_id_encoder_output_config_t enc_out_conf_param; - enc_out_conf_param.data_format = AGM_DATA_FORMAT_FIXED_POINT; - enc_out_conf_param.fmt_id = MEDIA_FMT_AAC; - enc_out_conf_param.payload_size = size_aac_cfg; - memcpy(payload + size_apm_module, &enc_out_conf_param, - size_encoder_config); - - memcpy(payload + size_apm_and_encoder_config, - &(sess_obj->stream_config.codec.aac_enc.enc_cfg), - size_aac_cfg); - break; - } - - default: - ret = -EINVAL; - goto err; - break; - } - - header = (struct apm_module_param_data_t *)(payload); - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_ENCODER_OUTPUT_CONFIG; - header->error_code = 0x0; - header->param_size = sizeof(struct param_id_encoder_output_config_t); - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE( - "custom_config command for module %d with " - "PARAM_ID_ENCODER_OUTPUT_CONFIG failed with error %d", - mod->tag, ret); - goto err; - } else { - struct aac_enc_cfg_t *aac_cfg = - (struct aac_enc_cfg_t *)(payload + size_apm_and_encoder_config); - AGM_LOGD("AAC encode mode: 0x%x, fmt_flag: 0x%x", aac_cfg->enc_mode, - aac_cfg->aac_fmt_flag); - free(payload); - payload = NULL; - } - - /** - * For Encoder Module, PARAM_ID_ENC_BITRATE - * */ - switch (sess_obj->in_media_config.format) { - case AGM_FORMAT_AAC: { - struct param_id_enc_bitrate_param_t *bitrate_param = NULL; - size_t bitrate_param_size = - sizeof(struct param_id_enc_bitrate_param_t); - payload_size = size_apm_module + bitrate_param_size; - /*ensure that the payloadszie is byte multiple atleast*/ - ALIGN_PAYLOAD(payload_size, 8); - payload = (uint8_t *)calloc(1, payload_size); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto err; - } - - bitrate_param = - (struct param_id_enc_bitrate_param_t *)(payload + - size_apm_module); - bitrate_param->bitrate = - sess_obj->stream_config.codec.aac_enc.aac_bit_rate; - break; - } - - default: - ret = -EINVAL; - goto err; - break; - } - header = (struct apm_module_param_data_t *)(payload); - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_ENC_BITRATE; - header->error_code = 0x0; - header->param_size = sizeof(struct param_id_enc_bitrate_param_t); - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE( - "custom_config command for module %d with " - "PARAM_ID_ENC_BITRATE failed with error %d", - mod->tag, ret); - goto err; - } else { - struct param_id_enc_bitrate_param_t *bitrate_param = - (struct param_id_enc_bitrate_param_t *)(payload + size_apm_module); - AGM_LOGD("AAC bitrate: %d", bitrate_param->bitrate); - free(payload); - payload = NULL; - } - - if (sess_obj->in_media_config.format == AGM_FORMAT_AAC) { - ret = configure_aac_encoder(mod, graph_obj); - } - -err: -done: - if (payload) { - free(payload); - payload = NULL; - } - AGM_LOGV("Exit: %d", ret); - return ret; -} - -/** - *Configure placeholder encoder -*/ -int configure_placeholder_enc(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct gsl_key_vector tkv; - struct session_obj *sess_obj = NULL; - - size_t payload_size = 0, real_fmt_id = 0; - - AGM_LOGE("enter"); - if (graph_obj == NULL) { - AGM_LOGE("invalid graph object"); - return -EINVAL; - } - sess_obj = graph_obj->sess_obj; - - /* 1. Configure placeholder encoder with Real ID */ - ret = get_media_fmt_id_and_size(sess_obj->in_media_config.format, - &payload_size, &real_fmt_id); - if (ret) { - AGM_LOGD("module is not configured for format: %d\n", - sess_obj->in_media_config.format); - /* If ret is non-zero then placeholder module would be - * configured by client so return from here. - */ - return 0; - } - - tkv.num_kvps = 1; - tkv.kvp = calloc(tkv.num_kvps, sizeof(struct gsl_key_value_pair)); - if (!tkv.kvp) { - AGM_LOGE("Not enough memory for tkv.kvp\n"); - return -ENOMEM; - } - tkv.kvp->key = MEDIA_FMT_ID; - tkv.kvp->value = real_fmt_id; - - AGM_LOGD("Placeholder mod TKV key:%0x value: %0x", tkv.kvp->key, - tkv.kvp->value); - ret = gsl_set_config(graph_obj->graph_handle, (struct gsl_key_vector *)mod->gkv, - TAG_STREAM_PLACEHOLDER_ENCODER, &tkv); - - if (tkv.kvp) - free(tkv.kvp); - - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("set_config command failed with error: %d", ret); - return ret; - } - - /* configure only in case of compress capture */ - if (sess_obj->stream_config.sess_mode == AGM_SESSION_COMPRESS && - sess_obj->stream_config.dir == TX) { - ret = configure_encoder_output_media_format(mod, graph_obj); - if (ret != 0) - AGM_LOGE("configure_encoder_output_media_format failed: %d", ret); - } - - return ret; -} - - -int configure_compress_shared_mem_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct session_obj *sess_obj = graph_obj->sess_obj; - struct media_format_t *media_fmt_hdr; - struct apm_module_param_data_t *header; - uint8_t *payload = NULL; - size_t payload_size = 0, real_fmt_id = 0; - size_t actual_param_sz = 0; - - if (is_format_bypassed(sess_obj->out_media_config.format) || - sess_obj->stream_config.sess_mode == AGM_SESSION_NON_TUNNEL) { - AGM_LOGI("bypass shared mem ep config for format %x or sess_mode %d", - sess_obj->out_media_config.format, sess_obj->stream_config.sess_mode); - return 0; - } - - ret = get_media_fmt_id_and_size(sess_obj->out_media_config.format, - &payload_size, &real_fmt_id); - if (ret) { - AGM_LOGD("module is not configured for format: %d\n", - sess_obj->out_media_config.format); - /* If ret is non-zero then shared memory module would be - * configured by client so return from here. - */ - return 0; - } - /* - *We get the actual size of the PID being sent before the payload_size - *is updated for 8 byte alignment. - */ - actual_param_sz = payload_size - sizeof(struct apm_module_param_data_t); - - /*ensure that the payloadsize is byte multiple atleast*/ - ALIGN_PAYLOAD(payload_size, 8); - - payload = calloc(1, (size_t)payload_size); - if (!payload) { - AGM_LOGE("Not enough memory for payload\n"); - return -ENOMEM; - } - - header = (struct apm_module_param_data_t*)payload; - - media_fmt_hdr = (struct media_format_t*)(payload + - sizeof(struct apm_module_param_data_t)); - - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_MEDIA_FORMAT; - header->error_code = 0x0; - header->param_size = actual_param_sz; - - ret = set_compressed_media_format(sess_obj->out_media_config.format, - media_fmt_hdr, sess_obj); - if (ret) { - AGM_LOGD("Shared mem EP is not configured for format: %d\n", - sess_obj->out_media_config.format); - /* If ret is non-zero then shared memory module would be - * configured by client so return from here. - */ - goto free_payload; - } - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config command for module %d failed with error %d", - mod->tag, ret); - } - -free_payload: - free(payload); - return ret; -} - -static int configure_compress_shared_mem_ep_datapath(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct session_obj *sess_obj = graph_obj->sess_obj; - struct media_format_t *media_fmt_hdr; - uint8_t *payload = NULL; - size_t payload_size = 0, real_fmt_id = 0; - struct agm_buff buffer = {0}; - size_t consumed_size = 0; - - if (is_format_bypassed(sess_obj->out_media_config.format) || - sess_obj->stream_config.sess_mode == AGM_SESSION_NON_TUNNEL) { - AGM_LOGI("bypass shared mem ep config for format %x or sess_mode %d", - sess_obj->out_media_config.format, sess_obj->stream_config.sess_mode); - return 0; - } - - ret = get_media_fmt_id_and_size(sess_obj->out_media_config.format, - &payload_size, &real_fmt_id); - if (ret) { - AGM_LOGD("module is not configured for format: %d\n", - sess_obj->out_media_config.format); - /* If ret is non-zero then shared memory module would be - * configured by client so return from here. - */ - return 0; - } - - payload_size = payload_size - sizeof(struct apm_module_param_data_t); - media_fmt_hdr = (struct media_format_t *) calloc(1, (size_t)payload_size); - if (!media_fmt_hdr) { - AGM_LOGE("Not enough memory for payload\n"); - return -ENOMEM; - } - - - buffer.timestamp = 0x0; - buffer.flags = AGM_BUFF_FLAG_MEDIA_FORMAT; - buffer.size = payload_size; - buffer.addr = (uint8_t *)media_fmt_hdr; - - ret = set_compressed_media_format(sess_obj->out_media_config.format, - media_fmt_hdr, sess_obj); - if (ret) { - AGM_LOGD("Shared mem EP is not configured for format: %d\n", - sess_obj->out_media_config.format); - /* If ret is non-zero then shared memory module would be - * configured by client so return from here. - */ - goto free_payload; - } - - ret = graph_write(graph_obj, &buffer, &consumed_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config command for module %d failed with error %d", - mod->tag, ret); - } - -free_payload: - free(media_fmt_hdr); - return ret; -} - -int configure_pcm_shared_mem_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct session_obj *sess_obj = graph_obj->sess_obj; - struct media_format_t *media_fmt_hdr; - struct apm_module_param_data_t *header; - struct payload_media_fmt_pcm_t *media_fmt_payload; - uint8_t *payload = NULL; - size_t payload_size = 0; - int num_channels = MONO; - uint8_t *channel_map; - - AGM_LOGD("entry mod tag %x miid %x mid %x",mod->tag, mod->miid, mod->mid); - num_channels = sess_obj->out_media_config.channels; - - payload_size = sizeof(struct apm_module_param_data_t) + - sizeof(struct media_format_t) + - sizeof(struct payload_media_fmt_pcm_t) + - sizeof(uint8_t)*num_channels; - - /*ensure that the payloadszie is byte multiple atleast*/ - ALIGN_PAYLOAD(payload_size, 8); - - payload = calloc(1,(size_t)payload_size); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto done; - } - - header = (struct apm_module_param_data_t*)payload; - - media_fmt_hdr = (struct media_format_t*)(payload + - sizeof(struct apm_module_param_data_t)); - media_fmt_payload = (struct payload_media_fmt_pcm_t*)(payload + - sizeof(struct apm_module_param_data_t) + - sizeof(struct media_format_t)); - - channel_map = (uint8_t*)(payload + sizeof(struct apm_module_param_data_t) + - sizeof(struct media_format_t) + - sizeof(struct payload_media_fmt_pcm_t)); - - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_MEDIA_FORMAT; - header->error_code = 0x0; - header->param_size = sizeof(struct media_format_t) + - sizeof(struct payload_media_fmt_pcm_t) + - sizeof(uint8_t)*num_channels; - - media_fmt_hdr->data_format = AGM_DATA_FORMAT_FIXED_POINT; - media_fmt_hdr->fmt_id = MEDIA_FMT_ID_PCM; - media_fmt_hdr->payload_size = (uint32_t)(sizeof(payload_media_fmt_pcm_t) + - sizeof(uint8_t) * num_channels); - - media_fmt_payload->endianness = PCM_LITTLE_ENDIAN; - media_fmt_payload->bit_width = get_pcm_bit_width(sess_obj->out_media_config.format); - media_fmt_payload->sample_rate = sess_obj->out_media_config.rate; - /** - *alignment field is referred to only in case where bit width is - *24 and bits per sample is 32, tiny alsa only supports 24 bit - *in 32 word size in LSB aligned mode(AGM_FORMAT_PCM_S24_LE). - *Hence we hardcode this to PCM_LSB_ALIGNED; - */ - media_fmt_payload->alignment = PCM_LSB_ALIGNED; - media_fmt_payload->num_channels = num_channels; - media_fmt_payload->bits_per_sample = - GET_BITS_PER_SAMPLE(sess_obj->out_media_config.format, - media_fmt_payload->bit_width); - media_fmt_payload->q_factor = GET_Q_FACTOR(sess_obj->out_media_config.format, - media_fmt_payload->bit_width); - /** - *#TODO:As of now channel_map is not part of media_config - *ADD channel map part as part of the session/device media config - *structure and use that channel map if set by client otherwise - * use the default channel map - */ - get_default_channel_map(channel_map, num_channels); - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config command for module %d failed with error %d", - mod->tag, ret); - } -done: - if (payload) { - free(payload); - } - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int configure_wr_shared_mem_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct session_obj *sess_obj = graph_obj->sess_obj; - - /* - *This is for the write shared mem endpoint, - *hence we use out media config. - */ - if (is_format_pcm(sess_obj->out_media_config.format)) - ret = configure_pcm_shared_mem_ep(mod, graph_obj); - else { - if (graph_obj->state != STARTED) - ret = configure_compress_shared_mem_ep(mod, graph_obj); - else - ret = configure_compress_shared_mem_ep_datapath(mod, graph_obj); - } - - if (ret) - return ret; - - return 0; -} - -int configure_rd_shared_mem_ep(struct module_info *mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - struct session_obj *sess_obj = graph_obj->sess_obj; - struct apm_module_param_data_t *header; - struct param_id_rd_sh_mem_cfg_t *rd_sh_mem_cfg; - uint8_t *payload = NULL; - size_t payload_size = 0; - - AGM_LOGD("Enter"); - - /* - *Note: read shared mem ep is configured in case of non-tunnel - *decode sessions where the client has configured the session with - *AGM_SESSION_FLAG_INBAND_SRCM flag - *In case of non-tunnel encode sessions, we set the num_frames_per_buff cfg - *as a part of calibration itself. - *In case of compress capture case also , read shared mem ep is configured. - */ - if (!(sess_obj->stream_config.sess_flags & AGM_SESSION_FLAG_INBAND_SRCM) && - !(sess_obj->stream_config.sess_mode == AGM_SESSION_COMPRESS)) - goto done; - - AGM_LOGD("entry mod tag %x miid %x mid %x sess_flags %x",mod->tag, mod->miid, mod->mid, - sess_obj->stream_config.sess_flags); - - payload_size = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_rd_sh_mem_cfg_t); - - /*ensure that the payloadszie is byte multiple atleast*/ - ALIGN_PAYLOAD(payload_size, 8); - - payload = calloc(1,(size_t)payload_size); - if (!payload) { - AGM_LOGE("Not enough memory for payload"); - ret = -ENOMEM; - goto done; - } - - header = (struct apm_module_param_data_t*)payload; - - rd_sh_mem_cfg = (struct param_id_rd_sh_mem_cfg_t *)(payload - + sizeof(struct apm_module_param_data_t)); - - header->module_instance_id = mod->miid; - header->param_id = PARAM_ID_RD_SH_MEM_CFG; - header->error_code = 0x0; - header->param_size = sizeof(struct param_id_rd_sh_mem_cfg_t); - - /* - *In NT mode session in_media config represents config for data being captured - *Hence for NT Mode decode it would mean PCM data. - */ - if (sess_obj->stream_config.sess_mode == AGM_SESSION_NON_TUNNEL) { - rd_sh_mem_cfg->metadata_control_flags = 0x2; /*ENABLE_MEDIA_FORMAT_MD*/ - if (is_format_pcm(sess_obj->in_media_config.format)) - rd_sh_mem_cfg->num_frames_per_buffer = 0x0; /*As many frames as possible*/ - else - /*TODO:This is encode usecase hence ideally client wont enable SRCM event - *Even if the client wants it enabled, then we configure 1 frame every for - *every read call; - */ - rd_sh_mem_cfg->num_frames_per_buffer = 0x1; - } - - /* For compress capture */ - if (sess_obj->stream_config.sess_mode == AGM_SESSION_COMPRESS && - sess_obj->stream_config.dir == TX) { - rd_sh_mem_cfg->num_frames_per_buffer = 0x1; - AGM_LOGD("compress capture uses 1 frame per buffer"); - } - - - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("custom_config command for module %d failed with error %d", - mod->tag, ret); - } - free(payload); -done: - AGM_LOGD("exit, ret %d", ret); - return ret; -} - - -int configure_spr(struct module_info *spr_mod, - struct graph_obj *graph_obj) -{ - int ret = 0; - - struct listnode *node = NULL; - struct module_info *mod; - struct apm_module_param_data_t *header; - struct param_id_spr_delay_path_end_t *spr_hwep_delay; - uint8_t *payload = NULL; - size_t payload_size = 0; - - AGM_LOGD("SPR module IID %x", spr_mod->miid); - graph_obj->spr_miid = spr_mod->miid; - payload_size = sizeof(struct apm_module_param_data_t) + - sizeof(struct param_id_spr_delay_path_end_t); - ALIGN_PAYLOAD(payload_size, 8); - - payload = calloc(1, (size_t)payload_size); - if (!payload) { - AGM_LOGE("No memory to allocate for payload"); - ret = -ENOMEM; - goto done; - } - header = (struct apm_module_param_data_t*)payload; - spr_hwep_delay = (struct param_id_spr_delay_path_end_t *)(payload - + sizeof(struct apm_module_param_data_t)); - header->module_instance_id = spr_mod->miid; - header->param_id = PARAM_ID_SPR_DELAY_PATH_END; - header->error_code = 0x0; - header->param_size = sizeof(struct param_id_spr_delay_path_end_t); - - list_for_each(node, &graph_obj->tagged_mod_list) { - mod = node_to_item(node, module_info_t, list); - if (mod->tag == DEVICE_HW_ENDPOINT_RX) { - AGM_LOGD("HW EP module IID %x", mod->miid); - spr_hwep_delay->module_instance_id = mod->miid; - ret = gsl_set_custom_config(graph_obj->graph_handle, payload, payload_size); - if (ret !=0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("graph_set_custom_config failed %d", ret); - } - } - } -done: - if (payload) - free(payload); - return ret; -} - -int configure_gapless(struct module_info *gapless_mod, - struct graph_obj *gph_obj) -{ - int ret = 0; - struct gsl_cmd_register_custom_event *reg_ev_payload = NULL; - size_t payload_size = 0; - - AGM_LOGD("GAPLESS module \n"); - - if (gph_obj->graph_handle == NULL) { - pthread_mutex_unlock(&gph_obj->lock); - AGM_LOGE("invalid graph handle\n"); - ret = -EINVAL; - goto done; - } - payload_size = sizeof(struct gsl_cmd_register_custom_event); - - reg_ev_payload = calloc(1, payload_size); - if (reg_ev_payload == NULL) { - pthread_mutex_unlock(&gph_obj->lock); - AGM_LOGE("calloc failed for reg_ev_payload\n"); - ret = -ENOMEM; - goto done; - } - - AGM_LOGD("GAPLESS module IID = %d\n", gapless_mod->miid); - - reg_ev_payload->event_id = EVENT_ID_EARLY_EOS; - // Write shared memory end point module IID - reg_ev_payload->module_instance_id = gapless_mod->miid; - // No payload for early eos registration - reg_ev_payload->event_config_payload_size = 0; - reg_ev_payload->is_register = 1; - - ret = gsl_ioctl(gph_obj->graph_handle, GSL_CMD_REGISTER_CUSTOM_EVENT, - reg_ev_payload, payload_size); - if (ret != 0) { - ret = ar_err_get_lnx_err_code(ret); - AGM_LOGE("Early EOS event registration failed with error %d\n", ret); - } - -done: - if (reg_ev_payload) - free(reg_ev_payload); - return ret; -} - - -module_info_t stream_module_list[] = { - { - .module = MODULE_PCM_ENCODER, - .tag = STREAM_PCM_ENCODER, - .configure = configure_pcm_encoder_params, - }, - { - .module = MODULE_PCM_DECODER, - .tag = STREAM_PCM_DECODER, - .configure = configure_output_media_format, - }, - { - .module = MODULE_PLACEHOLDER_ENCODER, - .tag = TAG_STREAM_PLACEHOLDER_ENCODER, - .configure = configure_placeholder_enc, - }, - { - .module = MODULE_PLACEHOLDER_DECODER, - .tag = TAG_STREAM_PLACEHOLDER_DECODER, - .configure = configure_placeholder_dec, - }, - { - .module = MODULE_PCM_CONVERTER, - .tag = STREAM_PCM_CONVERTER, - .configure = configure_output_media_format, - }, - { - .module = MODULE_WR_SHARED_MEM, - .tag = STREAM_INPUT_MEDIA_FORMAT, - .configure = configure_wr_shared_mem_ep, - }, - { - .module = MODULE_STREAM_PAUSE, - .tag = TAG_PAUSE, - .configure = NULL, - }, - { - .module = MODULE_STREAM_SPR, - .tag = TAG_STREAM_SPR, - .configure = configure_spr, - }, - { - .module = MODULE_STREAM_GAPLESS, - .tag = MODULE_GAPLESS, - .configure = configure_gapless, - }, - { - .module = MODULE_RD_SHARED_MEM, - .tag = RD_SHMEM_ENDPOINT, - .configure = configure_rd_shared_mem_ep, - }, -}; - -module_info_t hw_ep_module[] = { - { - .module = MODULE_HW_EP_RX, - .tag = DEVICE_HW_ENDPOINT_RX, - .configure = configure_hw_ep, - }, - { - .module = MODULE_HW_EP_TX, - .tag = DEVICE_HW_ENDPOINT_TX, - .configure = configure_hw_ep, - } -}; - -void get_stream_module_list_array(module_info_t **info, size_t *size) -{ - *size = sizeof(stream_module_list); - *info = stream_module_list; -} - -void get_hw_ep_module_list_array(module_info_t **info, size_t *size) -{ - *size = sizeof(hw_ep_module); - *info = hw_ep_module; -} diff --git a/qcom/opensource/agm/service/src/metadata.c b/qcom/opensource/agm/service/src/metadata.c deleted file mode 100755 index d337ecd1..00000000 --- a/qcom/opensource/agm/service/src/metadata.c +++ /dev/null @@ -1,417 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#define LOG_TAG "AGM: metadata" -#include -#include -#include - -#include -#include - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_METADATA -#include -#endif - -/* - * Payload for metadata is expected in the following form - * - * struct { - * uint32_t num_gkv; - * struct agm_key_value gkv[num_gkv]; - * uint32_t num_ckv; - * struct agm_key_value ckv[num_ckv]; - * uint32_t prop_id; - * uint32_t num_props; - * uint32_t props[num_props]; - * - * } - * - * */ - -#define PTR_TO_NUM_GKV(x) (x) -#define NUM_GKV(x) *((uint32_t *) x) -#define PTR_TO_GKV(x) (x + sizeof(uint32_t)) - -#define PTR_TO_NUM_CKV(x) (x + sizeof(uint32_t) + (NUM_GKV(x) * (sizeof(struct agm_key_value)))) -#define NUM_CKV(x) *((uint32_t *) PTR_TO_NUM_CKV(x)) -#define PTR_TO_CKV(x) (PTR_TO_NUM_CKV(x) + sizeof(uint32_t)) - -#define PTR_TO_PROP_ID(x) (PTR_TO_CKV(x) + (NUM_CKV(x) * (sizeof(struct agm_key_value)))) -#define PROP_ID(x) *((uint32_t *) PTR_TO_PROP_ID(x)) - -#define PTR_TO_NUM_PROPS(x) (PTR_TO_PROP_ID(x) + sizeof(uint32_t)) -#define NUM_PROPS(x) *((uint32_t *) PTR_TO_NUM_PROPS(x)) -#define PTR_TO_PROPS(x) (PTR_TO_NUM_PROPS(x) + sizeof(uint32_t)) - -#define MAX_KVPAIR_PROPS 48 - -void metadata_print(struct agm_meta_data_gsl* metadata) -{ - int i, count = metadata->gkv.num_kvs; - AGM_LOGD("*************************Metadata*************************\n"); - AGM_LOGD("GKV size:%d\n", count); - for (i = 0; i < count; i++) { - AGM_LOGD("key:0x%x, value:0x%x ", metadata->gkv.kv[i].key, - metadata->gkv.kv[i].value); - } - - count = metadata->ckv.num_kvs; - AGM_LOGD("\nCKV count:%d\n", count); - for (i = 0; i < count; i++) { - AGM_LOGD("key:0x%x, value:0x%x ", metadata->ckv.kv[i].key, - metadata->ckv.kv[i].value); - } - AGM_LOGD("\n"); - - AGM_LOGD("Property ID:%d\n", metadata->sg_props.prop_id); - AGM_LOGD("property count:%d\n", metadata->sg_props.num_values); - - count = metadata->sg_props.num_values; - AGM_LOGD("Property Values: "); - for (i = 0; i < count; i++) { - AGM_LOGD("0x%x ", metadata->sg_props.values[i]); - } - AGM_LOGD("\n"); - AGM_LOGD("****************Metadata Done***************************\n\n"); - -} - -static void metadata_remove_dup( - struct agm_meta_data_gsl* meta_data) { - - int i, j, k, count; - - //remove duplicate gkvs - count = meta_data->gkv.num_kvs; - for (i = 0; i < count; i++) { - for (j = i + 1; j < count; j++) { - if (meta_data->gkv.kv[i].key == meta_data->gkv.kv[j].key) { - for (k = j; k < count-1; k++) { - meta_data->gkv.kv[k].key = meta_data->gkv.kv[k + 1].key; - meta_data->gkv.kv[k].value = meta_data->gkv.kv[k + 1].value; - } - count--; - j--; - } - } - } - meta_data->gkv.num_kvs = count; - - //remove duplicate ckvs - count = meta_data->ckv.num_kvs; - for (i = 0; i < count; i++) { - for (j = i + 1; j < count; j++) { - if (meta_data->ckv.kv[i].key == meta_data->ckv.kv[j].key) { - for (k = j; k < count-1; k++) { - meta_data->ckv.kv[k].key = meta_data->ckv.kv[k + 1].key; - meta_data->ckv.kv[k].value = meta_data->ckv.kv[k + 1].value; - } - count--; - j--; - } - } - } - meta_data->ckv.num_kvs = count; - - //remove duplicate props - count = meta_data->sg_props.num_values; - for (i = 0; i < count; i++) { - for (j = i + 1; j < count; j++) { - if (meta_data->sg_props.values[i] == meta_data->sg_props.values[j]) { - for (k = j; k < count-1; k++) { - meta_data->sg_props.values[k] = - meta_data->sg_props.values[k+1]; - } - count--; - j--; - } - } - } - meta_data->sg_props.num_values = count; - - //metadata_print(meta_data); -} - -void metadata_update_cal(struct agm_meta_data_gsl *meta_data, - struct agm_key_vector_gsl *ckv) -{ - int i, j; - - if (!meta_data || !ckv) { - AGM_LOGE("Invalid params\n"); - return; - } - - if (!(meta_data->ckv.kv)) { - AGM_LOGE("metadata->ckv.kv is NULL, num_kvs=%d\n", - meta_data->ckv.num_kvs); - return; - } - if (!(ckv->kv)) { - AGM_LOGE("ckv->kv is NULL, num_kvs=%d\n", - ckv->num_kvs); - return; - } - - for (i = 0; i < meta_data->ckv.num_kvs; i++) { - for (j = 0; j < ckv->num_kvs; j++) { - if (meta_data->ckv.kv[i].key == ckv->kv[j].key) { - meta_data->ckv.kv[i].value = ckv->kv[j].value; - } - } - } -} - -struct agm_meta_data_gsl* metadata_merge(int num, ...) -{ - struct agm_key_value *gkv_offset; - struct agm_key_value *ckv_offset; - uint32_t *prop_offset; - struct agm_meta_data_gsl *temp, *merged = NULL; - - va_list valist; - int i = 0; - - - merged = calloc(1, sizeof(struct agm_meta_data_gsl)); - if (!merged) { - AGM_LOGE("No memory to create merged metadata\n"); - return NULL; - } - - - va_start(valist, num); - for (i = 0; i < num; i++) { - temp = va_arg(valist, struct agm_meta_data_gsl*); - if (temp) { - merged->gkv.num_kvs += temp->gkv.num_kvs; - merged->ckv.num_kvs += temp->ckv.num_kvs; - merged->sg_props.num_values += temp->sg_props.num_values; - } - } - va_end(valist); - - if ((merged->gkv.num_kvs > MAX_KVPAIR_PROPS) || (merged->ckv.num_kvs > MAX_KVPAIR_PROPS) - || (merged->sg_props.num_values > MAX_KVPAIR_PROPS)) { - AGM_LOGE("Num GKVs %d Num CKVs %d Num Props %d more than expected: %d", merged->gkv.num_kvs, - merged->ckv.num_kvs, merged->sg_props.num_values, MAX_KVPAIR_PROPS); - free(merged); - return NULL; - } - - merged->gkv.kv = calloc(merged->gkv.num_kvs, sizeof(struct agm_key_value)); - if (!merged->gkv.kv) { - AGM_LOGE("No memory to merge gkv\n"); - free(merged); - return NULL; - } - - merged->ckv.kv = calloc(merged->ckv.num_kvs, sizeof(struct agm_key_value)); - if (!merged->ckv.kv) { - AGM_LOGE("No memory to merge ckv\n"); - free(merged->gkv.kv); - free(merged); - return NULL; - } - - merged->sg_props.values = calloc(merged->sg_props.num_values, - sizeof(uint32_t)); - if (!merged->sg_props.values) { - AGM_LOGE("No memory to merge properties\n"); - free(merged->gkv.kv); - free(merged->ckv.kv); - free(merged); - return NULL; - } - - gkv_offset = merged->gkv.kv; - ckv_offset = merged->ckv.kv; - prop_offset = merged->sg_props.values; - - va_start(valist, num); - for (i = 0; i < num; i++) { - temp = va_arg(valist, struct agm_meta_data_gsl*); - if (temp) { - if (temp->gkv.kv) { - memcpy(gkv_offset, temp->gkv.kv, temp->gkv.num_kvs * - sizeof(struct agm_key_value)); - gkv_offset += temp->gkv.num_kvs; - } - - if (temp->ckv.kv) { - memcpy(ckv_offset, temp->ckv.kv, temp->ckv.num_kvs * - sizeof(struct agm_key_value)); - ckv_offset += temp->ckv.num_kvs; - } - - if (temp->sg_props.values) { - merged->sg_props.prop_id = temp->sg_props.prop_id; - memcpy(prop_offset, temp->sg_props.values, - temp->sg_props.num_values * sizeof(uint32_t)); - prop_offset += temp->sg_props.num_values; - } - } - } - va_end(valist); - //metadata_print(merged); - metadata_remove_dup(merged); - - return merged; -} - -int metadata_copy(struct agm_meta_data_gsl *dest, uint32_t size, - uint8_t *metadata) -{ - - int ret = 0; - int min_req_len = 0; - - if (!metadata) { - AGM_LOGI("NULL metadata passed, ignoring\n"); - goto done; - } - min_req_len += sizeof(uint32_t); - if (size < min_req_len) { - AGM_LOGE("size should be atleast %d size for GKV\n", sizeof(uint32_t)); - ret = -EINVAL; - goto done; - - } - - dest->gkv.num_kvs = NUM_GKV(metadata); - if (dest->gkv.num_kvs > MAX_KVPAIR_PROPS) { - AGM_LOGE("Num GKVs %d more than expected: %d",dest->gkv.num_kvs, MAX_KVPAIR_PROPS); - ret = -EINVAL; - goto free_metadata; - } - dest->gkv.kv = calloc(dest->gkv.num_kvs, sizeof(struct agm_key_value)); - if (!dest->gkv.kv) { - AGM_LOGE("Memory allocation failed to copy GKV\n"); - dest->gkv.num_kvs = 0; - ret = -ENOMEM; - goto free_metadata; - } - - min_req_len += (dest->gkv.num_kvs * sizeof(struct agm_key_value)); - if (size < min_req_len) { - AGM_LOGE("Invalid GKV passed\n"); - ret = -EINVAL; - goto free_metadata; - } - memcpy(dest->gkv.kv, PTR_TO_GKV(metadata), dest->gkv.num_kvs * - sizeof(struct agm_key_value)); - - min_req_len += sizeof(uint32_t); - if (size < min_req_len) { - goto done; - } - - dest->ckv.num_kvs = NUM_CKV(metadata); - if (dest->ckv.num_kvs > MAX_KVPAIR_PROPS) { - AGM_LOGE("Num CKVs %d more than expected: %d",dest->ckv.num_kvs, MAX_KVPAIR_PROPS); - ret = -EINVAL; - goto free_metadata; - } - dest->ckv.kv = calloc(dest->ckv.num_kvs, sizeof(struct agm_key_value)); - if (!dest->ckv.kv) { - AGM_LOGE("Memory allocation failed to copy CKV\n"); - ret = -ENOMEM; - goto free_metadata; - } - min_req_len += (dest->ckv.num_kvs * sizeof(struct agm_key_value)); - if (size < min_req_len) { - AGM_LOGE("Invalid CKV passed\n"); - ret = -EINVAL; - goto free_metadata; - } - memcpy(dest->ckv.kv, PTR_TO_CKV(metadata), dest->ckv.num_kvs * - sizeof(struct agm_key_value)); - - min_req_len += sizeof(uint32_t); - if (size < min_req_len) { - goto done; - } - dest->sg_props.prop_id = PROP_ID(metadata); - - min_req_len += sizeof(uint32_t); - if (size < min_req_len) { - AGM_LOGE("Invalid properties passed\n"); - ret = -EINVAL; - goto free_metadata; - } - dest->sg_props.num_values = NUM_PROPS(metadata); - if (dest->sg_props.num_values > MAX_KVPAIR_PROPS) { - AGM_LOGE("Num Props %d more than expected: %d",dest->sg_props.num_values, MAX_KVPAIR_PROPS); - ret = -EINVAL; - goto free_metadata; - } - dest->sg_props.values = calloc(dest->sg_props.num_values, sizeof(uint32_t)); - if (!dest->sg_props.values) { - AGM_LOGE("Memory allocation failed to copy properties\n"); - ret = -ENOMEM; - goto free_metadata; - } - min_req_len += (dest->sg_props.num_values * sizeof(uint32_t)); - if (size < min_req_len) { - AGM_LOGE("Invalid properties passed\n"); - ret = -EINVAL; - goto free_metadata; - } - memcpy(dest->sg_props.values, PTR_TO_PROPS(metadata), - dest->sg_props.num_values * sizeof(uint32_t)); - goto done; - -free_metadata: - metadata_free(dest); - -done: - return ret; - -} - -void metadata_free(struct agm_meta_data_gsl *metadata) -{ - if (metadata) { - if (metadata->ckv.kv) - free(metadata->ckv.kv); - metadata->ckv.kv = NULL; - - if (metadata->gkv.kv) - free(metadata->gkv.kv); - metadata->gkv.kv = NULL; - - if (metadata->sg_props.values) - free(metadata->sg_props.values); - metadata->sg_props.values = NULL; - - memset(metadata, 0, sizeof(struct agm_meta_data_gsl)); - } -} diff --git a/qcom/opensource/agm/service/src/session_obj.c b/qcom/opensource/agm/service/src/session_obj.c deleted file mode 100755 index 73fe47c1..00000000 --- a/qcom/opensource/agm/service/src/session_obj.c +++ /dev/null @@ -1,2816 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -#define LOG_TAG "AGM: session" - -#include -#include -#include -#include - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK AGM_MOD_FILE_SESSION_OBJ -#include -#endif - -#ifdef AGM_USE_CUTILS -#include -#include -static uint32_t TRACE_TAG = ATRACE_TAG_NEVER; -char tracestr[100] = "agm: "; -#define agm_trace_begin(str) \ - strlcat(tracestr, str, sizeof(tracestr));\ - atrace_begin(TRACE_TAG, tracestr);\ - strlcpy(tracestr, "agm: ", sizeof(tracestr)); - -#define agm_trace_end() \ - atrace_end(TRACE_TAG); - -#define check_and_enable_traces() \ - char val[PROPERTY_VALUE_MAX] = {0}; \ - if (property_get("vendor.audio.agm.enable.traces", val, "") && !strncmp(val, "true", 4)) { \ - TRACE_TAG = ATRACE_TAG_AUDIO | ATRACE_TAG_HAL; \ - } -#else -#define agm_trace_begin(str) -#define agm_trace_end() -#define check_and_enable_traces() -#endif - -#define GSL_EVENT_SRC_MODULE_ID_GSL 0x2001 // DO NOT CHANGE - -//forward declarations -static int session_close(struct session_obj *sess_obj); -static int session_set_loopback(struct session_obj *sess_obj, - uint32_t session_id, bool enable); -static pthread_mutex_t hwep_lock; -static struct aif *aif_obj_get_from_pool(struct session_obj *sess_obj, - uint32_t aif) -{ - struct listnode *node; - struct aif *aif_node; - - list_for_each(node, &sess_obj->aif_pool) { - aif_node = node_to_item(node, struct aif, node); - if (aif_node->aif_id == aif) - return aif_node; - } - - return NULL; -} - -static struct aif* aif_obj_create(struct session_obj *sess_obj __unused, int aif_id) -{ - struct aif *aif_obj = NULL; - struct device_obj *dev_obj = NULL; - int ret = 0; - - aif_obj = calloc(1, sizeof(struct aif)); - if (!aif_obj) { - AGM_LOGE("Memory allocation failed for aif object\n"); - return aif_obj; - } - - ret = device_get_obj(aif_id, &dev_obj); - if (ret || !dev_obj) { - AGM_LOGE("Error:%d retrieving device object with id:%d \n", - ret, aif_obj->aif_id); - goto done; - } - aif_obj->aif_id = aif_id; - aif_obj->dev_obj = dev_obj; - -done: - return aif_obj; -} - -/* returns aif_obj associated with aif id in the session obj */ -int aif_obj_get(struct session_obj *sess_obj, int aif_id, struct aif **aif_obj) -{ - // return from list, if not there create, add to list and return - struct aif *tobj = NULL; - int ret = 0; - - tobj = aif_obj_get_from_pool(sess_obj, aif_id); - if (!tobj) { - //AGM_LOGE("Couldnt find a aif object in the list, creating one\n"); - - tobj = aif_obj_create(sess_obj, aif_id); - if (!tobj || !tobj->dev_obj) { - AGM_LOGE("Couldnt create an aif object\n"); - ret = -ENOMEM; - return ret; - } - list_add_tail(&sess_obj->aif_pool, &tobj->node); - } - - *aif_obj = tobj; - - return ret; -} - -/* returns aif_obj associated with aif id in the session obj with - * state not as specified in the argument */ -uint32_t aif_obj_get_count_with_state(struct session_obj *sess_obj, - enum aif_state state, bool exact_state_match) -{ - uint32_t count = 0; - struct listnode *node; - struct aif *temp = NULL; - - //check how many devices in connected state - list_for_each(node, &sess_obj->aif_pool) { - temp = node_to_item(node, struct aif, node); - if (!temp) { - AGM_LOGE("Error could not find aif node\n"); - continue; - } - - if ((exact_state_match && temp->state == state) || - (!exact_state_match && temp->state >= state)) { - count++; - } - } - - return count; -} - -static struct agm_meta_data_gsl* session_get_merged_metadata(struct session_obj *sess_obj) -{ - struct agm_meta_data_gsl *merged = NULL; - struct agm_meta_data_gsl *temp = NULL; - enum agm_session_mode sess_mode = sess_obj->stream_config.sess_mode; - struct listnode *node; - struct aif *aif_node; - - if (sess_mode != AGM_SESSION_NON_TUNNEL) { - list_for_each(node, &sess_obj->aif_pool) { - aif_node = node_to_item(node, struct aif, node); - if (aif_node->state == AIF_CLOSED) { - AGM_LOGD("ignore closed AIF node"); - continue; - } - pthread_mutex_lock(&aif_node->dev_obj->lock); - merged = metadata_merge(4, temp, &sess_obj->sess_meta, - &aif_node->sess_aif_meta, &aif_node->dev_obj->metadata); - pthread_mutex_unlock(&aif_node->dev_obj->lock); - if (temp) { - metadata_free(temp); - free(temp); - } - temp = merged; - } - } else { - merged = &sess_obj->sess_meta; - } - - return merged; -} - -static struct agm_meta_data_gsl* session_get_merged_metadata_without_aif(struct session_obj *sess_obj) -{ - struct agm_meta_data_gsl *merged = NULL; - struct agm_meta_data_gsl *temp = NULL; - struct listnode *node; - struct aif *aif_node; - - list_for_each(node, &sess_obj->aif_pool) { - aif_node = node_to_item(node, struct aif, node); - if (aif_node->state == AIF_CLOSED) { - AGM_LOGD("ignore closed AIF node"); - continue; - } - merged = metadata_merge(3, temp, &sess_obj->sess_meta, - &aif_node->sess_aif_meta); - if (temp) { - metadata_free(temp); - free(temp); - } - temp = merged; - } - - return merged; -} - -static int session_pool_init() -{ - int ret = 0; - sess_pool = calloc(1, sizeof(struct session_pool)); - if (!sess_pool) { - AGM_LOGE("No Memory to create sess_pool\n"); - ret = -ENOMEM; - goto done; - } - list_init(&sess_pool->session_list); - pthread_mutex_init(&sess_pool->lock, (const pthread_mutexattr_t *) NULL); - -done: - return ret; -} - -static void aif_free(struct aif *aif_obj) -{ - metadata_free(&aif_obj->sess_aif_meta); - free(aif_obj->params); - free(aif_obj); -} - -static void aif_pool_free(struct session_obj *sess_obj) -{ - struct aif *aif_obj; - struct listnode *node, *next; - - list_for_each_safe(node, next, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - list_remove(&aif_obj->node); - aif_free(aif_obj); - } -} - -static void session_cb_pool_free(struct session_obj *sess_obj) -{ - struct session_cb *sess_cb; - struct listnode *node, *next; - - list_for_each_safe(node, next, &sess_obj->cb_pool) { - sess_cb = node_to_item(node, struct session_cb, node); - list_remove(&sess_cb->node); - free(sess_cb); - } - -} - -static void sess_obj_free(struct session_obj *sess_obj) -{ - aif_pool_free(sess_obj); - session_cb_pool_free(sess_obj); - metadata_free(&sess_obj->sess_meta); - free(sess_obj->params); - free(sess_obj); -} - -static void session_pool_free() -{ - struct session_obj *sess_obj; - struct listnode *node, *next; - int ret = 0; - - pthread_mutex_lock(&sess_pool->lock); - list_for_each_safe(node, next, &sess_pool->session_list) { - sess_obj = node_to_item(node, struct session_obj, node); - pthread_mutex_lock(&sess_obj->lock); - ret = session_close(sess_obj); - if (ret) { - AGM_LOGE("Error:%d closing session with session id:%d\n", - ret, sess_obj->sess_id); - } - pthread_mutex_unlock(&sess_obj->lock); - - //cleanup aif pool from session_object - list_remove(&sess_obj->node); - sess_obj_free(sess_obj); - } - pthread_mutex_unlock(&sess_pool->lock); - free(sess_pool); -} - -static struct session_obj* session_obj_create(int session_id) -{ - struct session_obj *obj = NULL; - - obj = calloc(1, sizeof(struct session_obj)); - if (!obj) { - AGM_LOGE("Memory allocation failed for sesssion object\n"); - return obj; - } - - obj->sess_id = session_id; - list_init(&obj->aif_pool); - list_init(&obj->cb_pool); - pthread_mutex_init(&obj->lock, (const pthread_mutexattr_t *) NULL); - pthread_mutex_init(&obj->cb_pool_lock, (const pthread_mutexattr_t *) NULL); - - return obj; -} - -struct session_obj *session_obj_retrieve_from_pool(uint32_t session_id) -{ - struct session_obj *obj = NULL; - struct listnode *node; - - pthread_mutex_lock(&sess_pool->lock); - list_for_each(node, &sess_pool->session_list) { - obj = node_to_item(node, struct session_obj, node); - if (obj->sess_id == session_id) - break; - else - obj = NULL; - } - pthread_mutex_unlock(&sess_pool->lock); - - return obj; -} - -struct session_obj *session_obj_get_from_pool(uint32_t session_id) -{ - struct session_obj *obj = NULL; - struct listnode *node; - - pthread_mutex_lock(&sess_pool->lock); - list_for_each(node, &sess_pool->session_list) { - obj = node_to_item(node, struct session_obj, node); - if (obj->sess_id == session_id) - break; - else - obj = NULL; - } - - if (!obj) { - //AGM_LOGE("Couldnt find a session object in the list, - // creating one\n"); - obj = session_obj_create(session_id); - if (!obj) { - AGM_LOGE("Couldnt create a session object\n"); - goto done; - } - list_add_tail(&sess_pool->session_list, &obj->node); - } - -done: - pthread_mutex_unlock(&sess_pool->lock); - return obj; -} -int session_obj_valid_check(uint64_t hndl) -{ - - struct session_obj *obj = NULL; - struct listnode *node; - - pthread_mutex_lock(&sess_pool->lock); - list_for_each(node, &sess_pool->session_list) { - obj = node_to_item(node, struct session_obj, node); - if (obj == hndl) { - pthread_mutex_unlock(&sess_pool->lock); - return 1; - } - } - pthread_mutex_unlock(&sess_pool->lock); - return 0; -} - -/* returns session_obj associated with session id */ -int session_obj_get(int session_id, struct session_obj **obj) -{ - // return from list, if not there create, add to list and return - struct session_obj *tobj = NULL; - int ret = 0; - - tobj = session_obj_get_from_pool(session_id); - if (!tobj) { - AGM_LOGE("Couldnt find or create session_obj\n"); - ret = -ENOMEM; - } - - *obj = tobj; - return ret; -} - -static int session_set_loopback(struct session_obj *sess_obj, - uint32_t pb_id, bool enable) -{ - int ret = 0; - struct session_obj *pb_obj = NULL; - struct agm_meta_data_gsl *capture_metadata = NULL; - struct agm_meta_data_gsl *playback_metadata = NULL; - struct agm_meta_data_gsl *merged_metadata = NULL; - - /* - * 1. merged metadata of pb session + cap session - * 2. call graph_add - * 3. call start (prepare doesnt achieve anything so skip) - * 4. Expectation for loopback is that its establishing an edge b/w TX and RX session - * and no new subgraphs are added and hence no gsl_start/prepare. - * So no new modules/subgraphs which require configuration is expected and hence - * no separate setparams() for loopback for now. - */ - ret = session_obj_get(pb_id, &pb_obj); - if (ret) { - AGM_LOGE("Error:%d getting session object with session id:%d\n", - ret, pb_id); - goto done; - } - - capture_metadata = session_get_merged_metadata(sess_obj); - if (!capture_metadata) { - ret = -ENOMEM; - AGM_LOGE("Error:%d, merging metadata with session id=%d\n", - ret, sess_obj->sess_id); - goto done; - } - - playback_metadata = session_get_merged_metadata(pb_obj); - if (!playback_metadata) { - ret = -ENOMEM; - AGM_LOGE("Error:%d, merging metadata with session id=%d\n", - ret, pb_id); - goto done; - } - - merged_metadata = metadata_merge(2, capture_metadata, playback_metadata); - if (!merged_metadata) { - ret = -ENOMEM; - AGM_LOGE("Error:%d, merging metadata with playback" - "session id=%d and capture session id=%d\n", - ret, pb_id, sess_obj->sess_id); - goto done; - } - - if (enable) - ret = graph_add(sess_obj->graph, merged_metadata, NULL); - else - ret = graph_remove(sess_obj->graph, merged_metadata); - - if (ret) { - AGM_LOGE("Error:%d graph %s failed for session_id: %d\n", - ret, ((enable == true) ? "add":"remove"), sess_obj->sess_id); - goto done; - } - -done: - if (capture_metadata) { - metadata_free(capture_metadata); - free(capture_metadata); - } - if (playback_metadata) { - metadata_free(playback_metadata); - free(playback_metadata); - } - if (merged_metadata) { - metadata_free(merged_metadata); - free(merged_metadata); - } - return ret; -} - -static int session_set_ec_ref(struct session_obj *sess_obj, uint32_t aif_id, - bool enable) -{ - int ret = 0; - struct agm_meta_data_gsl *capture_metadata = NULL; - struct agm_meta_data_gsl *merged_metadata = NULL; - struct device_obj *dev_obj = NULL; - - - ret = device_get_obj(aif_id, &dev_obj); - if (ret) { - AGM_LOGE("Error:%d, unable to get dev_obj with aif_id=%d\n", - ret, aif_id); - goto done; - } - - capture_metadata = session_get_merged_metadata_without_aif(sess_obj); - if (!capture_metadata) { - ret = -ENOMEM; - AGM_LOGE("Error:%d, merging metadata with session id=%d\n", - ret, sess_obj->sess_id); - goto done; - } - - pthread_mutex_lock(&dev_obj->lock); - merged_metadata = metadata_merge(2, capture_metadata, &dev_obj->metadata); - pthread_mutex_unlock(&dev_obj->lock); - if (!merged_metadata) { - ret = -ENOMEM; - AGM_LOGE("Error:%d, merging metadata with capture \ - session id=%d aif_id:%d \n", - ret, sess_obj->sess_id, aif_id); - goto done; - } - - if (enable) - ret = graph_add(sess_obj->graph, merged_metadata, NULL); - else - ret = graph_remove(sess_obj->graph, merged_metadata); - - if (ret) { - AGM_LOGE("Error:%d graph %s failed for session_id: %d\n", - ret, ((enable == true) ? "add":"remove"), - sess_obj->sess_id); - goto done; - } - -done: - if (capture_metadata) { - metadata_free(capture_metadata); - free(capture_metadata); - } - if (merged_metadata) { - metadata_free(merged_metadata); - free(merged_metadata); - } - return ret; -} - -static int session_disconnect_aif(struct session_obj *sess_obj, - struct aif *aif_obj, uint32_t opened_count) -{ - int ret = 0; - struct agm_meta_data_gsl *merged_metadata = NULL; - struct agm_meta_data_gsl *merged_meta_sess_aif = NULL; - struct agm_meta_data_gsl temp = {0}; - struct graph_obj *graph = sess_obj->graph; - - pthread_mutex_lock(&aif_obj->dev_obj->lock); - merged_metadata = metadata_merge(3, &sess_obj->sess_meta, - &aif_obj->sess_aif_meta, &aif_obj->dev_obj->metadata); - pthread_mutex_unlock(&aif_obj->dev_obj->lock); - if (!merged_metadata) { - AGM_LOGE("No memory to create merged_metadata session_id: %d, \ - audio interface id:%d \n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -ENOMEM; - goto done; - } - - pthread_mutex_lock(&hwep_lock); - if (opened_count == 1) { - //this is SSSD condition, hence stop just the stream/stream-device, - //merged only sess-aif, aif - pthread_mutex_lock(&aif_obj->dev_obj->lock); - merged_meta_sess_aif = metadata_merge(2, &aif_obj->sess_aif_meta, - &aif_obj->dev_obj->metadata); - pthread_mutex_unlock(&aif_obj->dev_obj->lock); - if (!merged_meta_sess_aif) { - AGM_LOGE("No memory to create merged_metadata session_id: %d, \ - audio interface id:%d \n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -ENOMEM; - pthread_mutex_unlock(&hwep_lock); - goto done; - } - - temp.gkv = merged_metadata->gkv; - temp.ckv = merged_metadata->ckv; - temp.sg_props = merged_meta_sess_aif->sg_props; - agm_trace_begin("graph_stop"); - ret = graph_stop(graph, &temp); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d graph stop failed session_id: %d, \ - audio interface id:%d \n", - ret, sess_obj->sess_id, aif_obj->aif_id); - } - } else { - ret = graph_remove(graph, merged_metadata); - if (ret) { - AGM_LOGE("Error:%d graph remove failed session_id: %d, \ - audio interface id:%d \n", - ret, sess_obj->sess_id, aif_obj->aif_id); - } - } - agm_trace_begin("device_stop"); - if (sess_obj->state == SESSION_STARTED) - device_stop(aif_obj->dev_obj); - agm_trace_end(); - - agm_trace_begin("device_close"); - ret = device_close(aif_obj->dev_obj); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d closing device object with id:%d \n", - ret, aif_obj->aif_id); - } - pthread_mutex_unlock(&hwep_lock); - -done: - if (merged_meta_sess_aif) { - metadata_free(merged_meta_sess_aif); - free(merged_meta_sess_aif); - } - - if (merged_metadata) { - metadata_free(merged_metadata); - free(merged_metadata); - } - return ret; -} - -static void graph_event_cb(struct agm_event_cb_params *event_params, - void *client_data) -{ - struct session_obj *sess_obj = NULL; - struct session_cb *sess_cb; - struct listnode *node, *next; - uint32_t session_id = (uint32_t)((uintptr_t)client_data); - - if (!event_params) { - AGM_LOGE("event_parms is NULL"); - return; - } - - sess_obj = session_obj_retrieve_from_pool(session_id); - if (!sess_obj) { - AGM_LOGE("Incorrect client_data:%d, doesn't match sess_obj from pool", - session_id); - return; - } - - pthread_mutex_lock(&sess_obj->cb_pool_lock); - list_for_each_safe(node, next, &sess_obj->cb_pool) { - sess_cb = node_to_item(node, struct session_cb, node); - if (sess_cb && sess_cb->cb) { - /* Filter callbacks based on event_id and event_type */ - if (sess_cb->evt_type == AGM_EVENT_DATA_PATH && - event_params->source_module_id == GSL_EVENT_SRC_MODULE_ID_GSL && - (event_params->event_id == AGM_EVENT_EOS_RENDERED || - event_params->event_id == AGM_EVENT_READ_DONE || - event_params->event_id == AGM_EVENT_WRITE_DONE)) { - sess_cb->cb(sess_obj->sess_id, - (struct agm_event_cb_params *)event_params, - sess_cb->client_data); - } else if (sess_cb->evt_type == AGM_EVENT_MODULE && - event_params->source_module_id != GSL_EVENT_SRC_MODULE_ID_GSL) { - sess_cb->cb(sess_obj->sess_id, - (struct agm_event_cb_params *)event_params, - sess_cb->client_data); - } - } - } - pthread_mutex_unlock(&sess_obj->cb_pool_lock); -} - -static int session_apply_aif_tag_params(struct session_obj *sess_obj, - struct agm_meta_data_gsl *merged_metadata, struct aif *aif_obj) -{ - int ret = 0; - struct agm_tag_config_gsl tag_config_gsl; - struct agm_tag_config *tag_config = NULL; - - if (aif_obj->tag_config == NULL) - return ret; - - tag_config = aif_obj->tag_config; - - tag_config_gsl.tag_id = tag_config->tag; - tag_config_gsl.tkv.num_kvs = tag_config->num_tkvs; - tag_config_gsl.tkv.kv = tag_config->kv; - - ret = graph_set_config_with_tag(sess_obj->graph, &merged_metadata->gkv, - &tag_config_gsl); - if (ret) - AGM_LOGE("Error:%d setting for sess_aif params with tags \ - on sess_id:%d, aif_id:%d\n", - ret, sess_obj->sess_id, aif_obj->aif_id); - - // free aif tag param after setting. - // Client need to resend for configuring on next usecase - free(aif_obj->tag_config); - aif_obj->tag_config = NULL; - - return ret; -} - -static int session_apply_aif_device_params(struct session_obj *sess_obj, - struct device_obj *dev_obj) -{ - int ret = 0; - - if (!dev_obj) - return ret; - - pthread_mutex_lock(&dev_obj->lock); - - if ((device_get_state(dev_obj) != DEV_CLOSED) && dev_obj->params != NULL) { - ret = graph_set_config(sess_obj->graph, dev_obj->params, - dev_obj->params_size); - if (ret) - AGM_LOGE("Error:%d setting device cached params: %d\n", - ret, dev_obj->pcm_id); - - // free dev_obj params after setting. - // Client need to resend for configuring on next usecase - free(dev_obj->params); - dev_obj->params = NULL; - dev_obj->params_size = 0; - } - pthread_mutex_unlock(&dev_obj->lock); - - return ret; -} - -static int session_connect_aif(struct session_obj *sess_obj, - struct aif *aif_obj, uint32_t opened_count) -{ - int ret = 0; - struct agm_meta_data_gsl *merged_metadata = NULL; - struct graph_obj *graph = sess_obj->graph; - - //step 2.a merge metadata - pthread_mutex_lock(&aif_obj->dev_obj->lock); - merged_metadata = metadata_merge(3, &sess_obj->sess_meta, - &aif_obj->sess_aif_meta, &aif_obj->dev_obj->metadata); - pthread_mutex_unlock(&aif_obj->dev_obj->lock); - if (!merged_metadata) { - AGM_LOGE("Error merging metadata session_id:%d aif_id:%d\n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -ENOMEM; - goto done; - } - agm_trace_begin("session_connect_aif"); - - agm_trace_begin("device_open"); - ret = device_open(aif_obj->dev_obj); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d opening device object with id:%d \n", - ret, aif_obj->aif_id); - goto done; - } - - //step 2.b - if (opened_count == 0) { - if (sess_obj->state == SESSION_CLOSED) { - agm_trace_begin("graph_open"); - ret = graph_open(merged_metadata, sess_obj, aif_obj->dev_obj, - &sess_obj->graph); - agm_trace_end(); - graph = sess_obj->graph; - if (ret) { - AGM_LOGE("Error:%d graph open failed session_id: %d, \ - audio interface id:%d \n", - ret, sess_obj->sess_id, aif_obj->aif_id); - goto close_device; - } - - //register callback - ret = graph_register_cb(graph, graph_event_cb, - (void *)((uintptr_t) sess_obj->sess_id)); - if (ret) { - AGM_LOGE("Error:%d graph callback registration failed \ - session_id: %d\n", ret, sess_obj->sess_id); - goto graph_cleanup; - } - } else { - agm_trace_begin("graph_change"); - ret = graph_change(graph, merged_metadata, aif_obj->dev_obj); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d graph change failed session_id: %d, \ - audio interface id:%d \n", - ret, sess_obj->sess_id, aif_obj->aif_id); - goto close_device; - } - } - } else { - agm_trace_begin("graph_add"); - ret = graph_add(graph, merged_metadata, aif_obj->dev_obj); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d graph add failed session_id: %d, \ - audio interface id:%d \n", - ret, sess_obj->sess_id, aif_obj->aif_id); - goto close_device; - } - } - - //step 2.c set cached params for stream only in closed - if (sess_obj->state == SESSION_CLOSED && sess_obj->params != NULL) { - ret = graph_set_config(graph, sess_obj->params, sess_obj->params_size); - /* clean up params irrespective of success or failure to avoid - * impact to next usecase */ - free(sess_obj->params); - sess_obj->params = NULL; - sess_obj->params_size = 0; - if (ret) { - AGM_LOGE("Error:%d setting session cached params: %d\n", - ret, sess_obj->sess_id); - goto graph_cleanup; - } - } - - //step 2.d set cached streamdevice params - if (aif_obj->params != NULL) { - ret = graph_set_config(graph, aif_obj->params, aif_obj->params_size); - if (ret) { - AGM_LOGE("Error:%d setting session cached params: %d\n", - ret, sess_obj->sess_id); - goto graph_cleanup; - } - free(aif_obj->params); - aif_obj->params = NULL; - aif_obj->params_size = 0; - } - - //step 2.e set cached device params - ret = session_apply_aif_device_params(sess_obj, aif_obj->dev_obj); - if (ret) - goto graph_cleanup; - - //step 2.f set cached streamdevice tagparams - ret = session_apply_aif_tag_params(sess_obj, merged_metadata, aif_obj); - if (ret) - goto graph_cleanup; - - goto done; - -graph_cleanup: - if (opened_count == 0) { - graph_close(sess_obj->graph); - sess_obj->graph = NULL; - } else { - graph_remove(sess_obj->graph, merged_metadata); - } - -close_device: - if (aif_obj->params) { - free(aif_obj->params); - aif_obj->params = NULL; - aif_obj->params_size = 0; - } - device_close(aif_obj->dev_obj); - -done: - if (merged_metadata) { - metadata_free(merged_metadata); - free(merged_metadata); - } - agm_trace_end(); - return ret; -} - -static int session_open_with_first_device(struct session_obj *sess_obj) -{ - int ret = 0; - struct aif *aif_obj = NULL, *temp = NULL; - struct listnode *node; - - list_for_each(node, &sess_obj->aif_pool) { - temp = node_to_item(node, struct aif, node); - if (temp->state == AIF_OPEN) { - aif_obj = temp; - break; - } - } - - if (!aif_obj) { - AGM_LOGE("No Audio interface(Backend) set on session(Frontend):%d\n", - sess_obj->sess_id); - ret = -EPIPE; - goto done; - } - - ret = session_connect_aif(sess_obj, aif_obj, 0); - if (ret) { - AGM_LOGE("Audio interface(Backend):%d <-> session(Frontend):%d \ - Connect failed error:%d\n", - aif_obj->aif_id, sess_obj->sess_id, ret); - goto done; - } - aif_obj->state = AIF_OPENED; - -done: - return ret; -} - -static int session_connect_reminder_devices(struct session_obj *sess_obj) -{ - int ret = 0; - struct aif *aif_obj = NULL; - struct listnode *node; - uint32_t opened_count = 0; - - // opened_count is 1 because this function is being called - //after connecting with 1 device - opened_count = 1; - - list_for_each(node, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - if (aif_obj && aif_obj->state == AIF_OPEN) { - ret = session_connect_aif(sess_obj, aif_obj, opened_count); - if (ret) { - AGM_LOGE("Audio interface(Backend): %d <-> \ - session(Frontend):%d Connect failed error:%d\n", - aif_obj->aif_id, sess_obj->sess_id, ret); - goto unwind; - } - - aif_obj->state = AIF_OPENED; - opened_count++; - } - } - - return 0; - -unwind: - list_for_each(node, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - if (aif_obj && aif_obj->state == AIF_OPENED) { - /*TODO: fix the 3rd argument to provide correct count*/ - ret = session_disconnect_aif(sess_obj, aif_obj, 1); - if (ret) { - AGM_LOGE("Error:%d initializing session_pool\n", - ret); - } - aif_obj->state = AIF_OPEN; - opened_count--; - } - } - ret = graph_close(sess_obj->graph); - if (ret) { - AGM_LOGE("Error:%d initializing session_pool\n", ret); - } - sess_obj->graph = NULL; - - return ret; -} - -static int session_open_without_device(struct session_obj *sess_obj) -{ - int ret = 0; - struct graph_obj *graph = sess_obj->graph; - - if (sess_obj->state == SESSION_CLOSED) { - ret = graph_open(&sess_obj->sess_meta, sess_obj, NULL, &sess_obj->graph); - graph = sess_obj->graph; - if (ret) { - AGM_LOGE("Error:%d graph open failed session_id: %d\n", - ret, sess_obj->sess_id); - goto done; - } - /*register callback*/ - ret = graph_register_cb(graph, graph_event_cb, - (void *)((uintptr_t) sess_obj->sess_id)); - if (ret) { - AGM_LOGE("Error:%d graph callback registration failed \ - session_id: %d\n", ret, sess_obj->sess_id); - goto graph_cleanup; - } - } - //step 2.c set cached params for stream only in closed - if (sess_obj->state == SESSION_CLOSED && sess_obj->params != NULL) { - ret = graph_set_config(graph, sess_obj->params, sess_obj->params_size); - if (ret) { - AGM_LOGE("Error:%d setting session cached params: %d\n", - ret, sess_obj->sess_id); - goto graph_cleanup; - } - free(sess_obj->params); - sess_obj->params = NULL; - sess_obj->params_size = 0; - } - - goto done; - -graph_cleanup: - graph_close(sess_obj->graph); - sess_obj->graph = NULL; -done: - return ret; -} - -static int session_prepare(struct session_obj *sess_obj) -{ - int ret = 0; - struct aif *aif_obj = NULL; - enum agm_session_mode sess_mode = sess_obj->stream_config.sess_mode; - struct listnode *node = NULL; - uint32_t count = 0; - - if (sess_mode != AGM_SESSION_NON_TUNNEL && sess_mode != AGM_SESSION_NO_CONFIG) { - count = aif_obj_get_count_with_state(sess_obj, AIF_OPENED, false); - if (count == 0) { - AGM_LOGE("Error:%d No aif in right state to proceed with \ - session start for sessionid :%d\n", - ret, sess_obj->sess_id); - ret = -EINVAL; - goto done; - } - - list_for_each(node, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - if (!aif_obj) { - AGM_LOGE("Error:%d could not find aif node\n", ret); - goto done; - } - ret = session_apply_aif_device_params(sess_obj, aif_obj->dev_obj); - if (ret) - goto done; - } - - if ((sess_obj->state != SESSION_STARTED)) { - pthread_mutex_lock(&hwep_lock); - agm_trace_begin("graph_prepare"); - ret = graph_prepare(sess_obj->graph); - agm_trace_end(); - pthread_mutex_unlock(&hwep_lock); - if (ret) { - AGM_LOGE("Error:%d preparing graph\n", ret); - goto done; - } else { - sess_obj->state = SESSION_PREPARED; - } - } - } else if(sess_obj->state != SESSION_STARTED) { - agm_trace_begin("graph_prepare"); - ret = graph_prepare(sess_obj->graph); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d preparing graph\n", ret); - goto done; - } else { - sess_obj->state = SESSION_PREPARED; - } - } - -done: - return ret; -} - -static int session_start(struct session_obj *sess_obj) -{ - int ret = 0; - struct aif *aif_obj = NULL; - enum direction dir = sess_obj->stream_config.dir; - enum agm_session_mode sess_mode = sess_obj->stream_config.sess_mode; - struct listnode *node = NULL; - uint32_t count = 0; - struct session_obj *pb_obj = NULL; - struct device_obj *ec_ref_dev_obj = NULL; - - if (sess_mode != AGM_SESSION_NON_TUNNEL && sess_mode != AGM_SESSION_NO_CONFIG) { - count = aif_obj_get_count_with_state(sess_obj, AIF_OPENED, false); - if (count == 0) { - AGM_LOGE("Error:%d No aif in right state to proceed with \ - session start for session id :%d\n", - ret, sess_obj->sess_id); - ret = -EINVAL; - goto done; - } - - if (dir == TX) { - // For loopback, check if the playback session is in STARTED state, - //otherwise return failure - if (sess_obj->loopback_state == true) { - ret = session_obj_get(sess_obj->loopback_sess_id, &pb_obj); - if (ret) { - AGM_LOGE("Error:%d getting session object with \ - session id:%d\n", - ret, sess_obj->loopback_sess_id); - goto done; - } - - if (pb_obj->state != SESSION_STARTED) { - AGM_LOGE("Error:%d Playback session with session id:%d\n" - "not in STARTED state, current state:%d\n", - ret, pb_obj->sess_id, pb_obj->state); - ret = -EINVAL; - goto done; - } - } - - /* - * For ec ref, check if the device object is in STARTED, - * otherwise return failure. - * The RX(EC) device EP should be in started state, this ensures - * the RX EP is configured and hence capture session start() succeeds - * if RX(EC) device EP is not started, graph_start of capture will fail. - */ - if (sess_obj->ec_ref_state == true) { - ret = device_get_obj(sess_obj->ec_ref_aif_id, &ec_ref_dev_obj); - if (ret) { - AGM_LOGE("Error:%d getting device object with aif id:%d\n", - ret, sess_obj->ec_ref_aif_id); - goto done; - } - - if (device_get_state(ec_ref_dev_obj) != DEV_STARTED) { - AGM_LOGE("Error:%d Device object with aif id:%d\n" - "not in STARTED state, current state:%d\n", - ret, sess_obj->ec_ref_aif_id, - ec_ref_dev_obj->state); - ret = -EINVAL; - goto done; - } - } - } - - pthread_mutex_lock(&hwep_lock); - - //For Slimbus/CP EP - First configure the slave ports via device_prepare/start - //and then start the master side via graph_start. - list_for_each(node, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - if (!aif_obj) { - AGM_LOGE("Error:%d could not find aif node\n", ret); - goto device_stop; - } - - if ((aif_obj->dev_obj->hw_ep_info.intf == SLIMBUS) || - (aif_obj->dev_obj->hw_ep_info.intf == BTFM_PROXY)) { - AGM_LOGD("configuring device early - for SLIMBUS/Connectivity Proxy EPs\n"); - if (aif_obj->state == AIF_OPENED || aif_obj->state == AIF_STOPPED) { - agm_trace_begin("device_prepare"); - ret = device_prepare(aif_obj->dev_obj); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d preparing device\n", ret); - goto device_stop; - } - aif_obj->state = AIF_PREPARED; - } - - if (aif_obj->state == AIF_OPENED || aif_obj->state == AIF_PREPARED || - aif_obj->state == AIF_STOPPED ) { - agm_trace_begin("device_start"); - ret = device_start(aif_obj->dev_obj); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d starting device id:%d\n", - ret, aif_obj->aif_id); - goto device_stop; - } - aif_obj->state = AIF_STARTED; - } - } - } - agm_trace_begin("graph_start"); - ret = graph_start(sess_obj->graph); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d starting graph\n", ret); - goto device_stop; - } - - list_for_each(node, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - if (!aif_obj) { - AGM_LOGE("Error:%d could not find aif node\n", ret); - pthread_mutex_unlock(&hwep_lock); - goto unwind; - } - - //Continue/SKIP for SLIMBUS/Connectivity Proxy EP as they are started early. - if ((aif_obj->dev_obj->hw_ep_info.intf == SLIMBUS) || - (aif_obj->dev_obj->hw_ep_info.intf == BTFM_PROXY)) { - continue; - } - - if (aif_obj->state == AIF_OPENED || aif_obj->state == AIF_STOPPED) { - agm_trace_begin("device_prepare"); - ret = device_prepare(aif_obj->dev_obj); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d preparing device\n", ret); - pthread_mutex_unlock(&hwep_lock); - goto unwind; - } - aif_obj->state = AIF_PREPARED; - } - - if (aif_obj->state == AIF_OPENED || aif_obj->state == AIF_PREPARED || - aif_obj->state == AIF_STOPPED ) { - agm_trace_begin( "device_start"); - ret = device_start(aif_obj->dev_obj); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d starting device id:%d\n", - ret, aif_obj->aif_id); - pthread_mutex_unlock(&hwep_lock); - goto unwind; - } - aif_obj->state = AIF_STARTED; - } - } - pthread_mutex_unlock(&hwep_lock); - } else { - ret = graph_start(sess_obj->graph); - if (ret) { - AGM_LOGE("Error:%d starting graph\n", ret); - goto unwind; - } - } - - sess_obj->state = SESSION_STARTED; - goto done; - -unwind: - pthread_mutex_lock(&hwep_lock); - graph_stop(sess_obj->graph, NULL); -device_stop: - if (sess_mode != AGM_SESSION_NON_TUNNEL && sess_mode != AGM_SESSION_NO_CONFIG) { - list_for_each(node, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - if (aif_obj && (aif_obj->state == AIF_STARTED)) { - device_stop(aif_obj->dev_obj); - //If start fails, client will retry with a prepare call, - //so moving to opened state will allow prepare to go through - aif_obj->state = AIF_OPENED; - } - } - } - pthread_mutex_unlock(&hwep_lock); -done: - return ret; -} - -static int session_stop(struct session_obj *sess_obj) -{ - int ret = 0; - struct aif *aif_obj = NULL; - enum direction dir = sess_obj->stream_config.dir; - enum agm_session_mode sess_mode = sess_obj->stream_config.sess_mode; - struct listnode *node = NULL; - - if (sess_obj->state != SESSION_STARTED) { - AGM_LOGE("session not in STARTED state, current state:%d\n", - sess_obj->state); - ret = -EINVAL; - goto done; - } - - if (sess_mode != AGM_SESSION_NON_TUNNEL && sess_mode != AGM_SESSION_NO_CONFIG) { - pthread_mutex_lock(&hwep_lock); - if (dir == RX) { - agm_trace_begin("graph_stop"); - ret = graph_stop(sess_obj->graph, NULL); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d stopping graph\n", ret); - pthread_mutex_unlock(&hwep_lock); - goto done; - } - } - - list_for_each(node, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - if (!aif_obj) { - AGM_LOGE("Error:%d could not find aif node\n", ret); - continue; - } - - if (aif_obj->state == AIF_STARTED) { - agm_trace_begin("device_stop"); - ret = device_stop(aif_obj->dev_obj); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d stopping device id:%d\n", - ret, aif_obj->aif_id); - } - aif_obj->state = AIF_STOPPED; - } - } - - if (dir == TX) { - agm_trace_begin("graph_stop"); - ret = graph_stop(sess_obj->graph, NULL); - if (ret) { - AGM_LOGE("Error:%d stopping graph\n", ret); - } - agm_trace_end(); - } - pthread_mutex_unlock(&hwep_lock); - } else { - agm_trace_begin("graph_stop"); - ret = graph_stop(sess_obj->graph, NULL); - agm_trace_end(); - if (ret) { - AGM_LOGE("Error:%d stopping graph\n", ret); - } - } - sess_obj->state = SESSION_STOPPED; - -done: - return ret; -} - -static int session_close(struct session_obj *sess_obj) -{ - int ret = 0; - struct aif *aif_obj = NULL; - enum agm_session_mode sess_mode = sess_obj->stream_config.sess_mode; - struct listnode *node = NULL; - struct listnode *next = NULL; - - AGM_LOGD("enter"); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("session already in CLOSED state\n"); - ret = -EALREADY; - goto done; - } - - pthread_mutex_lock(&hwep_lock); - if (sess_obj->state == SESSION_STARTED) { - ret = graph_stop(sess_obj->graph, NULL); - if (ret) { - AGM_LOGE("Error:%d closing graph\n", ret); - } - } - - ret = graph_close(sess_obj->graph); - if (ret) { - AGM_LOGE("Error:%d closing graph\n", ret); - } - sess_obj->graph = NULL; - sess_obj->ec_ref_state = false; - sess_obj->loopback_state = false; - - if (sess_mode != AGM_SESSION_NON_TUNNEL && sess_mode != AGM_SESSION_NO_CONFIG) { - list_for_each_safe(node, next, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - if (!aif_obj) { - AGM_LOGE("Error:%d could not find aif node\n", ret); - continue; - } - - if (aif_obj->state >= AIF_OPENED) { - ret = device_close(aif_obj->dev_obj); - if (ret) { - AGM_LOGE("Error:%d stopping device id:%d\n", - ret, aif_obj->aif_id); - } -// { SEC_AUDIO_ADD_FOR_DEBUG - else { - AGM_LOGI("stopping device id:%d\n",aif_obj->aif_id); - } -// } SEC_AUDIO_ADD_FOR_DEBUG - aif_obj->state = AIF_CLOSED; - } - - if (aif_obj->tag_config) { - free(aif_obj->tag_config); - aif_obj->tag_config = NULL; - } - list_remove(&aif_obj->node); - aif_free(aif_obj); - } - } - pthread_mutex_unlock(&hwep_lock); - sess_obj->state = SESSION_CLOSED; -done: - AGM_LOGD("exit, ret %d", ret); - return ret; -} - -int session_obj_deinit() -{ - session_pool_free(); - device_deinit(); - graph_deinit(); - return 0; -} - -/* Initializes session_obj, enumerate and fill session related information */ -int session_obj_init() -{ - int ret = 0; - - ret = device_init(); - if (ret) { - AGM_LOGE("Error:%d initializing device\n", ret); - goto done; - } - - ret = graph_init(); - if (ret) { - AGM_LOGE("Error:%d initializing graph\n", ret); - goto device_deinit; - } - - ret = session_pool_init(); - if (ret) { - AGM_LOGE("Error:%d initializing session_pool\n", ret); - goto graph_deinit; - } - pthread_mutex_init(&hwep_lock, (const pthread_mutexattr_t *) NULL); - check_and_enable_traces(); - goto done; - -graph_deinit: - graph_deinit(); - -device_deinit: - device_deinit(); - -done: - return ret; -} - -int session_obj_set_sess_metadata(struct session_obj *sess_obj, - uint32_t size, uint8_t *metadata) -{ - - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - metadata_free(&(sess_obj->sess_meta)); - ret = metadata_copy(&(sess_obj->sess_meta), size, metadata); - pthread_mutex_unlock(&sess_obj->lock); - - return ret; -} - -int session_obj_set_sess_params(struct session_obj *sess_obj, - void *payload, size_t size) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - - if (sess_obj->params) { - free(sess_obj->params); - sess_obj->params = NULL; - sess_obj->params_size = 0; - } - - if ((size == 0) ||(payload == NULL)) - goto done; - - sess_obj->params = calloc(1, size); - if (!sess_obj->params) { - AGM_LOGE("No memory for sess params on sess_id:%d\n", - sess_obj->sess_id); - ret = -EINVAL; - goto done; - } - - memcpy(sess_obj->params, payload, size); - sess_obj->params_size = size; - - if (sess_obj->state != SESSION_CLOSED) { - ret = graph_set_config(sess_obj->graph, sess_obj->params, - sess_obj->params_size); - if (ret) { - AGM_LOGE("Error:%d setting for sess params on sess_id:%d\n", - ret, sess_obj->sess_id); - } - free(sess_obj->params); - sess_obj->params = NULL; - sess_obj->params_size = 0; - } - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_set_sess_aif_params(struct session_obj *sess_obj, - uint32_t aif_id, - void* payload, size_t size) -{ - int ret = 0; - struct aif *aif_obj = NULL; - - pthread_mutex_lock(&sess_obj->lock); - ret = aif_obj_get(sess_obj, aif_id, &aif_obj); - if (ret) { - AGM_LOGE("Error obtaining aif object with sess_id:%d, aif id:%d\n", - sess_obj->sess_id, aif_id); - goto done; - } - - if (aif_obj->params) { - free(aif_obj->params); - aif_obj->params = NULL; - aif_obj->params_size = 0; - } - - if ((size == 0) || (payload == NULL)) - goto done; - - aif_obj->params = calloc(1, size); - if (!aif_obj->params) { - AGM_LOGE("No memory for sess_aif params on sess_id:%d, aif_id:%d\n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -EINVAL; - goto done; - } - - memcpy(aif_obj->params, payload, size); - aif_obj->params_size = size; - - if (sess_obj->state != SESSION_CLOSED && aif_obj->state >= AIF_OPENED) { - ret = graph_set_config(sess_obj->graph, aif_obj->params, aif_obj->params_size); - if (ret) { - AGM_LOGE("Error:%d setting for sess_aif params on sess_id:%d, \ - aif_id:%d\n", ret, - sess_obj->sess_id, aif_obj->aif_id); - } - free(aif_obj->params); - aif_obj->params = NULL; - aif_obj->params_size = 0; - } - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; - -} - -int session_obj_set_sess_aif_params_with_tag(struct session_obj *sess_obj, - uint32_t aif_id, - struct agm_tag_config *tag_config) -{ - int ret = 0; - struct aif *aif_obj = NULL; - struct agm_meta_data_gsl *merged_metadata = NULL; - struct agm_tag_config_gsl tag_config_gsl; - size_t tkv_payload_size = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (aif_id < UINT_MAX) { - ret = aif_obj_get(sess_obj, aif_id, &aif_obj); - if (ret) { - AGM_LOGE("Error obtaining aif object with sess_id:%d, aif id:%d\n", - sess_obj->sess_id, aif_id); - goto done; - } - - if (sess_obj->state == SESSION_STARTED && aif_obj->state < AIF_OPENED) { - AGM_LOGE("AIF not opened on sess_id:%d, aif_id:%d, caching tkv\n", - sess_obj->sess_id, aif_obj->aif_id); - - if (aif_obj->tag_config) { - free(aif_obj->tag_config); - aif_obj->tag_config = NULL; - } - - tkv_payload_size = sizeof(struct agm_tag_config) + - (tag_config->num_tkvs * sizeof(struct agm_key_value)); - aif_obj->tag_config = (struct agm_tag_config *)calloc(1, tkv_payload_size); - if (!aif_obj->tag_config) { - AGM_LOGE("Tag_config memory allocation failed for sess_id:%d, aif_id:%d", - sess_obj->sess_id, aif_obj->aif_id); - ret = -ENOMEM; - goto done; - } - memcpy(aif_obj->tag_config, tag_config, tkv_payload_size); - goto done; - } - - if (sess_obj->state == SESSION_CLOSED && aif_obj->state < AIF_OPENED) { - AGM_LOGE("Invalid state on sess_id:%d, aif_id:%d\n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -EINVAL; - goto done; - } - - pthread_mutex_lock(&aif_obj->dev_obj->lock); - merged_metadata = metadata_merge(3, &sess_obj->sess_meta, - &aif_obj->sess_aif_meta, &aif_obj->dev_obj->metadata); - pthread_mutex_unlock(&aif_obj->dev_obj->lock); - if (!merged_metadata) { - AGM_LOGE("Error merging metadata session_id:%d aif_id:%d\n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -ENOMEM; - goto done; - } - - tag_config_gsl.tag_id = tag_config->tag; - tag_config_gsl.tkv.num_kvs = tag_config->num_tkvs; - tag_config_gsl.tkv.kv = tag_config->kv; - - ret = graph_set_config_with_tag(sess_obj->graph, &merged_metadata->gkv, - &tag_config_gsl); - if (ret) { - AGM_LOGE("Error:%d setting for sess_aif params with tags \ - on sess_id:%d, aif_id:%d\n", - ret, sess_obj->sess_id, aif_obj->aif_id); - } - } else { - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Invalid state on sess_id:%d\n", sess_obj->sess_id); - ret = -EINVAL; - goto done; - } - tag_config_gsl.tag_id = tag_config->tag; - tag_config_gsl.tkv.num_kvs = tag_config->num_tkvs; - tag_config_gsl.tkv.kv = tag_config->kv; - - ret = graph_set_config_with_tag(sess_obj->graph, &sess_obj->sess_meta.gkv, - &tag_config_gsl); - if (ret) { - AGM_LOGE("Error:%d setting for sess params with tags \ - on sess_id:%d\n", - ret, sess_obj->sess_id); - } - } - -done: - if (merged_metadata) { - metadata_free(merged_metadata); - free(merged_metadata); - } - - pthread_mutex_unlock(&sess_obj->lock); - - return ret; -} - -int session_obj_rw_acdb_params_with_tag( - struct session_obj *sess_obj, uint32_t aif_id, - struct agm_acdb_param *acdb_param, bool is_set) -{ - int ret = 0; - struct aif *aif_obj = NULL; - struct agm_meta_data_gsl *merged_metadata = NULL; - struct agm_key_vector_gsl tckv; - uint8_t *ptr = NULL; - uint8_t enable_flag = 1; - uint32_t actual_size = 0; - - pthread_mutex_lock(&sess_obj->lock); - ret = graph_enable_acdb_persistence(enable_flag); - if (ret) { - AGM_LOGE("Error: graph_enable_acdb_persistence failed. ret = %d\n", ret); - goto error; - } - - ret = aif_obj_get(sess_obj, aif_id, &aif_obj); - if (ret) { - AGM_LOGE("Error obtaining aif object with sess_id:%d, aif id:%d\n", - sess_obj->sess_id, aif_id); - goto error; - } - - pthread_mutex_lock(&aif_obj->dev_obj->lock); - merged_metadata = metadata_merge(3, &sess_obj->sess_meta, - &aif_obj->sess_aif_meta, &aif_obj->dev_obj->metadata); - pthread_mutex_unlock(&aif_obj->dev_obj->lock); - - if (!merged_metadata) { - AGM_LOGE("Error merging metadata session_id:%d aif_id:%d\n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -ENOMEM; - goto error; - } - - tckv.num_kvs= acdb_param->num_kvs; - tckv.kv = (struct agm_key_value *)calloc(1, - tckv.num_kvs * sizeof(struct agm_key_value)); - if (!tckv.kv) { - ret = -ENOMEM; - goto free_metadata; - } - - memcpy((uint8_t *)tckv.kv, acdb_param->blob, - tckv.num_kvs*sizeof(struct agm_key_value)); - ptr = acdb_param->blob + tckv.num_kvs * sizeof(struct agm_key_value); - AGM_LOGV("blob_size = %d", acdb_param->blob_size); - actual_size = acdb_param->blob_size - - acdb_param->num_kvs * sizeof(struct agm_key_value); - for (int f = 0; f < actual_size; f++) { - AGM_LOGV("%d blob data is 0x%x", f, ptr[f]); - } - if (acdb_param->isTKV) { - AGM_LOGI("%s: TKV param to ACDB.\n", __func__); - ret = graph_set_tag_data_to_acdb(&merged_metadata->gkv, - acdb_param->tag, &tckv, - ptr, actual_size); - } else { - AGM_LOGI("%s: CKV param to ACDB.\n", __func__); - ret = graph_set_cal_data_to_acdb(&merged_metadata->gkv, - &tckv, ptr, actual_size); - } - free(tckv.kv); - -free_metadata: - if (merged_metadata) { - metadata_free(merged_metadata); - free(merged_metadata); - } -error: - pthread_mutex_unlock(&sess_obj->lock); - - return ret; -} - -int session_dummy_rw_acdb_tunnel( - void *payload, bool is_param_set) -{ - int ret = 0; - uint8_t enable_flag = 1; - - AGM_LOGD("enter"); - ret = graph_enable_acdb_persistence(enable_flag); - if (ret) { - AGM_LOGE("Error: graph_enable_acdb_persistence failed. ret = %d\n", ret); - return ret; - } - - ret = graph_rw_acdb_param(payload, is_param_set); - - AGM_LOGD("exit status=%d", ret); - - return ret; -} - -int session_obj_set_sess_aif_cal(struct session_obj *sess_obj, - uint32_t aif_id, - struct agm_cal_config *cal_config) -{ - int ret = 0; - struct aif *aif_obj = NULL; - struct agm_meta_data_gsl *merged_metadata = NULL; - struct agm_meta_data_gsl *capture_metadata = NULL; - struct agm_key_vector_gsl ckv; - struct device_obj *ec_ref_dev_obj = NULL; - - pthread_mutex_lock(&sess_obj->lock); - if (aif_id < UINT_MAX) { - ret = aif_obj_get(sess_obj, aif_id, &aif_obj); - if (ret) { - AGM_LOGE("Error obtaining aif object with sess_id:%d, aif id:%d\n", - sess_obj->sess_id, aif_id); - goto done; - } - - if (sess_obj->state == SESSION_CLOSED || aif_obj->state < AIF_OPENED) { - AGM_LOGE("Invalid state on sess_id:%d, aif_id:%d\n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -EINVAL; - goto done; - } - - ckv.kv = cal_config->kv; - ckv.num_kvs = cal_config->num_ckvs; - metadata_update_cal(&sess_obj->sess_meta, &ckv); - metadata_update_cal(&aif_obj->sess_aif_meta, &ckv); - pthread_mutex_lock(&aif_obj->dev_obj->lock); - metadata_update_cal(&aif_obj->dev_obj->metadata, &ckv); - - merged_metadata = metadata_merge(3, &sess_obj->sess_meta, - &aif_obj->sess_aif_meta, &aif_obj->dev_obj->metadata); - pthread_mutex_unlock(&aif_obj->dev_obj->lock); - if (!merged_metadata) { - AGM_LOGE("Error merging metadata session_id:%d aif_id:%d\n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -ENOMEM; - goto done; - } - - ret = graph_set_cal(sess_obj->graph, merged_metadata); - if (ret) { - AGM_LOGE("Error:%d setting calibration on sess_id:%d, aif_id:%d\n", - ret, sess_obj->sess_id, aif_obj->aif_id); - } - // update CKV values for EC path as well - if (sess_obj->ec_ref_state == true) { - struct device_obj *ec_ref_dev_obj = NULL; - ret = device_get_obj(sess_obj->ec_ref_aif_id, &ec_ref_dev_obj); - if (ret) { - AGM_LOGE("Error:%d getting device object with aif id:%d\n", - ret, sess_obj->ec_ref_aif_id); - goto done; - } - capture_metadata = session_get_merged_metadata_without_aif(sess_obj); - if (!capture_metadata) { - ret = -ENOMEM; - AGM_LOGE("Error:%d, merging metadata with session id=%d\n", - ret, sess_obj->sess_id); - goto done; - } - metadata_free(merged_metadata); - free(merged_metadata); - pthread_mutex_lock(&ec_ref_dev_obj->lock); - merged_metadata = metadata_merge(2, capture_metadata, &ec_ref_dev_obj->metadata); - pthread_mutex_unlock(&ec_ref_dev_obj->lock); - if (!merged_metadata) { - ret = -ENOMEM; - AGM_LOGE("Error:%d, merging metadata with capture \ - session id=%d ec aif_id:%d \n", - ret, sess_obj->sess_id, sess_obj->ec_ref_aif_id); - goto done; - } - ret = graph_set_cal(sess_obj->graph, merged_metadata); - if (ret) { - AGM_LOGE("Error:%d setting EC calibration on sess_id:%d, aif_id:%d\n", - ret, sess_obj->sess_id, sess_obj->ec_ref_aif_id); - } - } - } else { - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Invalid state on sess_id:%d\n", sess_obj->sess_id); - ret = -EINVAL; - goto done; - } - - ckv.kv = cal_config->kv; - ckv.num_kvs = cal_config->num_ckvs; - metadata_update_cal(&sess_obj->sess_meta, &ckv); - - ret = graph_set_cal(sess_obj->graph, &sess_obj->sess_meta); - if (ret) { - AGM_LOGE("Error:%d setting calibration on sess_id:%d\n", - ret, sess_obj->sess_id); - } - } - -done: - if (capture_metadata) { - metadata_free(capture_metadata); - free(capture_metadata); - } - if (merged_metadata) { - metadata_free(merged_metadata); - free(merged_metadata); - } - - pthread_mutex_unlock(&sess_obj->lock); - - return ret; -} - - -int session_obj_set_sess_aif_metadata(struct session_obj *sess_obj, - uint32_t aif_id, uint32_t size, uint8_t *metadata) -{ - - int ret = 0; - struct aif *aif_obj = NULL; - - pthread_mutex_lock(&sess_obj->lock); - ret = aif_obj_get(sess_obj, aif_id, &aif_obj); - if (ret) { - AGM_LOGE("Error obtaining aif object with sess_id:%d, aif id:%d\n", - sess_obj->sess_id, aif_id); - goto done; - } - - metadata_free(&(aif_obj->sess_aif_meta)); - ret = metadata_copy(&(aif_obj->sess_aif_meta), size, metadata); - if (ret) { - AGM_LOGE("Error copying session audio interface metadata \ - sess_id:%d, aif_id:%d \n", - sess_obj->sess_id, aif_obj->aif_id); - } -#ifdef AGM_DEBUG_METADATA - AGM_LOGI("Setting metadata for sess_id %d, aif id %d\n", sess_obj->sess_id, aif_id); - metadata_print(&(aif_obj->sess_aif_meta)); -#endif -done: - pthread_mutex_unlock(&sess_obj->lock); - AGM_LOGI("Exit"); - return ret; -} - -int session_obj_get_sess_params(struct session_obj *sess_obj, - void *payload, size_t size) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - - if (sess_obj->state != SESSION_CLOSED) { - ret = graph_get_config(sess_obj->graph, payload, size); - if (ret) - AGM_LOGE("Error:%d get sess params on sess_id:%d\n", - ret, sess_obj->sess_id); - } - - - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_get_tag_with_module_info(struct session_obj *sess_obj, - uint32_t aif_id, void *payload, - size_t *size) -{ - int ret = 0; - struct aif *aif_obj = NULL; - struct agm_meta_data_gsl *merged_metadata = NULL; - enum agm_session_mode sess_mode = sess_obj->stream_config.sess_mode; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_mode != AGM_SESSION_NON_TUNNEL) { - if (aif_id < UINT_MAX) { - ret = aif_obj_get(sess_obj, aif_id, &aif_obj); - if (ret) { - AGM_LOGE("Error obtaining aif object with sess_id:%d, aif id:%d\n", - sess_obj->sess_id, aif_id); - goto done; - } - - pthread_mutex_lock(&aif_obj->dev_obj->lock); - merged_metadata = metadata_merge(3, &sess_obj->sess_meta, - &aif_obj->sess_aif_meta, &aif_obj->dev_obj->metadata); - pthread_mutex_unlock(&aif_obj->dev_obj->lock); - if (!merged_metadata) { - AGM_LOGE("Error merging metadata session_id:%d aif_id:%d\n", - sess_obj->sess_id, aif_obj->aif_id); - ret = -ENOMEM; - goto done; - } - } else { - ret = -EINVAL; - goto done; - } - } else { - merged_metadata = metadata_merge(1, &sess_obj->sess_meta); - if (!merged_metadata) { - AGM_LOGE("Error merging metadata session_id:%d aif_id:%d\n", - sess_obj->sess_id, aif_id); - ret = -ENOMEM; - goto done; - } - } - - ret = graph_get_tags_with_module_info(&merged_metadata->gkv, payload, size); - if (ret) { - AGM_LOGE("Error getting tag with module info from graph for \ - session_id:%d aif_id:%d\n", - sess_obj->sess_id, aif_id); - goto done; - } - -done: - if (merged_metadata) { - metadata_free(merged_metadata); - free(merged_metadata); - } - - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_dummy_get_tag_with_module_info(struct agm_key_vector_gsl *gkv, - void *payload, size_t *size) -{ - int ret = 0; - - ret = graph_get_tags_with_module_info(gkv, payload, size); - if (ret) { - AGM_LOGE("Error getting tag with module info from graph"); - } - - return ret; -} - -int session_obj_register_cb(struct session_obj *sess_obj, agm_event_cb cb, - enum event_type evt_type, void *client_data) -{ - int ret = 0; - struct session_cb *sess_cb = NULL; - - pthread_mutex_lock(&sess_obj->cb_pool_lock); - if (cb != NULL) { - sess_cb = calloc(1, sizeof(struct session_cb)); - if (!sess_cb) { - AGM_LOGE("Error creating session_cb object with sess_id:%d\n", - sess_obj->sess_id); - ret = -ENOMEM; - goto done; - } - - sess_cb->cb = cb; - sess_cb->client_data = client_data; - sess_cb->evt_type = evt_type; - AGM_LOGV("sess_cb %p client_data %p evt_type %d", sess_cb, - client_data, evt_type); - list_add_tail(&sess_obj->cb_pool, &sess_cb->node); - } else { - struct listnode *node, *next; - list_for_each_safe(node, next, &sess_obj->cb_pool) { - sess_cb = node_to_item(node, struct session_cb, node); - if (sess_cb->evt_type == evt_type && - sess_cb->client_data == client_data) { - AGM_LOGV("remove sess_cb %p client_data %p evt_type %d", - sess_cb, sess_cb->client_data, - sess_cb->evt_type); - list_remove(&sess_cb->node); - free(sess_cb); - } - } - } -done: - pthread_mutex_unlock(&sess_obj->cb_pool_lock); - return ret; -} - -int session_obj_register_for_events(struct session_obj *sess_obj, - struct agm_event_reg_cfg *evt_reg_cfg) -{ - - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Error registering for events, Session with sess_id:%d \ - in invalid state:%d\n", - sess_obj->sess_id, sess_obj->state); - ret = -EINVAL; - goto done; - } - - ret = graph_register_for_events(sess_obj->graph, evt_reg_cfg); - if (ret) { - AGM_LOGE("Error:%d registering events with graph for sess_id:%d\n", - ret, sess_obj->sess_id); - goto done; - } - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_sess_aif_connect(struct session_obj *sess_obj, - uint32_t aif_id, bool aif_state) -{ - int ret = 0; - struct aif *aif_obj = NULL; - uint32_t opened_count = 0; - - pthread_mutex_lock(&sess_obj->lock); - ret = aif_obj_get(sess_obj, aif_id, &aif_obj); - if (ret) { - AGM_LOGE("Error obtaining aif object with sess_id:%d, aif id:%d\n", - sess_obj->sess_id, aif_id); - goto done; - } - - if (((aif_state == true) && (aif_obj->state > AIF_OPENED)) || - ((aif_state == false) && (aif_obj->state < AIF_OPEN))) { - AGM_LOGE("AIF already in state %d\n", aif_obj->state); - ret = -EALREADY; - goto done; - } - - opened_count = aif_obj_get_count_with_state(sess_obj, AIF_OPENED, false); - - if (aif_state == true) { - //TODO: check if the assumption is correct - //Assumption: Each of the following state assumes that there was - //an Audio Interface in Connect state. - switch (sess_obj->state) { - case SESSION_OPENED: - ret = session_connect_aif(sess_obj, aif_obj, opened_count); - if (ret) { - AGM_LOGE("Error:%d, Unable to Connect device\n", - ret); - goto done; - } - aif_obj->state = AIF_OPENED; - opened_count++; - break; - case SESSION_PREPARED: - case SESSION_STOPPED: - ret = session_connect_aif(sess_obj, aif_obj, opened_count); - if (ret) { - AGM_LOGE("Error:%d, Unable to Connect device\n", - ret); - goto done; - } - aif_obj->state = AIF_OPENED; - opened_count++; - - ret = session_prepare(sess_obj); - if (ret) { - AGM_LOGE("Error:%d, Unable to prepare device\n", - ret); - goto unwind; - } - - break; - case SESSION_STARTED: - ret = session_connect_aif(sess_obj, aif_obj, opened_count); - if (ret) { - AGM_LOGE("Error:%d, Unable to Connect device\n", - ret); - goto done; - } - aif_obj->state = AIF_OPENED; - opened_count++; - - ret = session_prepare(sess_obj); - if (ret) { - AGM_LOGE("Error:%d, Unable to prepare device\n", - ret); - goto unwind; - } - ret = session_start(sess_obj); - if (ret) { - AGM_LOGE("Error:%d, Unable to start device\n", - ret); - goto unwind; - } - break; - - case SESSION_CLOSED: - aif_obj->state = AIF_OPEN; - break; - - } - - } else { - aif_obj->state = AIF_CLOSE; - - //if session is in started state and more than 1 device is connect, - //call remove, if only 1 device is connected, do graph stop - switch (sess_obj->state) { - case SESSION_OPENED: - case SESSION_PREPARED: - case SESSION_STARTED: - case SESSION_STOPPED: - ret = session_disconnect_aif(sess_obj, aif_obj, opened_count); - if (ret) { - AGM_LOGE("Error:%d, Unable to Connect device\n", - ret); - goto done; - } - default: - break; - } - aif_obj->state = AIF_CLOSED; - } - goto done; - -unwind: - aif_obj->state = AIF_CLOSE; - session_disconnect_aif(sess_obj, aif_obj, opened_count); - opened_count--; - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_open(uint32_t session_id, - enum agm_session_mode sess_mode, - struct session_obj **session) -{ - - struct session_obj *sess_obj = NULL; - int ret = 0; - int ret_unwind = 0; - struct listnode *node; - struct aif *aif_obj = NULL; - - ret = session_obj_get(session_id, &sess_obj); - if (ret) { - AGM_LOGE("Error getting session object\n"); - return ret; - } - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state != SESSION_CLOSED) { - AGM_LOGE("Session already Opened, session_state:%d\n", - sess_obj->state); - ret = -EALREADY; - goto done; - } - sess_obj->stream_config.sess_mode = sess_mode; - - if (sess_mode == AGM_SESSION_NON_TUNNEL || sess_mode == AGM_SESSION_NO_CONFIG) { - /** - *AGM session can be opened in any one of the agm_session_modes - *If it is a AGM_SESSUION_NON_TUNNEL mode, then that indicates - *there is no device leg associated with this session, and hence - *we skip setting up the same. - */ - ret = session_open_without_device(sess_obj); - if (ret) { - AGM_LOGE("Unable to open a session with Session ID:%d\n", - sess_obj->sess_id); - goto done; - } - } else { - /** - *1. get first device obj from the list for the session - *2. concatenate stream+dev metadata - *3. for playback, open alsa first, open graph - *4. get rest of the devices, call add graph - *5. update state as opened - **/ - ret = session_open_with_first_device(sess_obj); - if (ret) { - AGM_LOGE("Unable to open a session with Session ID:%d\n", - sess_obj->sess_id); - goto done; - } - - ret = session_connect_reminder_devices(sess_obj); - if (ret) { - AGM_LOGE("Unable to open a session with Session ID:%d\n", - sess_obj->sess_id); - goto done; - } - - - //configure ecref if valid session id has been set - if (sess_obj->ec_ref_state == true) { - ret = session_set_ec_ref(sess_obj, sess_obj->ec_ref_aif_id, - sess_obj->ec_ref_state); - if (ret) { - sess_obj->ec_ref_state = false; - sess_obj->ec_ref_aif_id = 0; - goto unwind; - } - } - } - //configure loopback if loopback state is true - if (sess_obj->loopback_state == true) { - ret = session_set_loopback(sess_obj, sess_obj->loopback_sess_id, - sess_obj->loopback_state); - if (ret) { - sess_obj->loopback_state = false; - sess_obj->loopback_sess_id = 0; - goto unwind; - } - } - - sess_obj->state = SESSION_OPENED; - *session = sess_obj; - goto done; - -unwind: - list_for_each(node, &sess_obj->aif_pool) { - aif_obj = node_to_item(node, struct aif, node); - if (aif_obj && aif_obj->state == AIF_OPENED) { - /*TODO: fix the 3rd argument to provide correct count*/ - ret_unwind = session_disconnect_aif(sess_obj, aif_obj, 1); - if (ret_unwind) { - AGM_LOGE("Error:%d Failed to disconnect device\n", - ret_unwind); - } - aif_obj->state = AIF_OPEN; - } - } - ret_unwind = graph_close(sess_obj->graph); - if (ret_unwind) { - AGM_LOGE("Error:%d Failed to close graph\n", ret_unwind); - } - sess_obj->graph = NULL; - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_set_config(struct session_obj *sess_obj, - struct agm_session_config *stream_config, - struct agm_media_config *media_config, - struct agm_buffer_config *buffer_config) -{ - int ret = 0; - pthread_mutex_lock(&sess_obj->lock); - - sess_obj->stream_config = *stream_config; - - if (sess_obj->stream_config.dir == TX) { - /*Capture session config*/ - sess_obj->in_media_config = *media_config; - sess_obj->in_buffer_config = *buffer_config; - } else { - /*Playback session config*/ - sess_obj->out_media_config = *media_config; - sess_obj->out_buffer_config = *buffer_config; - - /* During gapless playback, when clips are switched from - * in between, pause, flush and resume gets called from client, - * flush makes session state as SESSION_STOPPED, so codec param - * needs to be sent to ADSP in this state as well. - */ - if (sess_obj->state == SESSION_STARTED || sess_obj->state == SESSION_STOPPED) { - ret = graph_set_media_config_datapath(sess_obj->graph); - if (ret < 0) - AGM_LOGE("Failed to set media config on datapath ret %d", ret); - } - } - - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_prepare(struct session_obj *sess_obj) -{ - int ret = 0; - - agm_trace_begin("session_prepare"); - pthread_mutex_lock(&sess_obj->lock); - ret = session_prepare(sess_obj); - pthread_mutex_unlock(&sess_obj->lock); - agm_trace_end(); - return ret; -} - -int session_obj_start(struct session_obj *sess_obj) -{ - int ret = 0; - agm_trace_begin( "session_start"); - pthread_mutex_lock(&sess_obj->lock); - ret = session_start(sess_obj); - pthread_mutex_unlock(&sess_obj->lock); - agm_trace_end(); - - return ret; -} - -int session_obj_stop(struct session_obj *sess_obj) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - ret = session_stop(sess_obj); - pthread_mutex_unlock(&sess_obj->lock); - - return ret; -} - - -int session_obj_close(struct session_obj *sess_obj) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - ret = session_close(sess_obj); - pthread_mutex_unlock(&sess_obj->lock); - - return ret; -} - -int session_obj_pause(struct session_obj *sess_obj) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - /* TODO: should pause be issued in specific state, - for now ensure its in started state */ - if (sess_obj->state != SESSION_STARTED) { - AGM_LOGE("Cannot issue pause in state:%d\n", - sess_obj->state); - ret = -EINVAL; - goto done; - } - - ret = graph_pause(sess_obj->graph); - if (ret) { - AGM_LOGE("Error:%d pausing graph\n", ret); - } - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_flush(struct session_obj *sess_obj) -{ - int ret = 0; - struct session_cb *sess_cb; - struct listnode *node, *next; - struct agm_event_cb_params *event_params = NULL; - - pthread_mutex_lock(&sess_obj->lock); - - ret = graph_flush(sess_obj->graph); - if (ret) { - AGM_LOGE("Error:%d flushing graph\n", ret); - goto done; - } - - // Unblock the call waiting for EARLY_EOS callback - event_params = (struct agm_event_cb_params*) calloc(1, - (sizeof(struct agm_event_cb_params))); - if (!event_params) { - AGM_LOGE("Not enough memory for event_params"); - goto done; - } - - pthread_mutex_lock(&sess_obj->cb_pool_lock); - list_for_each_safe(node, next, &sess_obj->cb_pool) { - sess_cb = node_to_item(node, struct session_cb, node); - if (sess_cb && sess_cb->cb) { - event_params->event_id = AGM_EVENT_EARLY_EOS_INTERNAL; - sess_cb->cb(sess_obj->sess_id, - (struct agm_event_cb_params *)event_params, - sess_cb->client_data); - } - } - pthread_mutex_unlock(&sess_obj->cb_pool_lock); - if (event_params) - free(event_params); - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - - -int session_obj_resume(struct session_obj *sess_obj) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - - ret = graph_resume(sess_obj->graph); - if (ret) { - AGM_LOGE("Error:%d resuming graph\n", ret); - } - - - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_suspend(struct session_obj *sess_obj) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - - ret = graph_suspend(sess_obj->graph); - if (ret) { - AGM_LOGE("Error:%d suspending graph\n", ret); - } - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_read(struct session_obj *sess_obj, void *buff, size_t *count) -{ - int ret = 0; - struct agm_buff buffer = {0}; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Cannot issue read in state:%d\n", - sess_obj->state); - ret = -EINVAL; - goto done; - } - - buffer.timestamp = 0x0; - buffer.flags = 0; - buffer.size = *count; - buffer.addr = (uint8_t *)(buff); - - ret = graph_read(sess_obj->graph, &buffer, count); - if (ret) { - AGM_LOGE("Error:%d reading from graph\n", ret); - } - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_write(struct session_obj *sess_obj, void *buff, size_t *count) -{ - int ret = 0; - struct agm_buff buffer = {0}; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Cannot issue write in state:%d\n", - sess_obj->state); - ret = -EINVAL; - goto done; - } - - buffer.timestamp = 0x0; - buffer.flags = 0; - buffer.size = *count; - buffer.addr = (uint8_t *)(buff); - - ret = graph_write(sess_obj->graph, &buffer, count); - if (ret) { - AGM_LOGE("Error:%d writing to graph\n", ret); - } - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -size_t session_obj_hw_processed_buff_cnt(struct session_obj *sess_obj, - enum direction dir) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Cannot issue resume in state:%d\n", - sess_obj->state); - ret = -EINVAL; - goto done; - } - - ret = (int)graph_get_hw_processed_buff_cnt(sess_obj->graph, dir); - - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_set_loopback(struct session_obj *sess_obj, - uint32_t playback_sess_id, bool state) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (playback_sess_id == sess_obj->loopback_sess_id && - state == sess_obj->loopback_state) { - AGM_LOGE("loopback already in %s state for session:%d\n", - ((state != false) ? "enabled":"disabled"), - sess_obj->sess_id); - ret = -EALREADY; - goto done; - } - - /* - * loopback enables just the edge b/w capture and playback sessions. - * There is no need to call prepare/start on added graphs as their states are - * are updated as each of these session states are updated. - */ - - switch(sess_obj->state) { - case SESSION_OPENED: - case SESSION_PREPARED: - case SESSION_STARTED: - case SESSION_STOPPED: - if (state == true) - ret = session_set_loopback(sess_obj, playback_sess_id, state); - else - ret = session_set_loopback(sess_obj, sess_obj->loopback_sess_id, - state); - - if (ret) { - AGM_LOGE("Error:%d setting loopback state:%s for session:%d\n", - ret, ((state != false) ? "enable":"disable"), - sess_obj->sess_id); - goto done; - } - - break; - - case SESSION_CLOSED: - break; - } - sess_obj->loopback_sess_id = playback_sess_id; - sess_obj->loopback_state = state; - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_set_ec_ref(struct session_obj *sess_obj, uint32_t aif_id, - bool state) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (aif_id == sess_obj->ec_ref_aif_id && state == sess_obj->ec_ref_state) { - AGM_LOGE("ec_ref already in %s state for session:%d\n", - ((state != false) ? "enabled":"disabled"), - sess_obj->sess_id); - ret = -EALREADY; - goto done; - } - - /* - * ec_ref enables just the edge b/w capture and playback aif id. - * There is no need to call prepare/start on added graphs as their states - * are updated as each of these session states are updated. - */ - - switch (sess_obj->state) { - case SESSION_OPENED: - case SESSION_PREPARED: - case SESSION_STARTED: - case SESSION_STOPPED: - if (state == true) - ret = session_set_ec_ref(sess_obj, aif_id, state); - else - ret = session_set_ec_ref(sess_obj, sess_obj->ec_ref_aif_id, state); - - if (ret) { - AGM_LOGE("Error:%d setting ec_ref state:%s for session:%d\n", - ret, ((state != false) ? "enable":"disable"), - sess_obj->sess_id); - goto done; - } - - break; - - case SESSION_CLOSED: - break; - } - sess_obj->ec_ref_aif_id = aif_id; - sess_obj->ec_ref_state = state; - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_eos(struct session_obj *sess_obj) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Cannot issue EOS in state:%d\n", - sess_obj->state); - ret = -EINVAL; - goto done; - } - - ret = graph_eos(sess_obj->graph); - if (ret) { - AGM_LOGE("Error:%d sending EOS cmd \n", ret); - } - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - - -int session_obj_get_timestamp(struct session_obj *sess_obj, - uint64_t *timestamp) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Cannot get timestamp in state:%d\n", - sess_obj->state); - ret = -EINVAL; - goto done; - } - - ret = graph_get_session_time(sess_obj->graph, timestamp); - if (ret) - AGM_LOGE("Error:%d for get_timestamp \n", ret); - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_buffer_timestamp(struct session_obj *sess_obj, uint64_t *timestamp) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state != SESSION_STARTED) { - AGM_LOGE("Cannot get timestamp in state:%d\n", sess_obj->state); - ret = -EINVAL; - goto done; - } - - ret = graph_get_buffer_timestamp(sess_obj->graph, timestamp); - if (ret) - AGM_LOGE("Error:%d cannot get buffer timestamp\n", - ret); - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_get_sess_buf_info(struct session_obj *sess_obj, struct agm_buf_info *buf_info, uint32_t flag) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Cannot get timestamp in state:%d\n", sess_obj->state); - ret = -EINVAL; - goto done; - } - - ret = graph_get_buf_info(sess_obj->graph, buf_info, flag); - if (ret) - AGM_LOGE("graph_get_buf_info failed %d\n", ret); - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_set_gapless_metadata(struct session_obj *sess_obj, - enum agm_gapless_silence_type type, - uint32_t silence) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Cannot set gapless data in state:%d\n", sess_obj->state); - ret = -EINVAL; - goto done; - } - - ret = graph_set_gapless_metadata(sess_obj->graph, type, - silence); - if (ret) - AGM_LOGE("failed to set gapless metadata :%d\n", ret); -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_write_with_metadata(struct session_obj *sess_obj, - struct agm_buff *buffer, - size_t *consumed_size) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Cannot issue write in state:%d\n", - sess_obj->state); - ret = -EINVAL; - goto done; - } - - ret = graph_write(sess_obj->graph, buffer, consumed_size); - if (ret) { - AGM_LOGE("Error:%d writing to graph\n", ret); - } - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_read_with_metadata(struct session_obj *sess_obj, - struct agm_buff *buffer, - uint32_t *captured_size) -{ - int ret = 0; - pthread_mutex_lock(&sess_obj->lock); - if (sess_obj->state == SESSION_CLOSED) { - AGM_LOGE("Cannot issue read in state:%d\n", - sess_obj->state); - ret = -EINVAL; - goto done; - } - - size_t read_size; - ret = graph_read(sess_obj->graph, buffer, &read_size); - if (ret) { - AGM_LOGE("Error:%d reading from graph\n", ret); - } - - *captured_size = (uint32_t)read_size; - -done: - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} - -int session_obj_set_non_tunnel_mode_config(struct session_obj *sess_obj, - struct agm_session_config *session_config, - struct agm_media_config *in_media_config, - struct agm_media_config *out_media_config, - struct agm_buffer_config *in_buffer_config, - struct agm_buffer_config *out_buffer_config) -{ - int ret = 0; - - pthread_mutex_lock(&sess_obj->lock); - sess_obj->stream_config = *session_config; - sess_obj->in_media_config = *in_media_config; - sess_obj->out_media_config = *out_media_config; - sess_obj->in_buffer_config = *in_buffer_config; - sess_obj->out_buffer_config = *out_buffer_config; - pthread_mutex_unlock(&sess_obj->lock); - return ret; -} diff --git a/qcom/opensource/agm/service/src/utils.c b/qcom/opensource/agm/service/src/utils.c deleted file mode 100755 index 6eba3a61..00000000 --- a/qcom/opensource/agm/service/src/utils.c +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#define LOG_TAG "AGM" - -#include - -#include - -/* ERROR STRING */ -#define AR_EOK_STR "AR_EOK" -#define AR_EFAILED_STR "AR_EFAILED" -#define AR_EBADPARAM_STR "AR_EBADPARAM" -#define AR_EUNSUPPORTED_STR "AR_EUNSUPPORTED" -#define AR_EVERSION_STR "AR_EVERSION" -#define AR_EUNEXPECTED_STR "AR_EUNEXPECTED" -#define AR_EPANIC_STR "AR_EPANIC" -#define AR_ENORESOURCE_STR "AR_ENORESOURCE" -#define AR_EHANDLE_STR "AR_EHANDLE" -#define AR_EALREADY_STR "AR_EALREADY" -#define AR_ENOTREADY_STR "AR_ENOTREADY" -#define AR_EPENDING_STR "AR_EPENDING" -#define AR_EBUSY_STR "AR_EBUSY" -#define AR_EABORTED_STR "AR_EABORTED" -#define AR_ECONTINUE_STR "AR_ECONTINUE" -#define AR_EIMMEDIATE_STR "AR_EIMMEDIATE" -#define AR_ENOTIMPL_STR "AR_ENOTIMPL" -#define AR_ENEEDMORE_STR "AR_ENEEDMORE" -#define AR_ENOMEMORY_STR "AR_ENOMEMORY" -#define AR_ENOTEXIST_STR "AR_ENOTEXIST" -#define AR_ETERMINATED_STR "AR_ETERMINATED" -#define AR_ETIMEOUT_STR "AR_ETIMEOUT" -#define AR_EIODATA_STR "AR_EIODATA" -#define AR_ESUBSYSRESET_STR "AR_ESUBSYSRESET" -#define AR_ERR_MAX_STR "AR_ERR_MAX" - -/* - *osal layer does not define a max error code hence assigning it - *from based on the latest header, need to revisit each time - *a new error code is added - */ -#define AR_ERR_MAX AR_ESUBSYSRESET + 1 - -struct ar_err_code { - int lnx_err_code; - char *ar_err_str; -}; - -static struct ar_err_code ar_err_code_info[AR_ERR_MAX+1] = { - { 0, AR_EOK_STR}, - { -ENOTRECOVERABLE, AR_EFAILED_STR}, - { -EINVAL, AR_EBADPARAM_STR}, - { -EOPNOTSUPP, AR_EUNSUPPORTED_STR}, - { -ENOPROTOOPT, AR_EVERSION_STR}, - { -ENOTRECOVERABLE, AR_EUNEXPECTED_STR}, - { -ENOTRECOVERABLE, AR_EPANIC_STR}, - { -ENOSPC, AR_ENORESOURCE_STR}, - { -EBADR, AR_EHANDLE_STR}, - { -EALREADY, AR_EALREADY_STR}, - { -EPERM, AR_ENOTREADY_STR}, - { -EINPROGRESS, AR_EPENDING_STR}, - { -EBUSY, AR_EBUSY_STR}, - { -ECANCELED, AR_EABORTED_STR}, - { -EAGAIN, AR_ECONTINUE_STR}, - { -EAGAIN, AR_EIMMEDIATE_STR}, - { -EAGAIN, AR_ENOTIMPL_STR}, - { -ENODATA, AR_ENEEDMORE_STR}, - { -ENOMEM, AR_ENOMEMORY_STR}, - { -ENODEV, AR_ENOTEXIST_STR}, - { -ENODEV, AR_ETERMINATED_STR}, - { -ETIMEDOUT, AR_ETIMEOUT_STR}, - { -EIO, AR_EIODATA_STR}, - { -ENETRESET, AR_ESUBSYSRESET_STR}, - { -EADV, AR_ERR_MAX_STR}, -}; - -int ar_err_get_lnx_err_code(uint32_t error) -{ - if (error > AR_ERR_MAX) - return ar_err_code_info[AR_ERR_MAX].lnx_err_code; - else - return ar_err_code_info[error].lnx_err_code; -} - -char *ar_err_get_err_str(uint32_t error) -{ - if (error > AR_ERR_MAX) - return ar_err_code_info[AR_ERR_MAX].ar_err_str; - else - return ar_err_code_info[error].ar_err_str; -} diff --git a/qcom/opensource/agm/service/test/Makefile.am b/qcom/opensource/agm/service/test/Makefile.am deleted file mode 100755 index e9a781c7..00000000 --- a/qcom/opensource/agm/service/test/Makefile.am +++ /dev/null @@ -1,10 +0,0 @@ -AM_CPPFLAGS := -I $(PKG_CONFIG_SYSROOT_DIR)/usr/include/agm/ -I ${top_srcdir}/src -bin_PROGRAMS := agm_ipc_test -agm_ipc_test_SOURCES = ${top_srcdir}/src/agm_test.c -agm_ipc_test_CPPFLAGS := $(AM_CPPFLAGS) -agm_ipc_test_LDADD = -lagmclient - -bin_PROGRAMS += agmtest -agmtest_SOURCES = ${top_srcdir}/src/agm_test.c -agmtest_CPPFLAGS := $(AM_CPPFLAGS) -agmtest_LDADD = -lagm diff --git a/qcom/opensource/agm/service/test/agmtest.pc.in b/qcom/opensource/agm/service/test/agmtest.pc.in deleted file mode 100755 index e53d64bb..00000000 --- a/qcom/opensource/agm/service/test/agmtest.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: agmtest -Description: agmtest binaries -Version: @VERSION@ -Libs: -L${libdir} -lagmclient -lagm -Cflags: -I${includedir}/agm_test/ diff --git a/qcom/opensource/agm/service/test/configure.ac b/qcom/opensource/agm/service/test/configure.ac deleted file mode 100755 index a3696a38..00000000 --- a/qcom/opensource/agm/service/test/configure.ac +++ /dev/null @@ -1,38 +0,0 @@ -# -*- Autoconf -*- -# configure.ac -- Autoconf script for halinterface -# - -# Process this file with autoconf to produce a configure script. - -# Requires autoconf tool later than 2.61 -AC_PREREQ([2.69]) -# Initialize the hal-interface package version 1.0.0 -AC_INIT(halinterface,1.0.0) -# Does not strictly follow GNU Coding standards -AM_INIT_AUTOMAKE([foreign]) -# Disables auto rebuilding of configure, Makefile.ins -#AM_MAINTAINER_MODE -# defines some macros variable to be included by source -AC_CONFIG_HEADERS([config.h]) -# defines some macros variable to be included by source -AC_CONFIG_MACRO_DIR([m4]) - -# Checks for programs. -AC_PROG_CC - -AM_PROG_CC_C_O -AC_PROG_CXX -AC_PROG_LIBTOOL -AC_PROG_AWK -AC_PROG_CPP -AC_PROG_INSTALL -AC_PROG_LN_S -AC_PROG_MAKE_SET -PKG_PROG_PKG_CONFIG - -AC_CONFIG_FILES([ \ - Makefile\ - agmtest.pc - ]) - -AC_OUTPUT diff --git a/qcom/opensource/agm/service/test/src/agm_test.c b/qcom/opensource/agm/service/test/src/agm_test.c deleted file mode 100755 index a3a4f2be..00000000 --- a/qcom/opensource/agm/service/test/src/agm_test.c +++ /dev/null @@ -1,1510 +0,0 @@ -/* -** Copyright (c) 2019, 2021 The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -//#include "pch.h" -#include -#include - -typedef int(*testcase)(void); - -struct agm_session_config stream_config = { 1, false, true, 0, 0 }; -struct agm_media_config media_config = { 48000, 2, 16, 1}; -struct agm_buffer_config buffer_config = { 4, 320 }; - -uint32_t session_id_rx1 = 1; -uint32_t session_id_rx2 = 2; - -struct session_obj *sess_handle_rx1 = NULL; -struct session_obj *sess_handle_rx2 = NULL; - -uint32_t aif_id_rx1 = 1; -uint32_t aif_id_rx2 = 2; -uint32_t aif_id_rx3 = 3; - -uint32_t session_id_tx1 = 3; -uint32_t aif_id_tx = 4; - -struct session_obj *sess_handle_tx1 = NULL; - - -uint32_t stream_metadata[] = { - 1, /* No of GKVS*/ - 0xA1000000, 0xA1000001, /*GKVS*/ - 2, /* No of CKVS*/ - 0xA5000000, 48000, 0xA6000000, 16, /*CKVS*/ - 1, /* Property ID*/ - 2, /* No of Properties*/ - 1, 2, /* Properties*/ -}; - -uint32_t dev_rx_metadata[] = { - 3, /* No of GKVS*/ - 0xA2000000, 0xA2000001, 0xA2000000, 0xA2000001, 0xA2000000, 0xA2000001, /*GKVS*/ - 2, /* No of CKVS*/ - 0xA5000000, 48000, 0xA6000000, 16, /*CKVS*/ - 1, /* Property ID*/ - 3, /* No of Properties*/ - 5,/* Properties*/ - 105, - 205, -}; - -uint32_t dev_tx_metadata[] = { - 1, /* No of GKVS*/ - 0xA3000000, 0xA3000001, /*GKVS*/ - 2, /* No of CKVS*/ - 0xA5000000, 48000, 0xA6000000, 16, /*CKVS*/ - 1, /* Property ID*/ - 1, /* No of Properties*/ - 5, /* Properties*/ -}; - -uint32_t dev_rx2_metadata[] = { - 3, /* No of GKVS*/ - 5555, 6666, 7777, 8888, 9999, 1000, /*GKVS*/ - 2, /* No of CKVS*/ - 0xA5000000, 48000, 0xA6000000, 16, /*CKVS*/ - 1, /* Property ID*/ - 1, /* No of Properties*/ - 5, /* Properties*/ -}; - -uint32_t dev_rx3_metadata[] = { - 3, /* No of GKVS*/ - 5555, 6666, 7777, 8888, 9999, 1000, /*GKVS*/ - 2, /* No of CKVS*/ - 0xA5000000, 48000, 0xA6000000, 16, /*CKVS*/ - 1, /* Property ID*/ - 1, /* No of Properties*/ - 5, /* Properties*/ -}; - -struct agm_tag_config tag_config = { - 123, 1, - {{0x2, 0x3}}, -}; - -struct agm_cal_config cal = { - 2, {{0xA5000000, 48000}, {0xA6000000, 16}}, -}; - -int testcase_common_init(const char *caller) { - printf("%s: init\n", caller); - agm_init(); - return 0; -} - -int testcase_common_deinit(const char *caller) { - agm_deinit(); - printf("%s: deinit\n", caller); - return 0; -} - -int setup_device_rx() -{ - int ret = 0; - - // device config - ret = agm_aif_set_media_config(aif_id_rx1, &media_config); - if (ret) { - goto done; - } - - // device metadata - ret = agm_aif_set_metadata(aif_id_rx1, sizeof(dev_rx_metadata), dev_rx_metadata); - if (ret) { - goto done; - } - - // stream metadata - ret = agm_session_aif_set_metadata(session_id_rx1, aif_id_rx1, sizeof(dev_rx_metadata), dev_rx_metadata); - if (ret) { - goto done; - } - -done: - return ret; -} - -int setup_device_tx() -{ - int ret = 0; - - // device config - ret = agm_aif_set_media_config(aif_id_tx, &media_config); - if (ret) { - goto done; - } - - // device metadata - ret = agm_aif_set_metadata(aif_id_tx, sizeof(dev_tx_metadata), dev_tx_metadata); - if (ret) { - goto done; - } - - // stream metadata - ret = agm_session_aif_set_metadata(session_id_tx1, aif_id_tx, sizeof(dev_tx_metadata), dev_tx_metadata); - if (ret) { - goto done; - } - -done: - return ret; -} - - -int setup_device_rx2() -{ - int ret = 0; - - // device config - ret = agm_aif_set_media_config(aif_id_rx2, &media_config); - if (ret) { - goto done; - } - - // device metadata - ret = agm_aif_set_metadata(aif_id_rx3, sizeof(dev_rx2_metadata), dev_rx2_metadata); - if (ret) { - goto done; - } - - // stream device2 metadata - ret = agm_session_aif_set_metadata(session_id_rx1, aif_id_rx2, sizeof(dev_rx2_metadata), dev_rx2_metadata); - if (ret) { - goto done; - } - -done: - return ret; -} - -int setup_device_rx3() -{ - int ret = 0; - - // device config - ret = agm_aif_set_media_config(aif_id_rx3, &media_config); - if (ret) { - goto done; - } - - // device3 metadata - ret = agm_aif_set_metadata(aif_id_rx3, sizeof(dev_rx3_metadata), dev_rx3_metadata); - if (ret) { - goto done; - } - - // stream device3 metadata - ret = agm_session_aif_set_metadata(session_id_rx1, aif_id_rx3, sizeof(dev_rx3_metadata), dev_rx3_metadata); - if (ret) { - goto done; - } - -done: - return ret; -} - -int setup_playback_stream() { - - int ret =0; - - // stream metadata - ret = agm_session_set_metadata(session_id_rx1, sizeof(stream_metadata), stream_metadata); - if (ret) { - goto done; - } - -done: - return ret; -} - -int setup_playback_stream_open_prepare_start_with_device_rx() -{ - int ret = 0; - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx1, true); - if (ret) { - goto done; - } - - ret = agm_session_open(session_id_rx1, AGM_SESSION_DEFAULT, &sess_handle_rx1); - if (ret) { - goto done; - } - - ret = agm_session_set_config(sess_handle_rx1, &stream_config, &media_config, - &buffer_config); - if (ret) { - goto done; - } - - ret = agm_session_prepare(sess_handle_rx1); - if (ret) { - goto done; - } - - ret = agm_session_start(sess_handle_rx1); - if (ret) { - goto done; - } - -done: - return ret; -} - -int setup_playback_stream_stop_close() { - int ret = 0; - ret = agm_session_stop(sess_handle_rx1); - if (ret) { - goto done; - } - - ret = agm_session_close(sess_handle_rx1); - if (ret) { - goto done; - } - - done: return ret; -} - -int setup_playback_stream_2() { - - int ret =0; - - // stream metadata - ret = agm_session_set_metadata(session_id_rx2, sizeof(stream_metadata), stream_metadata); - if (ret) { - goto done; - } - -done: - return ret; -} - -int setup_playback_stream_2_open_prepare_start_with_device_rx() -{ - int ret = 0; - ret = agm_session_aif_connect(session_id_rx2, aif_id_rx1, true); - if (ret) { - goto done; - } - - ret = agm_session_open(session_id_rx2, AGM_SESSION_DEFAULT, &sess_handle_rx2); - if (ret) { - goto done; - } - - ret = agm_session_set_config(sess_handle_rx2, &stream_config, &media_config, - &buffer_config); - if (ret) { - goto done; - } - - ret = agm_session_prepare(sess_handle_rx2); - if (ret) { - goto done; - } - - ret = agm_session_start(sess_handle_rx2); - if (ret) { - goto done; - } - -done: - return ret; -} - -int setup_playback_stream_2_stop_close() { - int ret = 0; - ret = agm_session_stop(sess_handle_rx2); - if (ret) { - goto done; - } - - ret = agm_session_close(sess_handle_rx2); - if (ret) { - goto done; - } - - done: return ret; -} - - -int setup_capture_stream() { - - int ret =0; - - // stream metadata - agm_session_set_metadata(session_id_tx1, sizeof(stream_metadata), stream_metadata); - if (ret) { - goto done; - } - -done: - return ret; -} - -int setup_capture_stream_open_prepare_start_with_device_tx() -{ - int ret = 0; - struct agm_session_config capture_stream_config = { TX, false, true, 0, 0 }; - - ret = agm_session_aif_connect(session_id_tx1, aif_id_tx, true); - if (ret) { - goto done; - } - - ret = agm_session_open(session_id_tx1, AGM_SESSION_DEFAULT, &sess_handle_tx1); - if (ret) { - goto done; - } - - ret = agm_session_set_config(sess_handle_tx1, &capture_stream_config, &media_config, - &buffer_config); - if (ret) { - goto done; - } - - ret = agm_session_prepare(sess_handle_tx1); - if (ret) { - goto done; - } - - ret = agm_session_start(sess_handle_tx1); - if (ret) { - goto done; - } - -done: - return ret; -} - -int setup_capture_stream_stop_close() { - int ret = 0; - ret = agm_session_stop(sess_handle_tx1); - if (ret) { - goto done; - } - - ret = agm_session_close(sess_handle_tx1); - if (ret) { - goto done; - } - - done: return ret; -} - -int test_stream_open_without_aif_connected(void) { - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - // stream open with no device connected state - ret = agm_session_open(session_id_rx1, AGM_SESSION_DEFAULT, &sess_handle_rx1); - if (ret == 0) { - goto fail; - } - else { - //overwrite ret so test passess as its adverserial test case - ret = 0; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_device_get_aif_list() { - int ret = 0; - size_t num_aif_info = 0; - struct aif_info *aifinfo = NULL; - int i = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = agm_get_aif_info_list(aifinfo, &num_aif_info); - if (ret) { - goto fail; - } - - if (num_aif_info > 0) { - aifinfo = calloc(num_aif_info, sizeof(struct aif_info)); - if (aifinfo == NULL) { - ret = -1; - goto fail; - } - } else { - ret = -1; - goto fail; - } - - ret = agm_get_aif_info_list(aifinfo, &num_aif_info); - if (ret) { - goto fail; - } - - for (i = 0; i < num_aif_info; i++) - printf("aif %d %s %d\n", i, aifinfo[i].aif_name, aifinfo[i].dir); - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; - -} - -int test_stream_sssd_with_buf_writes(void) { - int ret = 0; - char buff[512] = {0}; - int i = 0; - size_t count = 0; - size_t size = 512; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - for(i = 0; i < 10; i++) { - ret = agm_session_write(sess_handle_rx1, buff, &size); - if (ret) { - printf("%s: Error:%d, session write failed\n", __func__, ret); - goto fail; - } - - count = agm_get_hw_processed_buff_cnt(sess_handle_rx1, RX); - if (!count) { - printf("%s: Error:%d, getting session buf count failed\n", __func__, ret); - goto fail; - } - } - - ret = setup_playback_stream_stop_close(); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_pause_resume(void) { - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = agm_session_pause(sess_handle_rx1); - if (ret) { - goto fail; - } - - ret = agm_session_resume(sess_handle_rx1); - if (ret) { - goto fail; - } - - ret = agm_session_stop(sess_handle_rx1); - if (ret) { - goto fail; - } - - ret = agm_session_pause(sess_handle_rx1); - if (ret == 0) { - goto fail; - } else { - //overwrite ret so test passess - ret = 0; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_open_with_same_aif_twice(void) { - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx1, true); - if (ret == 0) { - goto fail; - } - else { - ret = 0; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_sssd_deviceswitch(void) { - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - // disconnect device 1 - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx1, false); - if (ret) { - goto fail; - } - - ret = setup_device_rx2(); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx2, true); - if (ret) { - goto fail; - } - - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_ssmd(void) { - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_device_rx2(); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx2, true); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_ssmd_teardown_first_device(void) { - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_device_rx2(); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx2, true); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx1, false); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_ssmd_teardown_both_devices_resetup_firstdevice(void) { - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_device_rx2(); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx2, true); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx1, false); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx2, false); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx1, true); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_ssmd_deviceswitch_second_device(void) { - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_device_rx2(); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx2, true); - if (ret) { - goto fail; - } - - //tear down second device - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx2, false); - if (ret) { - goto fail; - } - - ret = setup_device_rx3(); - if (ret) { - goto fail; - } - - ret = agm_session_aif_connect(session_id_rx1, aif_id_rx3, true); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_deint_with_mssd(void) { - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_2(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_2_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = agm_deinit(); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_capture_sess_loopback() -{ - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_device_tx(); - if (ret) { - goto fail; - } - - ret = setup_capture_stream(); - if (ret) { - goto fail; - } - - ret = agm_session_set_loopback(session_id_tx1, session_id_rx1, true); - if (ret) { - goto fail; - } - - ret = setup_capture_stream_open_prepare_start_with_device_tx(); - if (ret) { - goto fail; - } - - ret = agm_session_set_loopback(session_id_tx1, session_id_rx1, false); - if (ret) { - goto fail; - } - - ret = agm_session_set_loopback(session_id_tx1, session_id_rx1, true); - if (ret) { - goto fail; - } - - ret = agm_deinit(); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - - -int test_capture_sess_loopback2() -{ - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = agm_session_set_loopback(session_id_tx1, session_id_rx1, true); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_device_tx(); - if (ret) { - goto fail; - } - - ret = setup_capture_stream(); - if (ret) { - goto fail; - } - - ret = setup_capture_stream_open_prepare_start_with_device_tx(); - if (ret) { - goto fail; - } - - ret = agm_session_set_loopback(session_id_tx1, session_id_rx1, false); - if (ret) { - goto fail; - } - - ret = agm_session_set_loopback(session_id_tx1, session_id_rx1, true); - if (ret) { - goto fail; - } - - ret = agm_deinit(); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_set_ecref(void) -{ - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = agm_session_set_ec_ref(session_id_tx1, aif_id_rx1, true); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_device_tx(); - if (ret) { - goto fail; - } - - ret = setup_capture_stream(); - if (ret) { - goto fail; - } - - ret = agm_session_set_ec_ref(session_id_tx1, aif_id_rx1, false); - if (ret) { - goto fail; - } - - ret = agm_session_set_ec_ref(session_id_tx1, 0, true); - if (ret) { - goto fail; - } - - - ret = agm_deinit(); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_setparams(void) -{ - int ret = 0; - char params[512] = {0}; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - // stream + aif params - ret = agm_session_aif_set_params(session_id_rx1, aif_id_rx1, params, sizeof(params)); - if (ret) { - goto fail; - } - - // stream params - ret = agm_session_set_params(session_id_rx1, params, sizeof(params)); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_stop_close(); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; - -} - -int test_stream_setparams_with_tags() -{ - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = agm_set_params_with_tag(session_id_rx1, aif_id_rx1, &tag_config); - if (!ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = agm_set_params_with_tag(session_id_rx1, aif_id_rx1, &tag_config); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_stop_close(); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -int test_stream_set_cal() -{ - int ret = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = agm_session_aif_set_cal(session_id_rx1, aif_id_rx1, &cal); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_stop_close(sess_handle_rx1); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - -fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - -done: - testcase_common_deinit(__func__); - return ret; -} - -void agmevent_cb(uint32_t session_id, struct agm_event_cb_params *event_params, void *client_data) -{ - uint32_t cookie = (uint32_t) client_data; - printf("%s session_id:%d, client_data:%d\n", __func__, session_id, cookie); - printf("%s: source_module_id:%d, event_id:%d, event_payload_size:%d\n", - __func__,event_params->source_module_id, event_params->event_id, event_params->event_payload_size); -} - -int test_event_registration_and_notification() -{ - int ret = 0; - struct agm_event_reg_cfg evt_cfg; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = agm_session_register_cb(session_id_rx1, agmevent_cb, AGM_EVENT_MODULE, (void *) session_id_rx1); - if(ret) { - goto fail; - } - - ret = agm_session_register_cb(session_id_rx1, agmevent_cb, AGM_EVENT_MODULE, (void *) session_id_rx1+1); - if(ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream_open_prepare_start_with_device_rx(); - if (ret) { - goto fail; - } - - ret = agm_session_register_for_events(session_id_rx1, &evt_cfg); - if (ret) { - goto fail; - } - - sleep(3); - - ret = setup_playback_stream_stop_close(sess_handle_rx1); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - - fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - - done: - //testcase_common_deinit(__func__); - return ret; -} - -int test_get_tagged_module_info() -{ - int ret = 0; - char buf[512]; - size_t size = 0; - - ret = testcase_common_init(__func__); - if (ret) { - goto fail; - } - - ret = setup_device_rx(); - if (ret) { - goto fail; - } - - ret = setup_playback_stream(); - if (ret) { - goto fail; - } - - // Module info list - ret = agm_session_aif_get_tag_module_info(session_id_rx1, aif_id_rx1, NULL, &size); - if (ret) { - goto fail; - } - - ret = agm_session_aif_get_tag_module_info(session_id_rx1, aif_id_rx1, buf, &size); - if (ret) { - goto fail; - } - - printf("TEST PASS: %s()\n", __func__); - goto done; - - fail: - printf("TEST FAIL: %s()\n", __func__); - goto done; - - done: - //testcase_common_deinit(__func__); - return ret; -} - -int main() { - int ret = 0; - int i = 0; - - testcase testcases[] = { - test_device_get_aif_list, - test_stream_sssd_with_buf_writes, - test_stream_sssd_deviceswitch, - test_stream_ssmd, - test_stream_ssmd_teardown_first_device, - test_stream_ssmd_deviceswitch_second_device, - test_stream_ssmd_teardown_both_devices_resetup_firstdevice, - test_stream_pause_resume, - test_capture_sess_loopback, - test_capture_sess_loopback2, - test_stream_setparams, - test_stream_setparams_with_tags, - test_stream_set_cal, - test_stream_set_ecref, - test_get_tagged_module_info, - test_event_registration_and_notification, - //adverserial test cases - test_stream_open_without_aif_connected, - test_stream_open_with_same_aif_twice, - test_stream_deint_with_mssd, - - }; - - int testcount = sizeof(testcases)/sizeof(testcase); - int failed_count = 0; - - for (i = 0; i < testcount; i++) { - printf("************* Start TestCase:%d*************\n", i+1); - ret = testcases[i](); - if (ret) { - printf("Failed @ testcase no :%d\n", i+1); - failed_count++; - } - printf("************* End TestCase:%d*************\n", i+1); - printf("\n\n"); - } - - printf("\n\n"); - printf("*************TEST REPORT*************\n"); - printf("RAN: %d/%d\n", i, testcount); - printf("SUCCESSESFULL: %d\n", testcount- failed_count); - printf("FAILED: %d\n", failed_count); - printf("*************************************\n\n\n\n"); - return 0; -} diff --git a/qcom/opensource/agm/snd_parser/Android.mk b/qcom/opensource/agm/snd_parser/Android.mk deleted file mode 100755 index 976459b6..00000000 --- a/qcom/opensource/agm/snd_parser/Android.mk +++ /dev/null @@ -1,22 +0,0 @@ -LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) - -LOCAL_MODULE := libsndcardparser -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_CFLAGS := -Wno-unused-parameter -Wall -LOCAL_CFLAGS += -DCARD_DEF_FILE=\"/vendor/etc/card-defs.xml\" - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/inc -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/inc -LOCAL_SRC_FILES := src/snd-card-parser.c - -LOCAL_HEADER_LIBRARIES := libagm_headers - -LOCAL_SHARED_LIBRARIES := \ - libexpat \ - libcutils - -include $(BUILD_SHARED_LIBRARY) diff --git a/qcom/opensource/agm/snd_parser/Makefile.am b/qcom/opensource/agm/snd_parser/Makefile.am deleted file mode 100755 index da05f676..00000000 --- a/qcom/opensource/agm/snd_parser/Makefile.am +++ /dev/null @@ -1,31 +0,0 @@ -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = sndparser.pc -EXTRA_DIST = $(pkgconfig_DATA) - -AUTOMAKE_OPTIONS = subdir-objects - -h_sources = inc/snd-card-def.h - -lib_include_HEADERS = $(h_sources) -lib_includedir = $(includedir)/sndparser/ - -if BUILDSYSTEM_OPENWRT -AM_CFLAGS := -I ./inc -else -AM_CFLAGS := -I $(top_srcdir)/inc -endif -AM_CFLAGS += -Wno-unused-parameter -AM_CFLAGS += -DCARD_DEF_FILE=\"/etc/card-defs.xml\" - -lib_LTLIBRARIES = libsndcardparser.la -libsndcardparser_la_SOURCES = src/snd-card-parser.c -libsndcardparser_la_LIBADD = @GLIB_LIBS@ -lexpat -lpthread -libsndcardparser_la_CFLAGS := $(AM_CFLAGS) -libsndcardparser_la_CFLAGS += @GLIB_CFLAGS@ -Dstrlcpy=g_strlcpy -Dstrlcat=g_strlcat -include glib.h -libsndcardparser_la_LDFLAGS = -avoid-version -shared -libsndcardparser_la_list = $(top_srcdir)/configs/$(MACHINE_ENABLED)/card-defs.xml -#install xml files under /etc -root_etcdir = "/etc" -root_etc_SCRIPTS = $(libsndcardparser_la_list) -install-data-hook: - chmod go+r $(DESTDIR)$(root_etcdir)/card-defs.xml diff --git a/qcom/opensource/agm/snd_parser/configs/neo/card-defs.xml b/qcom/opensource/agm/snd_parser/configs/neo/card-defs.xml deleted file mode 100755 index d59e6695..00000000 --- a/qcom/opensource/agm/snd_parser/configs/neo/card-defs.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - auroravirtualsndcard - - - 100 - PCM100 - - libagm_pcm_passthrough_plugin.so - - - 1 - 0 - - - - - 101 - PCM101 - - libagm_pcm_passthrough_plugin.so - - - 0 - 1 - - - - - 103 - PCM103 - - libagm_pcm_passthrough_plugin.so - - - 1 - 0 - 1 - - - - - 104 - PCM104 - - libagm_pcm_passthrough_plugin.so - - - 0 - 1 - 1 - - - - - 105 - COMPRESS105 - - libagm_compress_passthrough_plugin.so - - - 1 - 0 - 0 - - - - - 1 - agm_mixer - - libagm_mixer_passthrough_plugin.so - - - - - diff --git a/qcom/opensource/agm/snd_parser/configs/qcs40x/card-defs.xml b/qcom/opensource/agm/snd_parser/configs/qcs40x/card-defs.xml deleted file mode 100755 index 7002713a..00000000 --- a/qcom/opensource/agm/snd_parser/configs/qcs40x/card-defs.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 100 - qcs405wsasndcard - - - 100 - PCM100 - - libagm_pcm_plugin.so - - - 1 - 0 - - - - - 101 - PCM101 - - libagm_pcm_plugin.so - - - 0 - 1 - - - - - 103 - PCM103 - - libagm_pcm_plugin.so - - - 1 - 0 - 1 - - - - - 104 - PCM104 - - libagm_pcm_plugin.so - - - 0 - 1 - 1 - - - - - 105 - COMPRESS105 - - libagm_compress_plugin.so - - - 1 - 0 - 0 - - - - - 1 - agm_mixer - - libagm_mixer_plugin.so - - - - - diff --git a/qcom/opensource/agm/snd_parser/configs/sxr2130/card-defs.xml b/qcom/opensource/agm/snd_parser/configs/sxr2130/card-defs.xml deleted file mode 100755 index 41e835b6..00000000 --- a/qcom/opensource/agm/snd_parser/configs/sxr2130/card-defs.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 100 - konavirtualsndcard - - - 100 - PCM100 - - libagm_pcm_passthrough_plugin.so - - - 1 - 0 - - - - - 101 - PCM101 - - libagm_pcm_passthrough_plugin.so - - - 0 - 1 - - - - - 103 - PCM103 - - libagm_pcm_passthrough_plugin.so - - - 1 - 0 - 1 - - - - - 104 - PCM104 - - libagm_pcm_passthrough_plugin.so - - - 0 - 1 - 1 - - - - - 105 - COMPRESS105 - - libagm_compress_passthrough_plugin.so - - - 1 - 0 - 0 - - - - - 1 - agm_mixer - - libagm_mixer_passthrough_plugin.so - - - - - diff --git a/qcom/opensource/agm/snd_parser/configure.ac b/qcom/opensource/agm/snd_parser/configure.ac deleted file mode 100755 index 5314aead..00000000 --- a/qcom/opensource/agm/snd_parser/configure.ac +++ /dev/null @@ -1,71 +0,0 @@ -# -*- Autoconf -*- -# configure.ac -- Autoconf script for libacdbloader -# - -# Process this file with autoconf to produce a configure script - -# Requires autoconf tool later than 2.61 -AC_PREREQ(2.61) -# Initialize the sndparsr package version 1.0.0 -AC_INIT([sndparser],1.0.0) -# Does not strictly follow GNU Coding standards -AM_INIT_AUTOMAKE([foreign]) -# Disables auto rebuilding of configure, Makefile.ins -AM_MAINTAINER_MODE -# Verifies the --srcdir is correct by checking for the path -AC_CONFIG_SRCDIR([src/snd-card-parser.c]) -# defines some macros variable to be included by source -AC_CONFIG_MACRO_DIR([m4]) - -#basemachine -AC_MSG_CHECKING([which base machine to use]) -AC_ARG_WITH([basemachine], - [AS_HELP_STRING([--with-basemachine], - [Specify the base machine])], - [machine_selected="$withval"], - [machine_selected=none]) - -AC_MSG_RESULT([$machine_selected]) -AC_SUBST([MACHINE_ENABLED],[$machine_selected]) - -# Checks for programs. -AC_PROG_CC -AM_PROG_CC_C_O -AC_PROG_CXX -AC_PROG_LIBTOOL -AC_PROG_AWK -AC_PROG_CPP -AC_PROG_INSTALL -AC_PROG_LN_S -AC_PROG_MAKE_SET -PKG_PROG_PKG_CONFIG -AC_ARG_WITH([glib], -AC_HELP_STRING([--with-glib], - [enable glib, Build against glib. Use this when building for HLOS systems which use glib])) - -if (test "x${with_glib}" = "xyes"); then - PKG_CHECK_MODULES(GTHREAD, gthread-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GThread >= 2.16 is required)) - PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.16, dummy=yes, - AC_MSG_ERROR(GLib >= 2.16 is required)) - GLIB_CFLAGS="$GLIB_CFLAGS $GTHREAD_CFLAGS" - GLIB_LIBS="$GLIB_LIBS $GTHREAD_LIBS" - - AC_SUBST(GLIB_CFLAGS) - AC_SUBST(GLIB_LIBS) -fi - -AM_CONDITIONAL(USE_GLIB, test "x${with_glib}" = "xyes") - -AC_ARG_WITH([openwrt], - AS_HELP_STRING([use openwrt (default is no)]), - [with_openwrt=$withval], - [with_openwrt=no]) -AM_CONDITIONAL([BUILDSYSTEM_OPENWRT], [test "x${with_openwrt}" = "xyes"]) - -AC_CONFIG_FILES([ \ - Makefile \ - sndparser.pc - ]) - -AC_OUTPUT diff --git a/qcom/opensource/agm/snd_parser/inc/snd-card-def.h b/qcom/opensource/agm/snd_parser/inc/snd-card-def.h deleted file mode 100755 index 2d73b068..00000000 --- a/qcom/opensource/agm/snd_parser/inc/snd-card-def.h +++ /dev/null @@ -1,198 +0,0 @@ -/* -** Copyright (c) 2019, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ - -#ifndef __SND_CARD_DEF_H__ -#define __SND_CARD_DEF_H__ - -enum snd_node_type { - SND_NODE_TYPE_MIN = 0, - SND_NODE_TYPE_PCM = SND_NODE_TYPE_MIN, - SND_NODE_TYPE_MIXER, - SND_NODE_TYPE_COMPR, - SND_NODE_TYPE_MAX, -}; - -enum snd_dev_type { - SND_NODE_DEV_TYPE_HW = 0, - SND_NODE_DEV_TYPE_PLUGIN, -}; - -/* - * TBD: Need to add compile time functionality to stub out APIs if - * snd-card-def library is not compiled. - */ -#if defined(SOME_COMPILE_TIME_FLAG_HERE) -void *snd_card_def_get_card(unsigned int card) -{ - return NULL; -} - -void snd_card_def_put_card(void *card_node) -{ -} - -void *snd_card_def_get_node(void *card_node, unsigned int id, - int type) -{ - return NULL; -} - -int snd_card_def_get_num_node(void *card_node, int type) -{ - return 0; -} - -int snd_card_def_get_nodes_for_type(void *card_node, int type, - void **list, int num_nodes) -{ - return -EINVAL; -} - -int snd_card_def_get_int(void *node, const char *prop, - int *val) -{ - return -EINVAL; -} - -int snd_card_def_get_str(void *node, const char *prop, - char **val) -{ - return -EINVAL; -} - -#else - -/* - * snd_card_def_get_card: - * Get handle to the sound card definition entry in the - * sound card definition XML - * - * @card: card-id (either physical or virtual) - * - * Returns: - * - Valid pointer pointing to the card handle or - * - NULL in error cases or if valid entry cannot be - * found in the card definition file. - */ -void *snd_card_def_get_card(unsigned int card); - -/* - * snd_card_def_put_card: - * Release resources associated with handle to the - * sound card definition entry in the sound card - * definition XML. - * - * @card_node: card handle - */ -void snd_card_def_put_card(void *card_node); - -/* - * snd_card_def_get_node: - * Get handle to the node from the sound card definition XML - * - * @card_node: Handle to the card node - * returned from a call to snd_card_def_get_card - * @id: Id for the node (PCM/Compress/mixer device) - * @type: enum to indicate type of node to be found - * - * Returns: - * - Valid pointer pointing to the node requested - * - NULL in error case or entry not found - */ -void *snd_card_def_get_node(void *card_node, unsigned int id, - int type); - -/* - * snd_card_def_get_num_node: - * Get number of nodes from the sound card definition XML - * - * @card_node: Handle to the card node - * returned from a call to snd_card_def_get_card - * @type: enum to indicate type of node to be found - * - * Returns: - * - number of nodes of the requested type - * - 0 in error case or entry not found - */ -int snd_card_def_get_num_node(void *card_node, int type); - -/* - * snd_card_def_get_nodes_for_type: - * Get list of nodes from the sound card definition XML - * - * @card_node: Handle to the card node - * returned from a call to snd_card_def_get_card - * @type: enum to indicate type of node to be found - * @list: List of device nodes requested - * @num_nodes: Count of nodes requested - * - * Returns: - * - 0 on success - * - non zero in error case or entry not found - */ -int snd_card_def_get_nodes_for_type(void *card_node, int type, - void **list, int num_nodes); -/* - * snd_card_def_get_int: - * Get the integer value for the property under a node in the - * sound card definition XML - * - * @node: Handle to node under which the property is to be found - * returned from a call to snd_card_def_get_node - * @prop: Name of the property to be read under the given node - * @val: pointer to caller allocated memory where the integer - * value can be stored - * - * Returns: - * - zero on success with the value copied in val - * - negative error code on failure - */ -int snd_card_def_get_int(void *node, const char *prop, - int *val); - -/* - * snd_card_def_get_str: - * Get the string value for the property under a node in the - * sound card definition XML - * - * @node: Handle to node under which the property is to be found - * returned from a call to snd_card_def_get_node - * @prop: Name of the property to be read under the given node - * @val: pointer to caller allocated memory where the string - * value can be stored - * - * Returns: - * - zero on success with the value copied in val - * - negative error code on failure - */ -int snd_card_def_get_str(void *node, const char *prop, - char **val); - -#endif // end of SOME_COMPILE_TIME_FLAG_HERE -#endif // end of __SND_CARD_DEF_H__ diff --git a/qcom/opensource/agm/snd_parser/samples/card-defs.xml b/qcom/opensource/agm/snd_parser/samples/card-defs.xml deleted file mode 100755 index ec14d174..00000000 --- a/qcom/opensource/agm/snd_parser/samples/card-defs.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 100 - qcs405tdmsndcard,qcs405csrasndcard, qcs405wsasndcard - - - 100 - PCM100 - - libagm_pcm_plugin.so - - - 1 - 0 - - - - - 101 - PCM101 - - libagm_pcm_plugin.so - - - 0 - 1 - - - - - 102 - PCM102 - - libagm_pcm_plugin.so - - - 1 - 0 - - - - - 103 - PCM103 - - libagm_pcm_plugin.so - - - 1 - 0 - 1 - - - - - 104 - PCM104 - - libagm_pcm_plugin.so - - - 0 - 1 - 1 - - - - - 105 - COMPRESS105 - - libagm_compress_plugin.so - - - 1 - 0 - 0 - - - - - 1 - agm_mixer - - libagm_mixer_plugin.so - - - - - diff --git a/qcom/opensource/agm/snd_parser/sndparser.pc.in b/qcom/opensource/agm/snd_parser/sndparser.pc.in deleted file mode 100755 index 7f9277de..00000000 --- a/qcom/opensource/agm/snd_parser/sndparser.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: sndparser -Description: sndparser library -Version: @VERSION@ -Libs: -L${libdir} -Cflags: -I${includedir}/sndparser diff --git a/qcom/opensource/agm/snd_parser/src/snd-card-parser.c b/qcom/opensource/agm/snd_parser/src/snd-card-parser.c deleted file mode 100755 index 4d565e25..00000000 --- a/qcom/opensource/agm/snd_parser/src/snd-card-parser.c +++ /dev/null @@ -1,754 +0,0 @@ -/* -** Copyright (c) 2019, 2021, The Linux Foundation. All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above -** copyright notice, this list of conditions and the following -** disclaimer in the documentation and/or other materials provided -** with the distribution. -** * Neither the name of The Linux Foundation nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -** IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* Changes from Qualcomm Innovation Center, Inc. are provided under the following license: -* -* Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -**/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define MAX_PATH 256 -#define BUF_SIZE 1024 - - -struct snd_prop_val_pair { - char *prop; - char *val; - struct listnode list_node; -}; - -struct snd_dev_def { - enum snd_node_type node_type; - - struct snd_dev_def_card *card; - - /* Mandatory properties from XML */ - unsigned int device; - int type; - char *name; - char *so_name; - - struct listnode list_node; - - /* List of custom properties */ - struct listnode prop_val_list; -}; - -struct snd_dev_def_card { - unsigned int card; - int type; - char *name; - - int refcnt; - struct listnode list_node; - /* child device details */ - struct listnode pcm_devs_list; - struct listnode mixer_devs_list; - struct listnode compr_devs_list; -}; - -static struct listnode snd_card_list; -static bool snd_card_list_init = false; -static pthread_rwlock_t snd_rwlock = PTHREAD_RWLOCK_INITIALIZER; - -typedef enum { - TAG_ROOT, - TAG_CARD, - TAG_DEVICE, - TAG_PLUGIN, - TAG_DEV_PROPS, -} snd_card_defs_xml_tags_t; - -struct xml_userdata { - char data_buf[BUF_SIZE]; - size_t offs; - - unsigned int card; - char *card_name; - struct snd_dev_def_card *cur_card_def; - struct snd_dev_def *cur_dev_def; - bool card_found; - bool card_parsed; - snd_card_defs_xml_tags_t current_tag; -}; - -static void snd_process_data_buf(struct xml_userdata *data, const XML_Char *tag_name); -static void snd_dev_def_init(struct xml_userdata *data, const XML_Char *tag_name, enum snd_node_type node_type); - -static void snd_reset_data_buf(struct xml_userdata *data) -{ - data->offs = 0; - data->data_buf[data->offs] = '\0'; -} - -static void snd_dev_set_type(struct snd_dev_def *dev_def, int type) -{ - if (dev_def) - dev_def->type = type; -} - -static void snd_start_tag(void *userdata, const XML_Char *tag_name, - const XML_Char **attr) -{ - struct xml_userdata *data = (struct xml_userdata *)userdata; - enum snd_node_type node_type = -1; - - if (data->card_parsed) - return; - - snd_reset_data_buf(data); - - if (!strcmp(tag_name, "card")) - data->current_tag = TAG_CARD; - - if (!strcmp(tag_name, "pcm-device")) { - data->current_tag = TAG_DEVICE; - node_type = SND_NODE_TYPE_PCM; - } else if (!strcmp(tag_name, "compress-device")) { - data->current_tag = TAG_DEVICE; - node_type = SND_NODE_TYPE_COMPR; - } else if (!strcmp(tag_name, "mixer")) { - data->current_tag = TAG_DEVICE; - node_type = SND_NODE_TYPE_MIXER; - } else if (strstr(tag_name, "plugin")) { - snd_dev_set_type(data->cur_dev_def, SND_NODE_DEV_TYPE_PLUGIN); - data->current_tag = TAG_PLUGIN; - } else if (!strcmp(tag_name, "props")) { - data->current_tag = TAG_DEV_PROPS; - } - - if (data->current_tag != TAG_CARD && !data->card_found) - return; - - snd_dev_def_init(data, tag_name, node_type); -} - -static void snd_end_tag(void *userdata, const XML_Char *tag_name) -{ - struct xml_userdata *data = (struct xml_userdata *)userdata; - - if (data->card_parsed) - return; - if (data->current_tag != TAG_CARD && !data->card_found) - return; - - snd_process_data_buf(data, tag_name); - snd_reset_data_buf(data); - if (!strcmp(tag_name, "mixer") || !strcmp(tag_name, "pcm-device") || !strcmp(tag_name, "compress-device")) - data->current_tag = TAG_CARD; - else if (strstr(tag_name, "plugin") || !strcmp(tag_name, "props")) - data->current_tag = TAG_DEVICE; - else if(!strcmp(tag_name, "card")) { - data->current_tag = TAG_ROOT; - if (data->card_found) - data->card_parsed = true; - } -} - -static void snd_data_handler(void *userdata, const XML_Char *s, int len) -{ - struct xml_userdata *data = (struct xml_userdata *)userdata; - - if (len + data->offs >= sizeof(data->data_buf) ) { - data->offs += len; - /* string length overflow, return */ - return; - } else { - memcpy(data->data_buf + data->offs, s, len); - data->offs += len; - } -} - -static void snd_dev_def_init(struct xml_userdata *data, const XML_Char *tag_name, enum snd_node_type node_type) -{ - struct snd_dev_def *dev_def = NULL; - struct snd_dev_def_card *card_def = NULL; - struct listnode *devs_list; - - card_def = data->cur_card_def; - if (!card_def) - return; - - if (node_type == SND_NODE_TYPE_PCM) - devs_list = &card_def->pcm_devs_list; - else if (node_type == SND_NODE_TYPE_COMPR) - devs_list = &card_def->compr_devs_list; - else if (node_type == SND_NODE_TYPE_MIXER) - devs_list = &card_def->mixer_devs_list; - else - return; - - if (!(!strcmp(tag_name, "pcm-device") | !strcmp(tag_name, "compress-device") | !strcmp(tag_name, "mixer"))) - return; - - dev_def = calloc(1, sizeof(struct snd_dev_def)); - if (!dev_def) - return; - - dev_def->node_type = node_type; - dev_def->card = card_def; - dev_def->type = SND_NODE_DEV_TYPE_HW; - list_init(&dev_def->prop_val_list); - list_add_tail(devs_list, &dev_def->list_node); - data->cur_dev_def = dev_def; -} - -static struct snd_dev_def_card *snd_parse_initialize_card_def(struct xml_userdata *data) -{ - struct snd_dev_def_card *card_def = NULL; - - if (data->cur_card_def) - return data->cur_card_def; - - card_def = calloc(1, sizeof(struct snd_dev_def_card)); - if (!card_def) - return card_def; - - data->card_found = true; - data->cur_card_def = card_def; - list_init(&card_def->pcm_devs_list); - list_init(&card_def->mixer_devs_list); - list_init(&card_def->compr_devs_list); - return card_def; -} - -static void snd_parse_card_properties(struct xml_userdata *data, const XML_Char *tag_name) -{ - struct snd_dev_def_card *card_def = NULL; - unsigned int card; - const char s[4] = ", "; - char *token = NULL; - char *tok_ptr; - - if (!strcmp(tag_name, "id")) { - card = atoi(data->data_buf); - if (card == data->card) { - card_def = snd_parse_initialize_card_def(data); - if (card_def) - card_def->card = card; - } - } else if (!strcmp(tag_name, "name")) { - card_def = data->cur_card_def; - if (!card_def) { - if (!data->card_name) - return; - token = strtok_r(data->data_buf, s, &tok_ptr); - - while (token != 0) { - if (!strncmp(data->card_name, token, strlen(data->card_name))) { - card_def = snd_parse_initialize_card_def(data); - if (!card_def) - return; - goto card_found; - } - - token = strtok_r(0, s, &tok_ptr); - } - return; - } - -card_found: - if (token) - strlcpy(data->data_buf, token, strlen(token) + 1); - - card_def->name = calloc(1, strlen(data->data_buf) + 1); - if (!card_def->name) - return; - - strlcpy(card_def->name, data->data_buf, strlen(data->data_buf) + 1); - } -} - -static void snd_parse_plugin_properties(struct xml_userdata *data, const XML_Char *tag_name) -{ - struct snd_dev_def *dev_def = NULL; - - dev_def = data->cur_dev_def; - if (!dev_def) - return; - - if (!strcmp(tag_name, "so-name")) { - dev_def->so_name = calloc(1, strlen(data->data_buf) + 1); - if (!dev_def->so_name) - return; - - strlcpy(dev_def->so_name, data->data_buf, strlen(data->data_buf) + 1); - } -} - -static void snd_parse_device_properties(struct xml_userdata *data, const XML_Char *tag_name) -{ - struct snd_dev_def *dev_def = NULL; - - if (!strcmp(tag_name, "pcm-device") || !strcmp(tag_name, "compress-device") || !strcmp(tag_name, "mixer")) - return; - - dev_def = data->cur_dev_def; - if (!dev_def) - return; - - if (!strcmp(tag_name, "id")) { - dev_def->device = atoi(data->data_buf); - } else if (!strcmp(tag_name, "name")) { - dev_def->name = calloc(1, strlen(data->data_buf) + 1); - if (!dev_def->name) - return; - - strlcpy(dev_def->name, data->data_buf, strlen(data->data_buf) + 1); - } -} - -static void snd_parse_device_custom_properties(struct xml_userdata *data, const XML_Char *tag_name) -{ - struct snd_dev_def *dev_def = NULL; - struct snd_prop_val_pair *pv_pair = NULL; - - if (!strcmp(tag_name, "props")) - return; - - dev_def = data->cur_dev_def; - if (!dev_def) - return; - - /* parse custom properties */ - if (!strlen(data->data_buf) || !strlen(tag_name)) - return; - - pv_pair = calloc(1, sizeof(struct snd_prop_val_pair)); - if (!pv_pair) - return; - - pv_pair->prop = calloc(1, strlen(tag_name) + 1); - if (!pv_pair->prop) { - free(pv_pair); - return; - } - strlcpy(pv_pair->prop, tag_name, strlen(tag_name) + 1); - pv_pair->val = calloc(1, strlen(data->data_buf) + 1); - if (!pv_pair->val) { - free(pv_pair->prop); - free(pv_pair); - return; - } - strlcpy(pv_pair->val, data->data_buf, strlen(data->data_buf) + 1); - list_add_tail(&dev_def->prop_val_list, &pv_pair->list_node); -} - -static void snd_process_data_buf (struct xml_userdata *data, const XML_Char *tag_name) -{ - if (data->offs <= 0) - return; - - data->data_buf[data->offs] = '\0'; - - if (data->card_parsed) - return; - - if (data->current_tag == TAG_ROOT) - return; - - if (data->current_tag == TAG_CARD) - snd_parse_card_properties(data, tag_name); - else if (data->current_tag == TAG_PLUGIN) - snd_parse_plugin_properties(data, tag_name); - else if (data->current_tag == TAG_DEVICE) - snd_parse_device_properties(data, tag_name); - else - snd_parse_device_custom_properties(data, tag_name); -} - -static void snd_free_card_devs_def(struct listnode *dev_list) -{ - struct snd_dev_def *dev_def = NULL; - struct snd_prop_val_pair *pv_pair; - struct listnode *pv_pair_node, *dev_node, *temp, *temp2; - - list_for_each_safe(dev_node, temp, dev_list) { - dev_def = node_to_item(dev_node, struct snd_dev_def, list_node); - list_remove(dev_node); - free(dev_def->name); - free(dev_def->so_name); - list_for_each_safe(pv_pair_node, temp2, &dev_def->prop_val_list) { - pv_pair = node_to_item(pv_pair_node, struct snd_prop_val_pair, list_node); - - list_remove(pv_pair_node); - free(pv_pair->prop); - free(pv_pair->val); - free(pv_pair); - } - free(dev_def); - } -} - -static void snd_free_card_def(struct snd_dev_def_card *card_def) -{ - struct listnode *dev_list; - - if (!card_def) - return; - - dev_list = &card_def->pcm_devs_list; - snd_free_card_devs_def(dev_list); - - dev_list = &card_def->compr_devs_list; - snd_free_card_devs_def(dev_list); - - dev_list = &card_def->mixer_devs_list; - snd_free_card_devs_def(dev_list); - - free(card_def->name); - - free(card_def); -} - -void *snd_card_def_get_card(unsigned int card) -{ - FILE *file; - XML_Parser parser; - void *buf; - int bytes_read, len = 0; - char *snd_card_name = NULL; - bool card_found = false; - struct listnode *snd_card_node, *temp; - struct xml_userdata card_data; - struct snd_dev_def_card *card_def = NULL; - char filename[MAX_PATH]; - - snprintf(filename, MAX_PATH, "/proc/asound/card%d/id", card); - if (access(filename, F_OK ) != -1 ) { - file = fopen(filename, "r"); - if (!file) { - printf("open %s: failed\n", filename); - } else { - snd_card_name = calloc(1, BUF_SIZE); - if (!snd_card_name) - return NULL; - - if (fgets(snd_card_name, BUF_SIZE - 1, file)) { - len = strlen(snd_card_name); - snd_card_name[len - 1] = '\0'; - card = UINT_MAX; - } else { - free(snd_card_name); - snd_card_name = NULL; - } - fclose(file); - } - } - file = NULL; - pthread_rwlock_wrlock(&snd_rwlock); - if (snd_card_list_init == false) { - list_init(&snd_card_list); - snd_card_list_init = true; - } - memset(&card_data, 0, sizeof(card_data)); - - list_for_each_safe(snd_card_node, temp, &snd_card_list) { - card_def = node_to_item(snd_card_node, struct snd_dev_def_card, list_node); - if (snd_card_name) { - if (!strncmp(snd_card_name, card_def->name, strlen(snd_card_name))) - card_found = true; - } else if (card_def->card == card) { - card_found = true; - } - if (card_found) { - card_def->refcnt++; - pthread_rwlock_unlock(&snd_rwlock); - if (snd_card_name != NULL) - free(snd_card_name); - return card_def; - } - } - - card_def = NULL; - /* read XML */ - file = fopen(CARD_DEF_FILE, "r"); - if (!file) { - pthread_rwlock_unlock(&snd_rwlock); - if (snd_card_name != NULL ) - free(snd_card_name); - return NULL; - } - - parser = XML_ParserCreate(NULL); - if (!parser) { - fclose(file); - pthread_rwlock_unlock(&snd_rwlock); - if (snd_card_name != NULL) - free(snd_card_name); - return NULL; - } - - card_data.card = card; - card_data.card_name = snd_card_name; - XML_SetUserData(parser, &card_data); - XML_SetElementHandler(parser, snd_start_tag, snd_end_tag); - XML_SetCharacterDataHandler(parser, snd_data_handler); - - /* parse XML */ - for (;;) { - buf = XML_GetBuffer(parser, BUF_SIZE); - if (buf == NULL) - goto ret; - bytes_read = fread(buf, 1, BUF_SIZE, file); - - if (bytes_read < 0) - goto ret; - - if (XML_ParseBuffer(parser, bytes_read, - bytes_read == 0) == XML_STATUS_ERROR) { - goto ret; - } - - if (bytes_read == 0) - break; - } - - card_def = card_data.cur_card_def; - if (card_def) { - list_add_tail(&snd_card_list, &card_def->list_node); - card_def->refcnt++; - } -ret: - if (snd_card_name != NULL) - free(snd_card_name); - card_data.card_name = NULL; - XML_ParserFree(parser); - fclose(file); - pthread_rwlock_unlock(&snd_rwlock); - return card_def; -} - -void snd_card_def_put_card(void *card_node) -{ - struct snd_dev_def_card *defs = (struct snd_dev_def_card *)card_node; - struct snd_dev_def_card *card_def = NULL; - struct listnode *snd_card_node, *temp; - - if (!defs) - return; - - pthread_rwlock_wrlock(&snd_rwlock); - list_for_each_safe(snd_card_node, temp, &snd_card_list) { - card_def = node_to_item(snd_card_node, struct snd_dev_def_card, list_node); - if (card_def == defs) { - card_def->refcnt--; - if (!card_def->refcnt) { - list_remove(snd_card_node); - snd_free_card_def(card_def); - } - } - } - pthread_rwlock_unlock(&snd_rwlock); -} - -void *snd_card_def_get_node(void *card_node, unsigned int id, int type) -{ - struct snd_dev_def_card *card_def = (struct snd_dev_def_card *)card_node; - struct snd_dev_def *dev_def = NULL; - struct listnode *dev_node, *temp, *devs_list; - - if (!card_def) - return NULL; - - if (type >= SND_NODE_TYPE_MAX) - return NULL; - - pthread_rwlock_rdlock(&snd_rwlock); - if (type == SND_NODE_TYPE_PCM) - devs_list = &card_def->pcm_devs_list; - else if (type == SND_NODE_TYPE_COMPR) - devs_list = &card_def->compr_devs_list; - else - devs_list = &card_def->mixer_devs_list; - - list_for_each_safe(dev_node, temp, devs_list) { - dev_def = node_to_item(dev_node, struct snd_dev_def, list_node); - if (dev_def->device == id) { - pthread_rwlock_unlock(&snd_rwlock); - return dev_def; - } - } - - pthread_rwlock_unlock(&snd_rwlock); - return NULL; -} - -int snd_card_def_get_num_node(void *card_node, int type) -{ - struct snd_dev_def_card *card_def = (struct snd_dev_def_card *)card_node; - struct listnode *temp, *dev_node, *devs_list; - int num_devs = 0; - - if (!card_def) - return 0; - - if (type >= SND_NODE_TYPE_MAX) - return 0; - - pthread_rwlock_rdlock(&snd_rwlock); - if (type == SND_NODE_TYPE_PCM) - devs_list = &card_def->pcm_devs_list; - else if (type == SND_NODE_TYPE_COMPR) - devs_list = &card_def->compr_devs_list; - else - devs_list = &card_def->mixer_devs_list; - - list_for_each_safe(dev_node, temp, devs_list) - num_devs++; - - pthread_rwlock_unlock(&snd_rwlock); - return num_devs; -} - -int snd_card_def_get_nodes_for_type(void *card_node, int type, - void **list, int num_nodes) -{ - struct snd_dev_def_card *card_def = (struct snd_dev_def_card *)card_node; - struct snd_dev_def *dev_def; - struct listnode *temp, *dev_node, *devs_list; - int num_devs = 0, i = 0; - - if (!card_def) - return -EINVAL; - - if (type >= SND_NODE_TYPE_MAX) - return -EINVAL; - - pthread_rwlock_rdlock(&snd_rwlock); - if (type == SND_NODE_TYPE_PCM) - devs_list = &card_def->pcm_devs_list; - else if (type == SND_NODE_TYPE_COMPR) - devs_list = &card_def->compr_devs_list; - else - devs_list = &card_def->mixer_devs_list; - - list_for_each_safe(dev_node, temp, devs_list) - num_devs++; - - if (num_nodes > num_devs) { - pthread_rwlock_unlock(&snd_rwlock); - return -EINVAL; - } - - list_for_each_safe(dev_node, temp, devs_list) { - dev_def = node_to_item(dev_node, struct snd_dev_def, list_node); - list[i++] = dev_def; - if (i == num_nodes) - break; - } - - pthread_rwlock_unlock(&snd_rwlock); - return 0; -} - -int snd_card_def_get_int(void *node, const char *prop, int *val) -{ - struct snd_dev_def *dev_def = (struct snd_dev_def *)node; - struct snd_prop_val_pair *pv_pair; - struct listnode *pv_pair_node, *temp; - int ret = -EINVAL; - - if (!dev_def) - return ret; - - pthread_rwlock_rdlock(&snd_rwlock); - if (!strcmp(prop, "type")) { - *val = dev_def->type; - pthread_rwlock_unlock(&snd_rwlock); - return 0; - } else if (!strcmp(prop, "id")) { - *val = dev_def->device; - pthread_rwlock_unlock(&snd_rwlock); - return 0; - } - - list_for_each_safe(pv_pair_node, temp, &dev_def->prop_val_list) { - pv_pair = node_to_item(pv_pair_node, struct snd_prop_val_pair, list_node); - if (!strcmp(pv_pair->prop, prop)) { - *val = atoi(pv_pair->val); - pthread_rwlock_unlock(&snd_rwlock); - return 0; - } - } - - pthread_rwlock_unlock(&snd_rwlock); - return ret; -} - -int snd_card_def_get_str(void *node, const char *prop, char **val) -{ - struct snd_dev_def *dev_def = (struct snd_dev_def *)node; - struct snd_prop_val_pair *pv_pair; - struct listnode *pv_pair_node, *temp; - int ret = -EINVAL; - - if (!dev_def) - return ret; - - pthread_rwlock_rdlock(&snd_rwlock); - if (!strcmp(prop, "so-name")) { - if (dev_def->so_name) - *val = dev_def->so_name; - - pthread_rwlock_unlock(&snd_rwlock); - return 0; - } - - if (!strcmp(prop, "name")) { - if (dev_def->name) - *val = dev_def->name; - - pthread_rwlock_unlock(&snd_rwlock); - return 0; - } - - list_for_each_safe(pv_pair_node, temp, &dev_def->prop_val_list) { - pv_pair = node_to_item(pv_pair_node, struct snd_prop_val_pair, list_node); - - if (!strcmp(pv_pair->prop, prop)) { - *val = pv_pair->val; - pthread_rwlock_unlock(&snd_rwlock); - return 0; - } - } - - pthread_rwlock_unlock(&snd_rwlock); - return ret; -} diff --git a/qcom/opensource/audio-hal/primary-hal/adsprpcd/Android.bp b/qcom/opensource/audio-hal/primary-hal/adsprpcd/Android.bp index 7d574bc6..3dfa8ed6 100755 --- a/qcom/opensource/audio-hal/primary-hal/adsprpcd/Android.bp +++ b/qcom/opensource/audio-hal/primary-hal/adsprpcd/Android.bp @@ -1,6 +1,6 @@ cc_binary { name: "audioadsprpcd", - + enabled: false, srcs: ["adsprpcd.c"], header_libs: ["libfastrpc_vendor_headers"], diff --git a/qcom/opensource/audio-hal/primary-hal/hal/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/Android.mk deleted file mode 100755 index 69f31888..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/Android.mk +++ /dev/null @@ -1,2 +0,0 @@ - -include $(call all-subdir-makefiles) diff --git a/qcom/opensource/audio-hal/primary-hal/hal/converter/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/converter/Android.mk deleted file mode 100755 index ef399c81..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/converter/Android.mk +++ /dev/null @@ -1,28 +0,0 @@ -LOCAL_PATH := $(call my-dir) -CURRENT_PATH := $(call my-dir) -include $(CLEAR_VARS) -LOCAL_MODULE := libaudioplatformconverter.qti -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_C_INCLUDES += \ - $(LOCAL_PATH)/include - -# { SEC_AUDIO_COMMON -LOCAL_C_INCLUDES += $(TOP)/system/media/audio/include -# } SEC_AUDIO_COMMON - -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include - -LOCAL_SRC_FILES := \ - PlatformConverter.cpp - -LOCAL_SHARED_LIBRARIES := \ - libbase \ - libstagefright_foundation \ - android.hardware.audio.core-V2-ndk \ - android.media.audio.common.types-V3-ndk \ - libar-pal - -include $(BUILD_SHARED_LIBRARY) diff --git a/qcom/opensource/audio-hal/primary-hal/hal/converter/PlatformConverter.cpp b/qcom/opensource/audio-hal/primary-hal/hal/converter/PlatformConverter.cpp deleted file mode 100755 index 882f9cfe..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/converter/PlatformConverter.cpp +++ /dev/null @@ -1,527 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_NDEBUG 0 -#define LOG_TAG "AHAL_PlatformConverter_QTI" - -#include -#include -#include - -// { SEC_AUDIO_COMMON -#include -// } SEC_AUDIO_COMMON - -using ::aidl::android::media::audio::common::AudioChannelLayout; -using ::aidl::android::media::audio::common::AudioDeviceAddress; -using ::aidl::android::media::audio::common::AudioDeviceDescription; -using ::aidl::android::media::audio::common::AudioDeviceType; -using ::aidl::android::media::audio::common::AudioFormatDescription; -using ::aidl::android::media::audio::common::AudioFormatType; -using ::aidl::android::media::audio::common::AudioOutputFlags; -using ::aidl::android::media::audio::common::PcmType; - -// clang-format off -namespace { -__attribute__((no_sanitize("unsigned-integer-overflow"))) -static void hash_combiner(std::size_t& seed, const std::size_t& v) { - // see boost::hash_combine - seed ^= v + 0x9e3779b9 + (seed << 6) + (seed >> 2); -} -} // namespace -// clang-format on - -namespace std { -template <> -struct hash<::aidl::android::media::audio::common::AudioDeviceDescription> { - std::size_t operator()(const ::aidl::android::media::audio::common::AudioDeviceDescription& add) - const noexcept { - std::size_t seed = 0; - hash_combiner(seed, std::hash<::aidl::android::media::audio::common::AudioDeviceType>{}( - add.type)); - hash_combiner(seed, std::hash{}(add.connection)); - return seed; - } -}; - -template <> -struct hash<::aidl::android::media::audio::common::AudioFormatDescription> { - std::size_t operator()(const ::aidl::android::media::audio::common::AudioFormatDescription& aft) - const noexcept { - std::size_t seed = 0; - hash_combiner(seed, std::hash<::aidl::android::media::audio::common::AudioFormatType>{}( - aft.type)); - hash_combiner(seed, std::hash<::aidl::android::media::audio::common::PcmType>{}(aft.pcm)); - hash_combiner(seed, std::hash{}(aft.encoding)); - return seed; - } -}; -} // namespace std - -namespace qti::audio { - -AudioDeviceDescription makeAudioDeviceDescription(AudioDeviceType type, - const std::string& connection = "") { - AudioDeviceDescription result; - result.type = type; - result.connection = connection; - return result; -} - -using DevicePair = std::pair; -using DevicePairs = std::vector; - -using outputFlagsStreamtypeMap = - std::unordered_map; - -// conversions -DevicePairs getDevicePairs() { - // No dupicates on first entry - DevicePairs pairs = { - {AudioDeviceDescription{}, PAL_DEVICE_NONE}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_DEFAULT), PAL_DEVICE_OUT_SPEAKER}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_SPEAKER_EARPIECE), - PAL_DEVICE_OUT_HANDSET}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_SPEAKER), PAL_DEVICE_OUT_SPEAKER}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_HEADPHONE, - AudioDeviceDescription::CONNECTION_ANALOG), - PAL_DEVICE_OUT_WIRED_HEADPHONE}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_DEVICE, - AudioDeviceDescription::CONNECTION_BT_SCO), - PAL_DEVICE_OUT_BLUETOOTH_SCO}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_CARKIT, - AudioDeviceDescription::CONNECTION_BT_SCO), - PAL_DEVICE_OUT_BLUETOOTH_SCO}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_TELEPHONY_TX), PAL_DEVICE_NONE}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_LINE_AUX), PAL_DEVICE_OUT_AUX_LINE}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_SPEAKER_SAFE), PAL_DEVICE_OUT_SPEAKER}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_SPEAKER, - AudioDeviceDescription::CONNECTION_BT_LE), - PAL_DEVICE_OUT_BLUETOOTH_BLE}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_BROADCAST, - AudioDeviceDescription::CONNECTION_BT_LE), - PAL_DEVICE_OUT_BLUETOOTH_BLE_BROADCAST}, - {makeAudioDeviceDescription(AudioDeviceType::IN_DEFAULT), PAL_DEVICE_IN_HANDSET_MIC}, - {makeAudioDeviceDescription(AudioDeviceType::IN_MICROPHONE), PAL_DEVICE_IN_HANDSET_MIC}, - {makeAudioDeviceDescription(AudioDeviceType::IN_MICROPHONE_BACK), - PAL_DEVICE_IN_SPEAKER_MIC}, -#ifdef SEC_AUDIO_COMMON - {makeAudioDeviceDescription(AudioDeviceType::IN_MICROPHONE_MULTI), // AUDIO_DEVICE_IN_2MIC - PAL_DEVICE_IN_SPEAKER_MIC}, - {makeAudioDeviceDescription(AudioDeviceType::IN_MICROPHONE_MULTI, // AUDIO_DEVICE_IN_MIC3 - AudioDeviceDescription::CONNECTION_BUILTIN_MIC3), - PAL_DEVICE_IN_SPEAKER_MIC}, - {makeAudioDeviceDescription(AudioDeviceType::IN_MICROPHONE_MULTI, // AUDIO_DEVICE_IN_MIC4 - AudioDeviceDescription::CONNECTION_BUILTIN_MIC4), - PAL_DEVICE_IN_SPEAKER_MIC}, - {makeAudioDeviceDescription(AudioDeviceType::IN_MICROPHONE_MULTI, // AUDIO_DEVICE_IN_MIC3_MIC4 - AudioDeviceDescription::CONNECTION_BUILTIN_MIC3_MIC4), - PAL_DEVICE_IN_SPEAKER_MIC}, - {makeAudioDeviceDescription(AudioDeviceType::IN_MICROPHONE_MULTI, // AUDIO_DEVICE_IN_MULTI_MIC - AudioDeviceDescription::CONNECTION_BUILTIN_MULTI_MIC), - PAL_DEVICE_IN_SPEAKER_MIC}, -#endif - {makeAudioDeviceDescription(AudioDeviceType::IN_TELEPHONY_RX), - PAL_DEVICE_IN_TELEPHONY_RX}, - - {makeAudioDeviceDescription(AudioDeviceType::IN_ECHO_REFERENCE), - PAL_DEVICE_IN_ECHO_REF}, - {makeAudioDeviceDescription(AudioDeviceType::IN_HEADSET, - AudioDeviceDescription::CONNECTION_ANALOG), - PAL_DEVICE_IN_WIRED_HEADSET}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_ANALOG), - PAL_DEVICE_OUT_WIRED_HEADSET}, - {makeAudioDeviceDescription(AudioDeviceType::IN_HEADSET, - AudioDeviceDescription::CONNECTION_BT_SCO), - PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_BT_SCO), - PAL_DEVICE_OUT_BLUETOOTH_SCO}, - {makeAudioDeviceDescription(AudioDeviceType::IN_DEVICE, - AudioDeviceDescription::CONNECTION_HDMI), - PAL_DEVICE_IN_HDMI}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_DEVICE, - AudioDeviceDescription::CONNECTION_HDMI), - PAL_DEVICE_OUT_AUX_DIGITAL}, - {makeAudioDeviceDescription(AudioDeviceType::IN_ACCESSORY, - AudioDeviceDescription::CONNECTION_USB), - PAL_DEVICE_IN_USB_ACCESSORY}, -#ifdef SEC_AUDIO_FMRADIO - {makeAudioDeviceDescription(AudioDeviceType::IN_FM_TUNER, - AudioDeviceDescription::VX_SEC_CONNECTION_FM), - PAL_DEVICE_IN_FM_TUNER}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_FM, - AudioDeviceDescription::VX_SEC_CONNECTION_FM), - PAL_DEVICE_OUT_FM}, -#else - {makeAudioDeviceDescription(AudioDeviceType::IN_FM_TUNER), PAL_DEVICE_IN_FM_TUNER}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_FM), PAL_DEVICE_OUT_FM}, -#endif - - {makeAudioDeviceDescription(AudioDeviceType::IN_DEVICE, - AudioDeviceDescription::CONNECTION_ANALOG), - PAL_DEVICE_IN_LINE}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_DEVICE, - AudioDeviceDescription::CONNECTION_ANALOG), - PAL_DEVICE_OUT_WIRED_HEADPHONE}, - - {makeAudioDeviceDescription(AudioDeviceType::IN_DEVICE, - AudioDeviceDescription::CONNECTION_SPDIF), - PAL_DEVICE_IN_SPDIF}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_DEVICE, - AudioDeviceDescription::CONNECTION_SPDIF), - PAL_DEVICE_OUT_SPDIF}, - - {makeAudioDeviceDescription(AudioDeviceType::IN_DEVICE, - AudioDeviceDescription::CONNECTION_BT_A2DP), - PAL_DEVICE_IN_BLUETOOTH_A2DP}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_DEVICE, - AudioDeviceDescription::CONNECTION_BT_A2DP), - PAL_DEVICE_OUT_BLUETOOTH_A2DP}, - - {makeAudioDeviceDescription(AudioDeviceType::IN_AFE_PROXY, - AudioDeviceDescription::CONNECTION_VIRTUAL), - PAL_DEVICE_IN_PROXY}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_AFE_PROXY, - AudioDeviceDescription::CONNECTION_VIRTUAL), - PAL_DEVICE_OUT_PROXY}, - - {makeAudioDeviceDescription(AudioDeviceType::IN_DEVICE, - AudioDeviceDescription::CONNECTION_IP_V4), - PAL_DEVICE_IN_RECORD_PROXY}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_DEVICE, - AudioDeviceDescription::CONNECTION_IP_V4), - PAL_DEVICE_OUT_RECORD_PROXY}, - - {makeAudioDeviceDescription(AudioDeviceType::OUT_DEVICE, - AudioDeviceDescription::CONNECTION_USB), - PAL_DEVICE_OUT_USB_DEVICE}, - {makeAudioDeviceDescription(AudioDeviceType::IN_HEADSET, - AudioDeviceDescription::CONNECTION_USB), - PAL_DEVICE_IN_USB_HEADSET}, - {makeAudioDeviceDescription(AudioDeviceType::IN_DEVICE, - AudioDeviceDescription::CONNECTION_USB), - PAL_DEVICE_IN_USB_HEADSET}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_USB), - PAL_DEVICE_OUT_USB_HEADSET}, - - {makeAudioDeviceDescription(AudioDeviceType::IN_HEADSET, - AudioDeviceDescription::CONNECTION_BT_LE), - PAL_DEVICE_IN_BLUETOOTH_BLE}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_BT_LE), - PAL_DEVICE_OUT_BLUETOOTH_BLE}, - {makeAudioDeviceDescription(AudioDeviceType::OUT_HEARING_AID, - AudioDeviceDescription::CONNECTION_WIRELESS), - PAL_DEVICE_OUT_HEARING_AID}}; - return pairs; -} - -// AudioFormat Conversions -AudioFormatDescription make_AudioFormatDescription(AudioFormatType type) { - AudioFormatDescription result; - result.type = type; - return result; -} - -AudioFormatDescription make_AudioFormatDescription(PcmType pcm) { - auto result = make_AudioFormatDescription(AudioFormatType::PCM); - result.pcm = pcm; - return result; -} - -AudioFormatDescription make_AudioFormatDescription(const std::string& encoding) { - AudioFormatDescription result; - result.type = ::aidl::android::media::audio::common::AudioFormatType::NON_PCM; - result.encoding = encoding; - return result; -} - -AudioFormatDescription make_AudioFormatDescription(PcmType transport, const std::string& encoding) { - auto result = make_AudioFormatDescription(encoding); - result.pcm = transport; - return result; -} - -using FormatPair = std::pair; -using FormatPairs = std::vector; - -FormatPairs getFormatPairs() { - // No duplicates on second entry - FormatPairs pairs = {{ - {PAL_AUDIO_FMT_PCM_S16_LE, make_AudioFormatDescription(PcmType::INT_16_BIT)}, - {PAL_AUDIO_FMT_PCM_S8, make_AudioFormatDescription(PcmType::UINT_8_BIT)}, - {PAL_AUDIO_FMT_PCM_S32_LE, make_AudioFormatDescription(PcmType::INT_32_BIT)}, - {PAL_AUDIO_FMT_PCM_S24_LE, make_AudioFormatDescription(PcmType::FIXED_Q_8_24)}, - {PAL_AUDIO_FMT_PCM_S32_LE, make_AudioFormatDescription(PcmType::FLOAT_32_BIT)}, - {PAL_AUDIO_FMT_PCM_S24_3LE, make_AudioFormatDescription(PcmType::INT_24_BIT)}, - {PAL_AUDIO_FMT_AAC, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_MP4)}, - {PAL_AUDIO_FMT_AAC_LATM, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC)}, - {PAL_AUDIO_FMT_AAC_ADTS, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS)}, - {PAL_AUDIO_FMT_AAC_ADIF, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_ADIF)}, - {PAL_AUDIO_FMT_AAC, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_LC)}, -#ifdef SEC_AUDIO_OFFLOAD - {PAL_AUDIO_FMT_AAC_ADTS, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC)}, -#else - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC)}, -#endif - {PAL_AUDIO_FMT_AAC, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V1)}, - {PAL_AUDIO_FMT_AAC, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V2)}, - {PAL_AUDIO_FMT_AAC, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_HE_V1)}, - {PAL_AUDIO_FMT_AAC, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_AAC_HE_V2)}, - {PAL_AUDIO_FMT_MP3, make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_MPEG)}, - {PAL_AUDIO_FMT_FLAC, make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_FLAC)}, - {PAL_AUDIO_FMT_VORBIS, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_VORBIS)}, - {PAL_AUDIO_FMT_ALAC, make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_ALAC)}, - {PAL_AUDIO_FMT_WMA_STD, - make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_WMA)}, - {PAL_AUDIO_FMT_APE, make_AudioFormatDescription("audio/x-ape")}, - {PAL_AUDIO_FMT_WMA_PRO, make_AudioFormatDescription("audio/x-ms-wma.pro")}, - {PAL_AUDIO_FMT_OPUS, make_AudioFormatDescription(::android::MEDIA_MIMETYPE_AUDIO_OPUS)}, - }}; - return pairs; -} - -template -std::map make_DirectMap(const std::vector>& v) { - std::map result(v.begin(), v.end()); - if (result.size() != v.size()) { - LOG(FATAL) << __func__ << "Duplicate key elements detected"; - } - return result; -} - -template -std::map make_ReverseMap(const std::vector>& v) { - std::map result; - std::transform(v.begin(), v.end(), std::inserter(result, result.begin()), - [](const std::pair& p) { return std::make_pair(p.second, p.first); }); - if (result.size() != v.size()) { - LOG(FATAL) << __func__ << "Duplicate key elements detected"; - } - return result; -} - -using AidlToPalDeviceMap = - std::map<::aidl::android::media::audio::common::AudioDeviceDescription, pal_device_id_t>; -using AidlToPalAudioFormatMap = - std::map<::aidl::android::media::audio::common::AudioFormatDescription, pal_audio_fmt_t>; - -const static AidlToPalDeviceMap kAidlToPalDeviceMap = - make_DirectMap(getDevicePairs()); -const static AidlToPalAudioFormatMap kAidlToPalAudioFormatMap = - make_ReverseMap(getFormatPairs()); - -// static -std::unique_ptr PlatformConverter::getPalChannelInfoForChannelCount( - int count) noexcept { - auto channelInfo = std::make_unique(); - channelInfo->channels = count; - if (count == 1) { - channelInfo->ch_map[0] = PAL_CHMAP_CHANNEL_FL; - } else if (count == 2) { - channelInfo->ch_map[0] = PAL_CHMAP_CHANNEL_FL; - channelInfo->ch_map[1] = PAL_CHMAP_CHANNEL_FR; - } else if (count == 3) { - channelInfo->ch_map[0] = PAL_CHMAP_CHANNEL_FL; - channelInfo->ch_map[1] = PAL_CHMAP_CHANNEL_FR; - channelInfo->ch_map[2] = PAL_CHMAP_CHANNEL_C; - } else if (count == 4) { - channelInfo->ch_map[0] = PAL_CHMAP_CHANNEL_FL; - channelInfo->ch_map[1] = PAL_CHMAP_CHANNEL_FR; - channelInfo->ch_map[2] = PAL_CHMAP_CHANNEL_C; - channelInfo->ch_map[3] = PAL_CHMAP_CHANNEL_LFE; - } else if (count == 5) { - channelInfo->ch_map[0] = PAL_CHMAP_CHANNEL_FL; - channelInfo->ch_map[1] = PAL_CHMAP_CHANNEL_FR; - channelInfo->ch_map[2] = PAL_CHMAP_CHANNEL_C; - channelInfo->ch_map[3] = PAL_CHMAP_CHANNEL_LFE; - channelInfo->ch_map[4] = PAL_CHMAP_CHANNEL_RC; - } else if (count == 6) { - channelInfo->ch_map[0] = PAL_CHMAP_CHANNEL_FL; - channelInfo->ch_map[1] = PAL_CHMAP_CHANNEL_FR; - channelInfo->ch_map[2] = PAL_CHMAP_CHANNEL_C; - channelInfo->ch_map[3] = PAL_CHMAP_CHANNEL_LFE; - channelInfo->ch_map[4] = PAL_CHMAP_CHANNEL_LB; - channelInfo->ch_map[5] = PAL_CHMAP_CHANNEL_RB; - } else if (count == 7) { - channelInfo->ch_map[0] = PAL_CHMAP_CHANNEL_FL; - channelInfo->ch_map[1] = PAL_CHMAP_CHANNEL_FR; - channelInfo->ch_map[2] = PAL_CHMAP_CHANNEL_C; - channelInfo->ch_map[3] = PAL_CHMAP_CHANNEL_LFE; - channelInfo->ch_map[4] = PAL_CHMAP_CHANNEL_LB; - channelInfo->ch_map[5] = PAL_CHMAP_CHANNEL_RB; - channelInfo->ch_map[6] = PAL_CHMAP_CHANNEL_LS; - } else if (count == 8) { - channelInfo->ch_map[0] = PAL_CHMAP_CHANNEL_FL; - channelInfo->ch_map[1] = PAL_CHMAP_CHANNEL_FR; - channelInfo->ch_map[2] = PAL_CHMAP_CHANNEL_C; - channelInfo->ch_map[3] = PAL_CHMAP_CHANNEL_LFE; - channelInfo->ch_map[4] = PAL_CHMAP_CHANNEL_LB; - channelInfo->ch_map[5] = PAL_CHMAP_CHANNEL_RB; - channelInfo->ch_map[6] = PAL_CHMAP_CHANNEL_LS; - channelInfo->ch_map[7] = PAL_CHMAP_CHANNEL_RS; - } else { - LOG(ERROR) << __func__ << "channel map not found for channels" << count; - } - return std::move(channelInfo); -} - -// static -uint16_t PlatformConverter::getBitWidthForAidlPCM( - const AudioFormatDescription& aidlFormat) noexcept { - if (aidlFormat.type != AudioFormatType::PCM) { - return 0; - } - if (aidlFormat.pcm == PcmType::UINT_8_BIT) { - return 8; - } else if (aidlFormat.pcm == PcmType::INT_16_BIT) { - return 16; - } else if (aidlFormat.pcm == PcmType::INT_24_BIT) { - return 24; - } else if (aidlFormat.pcm == PcmType::INT_32_BIT) { - return 32; - } else if (aidlFormat.pcm == PcmType::FIXED_Q_8_24) { - return 32; - } else if (aidlFormat.pcm == PcmType::FLOAT_32_BIT) { - return 32; - } - return 0; -} - -#ifdef SEC_AUDIO_SAMSUNGRECORD -uint32_t PlatformConverter::getAudioFormatForAidlPCM( - const AudioFormatDescription& aidlFormat) noexcept { - if (aidlFormat.type != AudioFormatType::PCM) { - return 0xFFFFFFFFu; - } - if (aidlFormat.pcm == PcmType::UINT_8_BIT) { // AUDIO_FORMAT_PCM_8_BIT - return 0x2u; - } else if (aidlFormat.pcm == PcmType::INT_16_BIT) { // AUDIO_FORMAT_PCM_16_BIT - return 0x1u; - } else if (aidlFormat.pcm == PcmType::INT_24_BIT) { // AUDIO_FORMAT_PCM_24_BIT_PACKED - return 0x6u; - } else if (aidlFormat.pcm == PcmType::INT_32_BIT) { // AUDIO_FORMAT_PCM_32_BIT - return 0x3u; - } else if (aidlFormat.pcm == PcmType::FIXED_Q_8_24) { // AUDIO_FORMAT_PCM_8_24_BIT - return 0x4u; - } else if (aidlFormat.pcm == PcmType::FLOAT_32_BIT) { // AUDIO_FORMAT_PCM_FLOAT - return 0x5u; - } - return 0xFFFFFFFFu; -} -#endif - -// static -pal_audio_fmt_t PlatformConverter::getPalFormatId( - const ::aidl::android::media::audio::common::AudioFormatDescription& - formatDescription) noexcept { - auto element = kAidlToPalAudioFormatMap.find(formatDescription); - if (element == kAidlToPalAudioFormatMap.cend()) { - LOG(ERROR) << __func__ << " failed to find corressponding pal format for " - << formatDescription.toString(); - // no format found hence return range end; - // Todo have PAL_AUDIO_FMT_INVALID as 0 - return PAL_AUDIO_FMT_COMPRESSED_RANGE_END; - } - return element->second; -} - -// static -pal_device_id_t PlatformConverter::getPalDeviceId( - const ::aidl::android::media::audio::common::AudioDeviceDescription& - deviceDescription) noexcept { - auto element = kAidlToPalDeviceMap.find(deviceDescription); - if (element == kAidlToPalDeviceMap.cend()) { - LOG(ERROR) << __func__ << " failed to find corressponding pal device for " - << deviceDescription.toString(); - // no device found hence return 0; - return PAL_DEVICE_OUT_MIN; - } - return element->second; -} - -outputFlagsStreamtypeMap populatemOutputFlagsStreamtypeMap() { - outputFlagsStreamtypeMap result; - constexpr auto flagCastToint = [](auto flag) { return static_cast(flag); }; - constexpr auto PrimaryPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::PRIMARY)); -#ifdef SEC_AUDIO_SUPPORT_MEDIA_OUTPUT - result[PrimaryPlaybackFlags] = PAL_STREAM_GENERIC; -#else // qc orig. - result[PrimaryPlaybackFlags] = PAL_STREAM_DEEP_BUFFER; -#endif - constexpr auto deepBufferPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::DEEP_BUFFER)); - result[deepBufferPlaybackFlags] = PAL_STREAM_DEEP_BUFFER; - constexpr auto compressOffloadPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::DIRECT) | - 1 << flagCastToint(AudioOutputFlags::COMPRESS_OFFLOAD) | - 1 << flagCastToint(AudioOutputFlags::NON_BLOCKING) | - 1 << flagCastToint(AudioOutputFlags::GAPLESS_OFFLOAD)); - result[compressOffloadPlaybackFlags] = PAL_STREAM_COMPRESSED; - constexpr auto lowLatencyPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::PRIMARY) | - 1 << flagCastToint(AudioOutputFlags::FAST)); - result[lowLatencyPlaybackFlags] = PAL_STREAM_LOW_LATENCY; - constexpr auto pcmOffloadPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::DIRECT)); - result[pcmOffloadPlaybackFlags] = PAL_STREAM_PCM_OFFLOAD; - constexpr auto voipPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::VOIP_RX)); - result[voipPlaybackFlags] = PAL_STREAM_VOIP_RX; - constexpr auto spatialPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::SPATIALIZER)); - result[spatialPlaybackFlags] = PAL_STREAM_SPATIAL_AUDIO; - constexpr auto ullPlaybackFlags = static_cast( - 1 << flagCastToint(AudioOutputFlags::FAST) | 1 << flagCastToint(AudioOutputFlags::RAW)); - result[ullPlaybackFlags] = PAL_STREAM_ULTRA_LOW_LATENCY; - constexpr auto mmapPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::DIRECT) | - 1 << flagCastToint(AudioOutputFlags::MMAP_NOIRQ)); - result[mmapPlaybackFlags] = PAL_STREAM_ULTRA_LOW_LATENCY; - constexpr auto inCallMusicFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::INCALL_MUSIC)); - result[inCallMusicFlags] = PAL_STREAM_VOICE_CALL_MUSIC; - return result; -} - -const static outputFlagsStreamtypeMap kOutputFlagsStreamtypeMap = - populatemOutputFlagsStreamtypeMap(); -pal_stream_type_t PlatformConverter::getPalStreamTypeId(int32_t outputFlag) noexcept { - return kOutputFlagsStreamtypeMap.at(outputFlag); -} - -// static -std::string PlatformConverter::toString() noexcept { - std::ostringstream os; - os << "### platform conversion start ###" << std::endl; - os << "devices: Aidl to PAL" << std::endl; - for (const auto& [key, value] : kAidlToPalDeviceMap) { - os << key.toString() << " => " << deviceNameLUT.at(value).c_str() << std::endl; - } - os << std::endl << "formats: Aidl to PAL " << std::endl; - for (const auto& [key, value] : kAidlToPalAudioFormatMap) { - os << key.toString() << " => " - << "pal format: 0x" << std::hex << value << std::endl; - } - os << "### platform conversion end ###" << std::endl; - return os.str(); -} - -} // namespace qti::audio diff --git a/qcom/opensource/audio-hal/primary-hal/hal/converter/include/qti-audio/PlatformConverter.h b/qcom/opensource/audio-hal/primary-hal/hal/converter/include/qti-audio/PlatformConverter.h deleted file mode 100755 index 5ccf80fc..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/converter/include/qti-audio/PlatformConverter.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include - -/* AIDL types */ -#include -#include -#include -#include -#include -#include -#include -#include -/* PAL types */ -#include - -namespace qti::audio { - -/** - * monostate singleton class - * APIs are designed to convert any AIDL Audio type to PAL type or vice versa - **/ -class PlatformConverter { - private: - PlatformConverter() = delete; - - PlatformConverter(const PlatformConverter&) = delete; - PlatformConverter& operator=(const PlatformConverter& x) = delete; - - PlatformConverter(PlatformConverter&& other) = delete; - PlatformConverter& operator=(PlatformConverter&& other) = delete; - - public: - static pal_audio_fmt_t getPalFormatId( - const ::aidl::android::media::audio::common::AudioFormatDescription& - formatDescription) noexcept; - static pal_device_id_t getPalDeviceId( - const ::aidl::android::media::audio::common::AudioDeviceDescription& - deviceDescription) noexcept; - static pal_stream_type_t getPalStreamTypeId(int32_t outputFlag) noexcept; - - static uint16_t getBitWidthForAidlPCM( - const ::aidl::android::media::audio::common::AudioFormatDescription&) noexcept; -#ifdef SEC_AUDIO_SAMSUNGRECORD - static uint32_t getAudioFormatForAidlPCM( - const ::aidl::android::media::audio::common::AudioFormatDescription&) noexcept; -#endif - static std::unique_ptr getPalChannelInfoForChannelCount(int count) noexcept; - static std::string toString() noexcept; -}; -} // namespace qti::audio diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/core/Android.mk deleted file mode 100755 index d8027826..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/Android.mk +++ /dev/null @@ -1,118 +0,0 @@ -ifneq ($(AUDIO_USE_STUB_HAL), true) -LOCAL_PATH := $(call my-dir) -CURRENT_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := libaudiocorehal.qti -LOCAL_VENDOR_MODULE := true -LOCAL_MODULE_RELATIVE_PATH := hw - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/include - -LOCAL_CFLAGS := \ - -DBACKEND_NDK \ - -Wall \ - -Wextra \ - -Werror \ - -Wthread-safety - -LOCAL_VINTF_FRAGMENTS := \ - ../../configs/common/manifest_non_qmaa.xml - -LOCAL_VINTF_FRAGMENTS += \ - ../../configs/common/manifest_non_qmaa_extn.xml - -LOCAL_SRC_FILES := \ - CoreService.cpp \ - Bluetooth.cpp \ - Module.cpp \ - ModulePrimary.cpp \ - ModuleStub.cpp \ - SoundDose.cpp \ - Stream.cpp \ - StreamStub.cpp \ - Telephony.cpp \ - StreamInPrimary.cpp \ - StreamOutPrimary.cpp \ - HalOffloadEffects.cpp - -# { SEC_AUDIO_COMMON -SEC_COMMON_HAL_PATH := ../../../../../../samsung/variant/audio/sec_audioreach/hal -LOCAL_SRC_FILES += \ - SecModulePrimary.cpp \ - $(SEC_COMMON_HAL_PATH)/SecFTM.cpp \ - $(SEC_COMMON_HAL_PATH)/AudioEffect.cpp \ - $(SEC_COMMON_HAL_PATH)/AudioDump.cpp -# { SEC_AUDIO_SAMSUNGRECORD -LOCAL_SRC_FILES += \ - $(SEC_COMMON_HAL_PATH)/AudioPreProcess.cpp -# } SEC_AUDIO_SAMSUNGRECORD -# } SEC_AUDIO_COMMON - -LOCAL_HEADER_LIBRARIES := \ - libxsdc-utils \ - libaudioeffects \ - liberror_headers \ - libaudioclient_headers \ - libaudio_system_headers \ - libmedia_helper_headers - -# defaults: [ -# "latest_android_media_audio_common_types_ndk_shared", -# "latest_android_hardware_audio_core_ndk_shared", -# ], -# mk equivalent find a way to fix this in mk file // TODO -# android.media.audio.common.types-V2-ndk \ -# android.hardware.audio.core-V1-ndk - -LOCAL_STATIC_LIBRARIES := \ - libaudiohalutils.qti \ - libaudio_module_config.qti \ - libaudiocore.extension - -LOCAL_WHOLE_STATIC_LIBRARIES := \ - libaudioplatform.qti - -LOCAL_SHARED_LIBRARIES := \ - libaudioaidlcommon \ - libbase \ - libbinder_ndk \ - libcutils \ - liblog \ - libdl \ - libhidlbase \ - libhardware \ - libfmq \ - libmedia_helper \ - libstagefright_foundation \ - libutils \ - libaudioutils \ - libxml2 \ - android.hardware.common-V2-ndk \ - android.media.audio.common.types-V3-ndk \ - android.hardware.audio.core-V2-ndk \ - $(LATEST_ANDROID_HARDWARE_AUDIO_EFFECT) \ - android.hardware.audio.core.sounddose-V1-ndk \ - libar-pal \ - libaudioserviceexampleimpl \ - libaudioplatformconverter.qti \ - qti-audio-types-aidl-V1-ndk - -# { SEC_AUDIO_COMMON -SEC_AUDIO_VARS := vendor/samsung/variant/audio/sec_audioreach_vars.mk -include $(SEC_AUDIO_VARS) -LOCAL_SHARED_LIBRARIES += libsecaudiohalproxy_vendor -# } SEC_AUDIO_COMMON - -ifneq (true,$(call spf_check,SEC_PRODUCT_FEATURE_AUDIO_CONFIG_SPEAKER_AMP,)) - LOCAL_SHARED_LIBRARIES += libspeakercalibration -endif - -include $(BUILD_SHARED_LIBRARY) - -include $(CURRENT_PATH)/fuzzer/Android.mk -include $(CURRENT_PATH)/extensions/Android.mk -include $(CURRENT_PATH)/platform/Android.mk -include $(CURRENT_PATH)/utils/Android.mk -endif \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/Bluetooth.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/Bluetooth.cpp deleted file mode 100755 index ad7be799..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/Bluetooth.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_Bluetooth_QTI" -#include -#include -#include -#include - -using aidl::android::hardware::audio::core::VendorParameter; -using aidl::android::media::audio::common::Boolean; -using aidl::android::media::audio::common::Float; -using aidl::android::media::audio::common::Int; - -namespace qti::audio::core { - -Bluetooth::Bluetooth() { - mScoConfig.isEnabled = Boolean{false}; - mScoConfig.isNrecEnabled = Boolean{false}; - mScoConfig.mode = ScoConfig::Mode::SCO; - mHfpConfig.isEnabled = Boolean{false}; - mHfpConfig.sampleRate = Int{8000}; - mHfpConfig.volume = Float{HfpConfig::VOLUME_MAX}; -} - -ndk::ScopedAStatus Bluetooth::setScoConfig(const ScoConfig& in_config, ScoConfig* _aidl_return) { - if (in_config.isEnabled.has_value()) { - mScoConfig.isEnabled = in_config.isEnabled; - mScoConfig.isEnabled.value().value == true ? mPlatform.setBluetoothParameters("BT_SCO=on") - : mPlatform.setBluetoothParameters("BT_SCO=off"); - /* never call telephony with any lock held*/ - if(auto telephony = mPlatform.getTelephony().lock()) { - // Todo remove the unsafe casting, although we ITelephony is also Telephony - auto tele = static_cast(telephony.get()); - tele->onBluetoothScoEvent(mScoConfig.isEnabled.value().value); - } - } - if (in_config.isNrecEnabled.has_value()) { - mScoConfig.isNrecEnabled = in_config.isNrecEnabled; - mScoConfig.isNrecEnabled.value().value == true - ? mPlatform.setBluetoothParameters("bt_headset_nrec=on") - : mPlatform.setBluetoothParameters("bt_headset_nrec=off"); - } - if (in_config.mode != ScoConfig::Mode::UNSPECIFIED) { - mScoConfig.mode = in_config.mode; - if (mScoConfig.mode == ScoConfig::Mode::SCO) { - mPlatform.setBluetoothParameters("bt_wbs=off"); - } - if (mScoConfig.mode == ScoConfig::Mode::SCO_WB) { - mPlatform.setBluetoothParameters("bt_wbs=on"); - } else if (mScoConfig.mode == ScoConfig::Mode::SCO_SWB) { - mPlatform.setBluetoothParameters("bt_swb=1"); - } - } - if (in_config.debugName.has_value()) { - mScoConfig.debugName = in_config.debugName; - } - *_aidl_return = mScoConfig; - LOG(DEBUG) << __func__ << ": received " << in_config.toString() << ", returning " - << _aidl_return->toString(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Bluetooth::setHfpConfig(const HfpConfig& in_config, HfpConfig* _aidl_return) { - struct str_parms* parms = nullptr; - std::string kvpairs = ""; - if (in_config.sampleRate.has_value() && in_config.sampleRate.value().value <= 0) { - LOG(ERROR) << __func__ << ": invalid sample rate: " << in_config.sampleRate.value().value; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_config.volume.has_value() && - (in_config.volume.value().value < static_cast(HfpConfig::VOLUME_MIN) || - in_config.volume.value().value > static_cast(HfpConfig::VOLUME_MAX))) { - LOG(ERROR) << __func__ << ": invalid volume: " << in_config.volume.value().value; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - if (in_config.isEnabled.has_value()) { - mHfpConfig.isEnabled = in_config.isEnabled; - std::string isEnabled = in_config.isEnabled.value().value?"true":"false"; - kvpairs += "hfp_enable=" + isEnabled + ";"; - } - if (in_config.sampleRate.has_value()) { - mHfpConfig.sampleRate = in_config.sampleRate; - kvpairs += "hfp_set_sampling_rate=" + std::to_string(in_config.sampleRate.value().value) + ";"; - } - if (in_config.volume.has_value()) { - mHfpConfig.volume = in_config.volume; - kvpairs += "hfp_volume=" + std::to_string(in_config.volume.value().value) + ";"; - } - if (!kvpairs.empty()) { - parms = str_parms_create_str(kvpairs.c_str()); - mAudExt.audio_extn_set_parameters(parms); -#ifdef SEC_AUDIO_COMMON - if (parms) - str_parms_destroy(parms); -#endif - } - *_aidl_return = mHfpConfig; - LOG(DEBUG) << __func__ << ": received " << in_config.toString() << ", returning " - << _aidl_return->toString(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus BluetoothA2dp::isEnabled(bool* _aidl_return) { - *_aidl_return = mEnabled; - LOG(DEBUG) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus BluetoothA2dp::setEnabled(bool in_enabled) { - mEnabled = in_enabled; - mEnabled == true ? mPlatform.setBluetoothParameters("A2dpSuspended=false") - : mPlatform.setBluetoothParameters("A2dpSuspended=true"); - LOG(DEBUG) << __func__ << ": " << mEnabled; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus BluetoothA2dp::supportsOffloadReconfiguration(bool* _aidl_return) { - bool supportReconfig = property_get_bool("ro.bluetooth.a2dp_offload.supported", false) && - !property_get_bool("persist.bluetooth.a2dp_offload.disabled", false); - *_aidl_return = supportReconfig; - LOG(DEBUG) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus BluetoothA2dp::reconfigureOffload( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& in_parameters - __unused) { - LOG(DEBUG) << __func__ << ": " << ::android::internal::ToString(in_parameters); - mPlatform.setBluetoothParameters("reconfigA2dp=true"); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus BluetoothLe::isEnabled(bool* _aidl_return) { - *_aidl_return = mEnabled; - LOG(DEBUG) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus BluetoothLe::setEnabled(bool in_enabled) { - mEnabled = in_enabled; - mEnabled == true ? mPlatform.setBluetoothParameters("LeAudioSuspended=false") - : mPlatform.setBluetoothParameters("LeAudioSuspended=true"); - LOG(DEBUG) << __func__ << ": " << mEnabled; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus BluetoothLe::supportsOffloadReconfiguration(bool* _aidl_return) { - *_aidl_return = true; - LOG(DEBUG) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus BluetoothLe::reconfigureOffload( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& in_parameters - __unused) { - LOG(DEBUG) << __func__ << ": " << ::android::internal::ToString(in_parameters); - return ndk::ScopedAStatus::ok(); -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/CoreService.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/CoreService.cpp deleted file mode 100755 index 6b7bffec..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/CoreService.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_CoreService_QTI" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -std::shared_ptr<::qti::audio::core::ModulePrimary> gModuleDefaultQti; - -auto registerBinderAsService = [](auto &&binder, const std::string &serviceName) { - AIBinder_setMinSchedulerPolicy(binder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO); - binder_exception_t status = AServiceManager_addService(binder.get(), serviceName.c_str()); - if (status != EX_NONE) { - LOG(ERROR) << __func__ << " failed to register " << serviceName << " ret:" << status; - } else { - LOG(INFO) << __func__ << " successfully registered " << serviceName << " ret:" << status; - } -}; - -void registerIModuleDefaultQti() { - gModuleDefaultQti = ndk::SharedRefBase::make<::qti::audio::core::ModulePrimary>(); - const std::string kServiceName = - std::string(gModuleDefaultQti->descriptor).append("/").append("default"); - registerBinderAsService(gModuleDefaultQti->asBinder(), kServiceName); -} - -extern "C" __attribute__((visibility("default"))) int32_t registerServices() { - registerIModuleDefaultQti(); - return STATUS_OK; -} diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/HalOffloadEffects.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/HalOffloadEffects.cpp deleted file mode 100755 index b572b4dc..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/HalOffloadEffects.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_HalOffloadEffects_QTI" - -#include -#include -#include - -namespace qti::audio::core { - -HalOffloadEffects::HalOffloadEffects() { - loadLibrary(kOffloadPostProcBundlePath); - loadLibrary(kOffloadVisualizerPath); -// { SEC_AUDIO_SUPPORT_AIDL_EFFECT - loadLibrary(kSecOffloadEffectLibraryPath); -// } SEC_AUDIO_SUPPORT_AIDL_EFFECT -} - -void HalOffloadEffects::loadLibrary(std::string path) { - // dlopen library and dlsym fptr. - std::function dlClose = [](void *handle) -> void { - if (handle && dlclose(handle)) { - LOG(ERROR) << "dlclose failed " << dlerror(); - } - }; - - auto libHandle = - std::unique_ptr{dlopen(path.c_str(), RTLD_LAZY), dlClose}; - if (!libHandle) { - LOG(ERROR) << __func__ << ": dlopen failed for " << path << " " << dlerror(); - return; - } - - // std::unique_ptr effectIntf; - auto effectIntf = new OffloadEffectLibIntf{nullptr, nullptr}; - effectIntf->mStartEffect = (StartEffectFptr)dlsym(libHandle.get(), "startEffect"); - if (!effectIntf->mStartEffect) { - LOG(ERROR) << "startEffect is missing in " << path << dlerror(); - return; - } - effectIntf->mStopEffect = (StopEffectFptr)dlsym(libHandle.get(), "stopEffect"); - if (!effectIntf->mStopEffect) { - LOG(ERROR) << "stopEffect is missing in " << path << dlerror(); - return; - } -// { SEC_AUDIO_VOLUME_MONITOR - effectIntf->mUpdateEffect = (UpdateEffectFptr)dlsym(libHandle.get(), "updateEffect"); - if (!effectIntf->mUpdateEffect) { - LOG(ERROR) << "updateEffect is missing in " << path << dlerror(); - return; - } -// } SEC_AUDIO_VOLUME_MONITOR - LOG(DEBUG) << "found post proc library" << path; - mEffects.emplace_back(std::make_pair(std::move(libHandle), - std::unique_ptr(effectIntf))); -} - -void HalOffloadEffects::startEffect(int ioHandle, pal_stream_handle_t *palHandle) { - for (const auto &effect : mEffects) { - effect.second->mStartEffect(ioHandle, palHandle); - } -} - -void HalOffloadEffects::stopEffect(int ioHandle) { - for (const auto &effect : mEffects) { - effect.second->mStopEffect(ioHandle); - } -} -// { SEC_AUDIO_VOLUME_MONITOR -void HalOffloadEffects::updateEffect(pal_stream_handle_t * palHandle, int updateType) { - for (const auto &effect : mEffects) { - effect.second->mUpdateEffect(palHandle, updateType); - } -} -// } SEC_AUDIO_VOLUME_MONITOR -} // namespace qti::audio::core \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/Module.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/Module.cpp deleted file mode 100755 index 3e07a77d..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/Module.cpp +++ /dev/null @@ -1,1805 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#include - -#define LOG_TAG "AHAL_Module_QTI" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO -#include -#endif -#ifdef SEC_AUDIO_USB_GAIN_CONTROL -#include -#endif - - -using aidl::android::hardware::audio::common::getFrameSizeInBytes; -using aidl::android::hardware::audio::common::isBitPositionFlagSet; -using aidl::android::hardware::audio::common::isValidAudioMode; -using aidl::android::hardware::audio::common::SinkMetadata; -using aidl::android::hardware::audio::common::SourceMetadata; -using aidl::android::hardware::audio::core::sounddose::ISoundDose; -using aidl::android::media::audio::common::AudioChannelLayout; -using aidl::android::media::audio::common::AudioDevice; -using aidl::android::media::audio::common::AudioFormatDescription; -using aidl::android::media::audio::common::AudioFormatType; -using aidl::android::media::audio::common::AudioInputFlags; -using aidl::android::media::audio::common::AudioIoFlags; -using aidl::android::media::audio::common::AudioMMapPolicy; -using aidl::android::media::audio::common::AudioMMapPolicyInfo; -using aidl::android::media::audio::common::AudioMMapPolicyType; -using aidl::android::media::audio::common::AudioMode; -using aidl::android::media::audio::common::AudioOffloadInfo; -using aidl::android::media::audio::common::AudioOutputFlags; -using aidl::android::media::audio::common::AudioPort; -using aidl::android::media::audio::common::AudioPortConfig; -using aidl::android::media::audio::common::AudioPortExt; -using aidl::android::media::audio::common::AudioProfile; -using aidl::android::media::audio::common::Boolean; -using aidl::android::media::audio::common::Int; -using aidl::android::media::audio::common::MicrophoneInfo; -using aidl::android::media::audio::common::PcmType; -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO -using aidl::android::media::audio::common::AudioDeviceType; -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioPortMixExtUseCase; -using aidl::android::media::audio::common::AudioSource; -#endif - -using ::aidl::android::hardware::audio::common::SinkMetadata; -using ::aidl::android::hardware::audio::common::SourceMetadata; -using ::aidl::android::hardware::audio::common::getFrameSizeInBytes; -using ::aidl::android::hardware::audio::common::isBitPositionFlagSet; -using ::aidl::android::hardware::audio::common::isValidAudioMode; - -using ::aidl::android::hardware::audio::core::IStreamOut; -using ::aidl::android::hardware::audio::core::IStreamIn; -using ::aidl::android::hardware::audio::core::AudioPatch; -using ::aidl::android::hardware::audio::core::AudioRoute; -using ::aidl::android::hardware::audio::core::IBluetooth; -using ::aidl::android::hardware::audio::core::VendorParameter; -using ::aidl::android::hardware::audio::core::StreamDescriptor; -using ::aidl::android::hardware::audio::core::sounddose::ISoundDose; - -namespace qti::audio::core { - -namespace { - -bool generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) { - *config = {}; - config->portId = port.id; - if (port.profiles.empty()) { - LOG(ERROR) << __func__ << ": port " << port.id << " has no profiles"; - return false; - } - const auto& profile = port.profiles.begin(); - config->format = profile->format; - if (profile->channelMasks.empty()) { - LOG(ERROR) << __func__ << ": the first profile in port " << port.id - << " has no channel masks"; - return false; - } - config->channelMask = *profile->channelMasks.begin(); - if (profile->sampleRates.empty()) { - LOG(ERROR) << __func__ << ": the first profile in port " << port.id - << " has no sample rates"; - return false; - } - Int sampleRate; - sampleRate.value = *profile->sampleRates.begin(); - config->sampleRate = sampleRate; - config->flags = port.flags; - config->ext = port.ext; - return true; -} - -bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format, - AudioProfile* profile) { - if (auto profilesIt = - find_if(port.profiles.begin(), port.profiles.end(), - [&format](const auto& profile) { return profile.format == format; }); - profilesIt != port.profiles.end()) { - *profile = *profilesIt; - return true; - } - return false; -} - -} // namespace - -std::ostream& operator<<(std::ostream& os, Module::Type t) { - switch (t) { - case Module::Type::DEFAULT: - os << "default"; - break; - case Module::Type::R_SUBMIX: - os << "r_submix"; - break; - case Module::Type::STUB: - os << "stub"; - break; - case Module::Type::USB: - os << "usb"; - break; - } - return os; -} - -Module::Module(Type type) : mType(type) { -#ifndef SEC_AUDIO_COMMON // QC - populateConnectedProfiles(); -#endif -} - -void Module::cleanUpPatch(int32_t patchId) { - erase_all_values(mPatches, std::set{patchId}); -} - -int32_t Module::getNominalLatencyMs(const AudioPortConfig& mixPortConfig) { - // Arbitrary value. Implementations must override this method to provide their actual latency. - static constexpr int32_t kLatencyMs = 5; - return kLatencyMs; -} - -ndk::ScopedAStatus Module::createStreamContext( - int32_t in_portConfigId, int64_t in_bufferSizeFrames, - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCallback> asyncCallback, - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamOutEventCallback> - outEventCallback, - StreamContext* out_context) { - if (in_bufferSizeFrames <= 0) { - LOG(ERROR) << __func__ << ": non-positive buffer size " << in_bufferSizeFrames; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_bufferSizeFrames < kMinimumStreamBufferSizeFrames) { - LOG(ERROR) << __func__ << ": insufficient buffer size " << in_bufferSizeFrames - << ", must be at least " << kMinimumStreamBufferSizeFrames; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - auto& configs = getConfig().portConfigs; - auto portConfigIt = findById(configs, in_portConfigId); - if (portConfigIt->ext.getTag() != AudioPortExt::Tag::mix) { - LOG(ERROR) << __func__ << ": could not find out mix port config " - << portConfigIt->toString(); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - // Since this is a private method, it is assumed that - // validity of the portConfigId has already been checked. - const size_t frameSize = - getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value()); - if (frameSize == 0) { - LOG(ERROR) << __func__ << ": could not calculate frame size for port config " - << portConfigIt->toString(); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - LOG(DEBUG) << __func__ << ": frame size " << frameSize << " bytes"; - if (frameSize > static_cast(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) { - LOG(ERROR) << __func__ << ": buffer size " << in_bufferSizeFrames - << " frames is too large, maximum size is " - << kMaximumStreamBufferSizeBytes / frameSize; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - const auto& flags = portConfigIt->flags.value(); - StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs, - mVendorDebug.forceTransientBurst, - mVendorDebug.forceSynchronousDrain}; - const int32_t& nominalLatency = getNominalLatencyMs(*portConfigIt); - - std::weak_ptr wTelephony; - if (mTelephony) { - wTelephony = mTelephony.getInstance(); - } - - StreamContext temp( - std::make_unique(1, true /*configureEventFlagWord*/), - std::make_unique(1, true /*configureEventFlagWord*/), - portConfigIt->format.value(), portConfigIt->channelMask.value(), - portConfigIt->sampleRate.value().value, - std::make_unique(frameSize * in_bufferSizeFrames), asyncCallback, - outEventCallback, *portConfigIt, params, nominalLatency, wTelephony); - if (temp.isValid()) { - *out_context = std::move(temp); - } else { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - return ndk::ScopedAStatus::ok(); -} - -std::vector Module::findConnectedDevices(int32_t portConfigId) { - std::vector result; - auto& ports = getConfig().ports; - auto portIds = portIdsFromPortConfigIds(findConnectedPortConfigIds(portConfigId)); - for (auto it = portIds.begin(); it != portIds.end(); ++it) { - auto portIt = findById(ports, *it); - if (portIt != ports.end() && portIt->ext.getTag() == AudioPortExt::Tag::device) { - result.push_back(portIt->ext.get().device); - } - } - return result; -} - -std::set Module::findConnectedPortConfigIds(int32_t portConfigId) { - std::set result; - auto patchIdsRange = mPatches.equal_range(portConfigId); - auto& patches = getConfig().patches; - for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) { - auto patchIt = findById(patches, it->second); - if (patchIt == patches.end()) { - LOG(FATAL) << __func__ << ": patch with id " << it->second << " taken from mPatches " - << "not found in the configuration"; - } - if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(), - portConfigId) != patchIt->sourcePortConfigIds.end()) { - result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end()); - } else { - result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end()); - } - } - return result; -} - -ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) { - auto& configs = getConfig().portConfigs; - auto portConfigIt = findById(configs, in_portConfigId); - if (portConfigIt == configs.end()) { - LOG(ERROR) << __func__ << ": existing port config id " << in_portConfigId << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - const int32_t portId = portConfigIt->portId; - // In our implementation, configs of mix ports always have unique IDs. - CHECK(portId != in_portConfigId); - auto& ports = getConfig().ports; - auto portIt = findById(ports, portId); - if (portIt == ports.end()) { - LOG(ERROR) << __func__ << ": port id " << portId << " used by port config id " - << in_portConfigId << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (mStreams.count(in_portConfigId) != 0) { - LOG(ERROR) << __func__ << ": port config id " << in_portConfigId - << " already has a stream opened on it"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - if (portIt->ext.getTag() != AudioPortExt::Tag::mix) { - LOG(ERROR) << __func__ << ": port config id " << in_portConfigId - << " does not correspond to a mix port"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - const size_t maxOpenStreamCount = portIt->ext.get().maxOpenStreamCount; - if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) { - LOG(ERROR) << __func__ << ": port id " << portId - << " has already reached maximum allowed opened stream count: " - << maxOpenStreamCount; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - *port = &(*portIt); - return ndk::ScopedAStatus::ok(); -} - - -static std::vector getStandard16And24BitPcmAudioProfiles() { - auto createStdPcmAudioProfile = [](const PcmType& pcmType) { - return AudioProfile{ - .format = AudioFormatDescription{.type = AudioFormatType::PCM, .pcm = pcmType}, - .channelMasks = {AudioChannelLayout::make( - AudioChannelLayout::LAYOUT_MONO), - AudioChannelLayout::make( - AudioChannelLayout::LAYOUT_STEREO)}, - .sampleRates = {8000, 11025, 16000, 32000, 44100, 48000}}; - }; - return { - createStdPcmAudioProfile(PcmType::INT_16_BIT), - createStdPcmAudioProfile(PcmType::INT_24_BIT), - }; -} - -void Module::populateConnectedProfiles() { - auto& config = getConfig(); - for (const AudioPort& port : config.ports) { - if (port.ext.getTag() == AudioPortExt::device) { - if (auto devicePort = port.ext.get(); - !devicePort.device.type.connection.empty() && port.profiles.empty()) { - if (auto connIt = config.connectedProfiles.find(port.id); - connIt == config.connectedProfiles.end()) { - config.connectedProfiles.emplace( - port.id, getStandard16And24BitPcmAudioProfiles()); - } - } - } - } -} -template -std::set Module::portIdsFromPortConfigIds(C portConfigIds) { - std::set result; - auto& portConfigs = getConfig().portConfigs; - for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) { - auto portConfigIt = findById(portConfigs, *it); - if (portConfigIt != portConfigs.end()) { - result.insert(portConfigIt->portId); - } - } - return result; -} - -std::unique_ptr Module::initializeConfig() { - std::unique_ptr config; -#ifdef SEC_AUDIO_COMMON - switch (getType()) { - case Type::DEFAULT: - case Type::STUB: - config = std::move(ModuleConfig::getPrimaryConfiguration( - Platform::getInstance().isSecAudioFeatureSupported())); - break; - default: - break; - } -#else // QC - switch (getType()) { - case Type::DEFAULT: - config = std::move(ModuleConfig::getPrimaryConfiguration()); - break; - case Type::R_SUBMIX: - break; - case Type::STUB: - // TODO provide stub config - config = std::move(ModuleConfig::getPrimaryConfiguration()); - break; - case Type::USB: - break; - } -#endif - return config; -} - -ModuleConfig& Module::getConfig() { - if (!mConfig) { - mConfig = std::move(initializeConfig()); -#ifdef SEC_AUDIO_COMMON - populateConnectedProfiles(); -#endif - } - return *mConfig; -} - -void Module::registerPatch(const AudioPatch& patch) { - auto& configs = getConfig().portConfigs; - auto do_insert = [&](const std::vector& portConfigIds) { - for (auto portConfigId : portConfigIds) { - auto configIt = findById(configs, portConfigId); - if (configIt != configs.end()) { - mPatches.insert(std::pair{portConfigId, patch.id}); - if (configIt->portId != portConfigId) { - mPatches.insert(std::pair{configIt->portId, patch.id}); - } - } - }; - }; - do_insert(patch.sourcePortConfigIds); - do_insert(patch.sinkPortConfigIds); -} - -ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch, - const AudioPatch& newPatch) { -#ifdef SEC_AUDIO_COMMON - auto& pf = Platform::getInstance(); -#endif - // Notify streams about the new set of devices they are connected to. - auto maybeFailure = ndk::ScopedAStatus::ok(); - using Connections = - std::map>; - Connections oldConnections, newConnections; - auto fillConnectionsHelper = [&](Connections& connections, - const std::vector& mixPortCfgIds, - const std::vector& devicePortCfgIds) { - for (int32_t mixPortCfgId : mixPortCfgIds) { - connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end()); - } - }; - auto fillConnections = [&](Connections& connections, const AudioPatch& patch) { - if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(), - [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) != - patch.sourcePortConfigIds.end()) { - // Sources are mix ports. - fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds); - } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(), - [&](int32_t portConfigId) { - return mStreams.count(portConfigId) > 0; - }) != patch.sinkPortConfigIds.end()) { - // Sources are device ports. - fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds); - } // Otherwise, there are no streams to notify. - }; - fillConnections(oldConnections, oldPatch); - fillConnections(newConnections, newPatch); - - std::for_each(oldConnections.begin(), oldConnections.end(), [&](const auto& connectionPair) { - const int32_t mixPortConfigId = connectionPair.first; - if (auto it = newConnections.find(mixPortConfigId); - it == newConnections.end() || it->second != connectionPair.second) { - if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, {}); - status.isOk()) { -#ifdef SEC_AUDIO_USB_GAIN_CONTROL - const auto connectedDevices = findConnectedDevices(mixPortConfigId); - for (auto& device : connectedDevices) { - if (isOutputAudioDevice(device) && - connectedDevices.size() == 1 && pf.getUSBGainForCombo()) { - pf.setUSBGainForCombo(false); - SecModulePrimary::updateUsbAudioGain(); - break; - } - } -#endif - LOG(DEBUG) << "updateStreamsConnectedState: The " - "stream on port config id " - << mixPortConfigId << " has been disconnected"; - } else { - // Disconnection is tricky to roll back, just - // register a failure. - maybeFailure = std::move(status); - } - } else { -#ifdef SEC_AUDIO_USB_GAIN_CONTROL - const auto connectedDevices = findConnectedDevices(mixPortConfigId); - for (auto& device : connectedDevices) { - if (isOutputAudioDevice(device) && pf.getUSBGainForCombo()) { - pf.setUSBGainForCombo(false); - SecModulePrimary::updateUsbAudioGain(); - break; - } - } -#endif - } - }); - if (!maybeFailure.isOk()) return maybeFailure; - std::set idsToDisconnectOnFailure; - -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - auto& configs = getConfig().portConfigs; - std::vector missingIds; - auto sources = selectByIds(configs, newPatch.sourcePortConfigIds, &missingIds); - auto sinks = selectByIds(configs, newPatch.sinkPortConfigIds, &missingIds); - bool preConditionPassed = false; - if(!sinks.empty() && !sources.empty()) { - if (isMixPortConfig(*(sinks.at(0))) && isDevicePortConfig(*(sources.at(0)))) { - const auto& source = getAudioSource(*(sinks.at(0))); - if (source && source.value() == AudioSource::CAMCORDER && pf.multidevice_rec) { - preConditionPassed = true; - } - } - } -#endif - - std::for_each(newConnections.begin(), newConnections.end(), [&](const auto& connectionPair) { - const int32_t mixPortConfigId = connectionPair.first; - if (auto it = oldConnections.find(mixPortConfigId); - it == oldConnections.end() || it->second != connectionPair.second - || hasBluetoothDevice(findConnectedDevices(mixPortConfigId)) - || hasBluetoothSCODevice(findConnectedDevices(mixPortConfigId)) -#ifdef SEC_AUDIO_USB_GAIN_CONTROL - || hasUsbHeadsetDevice(findConnectedDevices(mixPortConfigId)) -#endif - ) { - const auto connectedDevices = findConnectedDevices(mixPortConfigId); - if (connectedDevices.empty()) { - // This is important as workers use the vector size to - // derive the connection status. - LOG(FATAL) << "updateStreamsConnectedState: No connected " - "devices found for port " - "config id " - << mixPortConfigId; - } -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - std::vector newConnectedDevices = connectedDevices; - if(preConditionPassed) { - for (auto& device : connectedDevices) { - if (pf.isBtScoOn() && device.type.type == AudioDeviceType::IN_MICROPHONE_MULTI && device.type.connection.empty()) { // AUDIO_DEVICE_IN_2MIC - newConnectedDevices.push_back(AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_SCO}); // AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET - break; - } else if (device.type.type == AudioDeviceType::IN_HEADSET && device.type.connection == AudioDeviceDescription::CONNECTION_BT_LE) { - newConnectedDevices.push_back(AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_MULTI}); - } - } - } - if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, newConnectedDevices); -#else - if (auto status = mStreams.setStreamConnectedDevices(mixPortConfigId, connectedDevices); -#endif - status.isOk()) { - LOG(DEBUG) << "updateStreamsConnectedState: The stream on port " - "config id " - << mixPortConfigId << " has been connected to: " - << ::android::internal::ToString(connectedDevices); - } else { - maybeFailure = std::move(status); - idsToDisconnectOnFailure.insert(mixPortConfigId); - } - } - }); - if (!maybeFailure.isOk()) { - LOG(WARNING) << __func__ << ": Due to a failure, disconnecting streams on port config ids " - << ::android::internal::ToString(idsToDisconnectOnFailure); - std::for_each(idsToDisconnectOnFailure.begin(), idsToDisconnectOnFailure.end(), - [&](const auto& portConfigId) { -#ifdef SEC_AUDIO_EARLYDROP_PATCH - auto& ports = getConfig().ports; - std::vector prevDev; - if (auto it = oldConnections.find(portConfigId); it != oldConnections.end()){ - std::vector result; - auto portIds = portIdsFromPortConfigIds((std::set) it->second); - for (auto it = portIds.cbegin(); it != portIds.cend(); ++it) { - auto portIt = findById(ports, *it); - if (portIt != ports.end() && -#ifdef SEC_AUDIO_CALL - (pf.getCallMode() != AUDIO_MODE_IN_CALL) && -#endif - portIt->ext.getTag() == AudioPortExt::Tag::device) { - prevDev.push_back(portIt->ext.get().device); - if (auto status = - mStreams.setStreamConnectedDevices(portConfigId, prevDev); - status.isOk()) { - LOG(DEBUG) << "updateStreamsConnectedState: The stream on port " - "config id " - << portConfigId - << " has been connected to previous device: " - << ::android::internal::ToString(prevDev); - } - } - } - } -#else - auto status = mStreams.setStreamConnectedDevices(portConfigId, {}); - (void)status.isOk(); // Can't do much about a failure here. -#endif - }); - return maybeFailure; - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::setModuleDebug( - const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) { - LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString() - << ", new flags: " << in_debug.toString(); - if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections && - !mConnectedDevicePorts.empty()) { - LOG(ERROR) << __func__ << ": " << mType - << ": attempting to change device connections simulation while having external " - << "devices connected"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - if (in_debug.streamTransientStateDelayMs < 0) { - LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: " - << in_debug.streamTransientStateDelayMs; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - mDebug = in_debug; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getTelephony( - std::shared_ptr<::aidl::android::hardware::audio::core::ITelephony>* _aidl_return) { - *_aidl_return = nullptr; - LOG(DEBUG) << __func__ << ": returning null"; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getBluetooth( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetooth>* _aidl_return) { - *_aidl_return = nullptr; - LOG(DEBUG) << __func__ << ": returning null"; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getBluetoothA2dp( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothA2dp>* _aidl_return) { - *_aidl_return = nullptr; - LOG(DEBUG) << __func__ << ": returning null"; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getBluetoothLe( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothLe>* _aidl_return) { - *_aidl_return = nullptr; - LOG(DEBUG) << __func__ << ": returning null"; - return ndk::ScopedAStatus::ok(); -} - -std::vector<::aidl::android::media::audio::common::AudioProfile> Module::getDynamicProfiles( - const ::aidl::android::media::audio::common::AudioPort& audioPort) { - LOG(INFO) << __func__ << " no-op implementation for " << audioPort.toString(); - return {}; -} - -void Module::onPrepareToDisconnectExternalDevice( - const ::aidl::android::media::audio::common::AudioPort& audioPort __unused) { - LOG(DEBUG) << __func__ << ": do nothing and return"; -} - -ndk::ScopedAStatus Module::prepareToDisconnectExternalDevice(int32_t in_portId) { - auto& ports = getConfig().ports; - auto portIt = findById(ports, in_portId); - if (portIt == ports.end()) { - LOG(ERROR) << __func__ << ": port id " << in_portId << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (portIt->ext.getTag() != AudioPortExt::Tag::device) { - LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - auto connectedPortsIt = mConnectedDevicePorts.find(in_portId); - if (connectedPortsIt == mConnectedDevicePorts.end()) { - LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - onPrepareToDisconnectExternalDevice(*portIt); - - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData, - AudioPort* _aidl_return) { - LOG(DEBUG) << __func__ - << ": requested template port: " << in_templateIdAndAdditionalData.toString(); - const int32_t templateId = in_templateIdAndAdditionalData.id; - auto& ports = getConfig().ports; - AudioPort connectedPort; - { // Scope the template port so that we don't accidentally modify it. - auto templateIt = findById(ports, templateId); - if (templateIt == ports.end()) { - LOG(ERROR) << __func__ << ": port id " << templateId << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (templateIt->ext.getTag() != AudioPortExt::Tag::device) { - LOG(ERROR) << __func__ << ": port id " << templateId << " is not a device port"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (!templateIt->profiles.empty()) { - LOG(ERROR) << __func__ << ": port id " << templateId - << " does not have dynamic profiles"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - auto& templateDevicePort = templateIt->ext.get(); - if (templateDevicePort.device.type.connection.empty()) { - LOG(ERROR) << __func__ << ": port id " << templateId << " is permanently attached"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - // Postpone id allocation until we ensure that there are no client errors. - connectedPort = *templateIt; - connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors; - const auto& inputDevicePort = - in_templateIdAndAdditionalData.ext.get(); - auto& connectedDevicePort = connectedPort.ext.get(); - connectedDevicePort.device.address = inputDevicePort.device.address; - // Check if there is already a connected port with for the same external device. - for (auto connectedPortPair : mConnectedDevicePorts) { - auto connectedPortIt = findById(ports, connectedPortPair.first); - if (connectedPortIt->ext.get().device == - connectedDevicePort.device) { - LOG(ERROR) << __func__ << ": device " << connectedDevicePort.device.toString() - << " is already connected at the device port id " - << connectedPortPair.first; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - } - } - - RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort, templateId)); - if (!mDebug.simulateDeviceConnections) { - if (auto ret = onExternalDeviceConnectionChanged(connectedPort, true /*connected*/); ret) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - - const auto& dynamicProfiles = getDynamicProfiles(in_templateIdAndAdditionalData); - if (dynamicProfiles.size() != 0) { - connectedPort.profiles = dynamicProfiles; - LOG(VERBOSE) << __func__ << ": over writing with dynamic profiles " - << connectedPort.profiles; - } - // At this point it is safe to assume this audio port if of type audio device - if (mTelephony) { - const auto& extDevice = connectedPort.ext.get().device; - mTelephony->onExternalDeviceConnectionChanged(extDevice, true); - } - } else { - auto& connectedProfiles = getConfig().connectedProfiles; - if (auto connectedProfilesIt = connectedProfiles.find(templateId); - connectedProfilesIt != connectedProfiles.end()) { - connectedPort.profiles = connectedProfilesIt->second; - } - } - if (connectedPort.profiles.empty()) { - LOG(ERROR) << "Profiles of a connected port still empty after connecting external device " - << connectedPort.toString(); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - for (auto profile : connectedPort.profiles) { - if (profile.channelMasks.empty()) { - LOG(ERROR) << __func__ << ": the profile " << profile.name << " has no channel masks"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - if (profile.sampleRates.empty()) { - LOG(ERROR) << __func__ << ": the profile " << profile.name << " has no sample rates"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - } - - connectedPort.id = getConfig().nextPortId++; - auto[connectedPortsIt, _] = - mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set())); - ports.push_back(connectedPort); - - std::vector routablePortIds; - std::vector newRoutes; - auto& routes = getConfig().routes; - for (auto& r : routes) { - if (r.sinkPortId == templateId) { - AudioRoute newRoute; - newRoute.sourcePortIds = r.sourcePortIds; - newRoute.sinkPortId = connectedPort.id; - newRoute.isExclusive = r.isExclusive; - newRoutes.push_back(std::move(newRoute)); - routablePortIds.insert(routablePortIds.end(), r.sourcePortIds.begin(), - r.sourcePortIds.end()); - } else { - auto& srcs = r.sourcePortIds; - if (std::find(srcs.begin(), srcs.end(), templateId) != srcs.end()) { - srcs.push_back(connectedPort.id); - routablePortIds.push_back(r.sinkPortId); - } - } - } - routes.insert(routes.end(), newRoutes.begin(), newRoutes.end()); - - // Note: this is a simplistic approach assuming that a mix port can only be populated - // from a single device port. Implementing support for stuffing dynamic profiles with a superset - // of all profiles from all routable dynamic device ports would be more involved. - for (const auto mixPortId : routablePortIds) { - auto portsIt = findById(ports, mixPortId); - if (portsIt != ports.end()) { - if (portsIt->profiles.empty()) { - portsIt->profiles = connectedPort.profiles; - connectedPortsIt->second.insert(portsIt->id); - } else { - // Check if profiles are non empty because they were populated - // by a previous connection. Otherwise, it means that they are - // not empty because the mix port has static profiles. - for (const auto cp : mConnectedDevicePorts) { - if (cp.second.count(portsIt->id) > 0) { - connectedPortsIt->second.insert(portsIt->id); - break; - } - } - } - } - } - *_aidl_return = std::move(connectedPort); - LOG(DEBUG) << __func__ << ": for template port ID: " << templateId - << " created new external device port: " << _aidl_return->toString(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) { - auto& ports = getConfig().ports; - auto portIt = findById(ports, in_portId); - if (portIt == ports.end()) { - LOG(ERROR) << __func__ << ": port id " << in_portId << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (portIt->ext.getTag() != AudioPortExt::Tag::device) { - LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a device port"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - auto connectedPortsIt = mConnectedDevicePorts.find(in_portId); - if (connectedPortsIt == mConnectedDevicePorts.end()) { - LOG(ERROR) << __func__ << ": port id " << in_portId << " is not a connected device port"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - auto& configs = getConfig().portConfigs; - auto& initials = getConfig().initialConfigs; - auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) { - if (config.portId == in_portId) { - // Check if the configuration was provided by the client. - const auto& initialIt = findById(initials, config.id); - return initialIt == initials.end() || config != *initialIt; - } - return false; - }); - if (configIt != configs.end()) { - LOG(ERROR) << __func__ << ": port id " << in_portId << " has a non-default config with id " - << configIt->id; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - // upon this point let platform know about disconnection. - if (int ret = onExternalDeviceConnectionChanged(*portIt, false /*connected*/); ret) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - if (mTelephony) { - const auto& extDevice = portIt->ext.get().device; - mTelephony->onExternalDeviceConnectionChanged(extDevice, false); - } - - LOG(DEBUG) << __func__ << ": removed device port " << portIt->toString(); - ports.erase(portIt); - - auto& routes = getConfig().routes; - for (auto routesIt = routes.begin(); routesIt != routes.end();) { - if (routesIt->sinkPortId == in_portId) { - routesIt = routes.erase(routesIt); - } else { - // Note: the list of sourcePortIds can't become empty because there must - // be the id of the template port in the route. - erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; }); - ++routesIt; - } - } - - // Clear profiles for mix ports that are not connected to any other ports. - std::set mixPortsToClear = std::move(connectedPortsIt->second); - mConnectedDevicePorts.erase(connectedPortsIt); - for (const auto& connectedPort : mConnectedDevicePorts) { - for (int32_t mixPortId : connectedPort.second) { - mixPortsToClear.erase(mixPortId); - } - } - for (int32_t mixPortId : mixPortsToClear) { - auto mixPortIt = findById(ports, mixPortId); - if (mixPortIt != ports.end()) { - mixPortIt->profiles = {}; - } - } - - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getAudioPatches(std::vector* _aidl_return) { - *_aidl_return = getConfig().patches; - LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " patches"; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) { - auto& ports = getConfig().ports; - auto portIt = findById(ports, in_portId); - if (portIt != ports.end()) { - *_aidl_return = *portIt; - LOG(DEBUG) << __func__ << ": returning port by id " << in_portId; - return ndk::ScopedAStatus::ok(); - } - LOG(ERROR) << __func__ << ": port id " << in_portId << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); -} - -ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector* _aidl_return) { - *_aidl_return = getConfig().portConfigs; - LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " port configs"; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getAudioPorts(std::vector* _aidl_return) { - *_aidl_return = getConfig().ports; - LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " ports"; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getAudioRoutes(std::vector* _aidl_return) { - *_aidl_return = getConfig().routes; - LOG(DEBUG) << __func__ << ": returning " << _aidl_return->size() << " routes"; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId, - std::vector* _aidl_return) { - auto& ports = getConfig().ports; - if (auto portIt = findById(ports, in_portId); portIt == ports.end()) { - LOG(ERROR) << __func__ << ": port id " << in_portId << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - auto& routes = getConfig().routes; - std::copy_if(routes.begin(), routes.end(), std::back_inserter(*_aidl_return), - [&](const auto& r) { - const auto& srcs = r.sourcePortIds; - return r.sinkPortId == in_portId || - std::find(srcs.begin(), srcs.end(), in_portId) != srcs.end(); - }); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args, - OpenInputStreamReturn* _aidl_return) { - LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", buffer size " - << in_args.bufferSizeFrames << " frames"; - AudioPort* port = nullptr; - RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port)); - if (port->flags.getTag() != AudioIoFlags::Tag::input) { - LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId - << " does not correspond to an input mix port"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - StreamContext context; - RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, - nullptr, nullptr, &context)); - context.fillDescriptor(&_aidl_return->desc); - std::shared_ptr stream; -#ifdef SEC_AUDIO_SAMSUNGRECORD - auto& platform = Platform::getInstance(); - int32_t unconfiguredFlags = platform.getUnconfiguredFlagsReceived(); - if(unconfiguredFlags) { - context.setFlags(AudioIoFlags::make(unconfiguredFlags)); - platform.setUnconfiguredFlagsReceived(0); - } -#endif - RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata, - mConfig->microphones, &stream)); - StreamWrapper streamWrapper(stream); - if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) { - RETURN_STATUS_IF_ERROR( - streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId))); - } - - if (hasInputMMapFlag(port->flags)) { - int32_t fd, mmapFlags, bufferSizeFrames; - int64_t burstSizeFrames; - RETURN_STATUS_IF_ERROR(streamWrapper.configureMMapStream(&fd, &burstSizeFrames, &mmapFlags, - &bufferSizeFrames)); - _aidl_return->desc.audio.set(); - auto& mmapRef = _aidl_return->desc.audio - .get(); - mmapRef.sharedMemory.fd = ndk::ScopedFileDescriptor{fd}; - mmapRef.burstSizeFrames = burstSizeFrames; - mmapRef.flags = mmapFlags; - _aidl_return->desc.bufferSizeFrames = bufferSizeFrames; - } - - auto streamBinder = streamWrapper.getBinder(); - AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO); - AIBinder_setInheritRt(streamBinder.get(), true); - mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper)); - _aidl_return->stream = std::move(stream); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args, - OpenOutputStreamReturn* _aidl_return) { - LOG(DEBUG) << __func__ << ": port config id " << in_args.portConfigId << ", has offload info? " - << (in_args.offloadInfo.has_value()) << ", buffer size " << in_args.bufferSizeFrames - << " frames"; - AudioPort* port = nullptr; - RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port)); - if (port->flags.getTag() != AudioIoFlags::Tag::output) { - LOG(ERROR) << __func__ << ": port config id " << in_args.portConfigId - << " does not correspond to an output mix port"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - const bool isOffload = isBitPositionFlagSet(port->flags.get(), - AudioOutputFlags::COMPRESS_OFFLOAD); - if (isOffload && !in_args.offloadInfo.has_value()) { - LOG(ERROR) << __func__ << ": port id " << port->id - << " has COMPRESS_OFFLOAD flag set, requires offload info"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - const bool isNonBlocking = isBitPositionFlagSet(port->flags.get(), - AudioOutputFlags::NON_BLOCKING); - if (isNonBlocking && in_args.callback == nullptr) { - LOG(ERROR) << __func__ << ": port id " << port->id - << " has NON_BLOCKING flag set, requires async callback"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - StreamContext context; -#ifdef SEC_AUDIO_SUPPORT_UHQ - auto& pf = Platform::getInstance(); - int32_t uhqBufferSizeFrames = in_args.bufferSizeFrames; - if (!hasOutputMMapFlag(port->flags) && pf.isSecAudioFeatureSupported()) { - uhqBufferSizeFrames *= AUDIO_SAMPLINGRATE_SUHQ_RATIO; - } - RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, uhqBufferSizeFrames, - isNonBlocking ? in_args.callback : nullptr, - in_args.eventCallback, &context)); -#else - RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames, - isNonBlocking ? in_args.callback : nullptr, - in_args.eventCallback, &context)); -#endif - context.fillDescriptor(&_aidl_return->desc); - std::shared_ptr stream; - RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata, - in_args.offloadInfo, &stream)); - StreamWrapper streamWrapper(stream); - if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) { - RETURN_STATUS_IF_ERROR( - streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId))); - } - - if (hasOutputMMapFlag(port->flags)) { - int32_t fd, mmapFlags, bufferSizeFrames; - int64_t burstSizeFrames; - RETURN_STATUS_IF_ERROR(streamWrapper.configureMMapStream(&fd, &burstSizeFrames, &mmapFlags, - &bufferSizeFrames)); - _aidl_return->desc.audio.set(); - auto& mmapRef = _aidl_return->desc.audio - .get(); - mmapRef.sharedMemory.fd = ndk::ScopedFileDescriptor{fd}; - mmapRef.burstSizeFrames = burstSizeFrames; - mmapRef.flags = mmapFlags; - _aidl_return->desc.bufferSizeFrames = bufferSizeFrames; - } else if (mTelephony && hasOutputVoipRxFlag(port->flags)) { - // TODO remove this way of handling streams for telephony - mTelephony.getInstance()->setVoipPlaybackStream(stream); - } - - auto streamBinder = streamWrapper.getBinder(); - AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO); - AIBinder_setInheritRt(streamBinder.get(), true); - mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper)); - // Module::updateStreamOutList(stream); - _aidl_return->stream = std::move(stream); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors( - SupportedPlaybackRateFactors* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) { - LOG(INFO) << __func__ << ": requested patch " << in_requested.toString(); - if (in_requested.sourcePortConfigIds.empty()) { - LOG(ERROR) << __func__ << ": requested patch has empty sources list"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (!all_unique(in_requested.sourcePortConfigIds)) { - LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sources list"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_requested.sinkPortConfigIds.empty()) { - LOG(ERROR) << __func__ << ": requested patch has empty sinks list"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (!all_unique(in_requested.sinkPortConfigIds)) { - LOG(ERROR) << __func__ << ": requested patch has duplicate ids in the sinks list"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - auto& configs = getConfig().portConfigs; - std::vector missingIds; - auto sources = - selectByIds(configs, in_requested.sourcePortConfigIds, &missingIds); - if (!missingIds.empty()) { - LOG(ERROR) << __func__ << ": following source port config ids not found: " - << ::android::internal::ToString(missingIds); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - auto sinks = selectByIds(configs, in_requested.sinkPortConfigIds, &missingIds); - if (!missingIds.empty()) { - LOG(ERROR) << __func__ << ": following sink port config ids not found: " - << ::android::internal::ToString(missingIds); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - // bool indicates whether a non-exclusive route is available. - // If only an exclusive route is available, that means the patch can not be - // established if there is any other patch which currently uses the sink port. - std::map allowedSinkPorts; - auto& routes = getConfig().routes; - for (auto src : sources) { - for (const auto& r : routes) { - const auto& srcs = r.sourcePortIds; - if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) { - if (!allowedSinkPorts[r.sinkPortId]) { // prefer non-exclusive - allowedSinkPorts[r.sinkPortId] = !r.isExclusive; - } - } - } - } - for (auto sink : sinks) { - if (allowedSinkPorts.count(sink->portId) == 0) { - LOG(ERROR) << __func__ << ": there is no route to the sink port id " << sink->portId; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - } - - RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks)); - - auto& patches = getConfig().patches; - auto existing = patches.end(); - std::optional patchesBackup; - AudioPatch oldPatch{}; - if (in_requested.id != 0) { - existing = findById(patches, in_requested.id); - if (existing != patches.end()) { - patchesBackup = mPatches; - cleanUpPatch(existing->id); - } else { - LOG(ERROR) << __func__ << ": not found existing patch id " << in_requested.id; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - } - // Validate the requested patch. - for (const auto & [ sinkPortId, nonExclusive ] : allowedSinkPorts) { - if (!nonExclusive && mPatches.count(sinkPortId) != 0) { - LOG(ERROR) << __func__ << ": sink port id " << sinkPortId - << "is exclusive and is already used by some other patch"; - if (patchesBackup.has_value()) { - mPatches = std::move(*patchesBackup); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - } - - *_aidl_return = in_requested; - if (existing == patches.end()) { - // this suggests to create a new patch. - _aidl_return->id = getConfig().nextPatchId++; - _aidl_return->minimumStreamBufferSizeFrames = kMinimumStreamBufferSizeFrames; - _aidl_return->latenciesMs.clear(); - // LatencyMs for a new patch is provided with arbitary value. - // Real LatencyMs is fetched via StreamDescriptor::Reply::latencyMs - constexpr int32_t kLatencyMsDefault = 10; - _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(), - _aidl_return->sinkPortConfigIds.size(), kLatencyMsDefault); - onNewPatchCreation(sources, sinks, *_aidl_return); - patches.push_back(*_aidl_return); - } else { - if (in_requested.id == 0 ) { - _aidl_return->id = existing->id; - LOG(DEBUG) << __func__ << "patch id 0 updated to existing patch id " << existing->id; - } - // this suggests to update the existing patch. - oldPatch = *existing; - // update the existing patch to requested patch in module config. - *existing = *_aidl_return; - } - patchesBackup = mPatches; - registerPatch(*_aidl_return); - auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); - - // call this after streams devices got updated - setAudioPatchTelephony(sources, sinks, *_aidl_return); - - if (!status.isOk()) { - mPatches = std::move(*patchesBackup); - if (existing == patches.end()) { - patches.pop_back(); - } else { - *existing = oldPatch; - } - return status; - } - - if (oldPatch.id == 0) { - LOG(INFO) << __func__ << ": " - << "created " << getPatchDetails(*_aidl_return) << " " - << _aidl_return->toString(); - } else { -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - LOG(INFO) << __func__ << ": " - << "updated to " << getPatchDetails(*_aidl_return); -#endif - - LOG(INFO) << __func__ << ": " - << "updated from " << getPatchDetails(oldPatch) << " " << oldPatch.toString() - << " to " << getPatchDetails(*_aidl_return) << " " << _aidl_return->toString(); - } - return ndk::ScopedAStatus::ok(); -} - -void Module::onNewPatchCreation(const std::vector& sources, - const std::vector& sinks, AudioPatch& newPatch) { - LOG(INFO) << __func__ << " no-op implementation " << newPatch.toString(); - return; -} - -std::string Module::portNameFromPortConfigIds(int portConfigId) { - auto& portConfigs = getConfig().portConfigs; - auto portConfigIt = findById(portConfigs, portConfigId); - if (portConfigIt != portConfigs.end()) { - auto& ports = getConfig().ports; - auto portIt = findById(ports, portConfigIt->portId); - return portIt->name; - } - - return ""; -} - -std::string Module::getPatchDetails( - const ::aidl::android::hardware::audio::core::AudioPatch& patch) { - auto sourcePortConfigs = patch.sourcePortConfigIds; - auto sinkPortConfigs = patch.sinkPortConfigIds; - - std::string result = "["; - - for (auto src : sourcePortConfigs) { - result += portNameFromPortConfigIds(src); - result += " "; - } - - result += " -> "; - - for (auto sink : sinkPortConfigs) { - result += portNameFromPortConfigIds(sink); - result += " "; - } - - result += " ]"; - return result; -} - -void Module::setAudioPatchTelephony( - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sources, - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sinks, - const ::aidl::android::hardware::audio::core::AudioPatch& patch) { - LOG(INFO) << __func__ << " no-op implementation "; - return; -} - -void Module::resetAudioPatchTelephony(const AudioPatch& patch) { - LOG(INFO) << __func__ << " no-op implementation "; -} - -ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested, - AudioPortConfig* out_suggested, bool* _aidl_return) { - LOG(DEBUG) << __func__ << ": requested " << in_requested.toString(); - auto& configs = getConfig().portConfigs; - auto existing = configs.end(); - if (in_requested.id != 0) { - if (existing = findById(configs, in_requested.id); - existing == configs.end()) { - LOG(ERROR) << __func__ << ": existing port config id " << in_requested.id - << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - } - - const int portId = existing != configs.end() ? existing->portId : in_requested.portId; - if (portId == 0) { - LOG(ERROR) << __func__ << ": input port config does not specify portId"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - auto& ports = getConfig().ports; - auto portIt = findById(ports, portId); - if (portIt == ports.end()) { - LOG(ERROR) << __func__ << ": input port config points to non-existent portId " << portId; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (existing != configs.end()) { - *out_suggested = *existing; - } else { - AudioPortConfig newConfig; - if (generateDefaultPortConfig(*portIt, &newConfig)) { - *out_suggested = newConfig; - } else { - LOG(ERROR) << __func__ << ": unable generate a default config for port " << portId; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - } - // From this moment, 'out_suggested' is either an existing port config, - // or a new generated config. Now attempt to update it according to the specified - // fields of 'in_requested'. - - bool requestedIsValid = true, requestedIsFullySpecified = true; - - AudioIoFlags portFlags = portIt->flags; - if (in_requested.flags.has_value()) { - if (in_requested.flags.value() != portFlags) { - LOG(WARNING) << __func__ << ": requested flags " - << in_requested.flags.value().toString() << " do not match port's " - << portId << " flags " << portFlags.toString(); - requestedIsValid = false; - } - } else { - requestedIsFullySpecified = false; - } - - AudioProfile portProfile; - if (in_requested.format.has_value()) { - const auto& format = in_requested.format.value(); - if (findAudioProfile(*portIt, format, &portProfile)) { - out_suggested->format = format; - } else { - LOG(WARNING) << __func__ << ": requested format " << format.toString() - << " is not found in port's " << portId << " profiles"; - requestedIsValid = false; - } - } else { - requestedIsFullySpecified = false; - } - if (!findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) { - LOG(ERROR) << __func__ << ": port " << portId << " does not support format " - << out_suggested->format.value().toString() << " anymore"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - if (in_requested.channelMask.has_value()) { - const auto& channelMask = in_requested.channelMask.value(); - if (find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) != - portProfile.channelMasks.end()) { - out_suggested->channelMask = channelMask; - } else { - LOG(WARNING) << __func__ << ": requested channel mask " << channelMask.toString() - << " is not supported for the format " << portProfile.format.toString() - << " by the port " << portId; - requestedIsValid = false; - } - } else { - requestedIsFullySpecified = false; - } - - if (in_requested.sampleRate.has_value()) { - const auto& sampleRate = in_requested.sampleRate.value(); - if (find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(), - sampleRate.value) != portProfile.sampleRates.end()) { - out_suggested->sampleRate = sampleRate; - } else { - LOG(WARNING) << __func__ << ": requested sample rate " << sampleRate.value - << " is not supported for the format " << portProfile.format.toString() - << " by the port " << portId; - requestedIsValid = false; - } - } else { - requestedIsFullySpecified = false; - } - - if (in_requested.gain.has_value()) { - // Let's pretend that gain can always be applied. - out_suggested->gain = in_requested.gain.value(); - } - - if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) { - if (in_requested.ext.getTag() == out_suggested->ext.getTag()) { - if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) { - // 'AudioMixPortExt.handle' is set by the client, copy from in_requested - out_suggested->ext.get().handle = - in_requested.ext.get().handle; - out_suggested->ext.get().usecase = - in_requested.ext.get().usecase; - } - } else { - LOG(WARNING) << __func__ << ": requested ext tag " - << toString(in_requested.ext.getTag()) << " do not match port's tag " - << toString(out_suggested->ext.getTag()); - requestedIsValid = false; - } - } - - if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) { - out_suggested->id = getConfig().nextPortId++; - configs.push_back(*out_suggested); - *_aidl_return = true; - auto portName = portNameFromPortConfigIds(out_suggested->id); - LOG(DEBUG) << __func__ << ": created new port config for " << portName << " " - << out_suggested->toString(); - } else if (existing != configs.end() && requestedIsValid) { - *existing = *out_suggested; - *_aidl_return = true; - auto portName = portNameFromPortConfigIds(out_suggested->id); - LOG(DEBUG) << __func__ << ": updated port config for" << portName << " " - << out_suggested->toString(); - } else { - LOG(DEBUG) << __func__ << ": not applied; existing config ? " << (existing != configs.end()) - << "; requested is valid? " << requestedIsValid << ", fully specified? " - << requestedIsFullySpecified; - *_aidl_return = false; - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) { - auto& patches = getConfig().patches; - auto patchIt = findById(patches, in_patchId); - if (patchIt != patches.end()) { - resetAudioPatchTelephony(*patchIt); - auto patchesBackup = mPatches; - cleanUpPatch(patchIt->id); - if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) { - mPatches = std::move(patchesBackup); - return status; - } - std::string patchDetails = getPatchDetails(*patchIt); - patches.erase(patchIt); - LOG(DEBUG) << __func__ << ": erased patch " << in_patchId << " " << patchDetails; - return ndk::ScopedAStatus::ok(); - } - LOG(ERROR) << __func__ << ": patch id " << in_patchId << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); -} - -ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) { - auto& configs = getConfig().portConfigs; - auto configIt = findById(configs, in_portConfigId); - if (configIt != configs.end()) { - if (mStreams.count(in_portConfigId) != 0) { - LOG(ERROR) << __func__ << ": port config id " << in_portConfigId - << " has a stream opened on it"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - auto patchIt = mPatches.find(in_portConfigId); - if (patchIt != mPatches.end()) { - LOG(ERROR) << __func__ << ": port config id " << in_portConfigId - << " is used by the patch with id " << patchIt->second; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - auto& initials = getConfig().initialConfigs; - auto initialIt = findById(initials, in_portConfigId); - auto relatedPortName = portNameFromPortConfigIds(in_portConfigId); - if (initialIt == initials.end()) { - configs.erase(configIt); - LOG(DEBUG) << __func__ << ": erased port config " << in_portConfigId << " " - << relatedPortName; - } else if (*configIt != *initialIt) { - *configIt = *initialIt; - LOG(DEBUG) << __func__ << ": reset port config " << in_portConfigId << " " - << relatedPortName; - } - return ndk::ScopedAStatus::ok(); - } - LOG(ERROR) << __func__ << ": port config id " << in_portConfigId << " not found"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); -} - -ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) { - *_aidl_return = mMasterMute; - LOG(DEBUG) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::setMasterMute(bool in_mute) { - LOG(DEBUG) << __func__ << ": " << in_mute; - auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok() - : onMasterMuteChanged(in_mute); - if (result.isOk()) { - mMasterMute = in_mute; - } else { - LOG(ERROR) << __func__ << ": failed calling onMasterMuteChanged(" << in_mute - << "), error=" << result; - // Reset master mute if it failed. - onMasterMuteChanged(mMasterMute); - } - return std::move(result); -} - -ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) { - *_aidl_return = mMasterVolume; - LOG(DEBUG) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::setMasterVolume(float in_volume) { - LOG(DEBUG) << __func__ << ": " << in_volume; - if (in_volume >= 0.0f && in_volume <= 1.0f) { - auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok() - : onMasterVolumeChanged(in_volume); - if (result.isOk()) { - mMasterVolume = in_volume; - } else { - // Reset master volume if it failed. - LOG(ERROR) << __func__ << ": failed calling onMasterVolumeChanged(" << in_volume - << "), error=" << result; - onMasterVolumeChanged(mMasterVolume); - } - return std::move(result); - } - LOG(ERROR) << __func__ << ": invalid master volume value: " << in_volume; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); -} - -ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) { - LOG(ERROR) << __func__ << ": not implemented " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::setMicMute(bool in_mute) { - LOG(ERROR) << __func__ << ": not implemented" << in_mute; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getMicrophones(std::vector* _aidl_return) { - *_aidl_return = getConfig().microphones; - LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) { - if (!isValidAudioMode(in_mode)) { - LOG(ERROR) << __func__ << ": invalid mode " << toString(in_mode); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - // No checks for supported audio modes here, it's an informative notification. - LOG(DEBUG) << __func__ << ": " << toString(in_mode); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) { - LOG(DEBUG) << __func__ << ": " << toString(in_rotation); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) { - LOG(DEBUG) << __func__ << ": " << in_isTurnedOn; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getSoundDose( - std::shared_ptr<::aidl::android::hardware::audio::core::sounddose::ISoundDose>* - _aidl_return) { - if (!mSoundDose) { - mSoundDose = ndk::SharedRefBase::make(); - } - *_aidl_return = mSoundDose.getInstance(); - LOG(DEBUG) << __func__ << ": returning instance of ISoundDose: " << _aidl_return->get(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst"; -const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain"; - -ndk::ScopedAStatus Module::getVendorParameters(const std::vector& in_ids, - std::vector* _aidl_return) { - LOG(DEBUG) << __func__ << ": id count: " << in_ids.size(); - bool allParametersKnown = true; - for (const auto& id : in_ids) { - if (id == VendorDebug::kForceTransientBurstName) { - VendorParameter forceTransientBurst{.id = id}; - forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst}); - _aidl_return->push_back(std::move(forceTransientBurst)); - } else if (id == VendorDebug::kForceSynchronousDrainName) { - VendorParameter forceSynchronousDrain{.id = id}; - forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain}); - _aidl_return->push_back(std::move(forceSynchronousDrain)); - } else { - allParametersKnown = false; - LOG(ERROR) << __func__ << ": unrecognized parameter \"" << id << "\""; - } - } - if (allParametersKnown) return ndk::ScopedAStatus::ok(); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); -} - -ndk::ScopedAStatus Module::setVendorParameters(const std::vector& in_parameters, - bool in_async) { - LOG(DEBUG) << __func__ << ": parameter count " << in_parameters.size() - << ", async: " << in_async; - bool allParametersKnown = true; - for (const auto& p : in_parameters) { - if (p.id == VendorDebug::kForceTransientBurstName) { - if (!extractParameter(p, &mVendorDebug.forceTransientBurst)) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - } else if (p.id == VendorDebug::kForceSynchronousDrainName) { - if (!extractParameter(p, &mVendorDebug.forceSynchronousDrain)) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - } else { - allParametersKnown = false; - LOG(ERROR) << __func__ << ": unrecognized parameter \"" << p.id << "\""; - } - } - if (allParametersKnown) return ndk::ScopedAStatus::ok(); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); -} - -ndk::ScopedAStatus Module::addDeviceEffect( - int32_t in_portConfigId, - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) { - if (in_effect == nullptr) { - LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect"; - } else { - LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder " - << in_effect->asBinder().get(); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus Module::removeDeviceEffect( - int32_t in_portConfigId, - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) { - if (in_effect == nullptr) { - LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", null effect"; - } else { - LOG(DEBUG) << __func__ << ": port id " << in_portConfigId << ", effect Binder " - << in_effect->asBinder().get(); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType, - std::vector* _aidl_return) { - LOG(DEBUG) << __func__ << ": mmap policy type " << toString(mmapPolicyType); - std::set mmapSinks; - std::set mmapSources; - auto& ports = getConfig().ports; - for (const auto& port : ports) { - if (port.flags.getTag() == AudioIoFlags::Tag::input && - isBitPositionFlagSet(port.flags.get(), - AudioInputFlags::MMAP_NOIRQ)) { - mmapSinks.insert(port.id); - } else if (port.flags.getTag() == AudioIoFlags::Tag::output && - isBitPositionFlagSet(port.flags.get(), - AudioOutputFlags::MMAP_NOIRQ)) { - mmapSources.insert(port.id); - } - } - if (mmapSources.empty() && mmapSinks.empty()) { - AudioMMapPolicyInfo policyInfo; - policyInfo.mmapPolicy = AudioMMapPolicy::NEVER; - _aidl_return->push_back(policyInfo); - return ndk::ScopedAStatus::ok(); - } - for (const auto& route : getConfig().routes) { - if (mmapSinks.count(route.sinkPortId) != 0) { - // The sink is a mix port, add the sources if they are device ports. - for (int sourcePortId : route.sourcePortIds) { - auto sourcePortIt = findById(ports, sourcePortId); - if (sourcePortIt == ports.end()) { - // This must not happen - LOG(ERROR) << __func__ << ": port id " << sourcePortId << " cannot be found"; - continue; - } - if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) { - // The source is not a device port, skip - continue; - } - AudioMMapPolicyInfo policyInfo; - policyInfo.device = sourcePortIt->ext.get().device; - // Always return AudioMMapPolicy.AUTO if the device supports mmap for - // default implementation. - policyInfo.mmapPolicy = AudioMMapPolicy::AUTO; - _aidl_return->push_back(policyInfo); - } - } else { - auto sinkPortIt = findById(ports, route.sinkPortId); - if (sinkPortIt == ports.end()) { - // This must not happen - LOG(ERROR) << __func__ << ": port id " << route.sinkPortId << " cannot be found"; - continue; - } - if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) { - // The sink is not a device port, skip - continue; - } - if (count_any(mmapSources, route.sourcePortIds)) { - AudioMMapPolicyInfo policyInfo; - policyInfo.device = sinkPortIt->ext.get().device; - // Always return AudioMMapPolicy.AUTO if the device supports mmap for - // default implementation. - policyInfo.mmapPolicy = AudioMMapPolicy::AUTO; - _aidl_return->push_back(policyInfo); - } - } - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) { - LOG(DEBUG) << __func__; - *_aidl_return = true; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) { - if (!isMmapSupported()) { - LOG(DEBUG) << __func__ << ": mmap is not supported "; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT; - LOG(DEBUG) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) { - if (!isMmapSupported()) { - LOG(DEBUG) << __func__ << ": mmap is not supported "; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - const std::string kAaudioHwBurst = "aaudio.hw_burst_min_usec"; - auto burstSize = ::android::base::GetUintProperty(kAaudioHwBurst, 2000); - - *_aidl_return = burstSize; - LOG(DEBUG) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -bool Module::isMmapSupported() { - if (mIsMmapSupported.has_value()) { - return mIsMmapSupported.value(); - } - std::vector mmapPolicyInfos; - if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) { - mIsMmapSupported = false; - } else { - mIsMmapSupported = - std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) { - return info.mmapPolicy == AudioMMapPolicy::AUTO || - info.mmapPolicy == AudioMMapPolicy::ALWAYS; - }) != mmapPolicyInfos.end(); - } - return mIsMmapSupported.value(); -} - -ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* connectedDevicePort, - const int32_t templateDevicePortId) { - auto& externalDeviceProfiles = getConfig().mExternalDevicePortProfiles; - auto connectedProfilesIt = externalDeviceProfiles.find(templateDevicePortId); - - if (connectedProfilesIt != externalDeviceProfiles.end()) { - connectedDevicePort->profiles = connectedProfilesIt->second; - } else { - LOG(ERROR) << __func__ << ": failed to find profiles for template device port ID: " - << templateDevicePortId; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - LOG(VERBOSE) << __func__ << ": template device port ID: " << templateDevicePortId - << " attached profiles: " << connectedDevicePort->profiles; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch( - const std::vector& sources __unused, - const std::vector& sinks __unused) { - LOG(VERBOSE) << __func__ << ": do nothing and return ok"; - return ndk::ScopedAStatus::ok(); -} - -int Module::onExternalDeviceConnectionChanged( - const ::aidl::android::media::audio::common::AudioPort& audioPort, bool connected) { - LOG(INFO) << __func__ << " no-op implementation" << (connected ? " connect" : "disconnect") - << " for " << audioPort.toString(); - return 0; -} - -ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) { -#ifdef SEC_AUDIO_COMMON - LOG(VERBOSE) << __func__ << ": is not supported"; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -#else - LOG(VERBOSE) << __func__ << ": do nothing and return ok"; - return ndk::ScopedAStatus::ok(); -#endif -} - -ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) { - LOG(VERBOSE) << __func__ << ": do nothing and return ok"; - return ndk::ScopedAStatus::ok(); -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/ModulePrimary.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/ModulePrimary.cpp deleted file mode 100755 index 3d5fa32d..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/ModulePrimary.cpp +++ /dev/null @@ -1,1056 +0,0 @@ -/* - * Copyright (C) 2023 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. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include - -#define LOG_TAG "AHAL_ModulePrimary_QTI" -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef SEC_AUDIO_LEVEL_DUMP -#include "SecLevelDump.h" -#endif - -using aidl::android::hardware::audio::common::SinkMetadata; -using aidl::android::hardware::audio::common::SourceMetadata; -using aidl::android::media::audio::common::AudioOffloadInfo; -using aidl::android::media::audio::common::AudioPort; -using aidl::android::media::audio::common::AudioPortExt; -using aidl::android::media::audio::common::AudioDevice; -using aidl::android::media::audio::common::AudioPortConfig; -using aidl::android::media::audio::common::MicrophoneInfo; -using aidl::android::media::audio::common::Boolean; - -using ::aidl::android::hardware::audio::common::getFrameSizeInBytes; -using ::aidl::android::hardware::audio::common::isBitPositionFlagSet; -using ::aidl::android::hardware::audio::common::isValidAudioMode; -using ::aidl::android::hardware::audio::common::SinkMetadata; -using ::aidl::android::hardware::audio::common::SourceMetadata; - -using ::aidl::android::hardware::audio::core::AudioPatch; -using ::aidl::android::hardware::audio::core::AudioRoute; -using ::aidl::android::hardware::audio::core::IStreamIn; -using ::aidl::android::hardware::audio::core::IStreamOut; -using ::aidl::android::hardware::audio::core::ITelephony; -using ::aidl::android::hardware::audio::core::VendorParameter; -using ::aidl::qti::audio::core::VString; -using ::aidl::android::hardware::audio::core::IBluetooth; -using ::aidl::android::hardware::audio::core::IBluetoothA2dp; -using ::aidl::android::hardware::audio::core::IBluetoothLe; - -#ifdef SEC_AUDIO_COMMON -using aidl::android::media::audio::common::AudioDeviceType; -using aidl::android::media::audio::common::AudioDeviceAddress; -using aidl::android::media::audio::common::AudioDeviceDescription; -using qti::audio::core::SecModulePrimary; -#endif - -namespace qti::audio::core { - -std::vector> ModulePrimary::mStreamsOut; -std::vector> ModulePrimary::mStreamsIn; - -std::mutex ModulePrimary::outListMutex; -std::mutex ModulePrimary::inListMutex; - -std::string ModulePrimary::toStringInternal() { - std::ostringstream os; - os << "--- ModulePrimary start ---" << std::endl; - os << getConfig().toString() << std::endl; - - os << std::endl << " --- mPatches ---" << std::endl; - std::for_each(mPatches.cbegin(), mPatches.cend(), [&](const auto& pair) { - os << "PortConfigId/PortId:" << pair.first << " Patch Id:" << pair.second << std::endl; - }); - os << std::endl << " --- mPatches end ---" << std::endl << std::endl; - - os << mStreams.toString(); - - os << mPlatform.toString() << std::endl; - -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - os << mSecModulePrimary.toString(); -#endif - os << "--- ModulePrimary end ---" << std::endl; - return os.str(); -} - -void ModulePrimary::dumpInternal(const std::string& identifier) { - const auto realTimeMs = std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()) - .count(); - const std::string kDumpPath{std::string("/data/vendor/audio/audio_hal_service_") - .append(identifier) - .append("_") - .append(std::to_string(realTimeMs)) - .append(".dump")}; - - const auto fd = ::open(kDumpPath.c_str(), O_CREAT | O_WRONLY | O_TRUNC, - S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); - if (fd <= 0) { - LOG(ERROR) << __func__ << ": dump internal failed; fd:" << fd - << " unable to open file:" << kDumpPath; - return; - } - const auto dumpData = toStringInternal(); - auto b = ::write(fd, dumpData.c_str(), dumpData.size()); - if (b != static_cast(dumpData.size())) { - LOG(ERROR) << __func__ << ": dump internal failed to write in " << kDumpPath; - } - LOG(DEBUG) << __func__ << ": at: " << kDumpPath; - ::close(fd); - return; -} - -binder_status_t ModulePrimary::dump(int fd, const char** args, uint32_t numArgs) { - if (fd <= 0) { - LOG(ERROR) << ": fd:" << fd << " dump error"; - return -EINVAL; - } - auto dumpData = toStringInternal(); - auto b = ::write(fd, dumpData.c_str(), dumpData.size()); - if (b != static_cast(dumpData.size())) { - LOG(ERROR) << __func__ << " write error in dump"; - return -EIO; - } - LOG(INFO) << __func__ << " :success"; -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - mPlatform.dump(fd); -#endif -#ifdef SEC_AUDIO_LEVEL_DUMP - SEC_LEVEL_DUMP(fd); -#endif - return 0; -} - -ModulePrimary::ModulePrimary() : Module(Type::DEFAULT) { - mOffloadSpeedSupported = mPlatform.platformSupportsOffloadSpeed(); -} - -ndk::ScopedAStatus ModulePrimary::getMicrophones(std::vector* _aidl_return) { - *_aidl_return = mPlatform.getMicrophoneInfo(); - LOG(VERBOSE) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::getMicMute(bool* _aidl_return) { - if (!mTelephony) { - LOG(ERROR) << __func__ << ": Telephony not created "; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - *_aidl_return = mPlatform.getMicMuteStatus(); - LOG(VERBOSE) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::setMicMute(bool in_mute) { - if (!mTelephony) { - LOG(ERROR) << __func__ << ": Telephony not created "; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - LOG(DEBUG) << __func__ << ": " << in_mute; - - mPlatform.setMicMuteStatus(in_mute); - - mTelephony->setMicMute(in_mute); - - mAudExt.mHfpExtension->audio_extn_hfp_set_mic_mute(in_mute); - - for (const auto& inputMixPortConfigId : - getActiveInputMixPortConfigIds(getConfig().portConfigs)) { - if(!mPlatform.getTranslationRecordState()){ - mStreams.setStreamMicMute(inputMixPortConfigId, in_mute); - } else { - // Need to keep the Audio FFECNS Record stream unmuted when Translate Record Usecase Enabled - LOG(DEBUG) << __func__ << ": SetStreamMicMute skipped for Voice Translate Record"; - } - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::updateScreenState(bool in_isTurnedOn) { - LOG(VERBOSE) << __func__ << ": " << in_isTurnedOn; - mPlatform.updateScreenState(in_isTurnedOn); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::updateScreenRotation(ScreenRotation in_rotation) { - LOG(VERBOSE) << __func__ << ": " << toString(in_rotation); - mPlatform.updateScreenRotation(in_rotation); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::getBluetooth(std::shared_ptr* _aidl_return) { - if (!mBluetooth) { - mBluetooth = ndk::SharedRefBase::make<::qti::audio::core::Bluetooth>(); - } - *_aidl_return = mBluetooth.getInstance(); - LOG(DEBUG) << __func__ - << ": returning instance of IBluetooth: " << _aidl_return->get()->asBinder().get(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::getBluetoothA2dp(std::shared_ptr* _aidl_return) { - if (!mBluetoothA2dp) { - mBluetoothA2dp = ndk::SharedRefBase::make<::qti::audio::core::BluetoothA2dp>(); - } - *_aidl_return = mBluetoothA2dp.getInstance(); - LOG(DEBUG) << __func__ << ": returning instance of IBluetoothA2dp: " - << _aidl_return->get()->asBinder().get(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::getBluetoothLe(std::shared_ptr* _aidl_return) { - if (!mBluetoothLe) { - mBluetoothLe = ndk::SharedRefBase::make<::qti::audio::core::BluetoothLe>(); - } - *_aidl_return = mBluetoothLe.getInstance(); - LOG(DEBUG) << __func__ - << ": returning instance of IBluetoothLe: " << _aidl_return->get()->asBinder().get(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::getTelephony(std::shared_ptr* _aidl_return) { - if (!mTelephony) { - mTelephony = ndk::SharedRefBase::make(); - mPlatform.setTelephony(mTelephony.getInstance()); - } - *_aidl_return = mTelephony.getInstance(); - -#ifdef SEC_AUDIO_COMMON - mSecModulePrimary.setTelephony(mTelephony); - LOG(DEBUG) << __func__ << ": SecModulePrimary::setTelephony()"; -#endif - - LOG(DEBUG) << __func__ - << ": returning instance of ITelephony: " << _aidl_return->get()->asBinder().get(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::createInputStream(StreamContext&& context, - const SinkMetadata& sinkMetadata, - const std::vector& microphones, - std::shared_ptr* result) { - createStreamInstance(result, std::move(context), sinkMetadata, microphones); - ModulePrimary::inListMutex.lock(); - ModulePrimary::updateStreamInList(*result); - if (mTelephony) { - mTelephony->mStreamInPrimary = *result; - } - ModulePrimary::inListMutex.unlock(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModulePrimary::createOutputStream( - StreamContext&& context, const SourceMetadata& sourceMetadata, - const std::optional& offloadInfo, std::shared_ptr* result) { - if (mPlatform.isSoundCardDown() && - (hasOutputDirectFlag(context.getMixPortConfig().flags.value()) || - hasOutputCompressOffloadFlag(context.getMixPortConfig().flags.value()))) { - LOG(ERROR) << __func__ << ": avoid direct or compress streams as sound card is down"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - createStreamInstance(result, std::move(context), sourceMetadata, offloadInfo); - ModulePrimary::outListMutex.lock(); - ModulePrimary::updateStreamOutList(*result); - // save primary out stream weak ptr, as some other modules need it. - if (mTelephony) { - mTelephony->mStreamOutPrimary = *result; - } - - ModulePrimary::outListMutex.unlock(); - return ndk::ScopedAStatus::ok(); -} - -std::vector<::aidl::android::media::audio::common::AudioProfile> ModulePrimary::getDynamicProfiles( - const ::aidl::android::media::audio::common::AudioPort& audioPort) { - if (isUsbDevice(audioPort.ext.get().device)) { - /* as of now, we do dynamic fetching for usb devices*/ - auto dynamicProfiles = mPlatform.getDynamicProfiles(audioPort); - return dynamicProfiles; - } - return {}; -} - -void ModulePrimary::onNewPatchCreation(const std::vector& sources, - const std::vector& sinks, - AudioPatch& newPatch) { - if (!isMixPortConfig(*(sources.at(0))) && !isMixPortConfig(*(sinks.at(0)))) { - LOG(VERBOSE) << __func__ << ": no mix ports detected"; - return; - } - auto numFrames = mPlatform.getMinimumStreamSizeFrames(sources, sinks); - if (numFrames < kMinimumStreamBufferSizeFrames) { - LOG(DEBUG) << __func__ << ": got invalid stream size frames " << numFrames - << " adjusting to " << kMinimumStreamBufferSizeFrames; - numFrames = kMinimumStreamBufferSizeFrames; - } - newPatch.minimumStreamBufferSizeFrames = numFrames; -} - -void ModulePrimary::setAudioPatchTelephony(const std::vector& sources, - const std::vector& sinks, - const AudioPatch& patch) { - std::string patchDetails = getPatchDetails(patch); - - if (!mTelephony) { - LOG(ERROR) << __func__ << ": Telephony not created " << patchDetails << patch.toString(); - return; - } - - if (!isDevicePortConfig(*(sources.at(0))) || !isDevicePortConfig(*(sinks.at(0)))) { - return; - } - - bool updateRx = isTelephonyRXDevice(sources.at(0)->ext.get().device); - bool updateTx = isTelephonyTXDevice(sinks.at(0)->ext.get().device); - - if (!updateRx && !updateTx) { - LOG(ERROR) << __func__ << ": neither RX nor TX update " << patchDetails << patch.toString(); - return; - } - - const auto& portConfigsForDeviceChange = updateRx ? (sinks) : (sources); - - std::vector devices; - for (const auto portConfig : portConfigsForDeviceChange) { - devices.push_back(portConfig->ext.get().device); - } - - mTelephony->setDevices(devices, updateRx); - mAudExt.mHfpExtension->audio_extn_hfp_set_device(devices, updateRx); - LOG(INFO) << __func__ << ": set telephony " << (updateRx ? "RX" : "TX") << " devices"; -} - -void ModulePrimary::resetAudioPatchTelephony(const AudioPatch& patch) { - const std::string patchDetails = getPatchDetails(patch); - if (!mTelephony) { - LOG(ERROR) << __func__ << ": Telephony not created " << patchDetails << patch.toString(); - return; - } - - auto& configs = getConfig().portConfigs; - std::vector missingIds; - auto sources = selectByIds(configs, patch.sourcePortConfigIds, &missingIds); - if (!missingIds.empty()) { - LOG(ERROR) << __func__ << ": following source port config ids not found: " - << ::android::internal::ToString(missingIds); - } - auto sinks = selectByIds(configs, patch.sinkPortConfigIds, &missingIds); - if (!missingIds.empty()) { - LOG(ERROR) << __func__ << ": following sink port config ids not found: " - << ::android::internal::ToString(missingIds); - } - - if (!isDevicePortConfig(*(sources.at(0))) || !isDevicePortConfig(*(sinks.at(0)))) { - // atleast one of the port config is a mix port config. - return; - } - - bool updateRx = isTelephonyRXDevice(sources.at(0)->ext.get().device); - bool updateTx = isTelephonyTXDevice(sinks.at(0)->ext.get().device); - - if (!updateRx && !updateTx) { - LOG(ERROR) << __func__ << ": neither RX nor TX update " << patchDetails << patch.toString(); - return; - } - - mTelephony->resetDevices(updateRx); - - LOG(INFO) << __func__ << ": reset telephony " << (updateRx ? "RX" : "TX") << " devices"; -} - -int ModulePrimary::onExternalDeviceConnectionChanged( - const ::aidl::android::media::audio::common::AudioPort& audioPort, bool connected) { - if (mDebug.simulateDeviceConnections) { - LOG(DEBUG) << __func__ << ": connection is in simulation mode"; - return 0; - } - - if (int ret = mPlatform.handleDeviceConnectionChange(audioPort, connected); ret) { - LOG(WARNING) << __func__ << " failed to handle device connection change:" - << (connected ? " connect" : "disconnect") << " for " << audioPort.toString(); - return ret; - } - - return 0; -} - -int32_t ModulePrimary::getNominalLatencyMs(const AudioPortConfig& mixPortConfig) { - return mPlatform.getLatencyMs(mixPortConfig); -} - -ndk::ScopedAStatus ModulePrimary::getSupportedPlaybackRateFactors( - SupportedPlaybackRateFactors* _aidl_return) { - LOG(DEBUG) << __func__ << " speed supported " << mOffloadSpeedSupported; - if (mOffloadSpeedSupported) { - _aidl_return->minSpeed = 0.1f; - _aidl_return->maxSpeed = 2.0f; - _aidl_return->minPitch = 1.0f; - _aidl_return->maxPitch = 1.0f; - return ndk::ScopedAStatus::ok(); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} -// start of module parameters handling - -ndk::ScopedAStatus ModulePrimary::setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& in_parameters, - bool in_async) { - LOG(VERBOSE) << __func__ << ": parameter count " << in_parameters.size() - << ", async: " << in_async; - for (const auto& p : in_parameters) { - if (p.id == VendorDebug::kForceTransientBurstName) { - if (!extractParameter(p, &mVendorDebug.forceTransientBurst)) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - } else if (p.id == VendorDebug::kForceSynchronousDrainName) { - if (!extractParameter(p, &mVendorDebug.forceSynchronousDrain)) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - } else { - struct str_parms* parms = NULL; - std::string kvpairs = getkvPairsForVendorParameter(in_parameters); - if (!kvpairs.empty()) { - parms = str_parms_create_str(kvpairs.c_str()); - mAudExt.audio_extn_set_parameters(parms); -#ifdef SEC_AUDIO_COMMON - if (parms) - str_parms_destroy(parms); -#endif - } - - mPlatform.setVendorParameters(in_parameters, in_async); - } - } - processSetVendorParameters(in_parameters); - return ndk::ScopedAStatus::ok(); -} - -bool ModulePrimary::processSetVendorParameters(const std::vector& parameters) { - FeatureToVendorParametersMap pendingActions{}; - for (const auto& p : parameters) { - const auto searchId = mSetParameterToFeatureMap.find(p.id); - if (searchId == mSetParameterToFeatureMap.cend()) { - LOG(VERBOSE) << __func__ << ": not configured " << p.id; - continue; - } - - auto itr = pendingActions.find(searchId->second); - if (itr == pendingActions.cend()) { - pendingActions[searchId->second] = std::vector({p}); - continue; - } - itr->second.push_back(p); - } - - for (const auto & [ key, value ] : pendingActions) { - const auto search = mFeatureToSetHandlerMap.find(key); - if (search == mFeatureToSetHandlerMap.cend()) { - LOG(VERBOSE) << __func__ - << ": no handler set on Feature:" << static_cast(search->first); - continue; - } - auto handler = std::bind(search->second, this, value); - handler(); // a dynamic dispatch to a SetHandler - } - -#ifdef SEC_AUDIO_COMMON - mSecModulePrimary.processSetVendorParameters(parameters); -#endif - - return true; -} - -void ModulePrimary::onSetGenericParameters(const std::vector& params) { - for (const auto& param : params) { - std::string paramValue{}; - if (!extractParameter(param, ¶mValue)) { - LOG(ERROR) << ": extraction failed for " << param.id; - continue; - } - if (Parameters::kInCallMusic == param.id) { - const auto isOn = getBoolFromString(paramValue); - mPlatform.setInCallMusicState(isOn); - LOG(INFO) << __func__ << ": ICMD playback:" << isOn; - } else if (Parameters::kUHQA == param.id) { - const bool enable = paramValue == "on" ? true : false; - mPlatform.updateUHQA(enable); - } else if (Parameters::kTranslateRecord == param.id) { - // Add Translate_Record param check and update using the Set Function - const auto isOn = getBoolFromString(paramValue); - mPlatform.setTranslationRecordState(isOn); - LOG(INFO) << __func__ << ": PCM Record FFECNS for Translation:" << isOn; - } - } -} - -void ModulePrimary::onSetHDRParameters(const std::vector& params) { - for (const auto& param : params) { - std::string paramValue{}; - if (!extractParameter(param, ¶mValue)) { - LOG(ERROR) << __func__ << ": extraction failed for " << param.id; - continue; - } - if (param.id == Parameters::kHdrRecord) { - mPlatform.setHDREnabled(paramValue == "true"); - } else if (param.id == Parameters::kHdrSamplingRate) { - mPlatform.setHDRSampleRate(static_cast(getInt64FromString(paramValue))); - } else if (param.id == Parameters::kHdrChannelCount) { - mPlatform.setHDRChannelCount(static_cast(getInt64FromString(paramValue))); - } else if (param.id == Parameters::kWnr) { - mPlatform.setWNREnabled(paramValue == "true"); - } else if (param.id == Parameters::kAns) { - mPlatform.setANREnabled(paramValue == "true"); - } else if (param.id == Parameters::kOrientation) { - mPlatform.setOrientation(paramValue); - } else if (param.id == Parameters::kInverted) { - mPlatform.setInverted(paramValue == "true"); - } else if (param.id == Parameters::kFacing) { - mPlatform.setFacing(paramValue); - } - } - LOG(VERBOSE) << __func__ << ": processed"; -} - -void ModulePrimary::onSetTelephonyParameters(const std::vector& parameters) { - if (!mTelephony) { - LOG(ERROR) << __func__ << ": Telephony not created"; - return; - } - - Telephony::SetUpdates setUpdates{}; - bool isSetUpdate = false; - - bool isDeviceMuted = false; - std::string muteDirection{""}; - bool isDeviceMuteUpdate = false; - - for (const auto& p : parameters) { - std::string paramValue{}; - if (!extractParameter(p, ¶mValue)) { - LOG(ERROR) << ": extraction failed for " << p.id; - continue; - } - if (Parameters::kVoiceCallState == p.id) { - setUpdates.mCallState = - static_cast(getInt64FromString(paramValue)); - isSetUpdate = true; - } else if (Parameters::kVoiceVSID == p.id) { - setUpdates.mVSID = static_cast(getInt64FromString(paramValue)); - isSetUpdate = true; - } else if (Parameters::kVoiceCallType == p.id) { - setUpdates.mCallType = std::move(paramValue); - isSetUpdate = true; - } else if (Parameters::kVoiceCRSCall == p.id) { - setUpdates.mIsCrsCall = paramValue == "true" ? true : false; - isSetUpdate = true; - } else if (Parameters::kVoiceCRSVolume == p.id) { - mTelephony->setCRSVolumeFromIndex(getInt64FromString(paramValue)); - } else if (Parameters::kVolumeBoost == p.id) { - const bool enable = paramValue == "on" ? true : false; - mTelephony->updateVolumeBoost(enable); - } else if (Parameters::kVoiceSlowTalk == p.id) { - const bool enable = paramValue == "true" ? true : false; - mTelephony->updateSlowTalk(enable); - } else if (Parameters::kVoiceHDVoice == p.id) { - const bool enable = paramValue == "true" ? true : false; - mTelephony->updateHDVoice(enable); - } else if (Parameters::kVoiceDeviceMute == p.id) { - isDeviceMuted = paramValue == "true" ? true : false; - isDeviceMuteUpdate = true; - } else if (Parameters::kVoiceDirection == p.id) { - muteDirection = paramValue; - } else if (Parameters::kVoiceTranslationRxMute == p.id) { - const auto isOn = getBoolFromString(paramValue); - mPlatform.setTranslationRxMuteState(isOn); - LOG(DEBUG) << __func__ << " : translation Rx mute set as true" ; - mTelephony->updateVoiceVolume(); - } - } - - if (isSetUpdate) { - mTelephony->reconfigure(setUpdates); - } - if (isDeviceMuteUpdate) { - mTelephony->updateDeviceMute(isDeviceMuted, muteDirection); - } - - return; -} - -void ModulePrimary::onSetWFDParameters(const std::vector& parameters) { - for (const auto& p : parameters) { - std::string paramValue{}; - if (!extractParameter(p, ¶mValue)) { - LOG(ERROR) << ": extraction failed for " << p.id; - continue; - } - if (Parameters::kWfdChannelMap == p.id) { - auto numProxyChannels = static_cast(getInt64FromString(paramValue)); - mPlatform.setWFDProxyChannels(numProxyChannels); - } else if (Parameters::kWfdIPAsProxyDevConnected == p.id) { - auto isIPAsProxy = getBoolFromString(paramValue); - mPlatform.setIPAsProxyDeviceConnected(isIPAsProxy); - } else if (Parameters::kProxyRecordFMQSize == p.id) { - const size_t& proxyRecordFMQSize = static_cast(getInt64FromString(paramValue)); - mPlatform.setProxyRecordFMQSize(proxyRecordFMQSize); - } - } - return; -} - -void ModulePrimary::onSetFTMParameters(const std::vector& parameters) { - auto itrForCfgWaitTime = - std::find_if(parameters.cbegin(), parameters.cend(), - [](const auto& p) { return p.id == Parameters::kFbspCfgWaitTime; }); - auto itrForFTMWaitTime = - std::find_if(parameters.cbegin(), parameters.cend(), - [](const auto& p) { return p.id == Parameters::kFbspFTMWaitTime; }); - auto itrForValiWaitTime = - std::find_if(parameters.cbegin(), parameters.cend(), - [](const auto& p) { return p.id == Parameters::kFbspValiWaitTime; }); - auto itrForValiValiTime = - std::find_if(parameters.cbegin(), parameters.cend(), - [](const auto& p) { return p.id == Parameters::kFbspValiValiTime; }); - auto itrForTriggerSpeakerCall = - std::find_if(parameters.cbegin(), parameters.cend(), - [](const auto& p) { return p.id == Parameters::kTriggerSpeakerCall; }); - - if (itrForCfgWaitTime != parameters.cend() && itrForFTMWaitTime != parameters.cend()) { - std::string heatTime{}, runTime{}; - if ((!extractParameter(*itrForCfgWaitTime, &heatTime)) || - (!extractParameter(*itrForFTMWaitTime, &runTime))) { - LOG(ERROR) << __func__ << ": extraction failed!!!"; - return; - } - mPlatform.setFTMSpeakerProtectionMode(static_cast(getInt64FromString(heatTime)), - static_cast(getInt64FromString(runTime)), - true, false, false); - } else if (itrForValiWaitTime != parameters.cend() && itrForValiValiTime != parameters.cend()) { - std::string heatTime{}, runTime{}; - if ((!extractParameter(*itrForValiWaitTime, &heatTime)) || - (!extractParameter(*itrForValiValiTime, &runTime))) { - LOG(ERROR) << __func__ << ": extraction failed!!!"; - return; - } - mPlatform.setFTMSpeakerProtectionMode(static_cast(getInt64FromString(heatTime)), - static_cast(getInt64FromString(runTime)), - false, true, false); - } else if (itrForTriggerSpeakerCall != parameters.cend()) { - mPlatform.setFTMSpeakerProtectionMode(0, 0, false, false, true); - } - - return; -} - -void ModulePrimary::onSetHapticsParameters(const std::vector& parameters) { - for (const auto& param : parameters) { - std::string paramValue{}; - if (!extractParameter(param, ¶mValue)) { - LOG(ERROR) << ": extraction failed for " << param.id; - continue; - } - if (Parameters::kHapticsVolume == param.id) { - const float hapticsVolume = getFloatFromString(paramValue); - mPlatform.setHapticsVolume(hapticsVolume); - } else if (Parameters::kHapticsIntensity == param.id) { - const int hapticsIntensity = getInt64FromString(paramValue); - mPlatform.setHapticsIntensity(hapticsIntensity); - } - } - return; -} - -// static -ModulePrimary::SetParameterToFeatureMap ModulePrimary::fillSetParameterToFeatureMap() { - SetParameterToFeatureMap map{{Parameters::kHdrRecord, Feature::HDR}, - {Parameters::kWnr, Feature::HDR}, - {Parameters::kAns, Feature::HDR}, - {Parameters::kOrientation, Feature::HDR}, - {Parameters::kInverted, Feature::HDR}, - {Parameters::kHdrChannelCount, Feature::HDR}, - {Parameters::kHdrSamplingRate, Feature::HDR}, - {Parameters::kFacing, Feature::HDR}, - {Parameters::kVoiceCallState, Feature::TELEPHONY}, - {Parameters::kVoiceCallType, Feature::TELEPHONY}, - {Parameters::kVoiceVSID, Feature::TELEPHONY}, - {Parameters::kVoiceCRSCall, Feature::TELEPHONY}, - {Parameters::kVoiceCRSVolume, Feature::TELEPHONY}, - {Parameters::kVolumeBoost, Feature::TELEPHONY}, - {Parameters::kVoiceSlowTalk, Feature::TELEPHONY}, - {Parameters::kVoiceHDVoice, Feature::TELEPHONY}, - {Parameters::kVoiceDeviceMute, Feature::TELEPHONY}, - {Parameters::kVoiceDirection, Feature::TELEPHONY}, - {Parameters::kVoiceTranslationRxMute, Feature::TELEPHONY}, - {Parameters::kInCallMusic, Feature::GENERIC}, - {Parameters::kTranslateRecord, Feature::GENERIC}, - {Parameters::kUHQA, Feature::GENERIC}, - {Parameters::kFbspCfgWaitTime, Feature::FTM}, - {Parameters::kFbspFTMWaitTime, Feature::FTM}, - {Parameters::kFbspValiWaitTime, Feature::FTM}, - {Parameters::kFbspValiValiTime, Feature::FTM}, - {Parameters::kTriggerSpeakerCall, Feature::FTM}, - {Parameters::kWfdChannelMap, Feature::WFD}, - {Parameters::kWfdIPAsProxyDevConnected, Feature::WFD}, - {Parameters::kProxyRecordFMQSize, Feature::WFD}, - {Parameters::kHapticsVolume, Feature::HAPTICS}, - {Parameters::kHapticsIntensity, Feature::HAPTICS}}; - return map; -} - -// static -ModulePrimary::FeatureToSetHandlerMap ModulePrimary::fillFeatureToSetHandlerMap() { - FeatureToSetHandlerMap map{ - {Feature::GENERIC, &ModulePrimary::onSetGenericParameters}, - {Feature::HDR, &ModulePrimary::onSetHDRParameters}, - {Feature::TELEPHONY, &ModulePrimary::onSetTelephonyParameters}, - {Feature::WFD, &ModulePrimary::onSetWFDParameters}, - {Feature::FTM, &ModulePrimary::onSetFTMParameters}, - {Feature::HAPTICS, &ModulePrimary::onSetHapticsParameters}}; - return map; -} - -ndk::ScopedAStatus ModulePrimary::getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return) { - LOG(DEBUG) << __func__ << ": id count: " << in_ids.size(); - for (const auto& id : in_ids) { - if (id == VendorDebug::kForceTransientBurstName) { - VendorParameter forceTransientBurst{.id = id}; - forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst}); - _aidl_return->push_back(std::move(forceTransientBurst)); - } else if (id == VendorDebug::kForceSynchronousDrainName) { - VendorParameter forceSynchronousDrain{.id = id}; - forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain}); - _aidl_return->push_back(std::move(forceSynchronousDrain)); - } - } - - auto results = processGetVendorParameters(in_ids); - std::move(results.begin(), results.end(), std::back_inserter(*_aidl_return)); - - if (_aidl_return->size() != in_ids.size()) { - LOG(ERROR) << __func__ << ": handled parameters " << _aidl_return->size() - << " requested " << in_ids.size(); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - return ndk::ScopedAStatus::ok(); -} - -std::vector ModulePrimary::processGetVendorParameters( - const std::vector& ids) { - FeatureToStringMap pendingActions{}; - // only group of features are mapped to Feature, rest are kept as generic. - // If the key is found in feature map, use the feature otherwise call GENERIC feature. - for (const auto& id : ids) { - auto search = mGetParameterToFeatureMap.find(id); - Feature mappedFeature = Feature::GENERIC; - if (search != mGetParameterToFeatureMap.cend()) { - mappedFeature = search->second; - } - auto itr = pendingActions.find(mappedFeature); - if (itr == pendingActions.cend()) { - pendingActions[mappedFeature] = std::vector({id}); - continue; - } - itr->second.push_back(id); - } - - std::vector result{}; - for (const auto & [ key, value ] : pendingActions) { - const auto search = mFeatureToGetHandlerMap.find(key); - if (search == mFeatureToGetHandlerMap.cend()) { - LOG(ERROR) << __func__ - << ": no handler set on Feature:" << static_cast(search->first); - continue; - } - auto handler = std::bind(search->second, this, value); - auto keyResult = handler(); // a dynamic dispatch to GetHandler - result.insert(result.end(), keyResult.begin(), keyResult.end()); - } - -#ifdef SEC_AUDIO_COMMON - std::vector secResult{}; - secResult = mSecModulePrimary.processGetVendorParameters(ids); - if (secResult.size() > 0) { - result = secResult; - } -#endif - return result; -} - -std::vector ModulePrimary::onGetAudioExtnParams( - const std::vector& ids) { - std::vector results{}; - for (const auto& id : ids) { - if (id == Parameters::kFMStatus) { - bool fm_status = mAudExt.mFmExtension->audio_extn_fm_get_status(); - VendorParameter param; - param.id = id; - VString parcel; - parcel.value = fm_status ? "true" : "false"; - setParameter(parcel, param); - results.push_back(param); - } else if (id == Parameters::kCanOpenProxy) { - VendorParameter param; - param.id = id; - VString parcel; - parcel.value = "1"; - setParameter(parcel, param); - results.push_back(param); - } - } - return results; -} - -std::vector ModulePrimary::onGetGenericParams( - const std::vector& ids) { - std::vector results{}; - for (const auto& id : ids) { - if (id == Parameters::kOffloadPlaySpeedSupported) { - LOG(DEBUG) << __func__ << " " << id << " supported " << mOffloadSpeedSupported; - // std::string value = (mOffloadSpeedSupported ? "true" : "false"); // SEC_AUDIO_COMMON - - -#ifdef SEC_AUDIO_OFFLOAD_COMPRESSED_OPUS - std::string value = "1"; -#else - std::string value = "0"; -#endif - -#ifdef SEC_AUDIO_COMMON - LOG(DEBUG) << __func__ << " " << id << " sec supported " << value; -#endif - auto param = makeVendorParameter(id, value); - results.push_back(param); - } -#ifdef ENABLE_TAS_SPK_PROT - else if (id == Parameters::kTiSmartPaKey) { - VendorParameter param; - param.id = id; - VString parcel; - const auto& spkrProtResult = mPlatform.getSpeakerProtectionResult(); - if (spkrProtResult) { - parcel.value = spkrProtResult.value(); - } else { - parcel.value = "failed!!"; - } - setParameter(parcel, param); - results.push_back(param); - } -#endif - } - return results; -} - -std::vector ModulePrimary::onGetBluetoothParams( - const std::vector& ids) { - if (!mBluetoothA2dp) { - LOG(ERROR) << __func__ << ": Bluetooth not created"; - return {}; - } - std::vector results{}; - for (const auto& id : ids) { - if (id == Parameters::kA2dpSuspended) { - VendorParameter param; - bool a2dpEnabled = false; - param.id = id; - VString parcel; - mBluetoothA2dp->isEnabled(&a2dpEnabled); - //if a2dp enabled is true then suspend is 0, else suspend is 1 - parcel.value = a2dpEnabled ? "0" : "1"; - setParameter(parcel, param); - results.push_back(param); - } - } - return results; -} - -std::vector ModulePrimary::onGetHDRParameters( - const std::vector& ids) { - std::vector result; - for (const auto& id : ids) { - std::string value{}; - if (id == Parameters::kHdrRecord) { - value = makeParamValue(mPlatform.isHDREnabled()); - result.push_back(makeVendorParameter(id, value)); - } else if (id == Parameters::kHdrSamplingRate) { - value = std::to_string(mPlatform.getHDRSampleRate()); - result.push_back(makeVendorParameter(id, value)); - } else if (id == Parameters::kHdrChannelCount) { - value = std::to_string(mPlatform.getHDRChannelCount()); - result.push_back(makeVendorParameter(id, value)); - } else if (id == Parameters::kWnr) { - value = makeParamValue(mPlatform.isWNREnabled()); - result.push_back(makeVendorParameter(id, value)); - } else if (id == Parameters::kAns) { - value = makeParamValue(mPlatform.isANREnabled()); - result.push_back(makeVendorParameter(id, value)); - } else if (id == Parameters::kOrientation) { - value = mPlatform.getOrientation(); - result.push_back(makeVendorParameter(id, value)); - } else if (id == Parameters::kInverted) { - value = makeParamValue(mPlatform.isInverted()); - result.push_back(makeVendorParameter(id, value)); - } else if (id == Parameters::kFacing) { - value = mPlatform.getFacing(); - result.push_back(makeVendorParameter(id, value)); - } - } - LOG(VERBOSE) << __func__ << ": processed"; - return result; -} - -std::vector ModulePrimary::onGetTelephonyParameters( - const std::vector& ids) { - if (!mTelephony) { - LOG(ERROR) << __func__ << ": Telephony not created"; - return {}; - } - std::vector results{}; - for (const auto& id : ids) { - if (id == Parameters::kVoiceIsCRsSupported) { - VendorParameter param; - param.id = id; - VString parcel; - parcel.value = mTelephony->isCrsCallSupported() ? "1" : "0"; - setParameter(parcel, param); - results.push_back(param); - } - } - return results; -} - -std::vector ModulePrimary::onGetWFDParameters( - const std::vector& ids) { - std::vector results{}; - for (const auto& id : ids) { - if (id == Parameters::kCanOpenProxy) { - VendorParameter param; - param.id = id; - VString parcel; - parcel.value = "1"; // This "1" indicates WFD client can try AHAL Capture. - setParameter(parcel, param); - results.push_back(param); - } else if (id == Parameters::kWfdProxyRecordActive) { - VendorParameter param; - param.id = id; - VString parcel; - parcel.value = mPlatform.IsProxyRecordActive(); - setParameter(parcel, param); - results.push_back(param); - } else if (id == Parameters::kWfdIPAsProxyDevConnected) { - VendorParameter param; - param.id = id; - VString parcel; - parcel.value = mPlatform.isIPAsProxyDeviceConnected(); - setParameter(parcel, param); - results.push_back(param); - } else { - LOG(ERROR) << __func__ << ": unknown parameter in WFD feature. id:" << id; - } - } - return results; -} - -std::vector ModulePrimary::onGetFTMParameters( - const std::vector& ids) { - std::vector results{}; - for (const auto& id : ids) { - VendorParameter param; - VString parcel; - if (id == Parameters::kFTMParam) { - param.id = id; - const auto& ftmResult = mPlatform.getFTMResult(); - if (ftmResult) { - parcel.value = ftmResult.value(); - } else { - parcel.value = ""; - } - setParameter(parcel, param); - results.push_back(param); - } else if (id == Parameters::kFTMSPKRParam) { - param.id = id; - const auto& calResult = mPlatform.getSpeakerCalibrationResult(); - if (calResult) { - parcel.value = calResult.value(); - } else { - parcel.value = "false"; - } - setParameter(parcel, param); - results.push_back(param); - } else { - LOG(ERROR) << __func__ << ": unknown parameter in FTM feature. id:" << id; - } - } - return results; -} - -// static -ModulePrimary::GetParameterToFeatureMap ModulePrimary::fillGetParameterToFeatureMap() { - GetParameterToFeatureMap map{{Parameters::kHdrRecord, Feature::HDR}, - {Parameters::kWnr, Feature::HDR}, - {Parameters::kAns, Feature::HDR}, - {Parameters::kOrientation, Feature::HDR}, - {Parameters::kInverted, Feature::HDR}, - {Parameters::kHdrChannelCount, Feature::HDR}, - {Parameters::kHdrSamplingRate, Feature::HDR}, - {Parameters::kFacing, Feature::HDR}, - {Parameters::kVoiceIsCRsSupported, Feature::TELEPHONY}, - {Parameters::kA2dpSuspended, Feature::BLUETOOTH}, - {Parameters::kCanOpenProxy, Feature::WFD}, - {Parameters::kWfdProxyRecordActive, Feature::WFD}, - {Parameters::kWfdIPAsProxyDevConnected, Feature::WFD}, - {Parameters::kFTMParam, Feature::FTM}, - {Parameters::kFTMSPKRParam, Feature::FTM}, - {Parameters::kFMStatus, Feature::AUDIOEXTENSION}}; - return map; -} - -// static -ModulePrimary::FeatureToGetHandlerMap ModulePrimary::fillFeatureToGetHandlerMap() { - FeatureToGetHandlerMap map{{Feature::HDR, &ModulePrimary::onGetHDRParameters}, - {Feature::TELEPHONY, &ModulePrimary::onGetTelephonyParameters}, - {Feature::BLUETOOTH, &ModulePrimary::onGetBluetoothParams}, - {Feature::WFD, &ModulePrimary::onGetWFDParameters}, - {Feature::FTM, &ModulePrimary::onGetFTMParameters}, - {Feature::AUDIOEXTENSION, &ModulePrimary::onGetAudioExtnParams}, - {Feature::GENERIC, &ModulePrimary::onGetGenericParams}}; - return map; -} - -// end of module parameters handling - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/ModuleStub.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/ModuleStub.cpp deleted file mode 100755 index c92d6607..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/ModuleStub.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2023 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. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include - -#define LOG_TAG "AHAL_ModuleStub_QTI" -#include -#include - -#include -#include -#include - -using aidl::android::hardware::audio::common::SinkMetadata; -using aidl::android::hardware::audio::common::SourceMetadata; -using aidl::android::media::audio::common::AudioOffloadInfo; -using aidl::android::media::audio::common::AudioPort; -using aidl::android::media::audio::common::AudioPortConfig; -using aidl::android::media::audio::common::MicrophoneInfo; - -using ::aidl::android::hardware::audio::common::getFrameSizeInBytes; -using ::aidl::android::hardware::audio::common::isBitPositionFlagSet; -using ::aidl::android::hardware::audio::common::isValidAudioMode; -using ::aidl::android::hardware::audio::common::SinkMetadata; -using ::aidl::android::hardware::audio::common::SourceMetadata; - -using ::aidl::android::hardware::audio::core::AudioPatch; -using ::aidl::android::hardware::audio::core::AudioRoute; -using ::aidl::android::hardware::audio::core::IBluetooth; -using ::aidl::android::hardware::audio::core::IBluetoothA2dp; -using ::aidl::android::hardware::audio::core::IBluetoothLe; -using ::aidl::android::hardware::audio::core::IStreamIn; -using ::aidl::android::hardware::audio::core::IStreamOut; -using ::aidl::android::hardware::audio::core::VendorParameter; - -namespace qti::audio::core { - -ndk::ScopedAStatus ModuleStub::getBluetooth(std::shared_ptr* _aidl_return) { - if (!mBluetooth) { - mBluetooth = ndk::SharedRefBase::make(); - } - *_aidl_return = mBluetooth.getInstance(); - LOG(DEBUG) << __func__ - << ": returning instance of IBluetooth: " << _aidl_return->get()->asBinder().get(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModuleStub::getBluetoothA2dp(std::shared_ptr* _aidl_return) { - if (!mBluetoothA2dp) { - mBluetoothA2dp = ndk::SharedRefBase::make(); - } - *_aidl_return = mBluetoothA2dp.getInstance(); - LOG(DEBUG) << __func__ << ": returning instance of IBluetoothA2dp: " - << _aidl_return->get()->asBinder().get(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModuleStub::getBluetoothLe(std::shared_ptr* _aidl_return) { - if (!mBluetoothLe) { - mBluetoothLe = ndk::SharedRefBase::make(); - } - *_aidl_return = mBluetoothLe.getInstance(); - LOG(DEBUG) << __func__ - << ": returning instance of IBluetoothLe: " << _aidl_return->get()->asBinder().get(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus ModuleStub::createInputStream(StreamContext&& context, - const SinkMetadata& sinkMetadata, - const std::vector& microphones, - std::shared_ptr* result) { - return createStreamInstance(result, std::move(context), sinkMetadata, - microphones); -} - -ndk::ScopedAStatus ModuleStub::createOutputStream( - StreamContext&& context, const SourceMetadata& sourceMetadata, - const std::optional& offloadInfo, std::shared_ptr* result) { - return createStreamInstance(result, std::move(context), sourceMetadata, - offloadInfo); -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/SecModulePrimary.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/SecModulePrimary.cpp deleted file mode 100755 index 6424667d..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/SecModulePrimary.cpp +++ /dev/null @@ -1,2010 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_SecModulePrimary" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -#ifdef SEC_AUDIO_DUMP -#include "SecCoreUtils_Interface.h" -#endif - -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION -#include -#endif - -#ifdef SEC_AUDIO_SAMSUNGRECORD -#include -#endif - -#ifdef SEC_AUDIO_AMP_BIGDATA -#include "audioInfo.h" -#endif - -using aidl::android::hardware::audio::common::isValidAudioMode; -using aidl::android::media::audio::common::AudioDevice; -using aidl::android::media::audio::common::AudioDeviceAddress; -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; -using aidl::android::media::audio::common::AudioMode; -using aidl::android::media::audio::common::Boolean; -using aidl::android::media::audio::common::Float; - -using ::aidl::android::hardware::audio::core::VendorParameter; -using ::aidl::qti::audio::core::VString; - -namespace qti::audio::core { - -SecModulePrimary::SecModulePrimary() { - LOG(INFO) << __func__ << ": SecModulePrimary()"; -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - mAudExt.mKarokeExtension->init(); -#endif -#ifdef SEC_AUDIO_DSM_AMP - mAudExt.mSpeakerFeedbackExtension->init(); -#endif -} - - -SecModulePrimary::FeatureToSetHandlerMap SecModulePrimary::fillFeatureToSetHandlerMap() { - FeatureToSetHandlerMap map{ - {SecParameters::Feature_SEC::SEC_GENERIC, &SecModulePrimary::onSetSECGenericParameters}, - {SecParameters::Feature_SEC::SEC_TELEPHONY, &SecModulePrimary::onSetSECTelephonyParameters}, - {SecParameters::Feature_SEC::SEC_FTM, &SecModulePrimary::onSetSECFTMParameters}, - {SecParameters::Feature_SEC::SEC_SUBKEY, &SecModulePrimary::onSetSECSubkeyParameters}, - }; - return map; -} - - -SecModulePrimary::SetParameterToFeatureMap SecModulePrimary::fillSetParameterToFeatureMap() { - SetParameterToFeatureMap map{ -// SEC_TELEPHONY - {SecParameters::kVoiceCallBand, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceCallForwardingEnable, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceCallMemoState, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceCallNBQualityEnable, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceCallRingbacktoneState, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceCallSatelliteEnable, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceCallState, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceCallTranslationMode, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceEffectDVAdaptSound, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceEffectDVAdaptSoundCallPatam, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceFactoryEchoRefMuteCNGEnable, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceHACMode, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceMicInputControlMode, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceMicInputControlModeCall, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceRxControlMode, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceScreenCall, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceStreamEnforcedActiveInCall, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceTxControlMode, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceVSID, SecParameters::Feature_SEC::SEC_TELEPHONY}, -// SEC_FTM - {SecParameters::kFactoryTestLoopback, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestMicPath, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestPath, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestRoute, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestType, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestSpkPath, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestCalibration, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestCalAmpType, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestCalTarget, SecParameters::Feature_SEC::SEC_FTM}, -// SEC_GENERIC - {SecParameters::kAllSoundMuteEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kA2dpFormat, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kA2dpSuspendForBle, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kBtScoCodecType, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kDualSpeakerAmpLeftPowerEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kFMRadioMode, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kFMRadioVolume, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kFMRadioMute, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kGameChatEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwDisplayRotation, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwFlatMotionState, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwFolderState, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwSpeakerAmpTemperatureRCV, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwSpeakerAmpTemperatureSPK, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kInterpreterMode, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kPcmDumpApCallState, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kPcmDumpRecordState, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kPcmDumpState, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kScoRvcSupport, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kSupportSecAudioFeature, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kVoipViaSmartView, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRemoteMicEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRemoteMicVolume, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRecordBeamformingMode, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRecordSecVoiceRecorderEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRecordTxInversion, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kBargeinMode, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRecordNSRISecurityEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kVoiceWakeupRegisterVoiceKeyword, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kVoiceWakeupSeamlessEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kKaraokeEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kInputFlag, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kEffectOffloadVSPParam, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kEffectSoundBalanceValue, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kEffectToMonoEnable, SecParameters::Feature_SEC::SEC_GENERIC}, -// SEC_SUBKEY - {SecParameters::kDexKey, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyDexType, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyDexConnected, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kEffectListenBackKey, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyEffectListenBackState, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kMultiMicKey, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyMultiMicAudioFocusEnable, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyMultiMicCameraDirection, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyMultiMicFocusCoordinate, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyMultiMicMode, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyMultiMicPhoneOrientation, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyMultiMicSensitivityLevel, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyMultiMicZoomLevel, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyMultiMicZoomMax, SecParameters::Feature_SEC::SEC_SUBKEY}, - {SecParameters::kSubkeyMultiMicZoomMin, SecParameters::Feature_SEC::SEC_SUBKEY}, - }; - return map; -} - -bool SecModulePrimary::processSetVendorParameters(const std::vector& parameters) { - FeatureToVendorParametersMap pendingActions{}; - pendingActions.clear(); - for (const auto& p : parameters) { - const auto searchId = mSetParameterToFeatureMap_SEC.find(p.id); - if (searchId == mSetParameterToFeatureMap_SEC.cend()) { - LOG(DEBUG) << __func__ << ": not configured " << p.id; - continue; - } - LOG(DEBUG) << __func__ << ": configured " << p.id; - - auto itr = pendingActions.find(searchId->second); - if (itr == pendingActions.cend()) { - pendingActions[searchId->second] = std::vector({p}); - continue; - } - itr->second.push_back(p); - } - - for (const auto & [ key, value ] : pendingActions) { - const auto search = SecModulePrimary::mFeatureToSetHandlerMap.find(key); - if (search == SecModulePrimary::mFeatureToSetHandlerMap.cend()) { - LOG(DEBUG) << __func__ - << ": no handler set on Feature:" << static_cast(search->first); - continue; - } - LOG(DEBUG) << __func__ - << ": handler set on Feature:" << static_cast(search->first); - auto handler = std::bind(search->second, this, value); - handler(); // a dynamic dispatch to a SetHandler - } - - return true; -} - -void SecModulePrimary::onSetSECGenericParameters(const std::vector& params) { - for (const auto& param : params) { - std::string paramValue{}; - int val = 0; - if (!extractParameter(param, ¶mValue)) { - LOG(ERROR) << ": extraction failed for " << param.id; - continue; - } - -#ifdef SEC_AUDIO_BLUETOOTH - if (SecParameters::kBtScoCodecType == param.id) { - /* bt_sco_codec_type parameters */ - pal_param_btsco_t param_bt_sco; - memset(¶m_bt_sco, 0, sizeof(pal_param_btsco_t)); - if (paramValue == AUDIO_PARAMETER_VALUE_RVP) { - param_bt_sco.bt_sco_codec_type = PAL_BT_SCO_CODEC_TYPE_RVP; - } else { - param_bt_sco.bt_sco_codec_type = PAL_BT_SCO_CODEC_TYPE_NONE; - } - LOG(INFO) << __func__ << " BTSCO CODEC TYPE = " << param_bt_sco.bt_sco_codec_type; - pal_set_param(PAL_PARAM_ID_BT_SCO_CODEC_TYPE, (void*)¶m_bt_sco, sizeof(pal_param_btsco_t)); - } -#endif -#ifdef SEC_AUDIO_BT_OFFLOAD - else if (SecParameters::kA2dpFormat == param.id) { - mPlatform.setBtA2dpFormat(static_cast(getInt64FromString(paramValue))); - } -#endif -#ifdef SEC_AUDIO_BLE_OFFLOAD - else if (SecParameters::kA2dpSuspendForBle == param.id) { - /* bt sco/a2dp and ble cannot active at the same time */ - pal_param_bta2dp_t param_bt_a2dp; - memset(¶m_bt_a2dp, 0, sizeof(pal_param_bta2dp_t)); - param_bt_a2dp.a2dp_suspended_for_ble = getBoolFromString(paramValue); - if (param_bt_a2dp.a2dp_suspended_for_ble) { - UpdateSCOdeviceState(); - } - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - pal_set_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED_FOR_BLE, (void*)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_BT_RVC - else if (SecParameters::kScoRvcSupport == param.id) { - mPlatform.setBtRvcSupportState(getBoolFromString(paramValue)); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC - else if (SecParameters::kRemoteMicEnable == param.id) { - bool enableAas = getBoolFromString(paramValue); - if (mPlatform.isAasEnabled() != enableAas) { - pal_device_id_t deviceId = enableAas ? getPrimaryOutPalDeviceId() : PAL_DEVICE_NONE; - mPlatform.setAasEnabled(enableAas); - if (mAudExt.mAasExtension->updateAasStream(enableAas, deviceId) == 0) { - mAudioEffect.setAASVolume(mPlatform.getAasVolume()); - } - } - } else if (SecParameters::kRemoteMicVolume == param.id) { - mPlatform.setAasVolume(getFloatFromString(paramValue)); - mAudioEffect.setAASVolume(mPlatform.getAasVolume()); - } -#endif -#ifdef SEC_AUDIO_BARGEIN_MODE - else if (SecParameters::kBargeinMode == param.id) { - pal_param_bargein_mode_t param_bargein_mode; - memset(¶m_bargein_mode, 0, sizeof(param_bargein_mode)); - - param_bargein_mode.mode = getInt64FromString(paramValue); - LOG(INFO) << __func__ << " Bargein mode = " << param_bargein_mode.mode; - - pal_set_param(PAL_PARAM_ID_BARGEIN_MODE, (void *)¶m_bargein_mode, - sizeof(param_bargein_mode)); - } -#endif -#ifdef SEC_AUDIO_KARAOKE - else if (SecParameters::kKaraokeEnable == param.id) { - bool current = mPlatform.isKaraokeEnabled(); - mPlatform.setKaraokeEnabled(getBoolFromString(paramValue)); - if(mPlatform.isKaraokeEnabled() != current) { - setKaraokeDevice(); - } - } -#endif -#ifdef SEC_AUDIO_INTERPRETER_MODE - else if (SecParameters::kInterpreterMode == param.id) { - pal_param_interpreter_mode_t param_interpreter_mode; - memset(¶m_interpreter_mode, 0, sizeof(param_interpreter_mode)); - mPlatform.setInterpreterMode(getInt64FromString(paramValue)); - param_interpreter_mode.mode = mPlatform.getInterpreterMode(); - LOG(INFO) << __func__ << " interpreter_mode mode = " << param_interpreter_mode.mode; - pal_set_param(PAL_PARAM_ID_INTERPRETER_MODE, (void *)¶m_interpreter_mode, - sizeof(param_interpreter_mode)); - } -#endif -#ifdef SEC_AUDIO_DUMP - else if (SecParameters::kPcmDumpApCallState == param.id) { - sec_ap_call_pcm_set_dumpstate(getBoolFromString(paramValue)); - } else if (SecParameters::kPcmDumpRecordState == param.id) { - sec_rec_pcm_set_dumpstate(getInt64FromString(paramValue)); - } else if (SecParameters::kPcmDumpState == param.id) { - sec_pcm_set_dumpstate(getInt64FromString(paramValue)); - } -#endif -#ifdef SEC_AUDIO_SCREEN_MIRRORING // { SUPPORT_VOIP_VIA_SMART_VIEW - else if (SecParameters::kVoipViaSmartView == param.id) { - UpdateSmartViewState(getBoolFromString(paramValue)); - } -#endif // { SUPPORT_VOIP_VIA_SMART_VIEW -#ifdef SEC_AUDIO_ALL_SOUND_MUTE - else if (SecParameters::kAllSoundMuteEnable == param.id) { - LOG(INFO) << __func__ << "ALL Sound Mute = " << paramValue; - bool muteVoice = getBoolFromString(paramValue); - mPlatform.setAllSoundMute(muteVoice); - mTelephony->updateDeviceMute(muteVoice, std::string("rx")); -#ifdef SEC_AUDIO_CALL_SATELLITE - mTelephony->updateExtModemCallVolume(); -#endif -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC - mAudioEffect.setAASVolume(mPlatform.getAasVolume()); -#endif - } -#endif -#if defined(SEC_AUDIO_DUAL_SPEAKER) || defined(SEC_AUDIO_MULTI_SPEAKER) - else if (SecParameters::kHwDisplayRotation == param.id) { - mPlatform.updateRotationInfo(static_cast(getInt64FromString(paramValue))); - } else if (SecParameters::kHwFlatMotionState == param.id) { - // 0 : Not flat, Uneven motion state, 1 : Flat motion state - mPlatform.updateFlatmotionInfo(static_cast(getInt64FromString(paramValue))); -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP - mAudioEffect.send_soundbooster_flatmotion(); -#endif - } -#endif -#ifdef SEC_AUDIO_OFFLOAD - else if (SecParameters::kEffectSoundBalanceValue == param.id) { - mAudioEffect.set_soundbalance_value(getInt64FromString(paramValue)); - auto streamOut = SecModulePrimary::GetStreamOut(Usecase::COMPRESS_OFFLOAD_PLAYBACK); - if (streamOut) mAudioEffect.send_soundalive_lrsm_value(); - } else if (SecParameters::kEffectToMonoEnable == param.id) { - mAudioEffect.set_mono_enable(getBoolFromString(paramValue)); - auto streamOut = SecModulePrimary::GetStreamOut(Usecase::COMPRESS_OFFLOAD_PLAYBACK); - if (streamOut) mAudioEffect.send_soundalive_lrsm_value(); - } -#endif -#ifdef SEC_AUDIO_OFFLOAD_SOUNDSPEED - else if (SecParameters::kEffectOffloadVSPParam == param.id) { - mAudioEffect.set_soundspeed_value(getFloatFromString(paramValue)); - auto streamOut = SecModulePrimary::GetStreamOut(Usecase::COMPRESS_OFFLOAD_PLAYBACK); - if (streamOut) mAudioEffect.send_soundspeed_value(); - } -#endif -#ifdef SEC_AUDIO_SAMSUNGRECORD - else if (SecParameters::kRecordBeamformingMode == param.id) { - LOG(INFO) << __func__ << "Beamforming mode = " << paramValue; - if(getInt64FromString(paramValue) == 0 || getInt64FromString(paramValue) == 1) { - mPlatform.preprocess_eq_enables |= S_REC_BF; - } else { - mPlatform.preprocess_eq_enables &= ~(S_REC_BF); - } - } else if (SecParameters::kRecordSecVoiceRecorderEnable == param.id) { - if (strcmp(paramValue.c_str(), AUDIO_PARAMETER_VALUE_TRUE) == 0) { - mPlatform.preprocess_eq_enables |= S_REC_SS_VOICERECORDER; - } else { - mPlatform.preprocess_eq_enables &= ~(S_REC_SS_VOICERECORDER); - } - } else if (SecParameters::kInputFlag == param.id) { - LOG(INFO) << __func__ << "Received unconfigured input flag : " << paramValue; - mPlatform.setUnconfiguredFlagsReceived(getInt64FromString(paramValue)); - } -#endif -#ifdef SEC_AUDIO_CAMCORDER - else if (SecParameters::kRecordTxInversion == param.id) { - mPlatform.setTxDataInversion(getBoolFromString(paramValue)); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_NSRI - else if (SecParameters::kRecordNSRISecurityEnable == param.id) { - mPlatform.setNSRISecureEnabled(getBoolFromString(paramValue)); - LOG(DEBUG) << __func__ << " is_NSRI_secure state is changed to " << mPlatform.isNSRISecureEnabled(); - } -#endif -#ifdef SEC_AUDIO_SOUND_TRIGGER_TYPE - else if (SecParameters::kVoiceWakeupRegisterVoiceKeyword == param.id) { - mPlatform.setRegisterVoiceKeyword(getInt64FromString(paramValue)); - } else if (SecParameters::kVoiceWakeupSeamlessEnable == param.id) { - mPlatform.setSeamlessEnabled(getBoolFromString(paramValue)); - LOG(DEBUG) << __func__ << " seamless enabled: " << mPlatform.isSeamlessEnabled(); - } -#endif -#ifdef SEC_AUDIO_FMRADIO - else if (SecParameters::kFMRadioMode == param.id) { - LOG(VERBOSE) << __func__ << " fmradio_mode = " << paramValue; - mPlatform.setFMRadioOn(paramValue == AUDIO_PARAMETER_VALUE_ON); - audio_devices_t fmRadioMode = mPlatform.getFMRadioOn() ? AUDIO_DEVICE_OUT_FM : - AUDIO_DEVICE_NONE; - audio_devices_t fmRadioDevice = mPlatform.getFMRadioDevice(); -#ifdef SEC_AUDIO_PREVOLUME_SOUNDBOOSTER - if (!mPlatform.getFMRadioOn()) { - mAudioEffect.send_soundbooster_on(PARAM_VOLUME_FM, false); - } else if (mPlatform.getFMRadioOn() && (fmRadioDevice == AUDIO_DEVICE_OUT_SPEAKER)) { - mAudioEffect.send_soundbooster_on(PARAM_VOLUME_FM, true); - } -#endif - struct str_parms* fmParms = str_parms_create(); - str_parms_add_int(fmParms, kHandleFM.c_str(), (int)(fmRadioDevice | fmRadioMode)); - mAudExt.mFmExtension->audio_extn_fm_set_parameters(fmParms); - } else if (SecParameters::kFMRadioVolume == param.id) { - LOG(VERBOSE) << __func__ << " fmradio_volume = " << paramValue; - float fmRadioVolume = getFloatFromString(paramValue); - mPlatform.setFMRadioVolume(fmRadioVolume); -#if defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP) || defined(SEC_AUDIO_PREVOLUME_SOUNDBOOSTER) - mAudioEffect.setSoundBoosterVolumeForFMRadio(); -#else - struct str_parms* fmParms = str_parms_create(); - str_parms_add_float(fmParms, kFMVolume.c_str(), fmRadioVolume); - mAudExt.mFmExtension->audio_extn_fm_set_parameters(fmParms); -#endif - } else if (SecParameters::kFMRadioMute == param.id) { - LOG(VERBOSE) << __func__ << " fmradio_mute on/off state = " << paramValue; - const bool fmRadioMute = getBoolFromString(paramValue); - mPlatform.setFMRadioMute(fmRadioMute); -#if defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP) || defined(SEC_AUDIO_PREVOLUME_SOUNDBOOSTER) - mAudioEffect.setSoundBoosterVolumeForFMRadio(); -#else - struct str_parms* fmParms = str_parms_create(); - str_parms_add_int(fmParms, kFMMute.c_str(), fmRadioMute ? 1 : 0); - mAudExt.mFmExtension->audio_extn_fm_set_parameters(fmParms); -#endif - } -#endif -#if defined(SEC_AUDIO_SUPPORT_FLIP_CALL) || defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_FOLD_PARAM_ON_DSP) - else if (SecParameters::kHwFolderState == param.id) { - SetFolderState(getInt64FromString(paramValue)); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_GAMECHAT_SPK_AEC - else if (SecParameters::kGameChatEnable == param.id) { - bool newGamechatMode = getBoolFromString(paramValue); - if (mPlatform.getGamechatMode() != newGamechatMode) { - LOG(INFO) << __func__ << " gamechat mode is changed (" << - makeParamValue(mPlatform.getGamechatMode()) << " -> " << paramValue << ")"; - mPlatform.setGamechatMode(newGamechatMode); - // already ap call path enabled, need to re-route voip spk <-> game voip spk path - RerouteForVoip(); - } - } -#endif -#ifdef SEC_AUDIO_AMP_SDHMS - else if (SecParameters::kHwSpeakerAmpTemperatureRCV == param.id|| - SecParameters::kHwSpeakerAmpTemperatureSPK == param.id) { - uint32_t pal_param_id = 0; - pal_param_amp_ssrm_t param_amp_ssrm = {}; - - if (SecParameters::kHwSpeakerAmpTemperatureRCV == param.id) { - pal_param_id = PAL_PARAM_ID_SPEAKER_AMP_TEMPERATURE_RCV; - } else { - pal_param_id = PAL_PARAM_ID_SPEAKER_AMP_TEMPERATURE_SPK; - } - param_amp_ssrm.temperature = getInt64FromString(paramValue); - - LOG(DEBUG) << __func__ << " set temperature for " << param.id << ": " - << param_amp_ssrm.temperature; - pal_set_param(pal_param_id, (void*)¶m_amp_ssrm, sizeof(pal_param_amp_ssrm_t)); - } -#endif - else if (SecParameters::kSupportSecAudioFeature == param.id) { - LOG(INFO) << __func__ << " kSupportSecAudioFeature = " << paramValue; - mPlatform.setSecAudioFeatureSupported(true); - } - } - return; -} - -void SecModulePrimary::onSetSECTelephonyParameters(const std::vector& parameters) { - if (!mTelephony) { - LOG(ERROR) << __func__ << ": Telephony not created"; - return; - } - - for (const auto& p : parameters) { - std::string paramValue{}; - if (!extractParameter(p, ¶mValue)) { - LOG(ERROR) << ": extraction failed for " << p.id; - continue; - } - if (SecParameters::kVoiceCallState == p.id) { - int state = getInt64FromString(paramValue); - bool prevVoWiFiState = mPlatform.getVoWiFiState(); - // 1st : check volte status - mTelephony->updateSecCallState(state); - // 2nd : check voipWificalling state - if (state & CALL_STATUS_VOIPWIFICALLING) { - mPlatform.updateVoWiFiState( - (state & CALL_STATUS_VOIPWIFICALLING_ON) ? true : false); - } - // 3rd : check voip aosp state - if (state & CALL_STATUS_VOIP_AOSP_ON) { - mPlatform.updateVoWiFiState(false); // reset vowifi for aosp voip - } - // if other AP call path is already actived before, set path again here - if ((prevVoWiFiState != mPlatform.getVoWiFiState()) - && (mPlatform.getCallMode() == AUDIO_MODE_IN_COMMUNICATION)) { - LOG(INFO) << ": reroute voip for wifi call " - << mPlatform.getVoWiFiState() ? "ON" : "OFF"; - RerouteForVoip(); - } - } else if (SecParameters::kVoiceVSID == p.id) { - mTelephony->updateSecVSID(stoi(paramValue, nullptr, 16)); - } else if (SecParameters::kVoiceCallBand == p.id) { - int callBand = -1; - if (paramValue == AUDIO_PARAMETER_VALUE_SWB) callBand = SWB; - if (paramValue == AUDIO_PARAMETER_VALUE_WB) callBand = WB; - if (paramValue == AUDIO_PARAMETER_VALUE_NB) callBand = NB; - mTelephony->updateSecCallBand(callBand); - } -#ifdef SEC_AUDIO_CALL_SATELLITE - else if (SecParameters::kVoiceCallSatelliteEnable == p.id) { - LOG(DEBUG) << __func__ << " Satellite call = " << paramValue; - mPlatform.setSatelliteCall(getBoolFromString(paramValue)); - mTelephony->configureExtModemCall(); - } -#endif -#ifdef SEC_AUDIO_CALL_HAC - else if (SecParameters::kVoiceHACMode == p.id) { - int newHacMode = getInt64FromString(paramValue); - if (HAC_MODE_MIC <= newHacMode && newHacMode < HAC_MODE_MAX) { - mPlatform.setHacMode(newHacMode); - } else { - LOG(ERROR) << __func__ << "invalid hac mode: " << newHacMode; - } - } -#endif -#ifdef SEC_AUDIO_ENFORCED_AUDIBLE - else if (SecParameters::kVoiceStreamEnforcedActiveInCall == p.id) { - bool mute = getBoolFromString(paramValue); - mPlatform.updateEnforcePlaybackState(mute ? MUTE_CALL : NOT_MUTE); - if (mPlatform.getCallMode() == AUDIO_MODE_IN_CALL) { - mTelephony->setMicMute(mute); - mTelephony->updateDeviceMute(mute, std::string("rx")); - } else if (mute && mPlatform.getCallMode() != AUDIO_MODE_IN_COMMUNICATION) { -#ifdef SEC_AUDIO_SUPPORT_FAST_FLAG_SHUTTER - Usecase TargetUsecase = Usecase::LOW_LATENCY_PLAYBACK; -#else - Usecase TargetUsecase = Usecase::PRIMARY_PLAYBACK; -#endif - auto streamOut = GetStreamOut(TargetUsecase); - if (streamOut && (streamOut->isDeviceAvailable(PAL_DEVICE_OUT_USB_HEADSET) - || streamOut->isDeviceAvailable(PAL_DEVICE_OUT_BLUETOOTH_A2DP))) { - mPlatform.updateEnforcePlaybackState(MUTE_CALL_AND_REC); - } - } - } -#endif -#ifdef SEC_AUDIO_ADAPT_SOUND - else if (SecParameters::kVoiceEffectDVAdaptSound == p.id) { - LOG(INFO) << __func__ << " set DHA : " << paramValue; - mAudioEffect.SetDHAData(paramValue.c_str(), DHA_UPDATE); - } else if (SecParameters::kVoiceEffectDVAdaptSoundCallPatam == p.id) { - mAudioEffect.setSupportAdaptSoundCallParam(getBoolFromString(paramValue)); - } -#endif -#ifdef SEC_AUDIO_CALL - else if (SecParameters::kVoiceCallNBQualityEnable == p.id) { - bool enable = getBoolFromString(paramValue); - if (mPlatform.getNbQuality() != enable) { - mPlatform.setNbQuality(enable); - mAudioEffect.SetNBQuality(); - } - } - else if (SecParameters::kVoiceCallRingbacktoneState == p.id) { - bool enable = getBoolFromString(paramValue); - if (mPlatform.getRingbacktone() != enable) { - mPlatform.setRingbacktone(enable); - mAudioEffect.SetRingbackGain(); - } - } -#endif -#ifdef SEC_AUDIO_CALL_FORWARDING - else if (SecParameters::kVoiceCallForwardingEnable == p.id) { - bool enable = getBoolFromString(paramValue); - if (mPlatform.getCallForwarding() != enable) { - mPlatform.setCallForwarding(enable); - mTelephony->setCallForwarding(enable); - } - } - else if (SecParameters::kVoiceCallMemoState == p.id) { - int callMemoState = CALLMEMO_OFF; - if (getBoolFromString(paramValue)) { - callMemoState = CALLMEMO_ON; // use call music mixer/device - } else if (paramValue == AUDIO_PARAMETER_VALUE_RECORDING) { - callMemoState = CALLMEMO_REC; // use call mixer/device, tx/rx mut - } - - if (mPlatform.getCallMemo() != callMemoState) { - int preCallMemo = mPlatform.getCallMemo(); - bool needRouting = true; - if (mPlatform.getCallState() != 2/*CallState::ACTIVE*/) { - needRouting = false; // if not in call state, skip routing - } - LOG(INFO) << __func__ << " callmemo flag change 0x" << std::hex << mPlatform.getCallMemo() - << " to 0x" << std::hex << callMemoState << " needRouting " << needRouting; - - switch (callMemoState) { - case CALLMEMO_ON : - mPlatform.setCallMemo(callMemoState); - if (needRouting) { - mTelephony->setCallForwarding(true); - } - break; - case CALLMEMO_REC : - mPlatform.setCallMemo(CALLMEMO_OFF); // to disable music path - if (needRouting) { - mTelephony->setCallForwarding(false); - mTelephony->updateDeviceMute(true, std::string("rx")); - mTelephony->setMicMute(true); - } - mPlatform.setCallMemo(callMemoState); - break; - case CALLMEMO_OFF : - default : - mPlatform.setCallMemo(callMemoState); - if (needRouting) { - mTelephony->setCallForwarding(false); - } - if (preCallMemo == CALLMEMO_REC) { - // if rec -> off case, need to unmute rx/tx - mTelephony->updateDeviceMute(false, std::string("rx")); - mTelephony->setMicMute(false); - } - break; - } - } else { - LOG(INFO) << __func__ << " callmemo skip to set same flag on 0x" << std::hex << mPlatform.getCallMemo(); - } - } -#endif -#ifdef SEC_AUDIO_CALL_TRANSLATION - else if (SecParameters::kVoiceCallTranslationMode == p.id) { - LOG(DEBUG) << __func__ << " Enter CallTranslation " << paramValue; - bool enable = getBoolFromString(paramValue); - if (mPlatform.getCallTranslation() != enable) { - mPlatform.setCallTranslation(enable); - mTelephony->configureMicMode(); - // tx control for cp call - mAudioEffect.ControlTxVolumeDown(); - // tx control for ap call - mAudioEffect.SetVoipTxEffectForTranslation(enable); - // rx control for ap/cp call - mAudioEffect.SetVoiceRxEffectForTranslation(enable); - } - } else if (SecParameters::kVoiceTxControlMode == p.id) { - int mode = getInt64FromString(paramValue); - if (mPlatform.getVoiceTxControl() != mode) { - mPlatform.setVoiceTxControl(mode); - } - mAudioEffect.ControlTxVolumeDown(); - } else if (SecParameters::kVoiceRxControlMode == p.id) { - int mode = getInt64FromString(paramValue); - if (mPlatform.getVoiceRxControl() != mode) { - mPlatform.setVoiceRxControl((mode < 0) ? 0 : mode); - mTelephony->updateDeviceMute(mPlatform.getVoiceRxControl(), std::string("rx")); - LOG(INFO) << __func__ << " mVoiceRxControl " << paramValue; - } - } -#endif -#ifdef SEC_AUDIO_CALL_VOIP - else if (SecParameters::kVoiceFactoryEchoRefMuteCNGEnable == p.id) { - bool enable = getBoolFromString(paramValue); - if (mPlatform.getVoipIsolationMode() != enable) { - mPlatform.setCngEnable(enable); - mAudioEffect.SetCNGForEchoRefMute(enable); - } - } else if (SecParameters::kVoiceMicInputControlMode == p.id) { - uint32_t mode = getInt64FromString(paramValue); - if (mPlatform.getVoipIsolationMode() != mode) { - mPlatform.setVoipIsolationMode(mode); - LOG(INFO) << __func__ << " set voip_isolation_mode as " << mode; - mAudioEffect.SetVoipMicModeEffect(); - } - } else if (SecParameters::kVoiceMicInputControlModeCall == p.id) { - uint32_t mode = getInt64FromString(paramValue); - if (mPlatform.getCallIsolationMode() != mode) { - mPlatform.setCallIsolationMode(mode); - LOG(INFO) << __func__ << " set call_isolation_mode as " << mode; - mTelephony->configureMicMode(); - mAudioEffect.SetVoipMicModeEffect(); - } - } -#endif -#ifdef SEC_AUDIO_VOICE_TX_FOR_INCALL_MUSIC - else if (SecParameters::kVoiceScreenCall == p.id) { - LOG(DEBUG) << __func__ << " Enter new_screen_call " << paramValue; - mPlatform.setScreenCall(getBoolFromString(paramValue)); - } -#endif - } - return; -} - -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION -void SecModulePrimary::processCalibrationParameters(const std::vector& parameters) { - // processing in calibraion helper - struct str_parms* parms = NULL; - std::string kvpairs = getkvPairsForVendorParameter(parameters); - if (!kvpairs.empty()) { - parms = str_parms_create_str(kvpairs.c_str()); - LOG(DEBUG) << __func__ << " kvpairs : " << kvpairs; - sec_cal_process(NULL, parms); - if (parms) - str_parms_destroy(parms); - } -} - -std::string SecModulePrimary::getCalibrationResults(std::string calValue, std::string ampType) { - // processing in calibraion helper - std::string calResult{AUDIO_PARAMETER_VALUE_FAIL}; - struct str_parms* parms = NULL; - std::string ampInfo{""}; - if (calValue == AUDIO_PARAMETER_VALUE_READ) { - ampInfo = "amp=" + ampType; - } - std::string kvpairs = SecParameters::kFactoryTestCalibration+ "=" + calValue + ";" + ampInfo; - if (!kvpairs.empty()) { - parms = str_parms_create_str(kvpairs.c_str()); - LOG(DEBUG) << __func__ << " kvpairs : " << kvpairs; - calResult = std::string(sec_cal_get_result(NULL, parms)); - if (parms) - str_parms_destroy(parms); - } - return calResult; -} -#endif - -void SecModulePrimary::onSetSECFTMParameters(const std::vector& parameters) { - if (!mTelephony) { - LOG(ERROR) << __func__ << ": Telephony not created"; - return; - } - - AudioDevice factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}; - AudioDevice factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::NONE}; - int ftmode = mSecFTM.getFTMConfig().mode; - int loopbacktype = SecFTM::LOOPBACK_OFF; - bool loopbackOn = false; - std::string calCommand{""}; - std::string ampType{""}; - - for (const auto& param : parameters) { - std::string paramValue{}; - if (!extractParameter(param, ¶mValue)) { - LOG(ERROR) << ": extraction failed for " << param.id; - continue; - } - - if (SecParameters::kFactoryTestLoopback == param.id) {//set Loopback on/off - if (paramValue == AUDIO_PARAMETER_VALUE_ON) { - loopbackOn = true; - } - mSecFTM.setLoopbackMode(loopbackOn ? true : false); - if ((loopbackOn && (ftmode & SecFTM::FACTORY_LOOPBACK_ACTIVE)) - || (!loopbackOn && !(ftmode & SecFTM::FACTORY_LOOPBACK_ACTIVE))) { - LOG(DEBUG) << __func__ << "FACTORY_TEST_LOOPBACK already set as " - << (loopbackOn ? " on" : "off"); - } else if (loopbackOn) { - ftmode |= SecFTM::FACTORY_LOOPBACK_ACTIVE; - mSecFTM.setFactoryMode(ftmode); - } else { - bool isIncallMusicLoopbackOff = - (mSecFTM.getIncallmusicLoopbackType() - != SecFTM::INCALLMUSIC_LOOPBACK_OFF) ? true : false; - if (isIncallMusicLoopbackOff) { - mTelephony->setMicMute(false); - } - loopbackOn = false; - ftmode &= ~SecFTM::FACTORY_LOOPBACK_ACTIVE; - mSecFTM.setFactoryMode(ftmode); - mSecFTM.setLoopbackType(SecFTM::LOOPBACK_OFF); - mSecFTM.setIncallmusicLoopbackType(SecFTM::INCALLMUSIC_LOOPBACK_OFF); - mSecFTM.setRcvAsSpk2(false); - - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::NONE}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::NONE}; - mSecFTM.setDevices({factoryRxDevice, factoryTxDevice}, SecFTM::FTM_INOUT_BOTH); - if (isIncallMusicLoopbackOff) { - ForceSetOutDevices({factoryRxDevice}, true); - mTelephony->updateLoopback({factoryRxDevice, factoryTxDevice}, false); - } else { - mTelephony->updateLoopback({factoryRxDevice, factoryTxDevice}, false); - if (mSecFTM.getLoopbackScoOn()) { - mSecFTM.secFTMhandleBTScoConnection(false); - } - ForceSetOutDevices({factoryRxDevice}); - } - ForceSetInDevices({factoryTxDevice}); - } - } else if (SecParameters::kFactoryTestType == param.id) { //set Loopback type - if (paramValue == "packet") { - loopbacktype = SecFTM::LOOPBACK_PACKET; - } else if (paramValue == "packet_nodelay") { - loopbacktype = SecFTM::LOOPBACK_PACKET_NODELAY; - } else if (paramValue == "codec") { - loopbacktype = SecFTM::LOOPBACK_CODEC; - } else if (paramValue == "realtime") { - loopbacktype = SecFTM::LOOPBACK_REALTIME; - } else if (paramValue == "pcm") { - loopbacktype = SecFTM::LOOPBACK_PCM; - } - if (loopbacktype != SecFTM::LOOPBACK_OFF) { - mSecFTM.setLoopbackType(loopbacktype); - } - } else if (SecParameters::kFactoryTestPath == param.id) { - mSecFTM.setRcvAsSpk2(false); - if (paramValue == "ear_ear") { - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_USB}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_USB}; - // set dummpy usb address for factory test - factoryRxDevice.address = AudioDeviceAddress::make(std::vector{1, 0}); - factoryTxDevice.address = AudioDeviceAddress::make(std::vector{1, 0}); - } else if (paramValue == "mic_rcv") { - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER_EARPIECE}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else if (paramValue == "mic1_spk") { - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else if (paramValue == "mic1_spk2") { - // to checking rcv as spk2 on dualspk support models - mSecFTM.setRcvAsSpk2(true); - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else if (paramValue == "mic2_spk") { - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_BACK}; - } else if (paramValue == "mic3_spk") { - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}; - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_MIC3 - .type.type = AudioDeviceType::IN_MICROPHONE_MULTI, - .type.connection = AudioDeviceDescription::CONNECTION_BUILTIN_MIC3}; - } else if (paramValue == "dualmic_spk") { //need to check - } else if (paramValue == "dualmic_rcv") { - } else if (paramValue == "mic_ear") { - } else if (paramValue == "mic2_ear") { - } else if (paramValue == "dualmic_ear") { - } else if (paramValue == "incallmusic_rcv") { - mSecFTM.setIncallmusicLoopbackType(SecFTM::INCALLMUSIC_LOOPBACK_RCV); - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER_EARPIECE}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else if (paramValue == "incallmusic_spk") { - mSecFTM.setIncallmusicLoopbackType(SecFTM::INCALLMUSIC_LOOPBACK_SPK); - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_BACK}; - } else if (paramValue == "incallmusic_all_spk") { - mSecFTM.setIncallmusicLoopbackType(SecFTM::INCALLMUSIC_LOOPBACK_SPK_ALL); - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_BACK}; - } else if (paramValue == "bt_bt") { - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_DEVICE, - .type.connection = AudioDeviceDescription::CONNECTION_BT_SCO}; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_SCO}; - mSecFTM.secFTMhandleBTScoConnection(true); - } - mSecFTM.setDevices({factoryRxDevice, factoryTxDevice}, SecFTM::FTM_INOUT_BOTH); - if (loopbacktype != SecFTM::LOOPBACK_REALTIME && !mSecFTM.getLoopbackScoOn()) { - if (mSecFTM.getIncallmusicLoopbackType() != SecFTM::INCALLMUSIC_LOOPBACK_OFF) { - //close graph before opening incallmusic path - ForceSetOutDevices({factoryRxDevice}, true); - mTelephony->updateLoopback({factoryRxDevice, factoryTxDevice}, true); - //mute input from mic - mTelephony->setMicMute(true); - } else { - mTelephony->updateLoopback({factoryRxDevice, factoryTxDevice}, true); - } - } else { - ForceSetOutDevices({factoryRxDevice}); - ForceSetInDevices({factoryTxDevice}); - } - } else if (SecParameters::kFactoryTestRoute == param.id) { - if (paramValue == "rcv") { - ftmode |= SecFTM::FACTORY_ROUTE_ACTIVE; - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER_EARPIECE}; - mSecFTM.setDevices({factoryRxDevice}, SecFTM::FTM_OUTPUT); - } else if (paramValue == "spk") { - ftmode |= SecFTM::FACTORY_ROUTE_ACTIVE; - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}; - mSecFTM.setDevices({factoryRxDevice}, SecFTM::FTM_OUTPUT); - } else if (paramValue == "hdmi") { - ftmode |= SecFTM::FACTORY_ROUTE_ACTIVE; - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_DEVICE, - .type.connection = AudioDeviceDescription::CONNECTION_HDMI}; - mSecFTM.setDevices({factoryRxDevice}, SecFTM::FTM_OUTPUT); - } else if (paramValue == "off") { - ftmode &= ~SecFTM::FACTORY_ROUTE_ACTIVE; -#if SEC_AUDIO_MULTI_SPEAKER == 4 - if (mSecFTM.isSpeakerFactoryRxDevice() - && !(ftmode & SecFTM::FACTORY_LOOPBACK_ACTIVE)) { - mSecFTM.setFactorySoundBoosterMode(SecFTM::SB_ON_DEFAULT); - mAudioEffect.send_factory_soundbooster_mode(mSecFTM.getFactorySoundBoosterMode()); - } -#endif - factoryRxDevice = AudioDevice{.type.type = AudioDeviceType::NONE}; - mSecFTM.setDevices({factoryRxDevice}, SecFTM::FTM_OUTPUT); - } - mSecFTM.setFactoryMode(ftmode); - if ((ftmode & SecFTM::FACTORY_LOOPBACK_ACTIVE) == 0) { - ForceSetOutDevices({factoryRxDevice}); - } - } else if (SecParameters::kFactoryTestMicPath == param.id) { - ftmode &= ~SecFTM::FACTORY_ATCMD_ACTIVE; - if (paramValue == "on") { - ftmode |= SecFTM::FACTORY_IN_ROUTE_ACTIVE; - mSecFTM.setRMSTestMode(true); - } else if (paramValue == "all_mic") { - if (mSecFTM.getIncallmusicLoopbackType() == SecFTM::INCALLMUSIC_LOOPBACK_RCV) { - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_BUILTIN_MIC - .type.type = AudioDeviceType::IN_MICROPHONE}; - } else if (mSecFTM.getIncallmusicLoopbackType() == SecFTM::INCALLMUSIC_LOOPBACK_SPK - || mSecFTM.getIncallmusicLoopbackType() == SecFTM::INCALLMUSIC_LOOPBACK_SPK_ALL) { - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_BACK_MIC - .type.type = AudioDeviceType::IN_MICROPHONE_BACK}; - } else { - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_MULTI_MIC - .type.type = AudioDeviceType::IN_MICROPHONE_MULTI, - .type.connection = AudioDeviceDescription::CONNECTION_BUILTIN_MULTI_MIC}; - } - mSecFTM.setDevices({factoryTxDevice}, SecFTM::FTM_INPUT); - } else if (paramValue == "mic3_mic4") { - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_MIC3_MIC4 - .type.type = AudioDeviceType::IN_MICROPHONE_MULTI, - .type.connection = AudioDeviceDescription::CONNECTION_BUILTIN_MIC3_MIC4}; - mSecFTM.setDevices({factoryTxDevice}, SecFTM::FTM_INPUT); - } else if (paramValue == "mic3") { - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_MIC3 - .type.type = AudioDeviceType::IN_MICROPHONE_MULTI, - .type.connection = AudioDeviceDescription::CONNECTION_BUILTIN_MIC3}; - mSecFTM.setDevices({factoryTxDevice}, SecFTM::FTM_INPUT); - } else if (paramValue == "mic4") { - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_MIC4 - .type.type = AudioDeviceType::IN_MICROPHONE_MULTI, - .type.connection = AudioDeviceDescription::CONNECTION_BUILTIN_MIC4}; - mSecFTM.setDevices({factoryTxDevice}, SecFTM::FTM_INPUT); - } else if (paramValue == "2mic") { - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_2MIC - .type.type = AudioDeviceType::IN_MICROPHONE_MULTI}; - mSecFTM.setDevices({factoryTxDevice}, SecFTM::FTM_INPUT); - } else if (paramValue == "main") { - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_BUILTIN_MIC - .type.type = AudioDeviceType::IN_MICROPHONE}; - mSecFTM.setDevices({factoryTxDevice}, SecFTM::FTM_INPUT); - } else if (paramValue == "sub") { - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_BACK_MIC - .type.type = AudioDeviceType::IN_MICROPHONE_BACK}; - mSecFTM.setDevices({factoryTxDevice}, SecFTM::FTM_INPUT); - } else if (paramValue == "spk_mic1") { /*at + looptest=0,3,4 */ - factoryTxDevice = AudioDevice{ // AUDIO_DEVICE_IN_2MIC - .type.type = AudioDeviceType::IN_MICROPHONE_MULTI}; - mSecFTM.setDevices({factoryTxDevice}, SecFTM::FTM_INPUT); - ftmode |= SecFTM::FACTORY_ATCMD_ACTIVE; - } else if (paramValue == "off") { - ftmode &= ~SecFTM::FACTORY_IN_ROUTE_ACTIVE; - ftmode &= ~SecFTM::FACTORY_ATCMD_ACTIVE; - factoryTxDevice = AudioDevice{.type.type = AudioDeviceType::NONE}; - mSecFTM.setDevices({factoryTxDevice}, SecFTM::FTM_INPUT); - mSecFTM.setRMSTestMode(false); - } - mSecFTM.setFactoryMode(ftmode); - if (ftmode & SecFTM::FACTORY_IN_ROUTE_ACTIVE) { - ForceSetInDevices({factoryTxDevice}); - } - } -#if SEC_AUDIO_MULTI_SPEAKER == 4 - else if (SecParameters::kFactoryTestSpkPath == param.id) { - if (paramValue == "spk1") { - mSecFTM.setFactorySoundBoosterMode(SecFTM::SB_ON_TOP_LEFT); - } else if (paramValue == "spk2") { - mSecFTM.setFactorySoundBoosterMode(SecFTM::SB_ON_TOP_RIGHT); - } else if (paramValue == "spk3") { - mSecFTM.setFactorySoundBoosterMode(SecFTM::SB_ON_BOTTOM_RIGHT); - } else if (paramValue == "spk4") { - mSecFTM.setFactorySoundBoosterMode(SecFTM::SB_ON_BOTTOM_LEFT); - } else if (paramValue == "spk") { - mSecFTM.setFactorySoundBoosterMode(SecFTM::SB_ON_DEFAULT); - } - mAudioEffect.send_factory_soundbooster_mode(mSecFTM.getFactorySoundBoosterMode()); - } -#endif - else if (SecParameters::kFactoryTestCalibration == param.id) { - calCommand = paramValue; - } else if (SecParameters::kFactoryTestCalAmpType == param.id) { - ampType = paramValue; - } - } - -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION - if ((calCommand == AUDIO_PARAMETER_VALUE_ON) - || (calCommand == AUDIO_PARAMETER_VALUE_PASS) - || (calCommand == AUDIO_PARAMETER_VALUE_FAIL)) { - // processing in calibraion helper - processCalibrationParameters(parameters); - if ((calCommand == AUDIO_PARAMETER_VALUE_ON) - && (ampType != AUDIO_PARAMETER_VALUE_CIRRUS)) { - // send trigger calibration parameter to pal - LOG(DEBUG) << __func__ << " triggerSpeakerCalibration"; - mPlatform.triggerSpeakerCalibration(); - } - } -#endif - return; -} - -void SecModulePrimary::onSetSECSubkeyParameters(const std::vector& parameters) { - int ret = 0, val = 0; - char value[32]; - // because of subkey, all parameter sets should be processed at once without dividing. - std::string kvpairs = getkvPairsForVendorParameter(parameters); - struct str_parms *parms = str_parms_create_str(kvpairs.c_str()); - if (!parms) - return; - - LOG(DEBUG) << __func__ << " Enter: " << kvpairs.c_str(); - -#ifdef SEC_AUDIO_CALL - ret = str_parms_get_str(parms, AUDIO_PARAMETER_SEC_LOCAL_DEX_KEY, value, sizeof(value)); - if (ret >= 0) { - ret = str_parms_get_str(parms, AUDIO_PARAMETER_SUBKEY_DEX_TYPE, value, sizeof(value)); - if (ret >= 0) { - if (!strcmp(value, AUDIO_PARAMETER_VALUE_DEX_STATION)) { - ret = str_parms_get_str(parms, AUDIO_PARAMETER_SUBKEY_DEX_CONNECTED, value, sizeof(value)); - if (ret >= 0) { - bool is_connected = (strcmp(value, AUDIO_PARAMETER_VALUE_TRUE)) ? false : true; - if (mPlatform.getDexConnected() != is_connected) { - LOG(INFO) << __func__ << " DEXconnected changed from " - << makeParamValue(mPlatform.getDexConnected()) << " to " - << makeParamValue(is_connected); - mPlatform.setDexConnected(is_connected); - - if (mPlatform.getCallState() == 2/*CallState::ACTIVE*/) { - mTelephony->setDevices(mPlatform.getTelephonyDevices(), true); - } - RerouteForVoip(); - } - str_parms_del(parms, AUDIO_PARAMETER_SUBKEY_DEX_CONNECTED); - } - } else if (!strcmp(value, AUDIO_PARAMETER_VALUE_DEX_PAD)) { - ret = str_parms_get_str(parms, AUDIO_PARAMETER_SUBKEY_DEX_CONNECTED, value, sizeof(value)); - if (ret >= 0) { - bool is_connected = (strcmp(value, AUDIO_PARAMETER_VALUE_TRUE)) ? false : true; - if (mPlatform.getDexPadConnected() != is_connected) { - LOG(INFO) << __func__ << " DEXPADconnected changed from " - << makeParamValue(mPlatform.getDexPadConnected()) << " to " - << makeParamValue(is_connected); - mPlatform.setDexPadConnected(is_connected); -#ifdef SEC_AUDIO_SUPPORT_CALL_MICMODE - if ((mPlatform.getCallMode() == AUDIO_MODE_IN_CALL) - && (mPlatform.getCallIsolationMode() - == EFFECTS_MICMODE_VOICE_FOCUS)) { - if (mPlatform.getCallState() == 2/*CallState::ACTIVE*/) { - mTelephony->configureMicMode(); - } - } -#endif -#ifdef SEC_AUDIO_CALL_VOIP - if (mPlatform.getCallMode() == AUDIO_MODE_IN_COMMUNICATION) { - mAudioEffect.SetVoipMicModeEffect(); - } -#endif - } - str_parms_del(parms, AUDIO_PARAMETER_SUBKEY_DEX_CONNECTED); - } - } - str_parms_del(parms, AUDIO_PARAMETER_SUBKEY_DEX_TYPE); - } - str_parms_del(parms, AUDIO_PARAMETER_SEC_LOCAL_DEX_KEY); - } -#endif - -#ifdef SEC_AUDIO_SAMSUNGRECORD - ret = str_parms_get_str(parms, AUDIO_PARAMETER_SEC_LOCAL_MULTI_MIC_KEY, value, sizeof(value)); - if (ret >= 0) { - PreProcessSetParams(parms); -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_PROVIDEO - ret = str_parms_get_int(parms, AUDIO_PARAMETER_SUBKEY_MULTI_MIC_MODE, &val); - if (ret >= 0) { - SetProVideoState(val); - str_parms_del(parms, AUDIO_PARAMETER_SUBKEY_MULTI_MIC_MODE); - } -#endif - str_parms_del(parms, AUDIO_PARAMETER_SEC_LOCAL_MULTI_MIC_KEY); - } -#endif - -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - ret = str_parms_get_str(parms, AUDIO_PARAMETER_SEC_LOCAL_EFFECT_LISTENBACK_KEY, value, sizeof(value)); - if (ret >= 0) { - ret = str_parms_get_int(parms, AUDIO_PARAMETER_SUBKEY_EFFECT_LISTENBACK_STATE, &val); - if (ret >= 0) { - bool old_state = mPlatform.isListenBackEnabled(); - bool listenback_on = (val == 0) ? false : true; - mPlatform.setListenBackEnabled(listenback_on); - if (old_state != listenback_on) { - updateStreamListenbackMode(listenback_on); - } - str_parms_del(parms, AUDIO_PARAMETER_SUBKEY_EFFECT_LISTENBACK_STATE); - } - } -#endif - str_parms_destroy(parms); -} - -SecModulePrimary::GetParameterToFeatureMap SecModulePrimary::fillGetParameterToFeatureMap() { - GetParameterToFeatureMap map{ - {SecParameters::kAllSoundMuteEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kDualSpeakerAmpLeftPowerEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kGameChatEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwSpeakerAmpBigData, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwSpeakerAmpBigDataSupport, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwSpeakerAmpMaxTemperature, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwSpeakerAmpTemperatureRCV, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kHwSpeakerAmpTemperatureSPK, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kSetupTestcase, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kEffectSoundBoosterDspSupport, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kInterpreterMode, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRecordInputLatency, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRecordTxInversion, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kBargeinMode, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRecordNSRISecurityEnable, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kRecordConversationEnergyKey, SecParameters::Feature_SEC::SEC_GENERIC}, - {SecParameters::kVoiceFactoryEchoRefStatus, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestCalStatus, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestCalOff, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestCalRead, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryTestCalAmpTI, SecParameters::Feature_SEC::SEC_FTM}, - {SecParameters::kFactoryEchoRefMuteDetect, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceCallForwardingEnable, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceHAC, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceHACMode, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceMicInputControlMode, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceMicInputControlModeCall, SecParameters::Feature_SEC::SEC_TELEPHONY}, - {SecParameters::kVoiceScreenCall, SecParameters::Feature_SEC::SEC_TELEPHONY} - }; - return map; -} - -// static -SecModulePrimary::FeatureToGetHandlerMap SecModulePrimary::fillFeatureToGetHandlerMap() { - FeatureToGetHandlerMap map{ - {SecParameters::Feature_SEC::SEC_GENERIC, &SecModulePrimary::onGetSECGenericParameters}, - {SecParameters::Feature_SEC::SEC_TELEPHONY, &SecModulePrimary::onGetSECTelephonyParameters}, - {SecParameters::Feature_SEC::SEC_FTM, &SecModulePrimary::onGetSECFTMParameters} - }; - return map; -} - -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION -SecModulePrimary::CalValueToGetParameterMap SecModulePrimary::fillCalValueToGetParameterMap() { - CalValueToGetParameterMap map{{AUDIO_PARAMETER_VALUE_STATUS, SecParameters::kFactoryTestCalStatus}, - {AUDIO_PARAMETER_VALUE_OFF, SecParameters::kFactoryTestCalOff}, - {AUDIO_PARAMETER_VALUE_READ, SecParameters::kFactoryTestCalRead}}; - return map; -} -#endif - -std::vector SecModulePrimary::processGetVendorParameters( - const std::vector& ids) { - FeatureToStringMap pendingActions{}; - // only group of features are mapped to Feature, rest are kept as generic. - // If the key is found in feature map, use the feature otherwise call GENERIC feature. - for (const auto& id : ids) { - auto search = mGetParameterToFeatureMap.find(id); - SecParameters::Feature_SEC mappedFeature = SecParameters::Feature_SEC::SEC_GENERIC; - if (search != mGetParameterToFeatureMap.cend()) { - mappedFeature = search->second; - } - auto itr = pendingActions.find(mappedFeature); - if (itr == pendingActions.cend()) { - pendingActions[mappedFeature] = std::vector({id}); - continue; - } - itr->second.push_back(id); - } - - std::vector result{}; - for (const auto & [ key, value ] : pendingActions) { - const auto search = mFeatureToGetHandlerMap.find(key); - if (search == mFeatureToGetHandlerMap.cend()) { - LOG(ERROR) << __func__ - << ": no handler set on Feature:" << static_cast(search->first); - continue; - } - auto handler = std::bind(search->second, this, value); - auto keyResult = handler(); // a dynamic dispatch to GetHandler - result.insert(result.end(), keyResult.begin(), keyResult.end()); - } - return result; -} - -std::vector SecModulePrimary::onGetSECGenericParameters( - const std::vector& ids) { - std::vector results{}; - for (const auto& id : ids) { - VendorParameter param; - VString parcel; -#ifdef SEC_AUDIO_ALL_SOUND_MUTE - if (id == SecParameters::kAllSoundMuteEnable) { - param.id = SecParameters::kAllSoundMuteEnable; - parcel.value = makeParamValue(mPlatform.getAllSoundMute()); - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_SETUP_TC - else if (id == SecParameters::kSetupTestcase) { - param.id = SecParameters::kHwInterfaceTestcase; - /* AudioReach - hw interface name defined at SystemAudio */ - parcel.value = AUDIO_PARAMETER_VALUE_TRUE; - setParameter(parcel, param); - results.push_back(param); - } -#endif -#if defined(SEC_AUDIO_DUAL_SPEAKER) && !defined(SEC_AUDIO_FACTORY_TEST_MODE) - else if (id == SecParameters::kDualSpeakerAmpLeftPowerEnable) { - param.id = SecParameters::kDualSpeakerAmpLeftPowerEnable; - parcel.value = makeParamValue(mPlatform.isSpeakerLeftAmpOff()); - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_GAMECHAT_SPK_AEC - else if (id == SecParameters::kGameChatEnable) { - param.id = SecParameters::kGameChatEnable; - parcel.value = makeParamValue(mPlatform.getGamechatMode()); - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_INTERPRETER_MODE - else if (id == SecParameters::kInterpreterMode) { - param.id = SecParameters::kInterpreterMode; - parcel.value = std::to_string(mPlatform.getInterpreterMode()); - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_CAMCORDER - else if (id == SecParameters::kRecordTxInversion) { - param.id = SecParameters::kRecordTxInversion; - parcel.value = makeParamValue(mPlatform.isTxDataInversionEnabled()); - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_NSRI - else if (id == SecParameters::kRecordNSRISecurityEnable) { - param.id = SecParameters::kRecordNSRISecurityEnable; - parcel.value = makeParamValue(mPlatform.isNSRISecureEnabled()); - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_SAMSUNGRECORD - else if (id == SecParameters::kRecordInputLatency) { - param.id = SecParameters::kRecordInputLatency; - auto streamIn = getHighestPriorityStreamIn(); - parcel.value = "0"; - if (streamIn) { - parcel.value = std::to_string(AudioPreProcess::GetLatency(streamIn->getContext().getMixPortConfig(), streamIn->getConnectedDevices())); - } - setParameter(parcel, param); - results.push_back(param); - } -#endif -// { SEC_AUDIO_AMP_BIGDATA - else if (id == SecParameters::kHwSpeakerAmpBigDataSupport) { - param.id = SecParameters::kHwSpeakerAmpBigDataSupport; -#ifdef SEC_AUDIO_AMP_BIGDATA - parcel.value = AUDIO_PARAMETER_VALUE_TRUE; -#else - parcel.value = AUDIO_PARAMETER_VALUE_FALSE; -#endif - setParameter(parcel, param); - results.push_back(param); - } -// } SEC_AUDIO_AMP_BIGDATA -#ifdef SEC_AUDIO_AMP_BIGDATA - else if (id == SecParameters::kHwSpeakerAmpMaxTemperature) { - pal_param_amp_bigdata_t *param_amp_bigdata; - size_t size = 0; - if (int32_t ret = - ::pal_get_param(PAL_PARAM_ID_SPEAKER_AMP_BIGDATA_SAVE, - (void **)¶m_amp_bigdata, &size, nullptr); - (ret || size <= 0)) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_SPEAKER_AMP_BIGDATA_SAVE failed, ret:" << ret - << ", data size:" << size; - } - - if (param_amp_bigdata != NULL) { - param.id = SecParameters::kHwSpeakerAmpMaxTemperature; - std::string kvpairs = - ";rcv=" + std::to_string(param_amp_bigdata->value[KEEP_MAX_TEMP_L]) - + ";spk=" + std::to_string(param_amp_bigdata->value[KEEP_MAX_TEMP_R]); - parcel.value = kvpairs; - setParameter(parcel, param); - results.push_back(param); - } - } - else if (id == SecParameters::kHwSpeakerAmpBigData) { - pal_param_amp_bigdata_t *param_amp_bigdata; - size_t size = 0; - if (int32_t ret = - ::pal_get_param(PAL_PARAM_ID_SPEAKER_AMP_BIGDATA_SAVE_RESET, - (void **)¶m_amp_bigdata, &size, nullptr); - (ret || size <= 0)) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_SPEAKER_AMP_BIGDATA_SAVE_RESET failed, ret:" << ret - << ", data size:" << size; - } - - if (param_amp_bigdata != NULL) { - param.id = SecParameters::kHwSpeakerAmpBigData; - std::string kvpairs = ";"; - std::string logging_item; - for (int i = android::AUDIO_LOGGING_HW_AMP_INDEX_START; i < android::AUDIO_LOGGING_ITEM_MAX; i++) { - logging_item = android::logging_item[i]; - kvpairs += logging_item + "=" - + std::to_string(param_amp_bigdata->value[i-android::AUDIO_LOGGING_HW_AMP_INDEX_START]) + ";"; - } - parcel.value = kvpairs; - setParameter(parcel, param); - results.push_back(param); - } - } -#endif -#ifdef SEC_AUDIO_AMP_SDHMS - else if (id == SecParameters::kHwSpeakerAmpTemperatureRCV || - id == SecParameters::kHwSpeakerAmpTemperatureSPK) { - pal_param_amp_ssrm_t *param_amp_ssrm = NULL; - size_t size = 0; - uint32_t pal_param_id = 0; - if (id == SecParameters::kHwSpeakerAmpTemperatureRCV) { - pal_param_id = PAL_PARAM_ID_SPEAKER_AMP_TEMPERATURE_RCV; - } else { - pal_param_id = PAL_PARAM_ID_SPEAKER_AMP_TEMPERATURE_SPK; - } - - if (int32_t ret = - ::pal_get_param(pal_param_id, (void **)¶m_amp_ssrm, &size, nullptr); - (ret || size <= 0)) { - LOG(ERROR) << __func__ << " pal_param_id:" << pal_param_id <<" failed, ret:" << ret - << ", data size:" << size; - } - if (param_amp_ssrm != NULL) { - param.id = id; - if (param_amp_ssrm->temperature == AMP_OFF_VALUE) { - parcel.value = AUDIO_PARAMETER_VALUE_AMP_OFF; - } else { - LOG(DEBUG) << __func__ << " get temperature for " << id << ": " - << param_amp_ssrm->temperature; - parcel.value = std::to_string(param_amp_ssrm->temperature); - } - setParameter(parcel, param); - results.push_back(param); - } - } -#endif - else if (id == SecParameters::kEffectSoundBoosterDspSupport) { - param.id = SecParameters::kEffectSoundBoosterDspSupport; -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP - parcel.value = AUDIO_PARAMETER_VALUE_TRUE; -#else - parcel.value = AUDIO_PARAMETER_VALUE_FALSE; -#endif - setParameter(parcel, param); - results.push_back(param); - } -#ifdef SEC_AUDIO_BARGEIN_MODE - else if (id == SecParameters::kBargeinMode) { - pal_param_bargein_mode_t param_bargein_mode; - size_t size = 0; - int status = pal_get_param(PAL_PARAM_ID_BARGEIN_MODE, (void**)¶m_bargein_mode, - &size, nullptr); - param.id = SecParameters::kBargeinMode; - if (!status) { - parcel.value = std::to_string(param_bargein_mode.mode); - } else { - parcel.value = std::to_string(-1); - } - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_SAMSUNGRECORD - else if (id == SecParameters::kRecordConversationEnergyKey) { - param.id = "left"; - uint32_t power = mAudioEffect.getInterViewInputEnergy(); - parcel.value = std::to_string((power >> 16) & 0x0000ffff) + - ";right="+std::to_string(power & 0x0000ffff); - setParameter(parcel, param); - results.push_back(param); - } -#endif - else { - LOG(ERROR) << __func__ << ": unknown parameter in Generic feature. id:" << id; - } - } - return results; -} - -std::vector SecModulePrimary::onGetSECTelephonyParameters( - const std::vector& ids) { - std::vector results{}; - for (const auto& id : ids) { - VendorParameter param; - VString parcel; -#ifdef SEC_AUDIO_CALL_HAC - if (id == SecParameters::kVoiceHAC) { - param.id = SecParameters::kVoiceHAC; - parcel.value = mPlatform.getHacIncall() ? AUDIO_PARAMETER_VALUE_HAC_ON : - AUDIO_PARAMETER_VALUE_HAC_OFF; - setParameter(parcel, param); - results.push_back(param); - } - else if (id == SecParameters::kVoiceHACMode) { - param.id = SecParameters::kVoiceHACMode; - parcel.value = std::to_string(mPlatform.getHacMode()); - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_CALL - else if (id == SecParameters::kFactoryEchoRefMuteDetect) { - param.id = SecParameters::kFactoryEchoRefMuteValue; - const auto& ftmResult = mAudioEffect.getEchoRefMute(); - if (ftmResult) { - parcel.value = ftmResult.value(); - } else { - parcel.value = ""; - } - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_CALL_FORWARDING - else if (id == SecParameters::kVoiceCallForwardingEnable) { - param.id = SecParameters::kVoiceCallForwardingEnable; - parcel.value = makeParamValue(mPlatform.getCallForwarding()); - setParameter(parcel, param); - results.push_back(param); - } -#endif -#ifdef SEC_AUDIO_CALL_VOIP - else if (id == SecParameters::kVoiceMicInputControlMode) { - param.id = SecParameters::kVoiceMicInputControlMode; - parcel.value = std::to_string(mPlatform.getVoipIsolationMode()); - setParameter(parcel, param); - results.push_back(param); - } - else if (id == SecParameters::kVoiceMicInputControlModeCall) { - param.id = SecParameters::kVoiceMicInputControlModeCall; - parcel.value = std::to_string(mPlatform.getCallIsolationMode()); - setParameter(parcel, param); - results.push_back(param); - } -#endif - else { - LOG(ERROR) << __func__ << ": unknown parameter in Telephony feature. id:" << id; - } - } - return results; -} - -std::vector SecModulePrimary::onGetSECFTMParameters( - const std::vector& ids) { - std::vector results{}; - std::string calValue{""}; - std::string ampType{""}; - - for (const auto& id : ids) { - VendorParameter param; - VString parcel; - if (id == SecParameters::kVoiceFactoryEchoRefStatus) { - param.id = SecParameters::kVoiceFactoryEchoRefValue; - const auto& ftmResult = mAudioEffect.getSecFTMResult(); - if (ftmResult) { - parcel.value = ftmResult.value(); - } else { - parcel.value = ""; - } - setParameter(parcel, param); - results.push_back(param); - } else if (id == SecParameters::kFactoryTestCalStatus) { - calValue = AUDIO_PARAMETER_VALUE_STATUS; - } else if (id == SecParameters::kFactoryTestCalOff) { - calValue = AUDIO_PARAMETER_VALUE_OFF; - } else if (id == SecParameters::kFactoryTestCalRead) { - calValue = AUDIO_PARAMETER_VALUE_READ; - } else if (id == SecParameters::kFactoryTestCalAmpTI) { - ampType = SecParameters::kFactoryTestCalAmpTI; - results.push_back(makeVendorParameter(id, ampType)); - } else { - LOG(ERROR) << __func__ << ": unknown parameter in FTM feature. id:" << id; - } - } -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION - if (calValue == AUDIO_PARAMETER_VALUE_STATUS - || calValue == AUDIO_PARAMETER_VALUE_OFF - || calValue == AUDIO_PARAMETER_VALUE_READ) { - // processing in calibraion helper - VendorParameter param; - auto search = mCalValueToGetParameterMap.find(calValue); - std::string mappedParamId{}; - if (search != mCalValueToGetParameterMap.cend()) { - mappedParamId = search->second; - } - param = makeVendorParameter(mappedParamId, - getCalibrationResults(calValue, ampType)); - results.push_back(param); - } -#endif - return results; -} - -ndk::ScopedAStatus SecModulePrimary::ForceSetOutDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, bool force) { - - if (devices.empty()) { - LOG(DEBUG) << __func__ << ": stream is not connected"; - //return ndk::ScopedAStatus::ok(); - } - - ModulePrimary::outListMutex.lock(); - std::vector>& outStreams = ModulePrimary::getOutStreams(); - if (!outStreams.empty()) { - for (auto it = outStreams.begin(); it < outStreams.end(); it++) { - if (it->lock() && !it->lock()->isClosed()) { - it->lock()->ForceSetDevices(devices, force); - LOG(DEBUG) << __func__ << " connected to " << devices; - } - } - } - ModulePrimary::outListMutex.unlock(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus SecModulePrimary::ForceSetInDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) { - - if (devices.empty()) { - LOG(DEBUG) << __func__ << ": stream is not connected"; - //return ndk::ScopedAStatus::ok(); - } - - ModulePrimary::inListMutex.lock(); - std::vector>& inStreams = ModulePrimary::getInStreams(); - if (!inStreams.empty()) { - for (auto it = inStreams.begin(); it < inStreams.end(); it++) { - if (it->lock() && !it->lock()->isClosed()) { - it->lock()->ForceSetDevices(devices); - LOG(DEBUG) << __func__ << " connected to " << devices; - } - } - } - ModulePrimary::inListMutex.unlock(); - return ndk::ScopedAStatus::ok(); -} - -std::shared_ptr SecModulePrimary::GetStreamOut(Usecase tag) { - std::shared_ptr streamOut = nullptr; - ModulePrimary::outListMutex.lock(); - std::vector>& outStreams = ModulePrimary::getOutStreams(); - if (!outStreams.empty()) { - for (auto it = outStreams.begin(); it < outStreams.end(); it++) { - if (it->lock() && !it->lock()->isClosed() && it->lock()->isStreamUsecase(tag)) { - streamOut = it->lock(); - break; - } - } - } - ModulePrimary::outListMutex.unlock(); - return streamOut; -} - -std::shared_ptr SecModulePrimary::GetStreamIn(Usecase tag) { - std::shared_ptr streamIn = nullptr; - ModulePrimary::inListMutex.lock(); - std::vector>& inStreams = ModulePrimary::getInStreams(); - if (!inStreams.empty()) { - for (auto it = inStreams.begin(); it < inStreams.end(); it++) { - if (it->lock() && !it->lock()->isClosed() && it->lock()->isStreamUsecase(tag)) { - streamIn = it->lock(); - break; - } - } - } - ModulePrimary::inListMutex.unlock(); - return streamIn; -} - -#ifdef SEC_AUDIO_SAMSUNGRECORD -/* - * Aligned with policy.h - */ -static int source_priority(int inputSource) -{ - switch (inputSource) { - case AUDIO_SOURCE_VOICE_COMMUNICATION: - return 12; - case AUDIO_SOURCE_VOICE_UPLINK: - case AUDIO_SOURCE_VOICE_DOWNLINK: - case AUDIO_SOURCE_VOICE_CALL: - return 11; - case AUDIO_SOURCE_SEC_CAMCORDER: - case AUDIO_SOURCE_CAMCORDER: - return 10; - case AUDIO_SOURCE_VOICE_PERFORMANCE: - return 9; - case AUDIO_SOURCE_VOICENOTE_BEAMFORMING: - case AUDIO_SOURCE_UNPROCESSED: - return 8; - case AUDIO_SOURCE_MIC: - return 7; - case AUDIO_SOURCE_ECHO_REFERENCE: - return 6; - case AUDIO_SOURCE_2MIC_SVOICE_DRIVING: - case AUDIO_SOURCE_2MIC_SVOICE_NORMAL: - case AUDIO_SOURCE_BARGEIN_DRIVING: - case AUDIO_SOURCE_SEC_VOICE_RECOGNITION: - case AUDIO_SOURCE_FM_RX: - case AUDIO_SOURCE_FM_TUNER: - return 5; - case AUDIO_SOURCE_VOICE_RECOGNITION: - return 4; - case AUDIO_SOURCE_HOTWORD: - return 2; - case AUDIO_SOURCE_ULTRASOUND: - return 1; - default: - break; - } - return 0; -} - -std::shared_ptr SecModulePrimary::getHighestPriorityStreamIn() { - std::shared_ptr streamIn = nullptr; - ModulePrimary::inListMutex.lock(); - std::vector>& inStreams = ModulePrimary::getInStreams(); - int last_priority = -1; - int priority = 0; - if (!inStreams.empty()) { - for (auto it = inStreams.begin(); it < inStreams.end(); it++) { - if (it->lock()) { - const auto& source = getAudioSource(it->lock()->getContext().getMixPortConfig()); - priority = source_priority(static_cast(source.value())); - if (priority > last_priority) { - last_priority = priority; - streamIn = it->lock(); - } - } - } - } - ModulePrimary::inListMutex.unlock(); - return streamIn; -} -#endif - -#ifdef SEC_AUDIO_CALL_VOIP -ndk::ScopedAStatus SecModulePrimary::RerouteForVoip() { - auto streamOut = GetStreamOut(Usecase::VOIP_PLAYBACK); - auto streamIn = GetStreamIn(Usecase::VOIP_RECORD); - - if (streamIn) { - streamIn->ForceSetDevices(streamIn->getConnectedDevices()); - } - if (streamOut && mPlatform.getCallMode() == AUDIO_MODE_IN_COMMUNICATION) { - streamOut->ForceSetDevices(streamOut->getConnectedDevices()); - } - - if (streamIn && streamOut) { - mAudioEffect.SetVoipMicModeEffect(); - } - - return ndk::ScopedAStatus::ok(); -} -#endif - -#ifdef SEC_AUDIO_SCREEN_MIRRORING // { SUPPORT_VOIP_VIA_SMART_VIEW -ndk::ScopedAStatus SecModulePrimary::UpdateSmartViewState(bool newVoipViaSmartView) { - if (mPlatform.getVoipViaSmartView() != newVoipViaSmartView) { - mPlatform.setVoipViaSmartView(newVoipViaSmartView); - pal_param_speaker_status_t paramSpeakerStatus = - { newVoipViaSmartView ? PAL_DEVICE_SPEAKER_MUTE : PAL_DEVICE_SPEAKER_UNMUTE }; - if (newVoipViaSmartView) { // mute > routing - pal_set_param(PAL_PARAM_ID_SPEAKER_STATUS, (void*)¶mSpeakerStatus, - sizeof(pal_param_speaker_status_t)); - RerouteForVoip(); - } else { // routing > unmute - RerouteForVoip(); - pal_set_param(PAL_PARAM_ID_SPEAKER_STATUS, (void*)¶mSpeakerStatus, - sizeof(pal_param_speaker_status_t)); - } - } - return ndk::ScopedAStatus::ok(); -} -#endif // } SUPPORT_VOIP_VIA_SMART_VIEW - -#if defined(SEC_AUDIO_SUPPORT_FLIP_CALL) || defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_FOLD_PARAM_ON_DSP) -void SecModulePrimary::SetFolderState(int state) { - - // SEM_LID_STATE_OPEN : 1, SEM_LID_STATE_CLOSED : 0 - // 1) 90 (flex) : flex on & fold open => flex path - // 2) 90 -> 180 : flex off(change)/fold open => normal path - // 3) 90 -> 0 : flex on/fold close(change) => flip path - - bool prevFolderclosed = mPlatform.getFolderclosed(); - bool prevFlexmode = mPlatform.getFlexmode(); - switch (state) { - case FOLDER_CLOSE: - mPlatform.setFolderclosed(true); - break; - case FOLDER_OPEN: - mPlatform.setFolderclosed(false); - break; -#ifdef SEC_AUDIO_SUPPORT_PERSONAL_VIDEOCALL - case FOLDER_FLEX_ON: - mPlatform.setFlexmode(true); - break; - case FOLDER_FLEX_OFF: - mPlatform.setFlexmode(false); - break; -#endif - default: - break; - } - -#ifdef SEC_AUDIO_SUPPORT_FLIP_CALL - if ((prevFolderclosed != mPlatform.getFolderclosed()) || (prevFlexmode != mPlatform.getFlexmode())) { - - LOG(DEBUG) << "Folding(" << (prevFolderclosed != mPlatform.getFolderclosed() ? "Flip":"Flex") - << ") state changed, fold " << (mPlatform.getFolderclosed() ? "close":"open") - << ", flex " << (mPlatform.getFlexmode() ? "on":"off"); - - // by flip state, separate call tx path (folding : -flip path) - // by flex state, separate vt call tx path (flex mode : -flex path) - // by flip state, separate call tx path (folding : -flip path) - if (mPlatform.getCallState() == 2 /* CallState::ACTIVE */) { - mTelephony->setDevices(mPlatform.getTelephonyDevices(), true); - } - RerouteForVoip(); - - if (prevFolderclosed != mPlatform.getFolderclosed()) { - bool isVoicenoteBeamformingActive = false; - ModulePrimary::inListMutex.lock(); - std::vector>& inStreams = ModulePrimary::getInStreams(); - if (!inStreams.empty()) { - for (auto it = inStreams.begin(); it < inStreams.end(); it++) { - ::aidl::android::hardware::audio::common::SinkMetadata sinkMetadata; - if (it->lock() && !it->lock()->isClosed()) { - it->lock()->getMetadata(sinkMetadata); - isVoicenoteBeamformingActive |= - (std::find_if(sinkMetadata.tracks.cbegin(), sinkMetadata.tracks.cend(), - [&](const auto& t) { return static_cast(t.source) - == AUDIO_SOURCE_VOICENOTE_BEAMFORMING; }) - != sinkMetadata.tracks.cend()); - } - } - } - ModulePrimary::inListMutex.unlock(); - if (isVoicenoteBeamformingActive) { - mAudioEffect.SetInterviewMode(!mPlatform.getFolderclosed()); - } - } - } -#endif - -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_FOLD_PARAM_ON_DSP - if (prevFolderclosed != mPlatform.getFolderclosed()) { - mAudioEffect.updateSoundBoosterFoldDegree(); - } -#endif -} -#endif - -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_PROVIDEO -void SecModulePrimary::SetProVideoState(int mode) { -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - bool new_multidevice_rec_state = (mode == MULTIDEVICE_MIC_PROVIDEO_MODE) ? true : false; - if (mPlatform.multidevice_rec != new_multidevice_rec_state) { - LOG(DEBUG) << __func__ << ": multidevice_rec is changed (" << mPlatform.multidevice_rec << " -> " << new_multidevice_rec_state << ")"; - mPlatform.multidevice_rec = new_multidevice_rec_state; - pal_param_btmix_record_t param_btmix; - memset(¶m_btmix, 0, sizeof(param_btmix)); - param_btmix.enable = new_multidevice_rec_state; - pal_set_param(PAL_PARAM_ID_BTMIX_RECORD, (void *)¶m_btmix, - sizeof(param_btmix)); - } - - mPlatform.preprocess_eq_enables &= ~(S_REC_PROVIDEO|S_REC_PROVIDEO_MULTIDEVICE); - if (mode == MULTI_MIC_PROVIDEO_MODE) { - mPlatform.preprocess_eq_enables |= S_REC_PROVIDEO; - } else if (mode == MULTIDEVICE_MIC_PROVIDEO_MODE) { - mPlatform.preprocess_eq_enables |= (S_REC_PROVIDEO|S_REC_PROVIDEO_MULTIDEVICE); - } -#else - if (mode == MULTI_MIC_PROVIDEO_MODE) { - mPlatform.preprocess_eq_enables |= S_REC_PROVIDEO; - } else { - mPlatform.preprocess_eq_enables &= ~(S_REC_PROVIDEO); - } -#endif -} -#endif - -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC -pal_device_id_t SecModulePrimary::getPrimaryOutPalDeviceId() { - pal_device_id_t deviceId = PAL_DEVICE_NONE; - auto streamOut = GetStreamOut(Usecase::PRIMARY_PLAYBACK); - if (streamOut) { - auto connectedDevices = streamOut->getConnectedDevices(); - if (!connectedDevices.empty()) { - auto palDevices = mPlatform.convertToPalDevices(connectedDevices); - deviceId = palDevices[0].id; - } - } - return deviceId; -} -#endif - -#ifdef SEC_AUDIO_COMMON -bool SecModulePrimary::CheckComboDevice() { - - Usecase usecase_list[] = { -#ifdef SEC_AUDIO_SUPPORT_MEDIA_OUTPUT - Usecase::PRIMARY_PLAYBACK, -#else - Usecase::DEEP_BUFFER_PLAYBACK, -#endif - Usecase::HAPTICS_PLAYBACK}; - - int size = sizeof(usecase_list) / sizeof(usecase_list[0]); - for (int i = 0; i < size; i++) { - auto streamOut = GetStreamOut(usecase_list[i]); - if (streamOut == nullptr) { - continue; - } else if (streamOut->HasPalStreamHandle() && - (streamOut->getConnectedDevices().size() == 2)) { - return true; - } - } - return false; -} -#endif - -#ifdef SEC_AUDIO_KARAOKE -void SecModulePrimary::setKaraokeDevice() { - if (!mPlatform.isKaraokeEnabled()) - return; - - bool active_output = false; - std::shared_ptr streamOut = nullptr; - Usecase output_list[] = {Usecase::DEEP_BUFFER_PLAYBACK, - Usecase::ULL_PLAYBACK, - Usecase::LOW_LATENCY_PLAYBACK}; - int size = sizeof(output_list) / sizeof(output_list[0]); - for (int i = 0; i < size; i++) { - streamOut = GetStreamOut(output_list[i]); - if (!streamOut || !streamOut->HasPalStreamHandle() || streamOut->getConnectedDevices().size() > 1) { - continue; - } - - if (streamOut->isDeviceAvailable(PAL_DEVICE_OUT_SPEAKER)) { - std::vector devices = {AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}}; - streamOut->ForceSetDevices(devices); - active_output = true; - } - } - - if (active_output) { - ModulePrimary::inListMutex.lock(); - std::vector>& inStreams = ModulePrimary::getInStreams(); - //in force routing - if (!inStreams.empty()) { - std::vector devices; - devices.push_back(AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_BACK}); - for (auto it = inStreams.begin(); it < inStreams.end(); it++) { - if (it->lock() && !it->lock()->isClosed()) { - it->lock()->ForceSetDevices(devices); - } - } - } - ModulePrimary::inListMutex.unlock(); - } -} -#endif - -#ifdef SEC_AUDIO_BLE_OFFLOAD -void SecModulePrimary::UpdateSCOdeviceState() { - // if sco device active, do shutdown out stream - if (!mPlatform.isBtScoOn()) { - return; - } - - ModulePrimary::outListMutex.lock(); - std::vector>& outStreams = ModulePrimary::getOutStreams(); - if (!outStreams.empty()) { - for (auto it = outStreams.begin(); it < outStreams.end(); it++) { - if (it->lock() && !it->lock()->isClosed()) { - auto devices = it->lock()->getConnectedDevices(); - if (!devices.empty() && - it->lock()->HasPalStreamHandle() && - it->lock()->isDeviceAvailable(PAL_DEVICE_OUT_BLUETOOTH_SCO)) { - LOG(DEBUG) << __func__ << "do forceShutdown for re-open pcm"; - it->lock()->forceShutdown(); - } - } - } - } - ModulePrimary::outListMutex.unlock(); - return; -} -#endif - -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK -bool SecModulePrimary::isListenbackDevice(pal_device_id_t deviceId) { - if (deviceId == PAL_DEVICE_OUT_WIRED_HEADSET || - deviceId == PAL_DEVICE_OUT_WIRED_HEADPHONE || - deviceId == PAL_DEVICE_OUT_USB_HEADSET) { - return true; - } - - return false; -} - -bool SecModulePrimary::isListenbackUsecase(Usecase usecase) { - switch (usecase) { - case Usecase::DEEP_BUFFER_PLAYBACK: - case Usecase::ULL_PLAYBACK: - case Usecase::PCM_RECORD: - case Usecase::FAST_RECORD: - case Usecase::MMAP_RECORD: - return true; - default: - break; - } - return false; -} - -int SecModulePrimary::getListenbackOutputCount() { - Usecase output_list[] = {Usecase::DEEP_BUFFER_PLAYBACK, Usecase::ULL_PLAYBACK}; - int cnt = 0; - int size = sizeof(output_list) / sizeof(output_list[0]); - for (int i = 0; i < size; i++) { - auto streamOut = GetStreamOut(output_list[i]); - // support listenback for 3.5 pi or usb headset only - if (streamOut && streamOut->HasPalStreamHandle()) { - cnt++; - } - } - - return cnt; -} - -void SecModulePrimary::updateStreamListenbackMode(bool enable) { - Usecase output_list[] = {Usecase::DEEP_BUFFER_PLAYBACK, Usecase::ULL_PLAYBACK}; - int size = sizeof(output_list) / sizeof(output_list[0]); - for (int i = 0; i < size; i++) { - auto streamOut = GetStreamOut(output_list[i]); - // support listenback for 3.5 pi or usb headset only - if (streamOut && streamOut->HasPalStreamHandle()) { - streamOut->updateListenback(enable); - break; - } - } -} -#endif - -#ifdef SEC_AUDIO_USB_GAIN_CONTROL -void SecModulePrimary::updateUsbAudioGain() { - LOG(DEBUG) << __func__ << " do ForceSetDevices for gain setting for deep"; - auto streamOut = SecModulePrimary::GetStreamOut(Usecase::DEEP_BUFFER_PLAYBACK); - if (streamOut) { - streamOut->ForceSetDevices(streamOut->getConnectedDevices()); - } -} -#endif - -SecModulePrimary& SecModulePrimary::getInstance() { - static const auto instance = []() { - std::unique_ptr secModulePrimary{new SecModulePrimary()}; - return std::move(secModulePrimary); - }(); - return *(instance.get()); -} - -} diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/SoundDose.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/SoundDose.cpp deleted file mode 100755 index 431d40a6..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/SoundDose.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_SoundDose_QTI" - -#include -#include - -namespace qti::audio::core { - -ndk::ScopedAStatus SoundDose::setOutputRs2UpperBound(float in_rs2ValueDbA) { - if (in_rs2ValueDbA < static_cast(MIN_RS2) || - in_rs2ValueDbA > static_cast(DEFAULT_MAX_RS2)) { - LOG(ERROR) << __func__ << ": RS2 value is invalid: " << in_rs2ValueDbA; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - mRs2Value = in_rs2ValueDbA; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus SoundDose::getOutputRs2UpperBound(float* _aidl_return) { - *_aidl_return = mRs2Value; - LOG(DEBUG) << __func__ << ": returning " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus SoundDose::registerSoundDoseCallback( - const std::shared_ptr& in_callback) { - if (in_callback.get() == nullptr) { - LOG(ERROR) << __func__ << ": Callback is nullptr"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (mCallback != nullptr) { - LOG(ERROR) << __func__ << ": Sound dose callback was already registered"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - - mCallback = in_callback; - LOG(DEBUG) << __func__ << ": Registered sound dose callback "; - return ndk::ScopedAStatus::ok(); -} - -} // namespace qti::audio::core \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/Stream.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/Stream.cpp deleted file mode 100755 index 9b69a939..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/Stream.cpp +++ /dev/null @@ -1,1135 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define ATRACE_TAG (ATRACE_TAG_AUDIO | ATRACE_TAG_HAL) - -#define LOG_TAG "AHAL_Stream_QTI" -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -// uncomment this to enable logging of very verbose logs like burst commands. -// #define VERY_VERBOSE_LOGGING 1 -using aidl::android::hardware::audio::common::AudioOffloadMetadata; -using aidl::android::hardware::audio::common::getChannelCount; -using aidl::android::hardware::audio::common::getFrameSizeInBytes; -using aidl::android::hardware::audio::common::isBitPositionFlagSet; -using aidl::android::hardware::audio::common::SinkMetadata; -using aidl::android::hardware::audio::common::SourceMetadata; -using aidl::android::media::audio::common::AudioDevice; -using aidl::android::media::audio::common::AudioDualMonoMode; -using aidl::android::media::audio::common::AudioInputFlags; -using aidl::android::media::audio::common::AudioIoFlags; -using aidl::android::media::audio::common::AudioLatencyMode; -using aidl::android::media::audio::common::AudioOffloadInfo; -using aidl::android::media::audio::common::AudioOutputFlags; -using aidl::android::media::audio::common::AudioPlaybackRate; -using aidl::android::media::audio::common::MicrophoneDynamicInfo; -using aidl::android::media::audio::common::MicrophoneInfo; - -using ::aidl::android::hardware::audio::common::getChannelCount; -using ::aidl::android::hardware::audio::common::getFrameSizeInBytes; -using ::aidl::android::hardware::audio::core::IStreamCallback; -using ::aidl::android::hardware::audio::core::IStreamCommon; -using ::aidl::android::hardware::audio::core::StreamDescriptor; -using ::aidl::android::hardware::audio::core::VendorParameter; - -namespace qti::audio::core { - -void StreamContext::fillDescriptor(StreamDescriptor* desc) { - if (mCommandMQ) { - desc->command = mCommandMQ->dupeDesc(); - } - if (mReplyMQ) { - desc->reply = mReplyMQ->dupeDesc(); - } - if (mDataMQ) { - desc->frameSizeBytes = getFrameSize(); - desc->bufferSizeFrames = getBufferSizeInFrames(); - desc->audio.set(mDataMQ->dupeDesc()); - } -} - -size_t StreamContext::getBufferSizeInFrames() const { - if (mDataMQ) { - return getFrameSize() ? - mDataMQ->getQuantumCount() * mDataMQ->getQuantumSize() / getFrameSize() : 0; - } - return 0; -} - -size_t StreamContext::getFrameSize() const { - return getFrameSizeInBytes(mFormat, mChannelLayout); -} - -bool StreamContext::isValid() const { - if (mCommandMQ && !mCommandMQ->isValid()) { - LOG(ERROR) << "command FMQ is invalid"; - return false; - } - if (mReplyMQ && !mReplyMQ->isValid()) { - LOG(ERROR) << "reply FMQ is invalid"; - return false; - } - if (getFrameSize() == 0) { - LOG(ERROR) << "frame size is invalid"; - return false; - } - if (mDataMQ && !mDataMQ->isValid()) { - LOG(ERROR) << "data FMQ is invalid"; - return false; - } - return true; -} - -void StreamContext::reset() { - mCommandMQ.reset(); - mReplyMQ.reset(); - mDataMQ.reset(); -} - -pid_t StreamWorkerCommonLogic::getTid() const { -#if defined(__ANDROID__) - return pthread_gettid_np(pthread_self()); -#else - return 0; -#endif -} - -std::string StreamWorkerCommonLogic::init() { - if (mContext->getCommandMQ() == nullptr) return "Command MQ is null"; - if (mContext->getReplyMQ() == nullptr) return "Reply MQ is null"; - StreamContext::DataMQ* const dataMQ = mContext->getDataMQ(); - if (dataMQ == nullptr) return "Data MQ is null"; - if (sizeof(DataBufferElement) != dataMQ->getQuantumSize()) { - return "Unexpected Data MQ quantum size: " + std::to_string(dataMQ->getQuantumSize()); - } - mDataBufferSize = dataMQ->getQuantumCount() * dataMQ->getQuantumSize(); - mDataBuffer.reset(new (std::nothrow) DataBufferElement[mDataBufferSize]); - if (mDataBuffer == nullptr) { - return "Failed to allocate data buffer for element count " + - std::to_string(dataMQ->getQuantumCount()) + ", size in bytes: " + - std::to_string(mDataBufferSize); - } - if (::android::status_t status = mDriver->init(); status != STATUS_OK) { - return "Failed to initialize the driver: " + std::to_string(status); - } - return ""; -} - -void StreamWorkerCommonLogic::populateReply(StreamDescriptor::Reply* reply, - bool isConnected) const { - if (reply->status != STATUS_DEAD_OBJECT) { - reply->status = STATUS_OK; - } - - static const StreamDescriptor::Position kUnknownPosition = { - .frames = StreamDescriptor::Position::UNKNOWN, - .timeNs = StreamDescriptor::Position::UNKNOWN}; - - reply->latencyMs = mContext->getNominalLatencyMs(); - - reply->observable.frames = mContext->getFrameCount(); - reply->observable.timeNs = ::android::uptimeNanos(); - if (auto status = mDriver->refinePosition(reply); status == ::android::OK) { - return; - } - else { - if (hasMMapFlagsEnabled(mContext->getFlags())) { - // if mmap position fails,return error to framework - // for any error other than.. not enough data, AAudio will stop - reply->status = STATUS_INVALID_OPERATION; - } - } - - reply->observable = reply->hardware = kUnknownPosition; -} - -void StreamWorkerCommonLogic::populateReplyWrongState( - StreamDescriptor::Reply* reply, const StreamDescriptor::Command& command) const { - LOG(WARNING) << "command '" << toString(command.getTag()) - << "' can not be handled in the state " << toString(mState); - reply->status = STATUS_INVALID_OPERATION; -} - -const std::string StreamInWorkerLogic::kThreadName = "reader"; - -StreamInWorkerLogic::Status StreamInWorkerLogic::cycle() { - // Note: for input streams, draining is driven by the client, thus - // "empty buffer" condition can only happen while handling the 'burst' - // command. Thus, unlike for output streams, it does not make sense to - // delay the 'DRAINING' state here by 'mTransientStateDelayMs'. - // TODO: Add a delay for transitions of async operations when/if they added. - - StreamDescriptor::Command command{}; - if (!mContext->getCommandMQ()->readBlocking(&command, 1)) { - LOG(ERROR) << __func__ << ": reading of command from MQ failed"; - mState = StreamDescriptor::State::ERROR; - return Status::ABORT; - } - using Tag = StreamDescriptor::Command::Tag; - using LogSeverity = ::android::base::LogSeverity; - const LogSeverity severity = - command.getTag() == Tag::burst || command.getTag() == Tag::getStatus - ? LogSeverity::VERBOSE - : LogSeverity::DEBUG; - -#ifdef VERY_VERBOSE_LOGGING - LOG(severity) << __func__ << ": received command " << command.toString() << " in " - << kThreadName; -#else - if (command.getTag() != Tag::burst && command.getTag() != Tag::getStatus) - LOG(DEBUG) << __func__ << ": received command " << command.toString() << " in " - << kThreadName; -#endif - - StreamDescriptor::Reply reply{}; - reply.status = STATUS_BAD_VALUE; - switch (command.getTag()) { - case Tag::halReservedExit: - if (const int32_t cookie = command.get(); - cookie == mContext->getInternalCommandCookie()) { - mDriver->shutdown(); - setClosed(); - // This is an internal command, no need to reply. - return Status::EXIT; - } else { - LOG(WARNING) << __func__ << ": EXIT command has a bad cookie: " << cookie; - } - break; - case Tag::getStatus: - populateReply(&reply, mIsConnected); - break; - case Tag::start: - if (mState == StreamDescriptor::State::STANDBY || - mState == StreamDescriptor::State::DRAINING) { - if (::android::status_t status = mDriver->start(); status == ::android::OK) { - populateReply(&reply, mIsConnected); - mState = mState == StreamDescriptor::State::STANDBY - ? StreamDescriptor::State::IDLE - : StreamDescriptor::State::ACTIVE; - } else { - LOG(ERROR) << __func__ << ": start failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - } else { - populateReplyWrongState(&reply, command); - } - break; - case Tag::burst: - if (const int32_t fmqByteCount = command.get(); fmqByteCount >= 0) { -#ifdef VERY_VERBOSE_LOGGING - LOG(VERBOSE) << __func__ << ": '" << toString(command.getTag()) << "' command for " - << fmqByteCount << " bytes"; -#endif - if (mState == StreamDescriptor::State::IDLE || - mState == StreamDescriptor::State::ACTIVE || - mState == StreamDescriptor::State::PAUSED || - mState == StreamDescriptor::State::DRAINING) { - if (!read(fmqByteCount, &reply)) { - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - if (mState == StreamDescriptor::State::IDLE || - mState == StreamDescriptor::State::PAUSED) { - mState = StreamDescriptor::State::ACTIVE; - } else if (mState == StreamDescriptor::State::DRAINING) { - // To simplify the reference code, we assume that the - // read operation has consumed all the data remaining in - // the hardware buffer. In a real implementation, here - // we would either remain in the 'DRAINING' state, or - // transfer to 'STANDBY' depending on the buffer state. - mState = StreamDescriptor::State::STANDBY; - } - } else { - populateReplyWrongState(&reply, command); - } - } else { - LOG(WARNING) << __func__ << ": invalid burst byte count: " << fmqByteCount; - } - break; - case Tag::drain: - if (const auto mode = command.get(); - mode == StreamDescriptor::DrainMode::DRAIN_UNSPECIFIED) { - if (mState == StreamDescriptor::State::ACTIVE) { - if (::android::status_t status = mDriver->drain(mode); - status == ::android::OK) { - populateReply(&reply, mIsConnected); - mState = StreamDescriptor::State::DRAINING; - } else { - LOG(ERROR) << __func__ << ": drain failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - } else { - populateReplyWrongState(&reply, command); - } - } else { - LOG(WARNING) << __func__ << ": invalid drain mode: " << toString(mode); - } - break; - case Tag::standby: - if (mState == StreamDescriptor::State::IDLE) { - if (::android::status_t status = mDriver->standby(); status == ::android::OK) { - populateReply(&reply, mIsConnected); - mState = StreamDescriptor::State::STANDBY; - } else { - LOG(ERROR) << __func__ << ": standby failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - } else { - populateReplyWrongState(&reply, command); - } - break; - case Tag::pause: - if (mState == StreamDescriptor::State::ACTIVE) { - if (::android::status_t status = mDriver->pause(); status == ::android::OK) { - populateReply(&reply, mIsConnected); - mState = StreamDescriptor::State::PAUSED; - } else { - LOG(ERROR) << __func__ << ": pause failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - } else { - populateReplyWrongState(&reply, command); - } - break; - case Tag::flush: - if (mState == StreamDescriptor::State::PAUSED) { - if (::android::status_t status = mDriver->flush(); status == ::android::OK) { - populateReply(&reply, mIsConnected); - mState = StreamDescriptor::State::STANDBY; - } else { - LOG(ERROR) << __func__ << ": flush failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - } else { - populateReplyWrongState(&reply, command); - } - break; - } - reply.state = mState; - LOG(severity) << __func__ << ": writing reply " << reply.toString(); - if (!mContext->getReplyMQ()->writeBlocking(&reply, 1)) { - LOG(ERROR) << __func__ << ": writing of reply " << reply.toString() << " to MQ failed"; - mState = StreamDescriptor::State::ERROR; - return Status::ABORT; - } - return Status::CONTINUE; -} - -bool StreamInWorkerLogic::read(size_t clientSize, StreamDescriptor::Reply* reply) { - ATRACE_CALL(); - StreamContext::DataMQ* const dataMQ = mContext->getDataMQ(); - const size_t byteCount = std::min({clientSize, dataMQ->availableToWrite(), mDataBufferSize}); - const bool isConnected = mIsConnected; - const size_t frameSize = mContext->getFrameSize(); - size_t actualFrameCount = 0; - bool fatal = false; - int32_t latency = mContext->getNominalLatencyMs(); - if (frameSize == 0) { - LOG(ERROR) << __func__ << "frame size is invalid"; - return fatal; - } - if (isConnected) { - if (::android::status_t status = mDriver->transfer(mDataBuffer.get(), byteCount / frameSize, - &actualFrameCount, &latency); - status != ::android::OK) { - fatal = true; - LOG(ERROR) << __func__ << ": read failed: " << status; - } - } else { - usleep(3000); // Simulate blocking transfer delay. - for (size_t i = 0; i < byteCount; ++i) mDataBuffer[i] = 0; - actualFrameCount = byteCount / frameSize; - } - const size_t actualByteCount = actualFrameCount * frameSize; - if (bool success = actualByteCount > 0 ? dataMQ->write(&mDataBuffer[0], actualByteCount) : true; - success) { -#ifdef VERY_VERBOSE_LOGGING - LOG(VERBOSE) << __func__ << ": writing of " << actualByteCount << " bytes into data MQ" - << " succeeded; connected? " << isConnected; -#endif - // Frames are provided and counted regardless of connection status. - reply->fmqByteCount += actualByteCount; - mContext->advanceFrameCount(actualFrameCount); - populateReply(reply, isConnected); - } else { - LOG(WARNING) << __func__ << ": writing of " << actualByteCount - << " bytes of data to MQ failed"; - reply->status = STATUS_NOT_ENOUGH_DATA; - } - reply->latencyMs = latency; - return !fatal; -} - -const std::string StreamOutWorkerLogic::kThreadName = "writer"; - -void StreamOutWorkerLogic::publishTransferReady() { - if (!mContext->getAsyncCallback()) { - return; - } - std::unique_lock lock{mAsyncMutex}; - mPendingCallBack = std::nullopt; - if (mState == StreamDescriptor::State::TRANSFERRING) { - mState = StreamDescriptor::State::ACTIVE; - mContext->getAsyncCallback()->onTransferReady(); - LOG(VERBOSE) << __func__ << ": sent transfer ready to client"; - } else if (mState == StreamDescriptor::State::TRANSFER_PAUSED) { - mPendingCallBack = StreamCallbackType::TR; - LOG(VERBOSE) << __func__ << ": pending transfer ready"; - } else { - LOG(WARNING) << __func__ << ": shouldn't happen !!"; - } -} - -void StreamOutWorkerLogic::publishDrainReady() { - if (!mContext->getAsyncCallback()) { - return; - } - std::unique_lock lock{mAsyncMutex}; - mPendingCallBack = std::nullopt; - if (mState == StreamDescriptor::State::DRAINING) { - mContext->getAsyncCallback()->onDrainReady(); - if (mRecentDrainMode == StreamDescriptor::DrainMode::DRAIN_ALL) - mState = StreamDescriptor::State::IDLE; - LOG(VERBOSE) << __func__ << ": sent drain ready to client"; - } else if (mState == StreamDescriptor::State::DRAIN_PAUSED) { - mPendingCallBack = StreamCallbackType::DR; - LOG(VERBOSE) << __func__ << ": pending drain ready"; - } else { - LOG(WARNING) << __func__ << ": shouldn't happen !!"; - } -} - -void StreamOutWorkerLogic::publishError() { - if (!mContext->getAsyncCallback()) { - return; - } - mContext->getAsyncCallback()->onError(); - LOG(WARNING) << __func__ << ": sent Error to the client"; -} - -StreamOutWorkerLogic::Status StreamOutWorkerLogic::cycle() { - StreamDescriptor::Command command{}; - if (!mContext->getCommandMQ()->readBlocking(&command, 1)) { - LOG(ERROR) << __func__ << ": reading of command from MQ failed"; - mState = StreamDescriptor::State::ERROR; - return Status::ABORT; - } - - std::unique_lock asyncLock{mAsyncMutex, std::defer_lock}; - if (mContext->getAsyncCallback()) { - // Accquring the lock in case of Asynchronous Stream - asyncLock.lock(); - } else { - // Synchronous case - if (mState == StreamDescriptor::State::DRAINING) { - if (auto stateDurationMs = std::chrono::duration_cast( - std::chrono::steady_clock::now() - mTransientStateStart); - stateDurationMs >= mTransientStateDelayMs) { - // In blocking mode, after some duration, expecting, hardware is drained. - mState = StreamDescriptor::State::IDLE; - } - } - } - - LOG(VERBOSE) << __func__ << ": received command " << command.toString() << " in " - << kThreadName; - - StreamDescriptor::Reply reply{}; - reply.status = STATUS_BAD_VALUE; - using Tag = StreamDescriptor::Command::Tag; - switch (command.getTag()) { - case Tag::halReservedExit: - if (const int32_t cookie = command.get(); - cookie == mContext->getInternalCommandCookie()) { -#ifdef SEC_AUDIO_OFFLOAD - if (mContext->getAsyncCallback()) { - // do explicit unlock - asyncLock.unlock(); - } - mDriver->shutdown(); - if (mContext->getAsyncCallback()) { - // do explicit lock - asyncLock.lock(); - } -#else - mDriver->shutdown(); -#endif - setClosed(); - // This is an internal command, no need to reply. - return Status::EXIT; - } else { - LOG(WARNING) << __func__ << ": EXIT command has a bad cookie: " << cookie; - } - break; - case Tag::getStatus: - populateReply(&reply, mIsConnected); - break; - case Tag::start: { - std::optional nextState; - switch (mState) { - case StreamDescriptor::State::STANDBY: - nextState = StreamDescriptor::State::IDLE; - break; - case StreamDescriptor::State::PAUSED: - nextState = StreamDescriptor::State::ACTIVE; - break; - case StreamDescriptor::State::DRAIN_PAUSED: - nextState = StreamDescriptor::State::DRAINING; - break; - case StreamDescriptor::State::TRANSFER_PAUSED: - nextState = StreamDescriptor::State::TRANSFERRING; - break; - default: - populateReplyWrongState(&reply, command); - } - if (nextState.has_value()) { - if (::android::status_t status = mDriver->start(); status == ::android::OK) { - populateReply(&reply, mIsConnected); - if (*nextState == StreamDescriptor::State::IDLE || - *nextState == StreamDescriptor::State::ACTIVE) { - mState = *nextState; - } else { - switchToTransientState(*nextState); - } - } else { - LOG(ERROR) << __func__ << ": start failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - } - } break; - case Tag::burst: - if (const int32_t fmqByteCount = command.get(); fmqByteCount >= 0) { -#ifdef VERY_VERBOSE_LOGGING - LOG(VERBOSE) << __func__ << ": '" << toString(command.getTag()) << "' command for " - << fmqByteCount << " bytes"; -#endif - if (mState != StreamDescriptor::State::ERROR && - mState != StreamDescriptor::State::TRANSFERRING && - mState != StreamDescriptor::State::TRANSFER_PAUSED) { - if (!write(fmqByteCount, &reply)) { - LOG(ERROR) << __func__ << ": write failed, but dont put in error state "; - } - std::shared_ptr asyncCallback = mContext->getAsyncCallback(); - if (mState == StreamDescriptor::State::STANDBY || - mState == StreamDescriptor::State::DRAIN_PAUSED || - mState == StreamDescriptor::State::PAUSED) { - if (asyncCallback == nullptr || - mState != StreamDescriptor::State::DRAIN_PAUSED) { - mState = StreamDescriptor::State::PAUSED; - } else { - mState = StreamDescriptor::State::TRANSFER_PAUSED; - } - } else if (mState == StreamDescriptor::State::IDLE || - mState == StreamDescriptor::State::DRAINING || - mState == StreamDescriptor::State::ACTIVE) { - if (asyncCallback == nullptr || reply.fmqByteCount == fmqByteCount) { - mState = StreamDescriptor::State::ACTIVE; - } else { - //If write status is not ok, then dont put state in transferring - if (reply.status == STATUS_OK) { - switchToTransientState(StreamDescriptor::State::TRANSFERRING); - } - } - } - } else { - populateReplyWrongState(&reply, command); - } - } else { - LOG(WARNING) << __func__ << ": invalid burst byte count: " << fmqByteCount; - } - break; - case Tag::drain: - if (mRecentDrainMode = command.get(); - mRecentDrainMode == StreamDescriptor::DrainMode::DRAIN_ALL || - mRecentDrainMode == StreamDescriptor::DrainMode::DRAIN_EARLY_NOTIFY) { - if (mState == StreamDescriptor::State::ACTIVE || - mState == StreamDescriptor::State::TRANSFERRING) { - if (::android::status_t status = mDriver->drain(mRecentDrainMode); - status == ::android::OK) { - populateReply(&reply, mIsConnected); - if (mState == StreamDescriptor::State::ACTIVE && - mContext->getForceSynchronousDrain()) { - mState = StreamDescriptor::State::IDLE; - } else { - switchToTransientState(StreamDescriptor::State::DRAINING); - } - } else { - LOG(ERROR) << __func__ << ": drain failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - } else if (mState == StreamDescriptor::State::TRANSFER_PAUSED) { - mState = StreamDescriptor::State::DRAIN_PAUSED; - populateReply(&reply, mIsConnected); - } else { - populateReplyWrongState(&reply, command); - } - } else { - LOG(WARNING) << __func__ << ": invalid drain mode: " << toString(mRecentDrainMode); - } - break; - case Tag::standby: - if (mState == StreamDescriptor::State::IDLE) { - if (mContext->getAsyncCallback()) { - // do explicit unlock, so that callback can acquire - asyncLock.unlock(); - } - if (::android::status_t status = mDriver->standby(); status == ::android::OK) { - populateReply(&reply, mIsConnected); - mState = StreamDescriptor::State::STANDBY; - } else { - LOG(ERROR) << __func__ << ": standby failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - if (mContext->getAsyncCallback()) { - // do explicit lock - asyncLock.lock(); - } - } else { - populateReplyWrongState(&reply, command); - } - break; - case Tag::pause: { - std::optional nextState; - switch (mState) { - case StreamDescriptor::State::ACTIVE: - nextState = StreamDescriptor::State::PAUSED; - break; - case StreamDescriptor::State::DRAINING: - nextState = StreamDescriptor::State::DRAIN_PAUSED; - break; - case StreamDescriptor::State::TRANSFERRING: - nextState = StreamDescriptor::State::TRANSFER_PAUSED; - break; - default: - populateReplyWrongState(&reply, command); - } - if (nextState.has_value()) { - if (::android::status_t status = mDriver->pause(); status == ::android::OK) { - populateReply(&reply, mIsConnected); - mState = nextState.value(); - } else { - LOG(ERROR) << __func__ << ": pause failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - } - } break; - case Tag::flush: - if (mState == StreamDescriptor::State::PAUSED || - mState == StreamDescriptor::State::DRAIN_PAUSED || - mState == StreamDescriptor::State::TRANSFER_PAUSED) { - if (::android::status_t status = mDriver->flush(); status == ::android::OK) { - populateReply(&reply, mIsConnected); - mState = StreamDescriptor::State::IDLE; - } else { - LOG(ERROR) << __func__ << ": flush failed: " << status; - // uncomment below, to treat the failure as HARD error, stream not recoverable - // mState = StreamDescriptor::State::ERROR; - } - } else { - populateReplyWrongState(&reply, command); - } - break; - } - reply.state = mState; - - using LogSeverity = ::android::base::LogSeverity; - const LogSeverity severity = - (reply.status != STATUS_OK) ? LogSeverity::ERROR : LogSeverity::VERBOSE; - LOG(severity) << __func__ << ": writing reply " << reply.toString(); - - if (!mContext->getReplyMQ()->writeBlocking(&reply, 1)) { - LOG(ERROR) << __func__ << ": writing of reply " << reply.toString() << " to MQ failed"; - mState = StreamDescriptor::State::ERROR; - return Status::ABORT; - } - - if (mContext->getAsyncCallback() && mPendingCallBack && command.getTag() != Tag::getStatus) { - /** - * After the writing the reply, handle the pending callback, if any - * and issue to the client based on the stream state. - **/ - if (command.getTag() == Tag::start && mState == StreamDescriptor::State::TRANSFERRING && - mPendingCallBack == StreamCallbackType::TR) { - mContext->getAsyncCallback()->onTransferReady(); - mState = StreamDescriptor::State::ACTIVE; - mPendingCallBack = {}; - LOG(VERBOSE) << __func__ << ": sent pending transfer ready !!!"; - } else if (command.getTag() == Tag::start && mState == StreamDescriptor::State::DRAINING && - mPendingCallBack == StreamCallbackType::DR) { - mContext->getAsyncCallback()->onDrainReady(); - if (mRecentDrainMode == StreamDescriptor::DrainMode::DRAIN_ALL) - mState = StreamDescriptor::State::IDLE; - mPendingCallBack = {}; - LOG(VERBOSE) << __func__ << ": sent pending drain ready !!!"; - } else if (command.getTag() == Tag::flush || command.getTag() == Tag::drain) { - // clear the pending callbacks - mPendingCallBack = {}; - LOG(VERBOSE) << __func__ << ": cleared the pending callback !!!"; - } else { - // clear the pending callbacks - // mPendingCallBack = {}; - LOG(WARNING) << __func__ << ": shouldn't happen !!!"; - } - } - - return Status::CONTINUE; -} - -bool StreamOutWorkerLogic::write(size_t clientSize, StreamDescriptor::Reply* reply) { - ATRACE_CALL(); - StreamContext::DataMQ* const dataMQ = mContext->getDataMQ(); - const size_t readByteCount = dataMQ->availableToRead(); - const size_t frameSize = mContext->getFrameSize(); - bool fatal = false; - int32_t latency = mContext->getNominalLatencyMs(); - if (frameSize == 0) { - LOG(ERROR) << __func__ << "frame size is invalid"; - return fatal; - } - if (bool success = readByteCount > 0 ? dataMQ->read(&mDataBuffer[0], readByteCount) : true) { - const bool isConnected = mIsConnected; -#ifdef VERY_VERBOSE_LOGGING - LOG(VERBOSE) << __func__ << ": reading of " << readByteCount << " bytes from data MQ" - << " succeeded; connected? " << isConnected; -#endif - // Amount of data that the HAL module is going to actually use. - size_t byteCount = std::min({clientSize, readByteCount, mDataBufferSize}); - if (byteCount >= frameSize && mContext->getForceTransientBurst()) { - // In order to prevent the state machine from going to ACTIVE state, - // simulate partial write. - byteCount -= frameSize; - } - size_t actualFrameCount = 0; - // No need to check for connected device, if there is issue, write returns failure - if (::android::status_t status = mDriver->transfer( - mDataBuffer.get(), byteCount / frameSize, &actualFrameCount, &latency); - status != ::android::OK) { - reply->status = STATUS_DEAD_OBJECT; - fatal = true; - LOG(ERROR) << __func__ << ": write failed: " << status; - } - - const size_t actualByteCount = actualFrameCount * frameSize; - // Frames are consumed and counted regardless of the connection status. - if (actualByteCount > - static_cast(std::numeric_limits::max() - reply->fmqByteCount)) { - reply->fmqByteCount = std::numeric_limits::max(); - } else { - reply->fmqByteCount += actualByteCount; - } - if (actualByteCount > static_cast(LONG_MAX - mContext->getFrameCount())) { - mContext->advanceFrameCount(LONG_MAX - mContext->getFrameCount()); - } else { - mContext->advanceFrameCount(actualFrameCount); - } - populateReply(reply, isConnected); - } else { - LOG(WARNING) << __func__ << ": reading of " << readByteCount - << " bytes of data from MQ failed"; - reply->status = STATUS_NOT_ENOUGH_DATA; - } - reply->latencyMs = latency; - return !fatal; -} - -StreamCommonImpl::~StreamCommonImpl() { - if (!isClosed()) { - LOG(ERROR) << __func__ << ": stream was not closed prior to destruction, resource leak"; - stopWorker(); - // The worker and the context should clean up by themselves via - // destructors. - } - LOG(VERBOSE) << __func__ << ": destroy " << std::hex << this; -} - -ndk::ScopedAStatus StreamCommonImpl::initInstance( - const std::shared_ptr& delegate) { - mCommon = ndk::SharedRefBase::make(delegate); - if (!mWorker->start()) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - if (auto flags = getContext().getFlags(); - (flags.getTag() == AudioIoFlags::Tag::input && - isBitPositionFlagSet(flags.template get(), - AudioInputFlags::FAST)) || - (flags.getTag() == AudioIoFlags::Tag::output && - isBitPositionFlagSet(flags.template get(), - AudioOutputFlags::FAST))) { - // FAST workers should be run with a SCHED_FIFO scheduler, however the host process - // might be lacking the capability to request it, thus a failure to set is not an error. - pid_t workerTid = mWorker->getTid(); - if (workerTid > 0) { - struct sched_param param; - param.sched_priority = 3; // Must match SchedulingPolicyService.PRIORITY_MAX (Java). - LOG(DEBUG) << __func__ << ": increase scheduling for tid : " << workerTid; - if (sched_setscheduler(workerTid, SCHED_FIFO | SCHED_RESET_ON_FORK, ¶m) != 0) { - LOG(WARNING) << __func__ << ": failed to set FIFO scheduler for a fast thread"; - } - } else { - LOG(WARNING) << __func__ << ": invalid worker tid: " << workerTid; - } - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamCommonImpl::getStreamCommonCommon( - std::shared_ptr* _aidl_return) { - if (!mCommon) { - LOG(FATAL) << __func__ << ": the common interface was not created"; - } - *_aidl_return = mCommon.getInstance(); - LOG(DEBUG) << __func__ << ": returning " << _aidl_return->get()->asBinder().get(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamCommonImpl::updateHwAvSyncId(int32_t in_hwAvSyncId) { - LOG(DEBUG) << __func__ << ": id " << in_hwAvSyncId; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamCommonImpl::getVendorParameters( - const std::vector& in_ids, std::vector* _aidl_return) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamCommonImpl::setVendorParameters( - const std::vector& in_parameters, bool in_async) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamCommonImpl::addEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) { - if (in_effect == nullptr) { - LOG(DEBUG) << __func__ << ": null effect"; - } else { - LOG(DEBUG) << __func__ << ": effect Binder" << in_effect->asBinder().get(); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamCommonImpl::removeEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) { - if (in_effect == nullptr) { - LOG(DEBUG) << __func__ << ": null effect"; - } else { - LOG(DEBUG) << __func__ << ": effect Binder" << in_effect->asBinder().get(); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamCommonImpl::close() { - ModulePrimary::outListMutex.lock(); - LOG(DEBUG) << __func__; - if (!isClosed()) { - stopWorker(); - LOG(DEBUG) << __func__ << ": joining the worker thread..."; - mWorker->join(); - LOG(DEBUG) << __func__ << ": worker thread joined"; - onClose(); - mWorker->setClosed(); - ModulePrimary::outListMutex.unlock(); - return ndk::ScopedAStatus::ok(); - } else { - LOG(ERROR) << __func__ << ": stream was already closed"; - ModulePrimary::outListMutex.unlock(); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } -} - -ndk::ScopedAStatus StreamCommonImpl::prepareToClose() { - LOG(DEBUG) << __func__; - if (!isClosed()) { - return ndk::ScopedAStatus::ok(); - } - LOG(ERROR) << __func__ << ": stream was closed"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); -} - -void StreamCommonImpl::stopWorker() { - if (auto commandMQ = mContextRef.getCommandMQ(); commandMQ != nullptr) { - LOG(DEBUG) << __func__ << ": asking the worker to exit..."; - auto cmd = StreamDescriptor::Command::make( - mContextRef.getInternalCommandCookie()); - // Note: never call 'pause' and 'resume' methods of StreamWorker - // in the HAL implementation. These methods are to be used by - // the client side only. Preventing the worker loop from running - // on the HAL side can cause a deadlock. - if (!commandMQ->writeBlocking(&cmd, 1)) { - LOG(ERROR) << __func__ << ": failed to write exit command to the MQ"; - } - LOG(DEBUG) << __func__ << ": done"; - } -} - -ndk::ScopedAStatus StreamCommonImpl::updateMetadataCommon(const Metadata& metadata) { - LOG(DEBUG) << __func__; - if (!isClosed()) { - if (metadata.index() != mMetadata.index()) { - LOG(FATAL) << __func__ << ": changing metadata variant is not allowed"; - } - mMetadata = metadata; - return ndk::ScopedAStatus::ok(); - } - LOG(ERROR) << __func__ << ": stream was closed"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); -} - -ndk::ScopedAStatus StreamCommonImpl::setConnectedDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) { - mWorker->setIsConnected(!devices.empty()); - mConnectedDevices = devices; - return ndk::ScopedAStatus::ok(); -} - -void StreamCommonImpl::setStreamMicMute(const bool muted) { - return; -} - -ndk::ScopedAStatus StreamCommonImpl::configureMMapStream(int32_t* fd, int64_t* burstSizeFrames, - int32_t* flags, - int32_t* bufferSizeFrames) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -#ifdef SEC_AUDIO_COMMON -ndk::ScopedAStatus StreamCommonImpl::ForceSetDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, bool force) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); -} -bool StreamCommonImpl::isStreamUsecase(Usecase tag) { return false; }; -bool StreamCommonImpl::isDeviceAvailable(pal_device_id_t pal_device) { return false; }; -bool StreamCommonImpl::HasPalStreamHandle() { return false; }; -void StreamCommonImpl::forceShutdown() { return; }; -bool StreamCommonImpl::isCustomKeyRouted(const int ck_id) { - if (mPalDevices.size() == 0) { - return false; - } - return (strcmp(mPalDevices[0].custom_config.custom_key, ck_table[ck_id]) == 0); -} -#endif -#ifdef SEC_AUDIO_INTERPRETER_MODE -void StreamCommonImpl::RerouteForInterpreter() { return; }; -#endif - -namespace { -static std::map transformMicrophones( - const std::vector& microphones) { - std::map result; - std::transform(microphones.begin(), microphones.end(), std::inserter(result, result.begin()), - [](const auto& mic) { return std::make_pair(mic.device, mic.id); }); - return result; -} -} // namespace - -StreamIn::StreamIn(StreamContext&& context, const std::vector& microphones) - : mContext(std::move(context)), mMicrophones(transformMicrophones(microphones)) { - LOG(DEBUG) << __func__; -} - -void StreamIn::defaultOnClose() { - mContext.reset(); -} - -#ifdef SEC_AUDIO_SAMSUNGRECORD -std::shared_ptr StreamIn::PreProcessInit() { - std::shared_ptr preprocess(new AudioPreProcess()); - - return preprocess; -} -#endif - -ndk::ScopedAStatus StreamIn::getActiveMicrophones( - std::vector* _aidl_return) { - std::vector result; - std::vector channelMapping{ - getChannelCount(getContext().getChannelLayout()), - MicrophoneDynamicInfo::ChannelMapping::DIRECT}; - for (auto it = getConnectedDevices().begin(); it != getConnectedDevices().end(); ++it) { - if (auto micIt = mMicrophones.find(*it); micIt != mMicrophones.end()) { - MicrophoneDynamicInfo dynMic; - dynMic.id = micIt->second; - dynMic.channelMapping = channelMapping; - result.push_back(std::move(dynMic)); - } - } - *_aidl_return = std::move(result); - LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamIn::getMicrophoneDirection(MicrophoneDirection* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamIn::setMicrophoneDirection(MicrophoneDirection in_direction) { - LOG(DEBUG) << __func__ << ": direction " << toString(in_direction); - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamIn::getMicrophoneFieldDimension(float* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamIn::setMicrophoneFieldDimension(float in_zoom) { - LOG(DEBUG) << __func__ << ": zoom " << in_zoom; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamIn::getHwGain(std::vector* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamIn::setHwGain(const std::vector& in_channelGains) { - LOG(DEBUG) << __func__ << ": gains " << ::android::internal::ToString(in_channelGains); - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -StreamOut::StreamOut(StreamContext&& context, const std::optional& offloadInfo) - : mContext(std::move(context)), mOffloadInfo(offloadInfo) { - LOG(DEBUG) << __func__; -} - -void StreamOut::defaultOnClose() { - mContext.reset(); -} - -ndk::ScopedAStatus StreamOut::updateOffloadMetadata( - const AudioOffloadMetadata& in_offloadMetadata) { - LOG(DEBUG) << __func__; - if (isClosed()) { - LOG(ERROR) << __func__ << ": stream was closed"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - if (!mOffloadInfo.has_value()) { - LOG(ERROR) << __func__ << ": not a compressed offload stream"; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - if (in_offloadMetadata.sampleRate < 0) { - LOG(ERROR) << __func__ << ": invalid sample rate value: " << in_offloadMetadata.sampleRate; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_offloadMetadata.averageBitRatePerSecond < 0) { - LOG(ERROR) << __func__ - << ": invalid average BPS value: " << in_offloadMetadata.averageBitRatePerSecond; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_offloadMetadata.delayFrames < 0) { - LOG(ERROR) << __func__ - << ": invalid delay frames value: " << in_offloadMetadata.delayFrames; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_offloadMetadata.paddingFrames < 0) { - LOG(ERROR) << __func__ - << ": invalid padding frames value: " << in_offloadMetadata.paddingFrames; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - mOffloadMetadata = in_offloadMetadata; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamOut::getHwVolume(std::vector* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::setHwVolume(const std::vector& in_channelVolumes) { - LOG(DEBUG) << __func__ << ": gains " << ::android::internal::ToString(in_channelVolumes); - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::getAudioDescriptionMixLevel(float* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::setAudioDescriptionMixLevel(float in_leveldB) { - LOG(DEBUG) << __func__ << ": description mix level " << in_leveldB; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::getDualMonoMode(AudioDualMonoMode* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::setDualMonoMode(AudioDualMonoMode in_mode) { - LOG(DEBUG) << __func__ << ": dual mono mode " << toString(in_mode); - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::getRecommendedLatencyModes( - std::vector* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::setLatencyMode(AudioLatencyMode in_mode) { - LOG(DEBUG) << __func__ << ": latency mode " << toString(in_mode); - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::getPlaybackRateParameters(AudioPlaybackRate* _aidl_return) { - LOG(DEBUG) << __func__; - (void)_aidl_return; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::setPlaybackRateParameters(const AudioPlaybackRate& in_playbackRate) { - LOG(DEBUG) << __func__ << ": " << in_playbackRate.toString(); - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOut::selectPresentation(int32_t in_presentationId, int32_t in_programId) { - LOG(DEBUG) << __func__ << ": presentationId " << in_presentationId << ", programId " - << in_programId; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/StreamInPrimary.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/StreamInPrimary.cpp deleted file mode 100755 index da5c0b29..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/StreamInPrimary.cpp +++ /dev/null @@ -1,1399 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_StreamIn_QTI" - -#include - -#include - -#include -#include -#include -#include -#include -#include -#if SEC_AUDIO_MULTI_MIC >= 3 || defined (SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO) -#include -#endif -#include -#ifdef SEC_AUDIO_DUMP -#include "AudioDump.h" -#endif -#ifdef SEC_AUDIO_LEVEL_DUMP -#include "SecLevelDump.h" -#include -#endif -using aidl::android::hardware::audio::common::AudioOffloadMetadata; -using aidl::android::hardware::audio::common::getChannelCount; -using aidl::android::hardware::audio::common::getFrameSizeInBytes; -using aidl::android::hardware::audio::common::SinkMetadata; -using aidl::android::hardware::audio::common::SourceMetadata; -using aidl::android::media::audio::common::AudioDevice; -using aidl::android::media::audio::common::AudioDualMonoMode; -using aidl::android::media::audio::common::AudioLatencyMode; -using aidl::android::media::audio::common::AudioOffloadInfo; -using aidl::android::media::audio::common::AudioPortExt; -using aidl::android::media::audio::common::AudioSource; -using aidl::android::media::audio::common::MicrophoneDynamicInfo; -using aidl::android::media::audio::common::MicrophoneInfo; -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; -#endif - -using ::aidl::android::hardware::audio::common::getChannelCount; -using ::aidl::android::hardware::audio::common::getFrameSizeInBytes; -using ::aidl::android::hardware::audio::core::IStreamCallback; -using ::aidl::android::hardware::audio::core::IStreamCommon; -using ::aidl::android::hardware::audio::core::StreamDescriptor; -using ::aidl::android::hardware::audio::core::VendorParameter; -using ::aidl::android::hardware::audio::effect::getEffectTypeUuidAcousticEchoCanceler; -using ::aidl::android::hardware::audio::effect::getEffectTypeUuidNoiseSuppression; -using ::aidl::android::media::audio::common::AudioDeviceType; -using ::aidl::android::media::audio::common::AudioDeviceDescription; - -// uncomment this to enable logging of very verbose logs like burst commands. -// #define VERY_VERBOSE_LOGGING 1 - -namespace qti::audio::core { - -#define READ_RETRY_COUNT 10 - -std::mutex StreamInPrimary::sinkMetadata_mutex_; - -StreamInPrimary::StreamInPrimary(StreamContext&& context, const SinkMetadata& sinkMetadata, - const std::vector& microphones) - : StreamIn(std::move(context), microphones), - StreamCommonImpl(&(StreamIn::mContext), sinkMetadata), - mTag(getUsecaseTag(getContext().getMixPortConfig())), - mTagName(getName(mTag)), - mFrameSizeBytes(getContext().getFrameSize()), - mMixPortConfig(getContext().getMixPortConfig()) { - if (mTag == Usecase::PCM_RECORD) { - mExt.emplace(); - } else if (mTag == Usecase::COMPRESS_CAPTURE) { - mExt.emplace(mMixPortConfig.format.value(), - mMixPortConfig.sampleRate.value().value, - mMixPortConfig.channelMask.value()); - } else if (mTag == Usecase::VOIP_RECORD) { - mExt.emplace(); - } else if (mTag == Usecase::MMAP_RECORD) { - mExt.emplace(); - } else if (mTag == Usecase::VOICE_CALL_RECORD) { - mExt.emplace(); - } else if (mTag == Usecase::FAST_RECORD) { - mExt.emplace(); - } else if (mTag == Usecase::ULTRA_FAST_RECORD) { - mExt.emplace(); - } else if (mTag == Usecase::HOTWORD_RECORD) { - mExt.emplace(); - } - -#ifdef SEC_AUDIO_SAMSUNGRECORD - preprocess_ = PreProcessInit(); -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - const auto& source = getAudioSource(mMixPortConfig); - if (source && source.value() == AudioSource::VOICE_RECOGNITION) { - mAudExt.mKarokeExtension->setVoiceRecognitionStreamCreated(true); - } -#endif - /** - * In HIDL after open input stream there is subsequent call to - * update metadata, in AIDL its not present , so doing here. - */ - updateMetadata(sinkMetadata); - - std::ostringstream os; - os << " : usecase: " << mTagName; - os << " IoHandle:" << mMixPortConfig.ext.get().handle; - mLogPrefix = os.str(); - - LOG(DEBUG) << __func__ << mLogPrefix; -} - -StreamInPrimary::~StreamInPrimary() { - shutdown_I(); - -#ifdef SEC_AUDIO_DUMP - sec_hal_stop_read_pcm(mMixPortConfig); -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - const auto& source = getAudioSource(mMixPortConfig); - if (source && source.value() == AudioSource::VOICE_RECOGNITION) { - mAudExt.mKarokeExtension->setVoiceRecognitionStreamCreated(false); - } -#endif - LOG(DEBUG) << __func__ << mLogPrefix; -} - -ndk::ScopedAStatus StreamInPrimary::getActiveMicrophones( - std::vector* _aidl_return) { - *_aidl_return = mPlatform.getMicrophoneDynamicInfo(mConnectedDevices); - LOG(VERBOSE) << __func__ << mLogPrefix << " " << ::android::internal::ToString(*_aidl_return); - return ndk::ScopedAStatus::ok(); -} - -// start of methods called from IModule -ndk::ScopedAStatus StreamInPrimary::setConnectedDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) { - mWorker->setIsConnected(!devices.empty()); - mConnectedDevices = devices; - return configureConnectedDevices_I(); -} - -ndk::ScopedAStatus StreamInPrimary::reconfigureConnectedDevices() { - return configureConnectedDevices_I(); -} - -ndk::ScopedAStatus StreamInPrimary::configureConnectedDevices_I() { - auto connectedPalDevices = - mPlatform.configureAndFetchPalDevices(mMixPortConfig, mTag, mConnectedDevices); - if (mTag == Usecase::PCM_RECORD || mTag == Usecase::COMPRESS_CAPTURE) { - mPlatform.configurePalDevices(mMixPortConfig, connectedPalDevices); - if (mPlatform.getTranslationRecordState()) { - mPlatform.configurePalDevicesCustomKey(connectedPalDevices, "translate_record"); - LOG(INFO) << __func__ << "setting custom key as translate_record"; - } - } else if (mTag == Usecase::ULTRA_FAST_RECORD) { - auto countProxyDevices = std::count_if(mConnectedDevices.cbegin(), mConnectedDevices.cend(), - isInputAFEProxyDevice); - if (countProxyDevices > 0) { - std::get(mExt).mIsWFDCapture = true; - LOG(INFO) << __func__ << mLogPrefix - << ": ultra fast record on input AFE proxy (WFD client AHAL CAPTURE)"; - } else { - std::get(mExt).mIsWFDCapture = false; - auto channelCount = getChannelCount(mMixPortConfig.channelMask.value()); - if (channelCount == 2) { - mPlatform.configurePalDevicesCustomKey(connectedPalDevices, "dual-mic"); - } - } - } else if (mTag == Usecase::FAST_RECORD) { - auto countProxyDevices = std::count_if(mConnectedDevices.cbegin(), mConnectedDevices.cend(), - isInputAFEProxyDevice); - if (countProxyDevices > 0) { - std::get(mExt).mIsWFDCapture = true; - LOG(INFO) << __func__ << mLogPrefix - << ": ultra fast record on input AFE proxy (WFD client AHAL CAPTURE)"; - } else { - std::get(mExt).mIsWFDCapture = false; - auto channelCount = getChannelCount(mMixPortConfig.channelMask.value()); - if (channelCount == 2) { - mPlatform.configurePalDevicesCustomKey(connectedPalDevices, "dual-mic"); - } - } - } -#ifdef SEC_AUDIO_COMMON - connectedPalDevices = - mPlatform.configureSecPalDevicesForCapture(mMixPortConfig, mTag, mConnectedDevices); - - if (mSecFTM.getRMSTestMode() || mSecFTM.getLoopbackScoOn()) { - connectedPalDevices = mSecFTM.convertToPalDevices({mSecFTM.getTxFTMDevice()}); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - if (mPlatform.isListenBackEnabled()) { - SecModulePrimary::updateStreamListenbackMode(false); - } -#endif - if (this->mPalHandle != nullptr && connectedPalDevices.size() > 0) { - if (int32_t ret = ::pal_stream_set_device(this->mPalHandle, connectedPalDevices.size(), - connectedPalDevices.data()); - ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed pal_stream_set_device, ret:" << ret; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - } - -#ifdef SEC_AUDIO_COMMON - mPalDevices = connectedPalDevices; -#endif -#ifdef SEC_AUDIO_CALL_VOIP - if (mTag == Usecase::VOIP_RECORD) { - mAudioEffect.SetVoipMicModeEffect(); -#ifdef SEC_AUDIO_CALL_TRANSLATION - if (mPlatform.getCallTranslation()) { - mAudioEffect.SetVoipTxEffectForTranslation(true); - } -#endif - } -#endif - - auto devicesString = [](std::string prev, const auto& device) { - return std::move(prev) + ';' + device.toString(); - }; - - LOG(DEBUG) << __func__ << mLogPrefix << " stream is connected to devices:" - << std::accumulate(mConnectedDevices.cbegin(), mConnectedDevices.cend(), - std::string(""), devicesString); - -#ifdef SEC_AUDIO_SAMSUNGRECORD - preprocess_->SetParamPreProcessSolutions(mMixPortConfig, mDeviceFormat, mConnectedDevices, RECORD_PARAM_ROUTING); -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - if (mPlatform.isListenBackEnabled()) { - SecModulePrimary::updateStreamListenbackMode(true); - } -#endif - return ndk::ScopedAStatus::ok(); -} - -void StreamInPrimary::setStreamMicMute(const bool muted) { - if (mPalHandle == nullptr) { - return; - } - if (!mPlatform.setStreamMicMute(mPalHandle, muted)) { - LOG(ERROR) << __func__ << mLogPrefix << " failed"; - return; - } -} - -struct BufferConfig StreamInPrimary::getBufferConfig() { - return mPlatform.getBufferConfig(mMixPortConfig, mTag); -} - -#ifdef SEC_AUDIO_COMMON -ndk::ScopedAStatus StreamInPrimary::ForceSetDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, - bool force __unused) { - std::vector inDevices = devices; - if (devices.empty() || hasNoneDevice(devices)) { - inDevices = mConnectedDevices; - } - - auto connectedPalDevices = - mPlatform.configureAndFetchPalDevices(mMixPortConfig, mTag, inDevices); - if (mTag == Usecase::PCM_RECORD) { - mPlatform.configurePalDevices(mMixPortConfig, connectedPalDevices); - } else if (mTag == Usecase::ULTRA_FAST_RECORD) { - auto countProxyDevices = std::count_if(inDevices.cbegin(), inDevices.cend(), - isInputAFEProxyDevice); - if (countProxyDevices > 0) { - std::get(mExt).mIsWFDCapture = true; - LOG(INFO) << __func__ << mLogPrefix - << ": ultra fast record on input AFE proxy (WFD client AHAL CAPTURE)"; - } else { - std::get(mExt).mIsWFDCapture = false; - auto channelCount = getChannelCount(mMixPortConfig.channelMask.value()); - if (channelCount == 2) { - mPlatform.configurePalDevicesCustomKey(connectedPalDevices, "dual-mic"); - } - } - } - - connectedPalDevices = - mPlatform.configureSecPalDevicesForCapture(mMixPortConfig, mTag, inDevices); - - if (mSecFTM.getRMSTestMode() || mSecFTM.getLoopbackScoOn()) { - connectedPalDevices = mSecFTM.convertToPalDevices({mSecFTM.getTxFTMDevice()}); - } - - LOG(DEBUG) << __func__ << mLogPrefix << ": pal_stream_set_device"; - - if (this->mPalHandle != nullptr && connectedPalDevices.size() > 0) { - if (int32_t ret = ::pal_stream_set_device(this->mPalHandle, connectedPalDevices.size(), - connectedPalDevices.data()); - ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed pal_stream_set_device, ret:" << ret; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - } -#ifdef SEC_AUDIO_COMMON - mPalDevices = connectedPalDevices; -#endif - - auto devicesString = [](std::string prev, const auto& device) { - return std::move(prev) + ';' + device.toString(); - }; - - LOG(DEBUG) << __func__ << mLogPrefix << " stream is connected to devices:" - << std::accumulate(inDevices.cbegin(), inDevices.cend(), - std::string(""), devicesString); - - return ndk::ScopedAStatus::ok(); -} - -bool StreamInPrimary::isDeviceAvailable(pal_device_id_t pal_device) { - for (int i = 0; i < (int)mConnectedDevices.size(); i++) { - if (!mPalDevices.empty() && mPalDevices[i].id == pal_device) - return true; - } - return false; -} -#endif - -ndk::ScopedAStatus StreamInPrimary::configureMMapStream(int32_t* fd, int64_t* burstSizeFrames, - int32_t* flags, int32_t* bufferSizeFrames) { - if (mTag != Usecase::MMAP_RECORD) { - LOG(ERROR) << __func__ << mLogPrefix << " cannot call on non-MMAP stream types"; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - auto attr = mPlatform.getPalStreamAttributes(mMixPortConfig, true); - if (!attr) { - LOG(ERROR) << __func__ << mLogPrefix << " no pal attributes"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - attr->type = PAL_STREAM_ULTRA_LOW_LATENCY; - auto palDevices = mPlatform.configureAndFetchPalDevices(mMixPortConfig, mTag, mConnectedDevices, - true /*dummyDevice*/); - - uint64_t cookie = reinterpret_cast(this); - pal_stream_callback palFn = nullptr; - attr->flags = static_cast(PAL_STREAM_FLAG_MMAP_NO_IRQ); - -#ifdef SEC_AUDIO_COMMON - palDevices = - mPlatform.configureSecPalDevicesForCapture(mMixPortConfig, mTag, mConnectedDevices); - - if (mSecFTM.getRMSTestMode()) { - palDevices = mSecFTM.convertToPalDevices({mSecFTM.getTxFTMDevice()}); - } -#endif - if (int32_t ret = ::pal_stream_open(attr.get(), palDevices.size(), palDevices.data(), 0, - nullptr, palFn, cookie, &(this->mPalHandle)); - ret) { - LOG(ERROR) << __func__ << mLogPrefix - << " pal_stream_open failed, ret:" << std::to_string(ret); - mPalHandle = nullptr; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } -#ifdef SEC_AUDIO_COMMON - mPalDevices = palDevices; -#endif - auto bufConfig = getBufferConfig(); - const size_t ringBufSizeInBytes = bufConfig.bufferSize; - const size_t ringBufCount = bufConfig.bufferCount; - - auto palBufferConfig = mPlatform.getPalBufferConfig(ringBufSizeInBytes, ringBufCount); - LOG(DEBUG) << __func__ << mLogPrefix << " set pal_stream_set_buffer_size to " - << std::to_string(ringBufSizeInBytes) << " with count " - << std::to_string(ringBufCount); - if (int32_t ret = - ::pal_stream_set_buffer_size(this->mPalHandle, palBufferConfig.get(), nullptr); - ret) { - LOG(ERROR) << __func__ << mLogPrefix - << " pal_stream_set_buffer_size failed, ret:" << std::to_string(ret); - ::pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - - std::get(mExt).setPalHandle(mPalHandle); - - const auto frameSize = ::aidl::android::hardware::audio::common::getFrameSizeInBytes( - mMixPortConfig.format.value(), mMixPortConfig.channelMask.value()); - int32_t ret = std::get(mExt).createMMapBuffer(frameSize, fd, burstSizeFrames, flags, - bufferSizeFrames); - if (ret != 0) { - LOG(ERROR) << __func__ << mLogPrefix << " createMMapBuffer failed"; - ::pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - - if (mPlatform.getMicMuteStatus()) { - setStreamMicMute(true); - } - - LOG(INFO) << __func__ << mLogPrefix << ": stream is configured"; - - return ndk::ScopedAStatus::ok(); -} - -// end of methods called from IModule - -// start of driverInterface methods - -::android::status_t StreamInPrimary::init() { - return ::android::OK; -} - -::android::status_t StreamInPrimary::drain(StreamDescriptor::DrainMode mode) { - if (!mPalHandle) { - LOG(WARNING) << __func__ << mLogPrefix << " stream is not configured"; - return ::android::OK; - } - - if (mTag == Usecase::MMAP_RECORD) { - // drain in MMAP is stop - return stopMMAP(); - } - - return ::android::OK; -} - -::android::status_t StreamInPrimary::flush() { - if (!mPalHandle) { - LOG(WARNING) << __func__ << mLogPrefix << " stream is not configured"; - return ::android::OK; - } - - if (mTag == Usecase::MMAP_RECORD) { - // flush in MMAP is stop - return stopMMAP(); - } - - return ::android::OK; -} - -::android::status_t StreamInPrimary::pause() { - - if (mTag == Usecase::MMAP_RECORD) { - // pause in MMAP is stop - return stopMMAP(); - } - - // Todo check whether pause is possible in PAL - shutdown_I(); - return ::android::OK; -} - -void StreamInPrimary::resume() { - // No op -} - -::android::status_t StreamInPrimary::standby() { - if (!mPalHandle) { - LOG(WARNING) << __func__ << mLogPrefix << ": stream is not configured "; - return ::android::OK; - } - - shutdown_I(); - return ::android::OK; -} - -::android::status_t StreamInPrimary::start() { - LOG(DEBUG) << __func__ << mLogPrefix; - - if (mTag == Usecase::MMAP_RECORD) { - return startMMAP(); - } - - return ::android::OK; -} - -::android::status_t StreamInPrimary::onReadError(const size_t sleepFrameCount) { - shutdown_I(); - if (mTag == Usecase::COMPRESS_CAPTURE) { - LOG(ERROR) << __func__ << mLogPrefix << ": cannot afford read failure for compress"; - return ::android::UNEXPECTED_NULL; - } - auto& sampleRate = mMixPortConfig.sampleRate.value().value; - if (sampleRate == 0) { - LOG(ERROR) << __func__ << mLogPrefix << ": cannot afford read failure, sampleRate is zero"; - return ::android::UNEXPECTED_NULL; - } - std::this_thread::sleep_for(std::chrono::milliseconds((sleepFrameCount * 1000) / sampleRate)); - return ::android::OK; -} - -::android::status_t StreamInPrimary::transfer(void* buffer, size_t frameCount, - size_t* actualFrameCount, int32_t* latencyMs) { - int32_t bytesRead = 0; - - if (!mPalHandle) { - configure(); - if (!mPalHandle) { - LOG(ERROR) << __func__ << mLogPrefix << ": failed to configure"; - *actualFrameCount = frameCount; - return onReadError(frameCount); - } - } - - if (frameCount == 0) { - *actualFrameCount = 0; - return burstZero(); - } - - pal_buffer palBuffer{}; - palBuffer.buffer = static_cast(buffer); - palBuffer.size = frameCount * mFrameSizeBytes; -#ifdef VERY_VERBOSE_LOGGING - LOG(VERBOSE) << __func__ << mLogPrefix << ": framecount " << frameCount << " mFrameSizeBytes " - << mFrameSizeBytes; -#endif - - if (mTag == Usecase::HOTWORD_RECORD && - std::get(mExt).isStRecord()) { - if (std::get(mExt).getPalHandle(mMixPortConfig) != mPalHandle) { - LOG(DEBUG) << __func__ << mLogPrefix << ": invalid sound trigger stream handle"; - } else { - int32_t retryCnt = 0; - do { - bytesRead = ::pal_stream_read(mPalHandle, &palBuffer); - } while (bytesRead == 0 && ++retryCnt < READ_RETRY_COUNT); - } - - if (bytesRead <= 0) { - /* Send silence buffer to let app know to stop capture session. - * This would avoid continous read from Audioflinger to HAL. - */ - memset(palBuffer.buffer, 0, palBuffer.size); - bytesRead = palBuffer.size; - } - } else { - -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - const auto& source = getAudioSource(mMixPortConfig); - if (source && source.value() == AudioSource::CAMCORDER) { - if ((mPlatform.IsBtForMultiDevice(mConnectedDevices) && - mPlatform.multidevice_rec - && !isCustomKeyRouted(CUSTOM_KEY_CAMCORDER_MULTI_AND_BT_MIC)) - || (mConnectedDevices.size() == 2 && - !mPlatform.multidevice_rec && - mPlatform.IsBtForMultiDevice(mConnectedDevices) - && isCustomKeyRouted(CUSTOM_KEY_CAMCORDER_MULTI_AND_BT_MIC))) { - LOG(INFO) << __func__ << "reconfig for multidevice recording"; - return onReadError(0); - } - } -#endif -#ifdef SEC_AUDIO_SAMSUNGRECORD - size_t req_size = palBuffer.size; -#ifdef SEC_AUDIO_SUPPORT_UHQ_REC - if (preprocess_->forced_format - != (mPlatform.GetRecFormat(mMixPortConfig, mConnectedDevices, mTag) == AUDIO_SUPPORTED_FORMAT_24)) { - LOG(INFO) << __func__ << "reconfig to change format "; - *actualFrameCount = frameCount; - return onReadError(frameCount); - } -#endif -#if SEC_AUDIO_MULTI_MIC >= 3 - if (preprocess_->forced_channel != mPlatform.GetRecMultiMic(mMixPortConfig, mConnectedDevices, mTag)) { - LOG(INFO) << __func__ << "reconfig to change channel"; - *actualFrameCount = frameCount; - return onReadError(frameCount); - } -#endif -#ifdef SEC_AUDIO_COMPRESS_CAPTURE - if (mTag != UseCase::COMPRESS_CAPTURE) -#endif - { - palBuffer.size = preprocess_->SwapBuffer(mMixPortConfig, mDeviceChannels, mDeviceFormat, (void**)&palBuffer.buffer, req_size, palBuffer.size, frameCount, mTag); - } -#endif - - bytesRead = ::pal_stream_read(mPalHandle, &palBuffer); - -#ifdef SEC_AUDIO_SAMSUNGRECORD -#ifdef SEC_AUDIO_COMPRESS_CAPTURE - if (usecase_ != UseCase::COMPRESS_CAPTURE) -#endif - { -#ifdef SEC_AUDIO_LEVEL_DUMP - [[maybe_unused]] int muteChannels = - SEC_LEVEL_RUN(mMixPortConfig.ext.get().handle, - SEC_LEVEL_IN_PURE, palBuffer.buffer, palBuffer.size); -#ifdef SEC_AUDIO_REPORT_HAL_ERROR - if (muteChannels > 0) { - android::SecAudioHalProxy::onErrorReported(AUDIO_ERROR_RECORD_DATA_MUTE); - } -#endif -#endif - preprocess_->Process(mDeviceFormat, (void**)&palBuffer.buffer, palBuffer.size, frameCount); - palBuffer.size = preprocess_->SwapBuffer(mMixPortConfig, mDeviceChannels, mDeviceFormat, (void**)&palBuffer.buffer, req_size, palBuffer.size, frameCount, mTag); - if (bytesRead >= 0) { - bytesRead = palBuffer.size; - } -#ifdef SEC_AUDIO_LEVEL_DUMP - if (mPlatform.IsSupportPreprocess(mMixPortConfig, mTag)) { - [[maybe_unused]] int muteChannels = - SEC_LEVEL_RUN(mMixPortConfig.ext.get().handle, - SEC_LEVEL_IN_LAST, palBuffer.buffer, palBuffer.size); -#ifdef SEC_AUDIO_REPORT_HAL_ERROR - if (muteChannels > 0) { - android::SecAudioHalProxy::onErrorReported(AUDIO_ERROR_RECORD_SOLUTION_MUTE); - } -#endif - } -#endif - } -#endif - -#ifdef SEC_AUDIO_CAMCORDER - if (palBuffer.buffer && palBuffer.size > 0) { - if (isTxDataInvertable()) { - int32_t* iBuffer = (int32_t*)palBuffer.buffer; - int32_t left, right; - size_t i = 0; - for (i = (palBuffer.size >> 2); i > 0; i--) { - left = (*iBuffer & 0x0000FFFF); - right = (((*iBuffer) >> 16) & 0x0000FFFF); - *iBuffer = (left << 16 | right); - iBuffer++; - } - } - } -#endif - - } - -#ifdef SEC_AUDIO_COMMON // SEC_AUDIO_ENFORCED_AUDIBLE //SEC_AUDIO_SUPPORT_NSRI - if (palBuffer.buffer && palBuffer.size > 0) { - bool need_mute = false; -#ifdef SEC_AUDIO_ENFORCED_AUDIBLE - auto enforcePlaybackState = mPlatform.getEnforcePlaybackState(); - if (enforcePlaybackState != NOT_MUTE) { - const auto& source = getAudioSource(mMixPortConfig); - need_mute |= (enforcePlaybackState == MUTE_CALL_AND_REC - && source && source.value() == AudioSource::CAMCORDER - && mTag == Usecase::PCM_RECORD) - || mTag == Usecase::VOIP_RECORD; - } -#endif -#ifdef SEC_AUDIO_SUPPORT_NSRI - need_mute |= mPlatform.isNSRISecureEnabled(); -#endif - if (need_mute) { - memset(palBuffer.buffer, 0, palBuffer.size); - } - } -#endif - -#ifdef SEC_AUDIO_DUMP - sec_hal_read_pcm(mMixPortConfig, palBuffer.buffer, palBuffer.size, PCM_DUMP_LAST); -#endif -#ifdef SEC_AUDIO_KARAOKE - if (mPlatform.isKaraokeEnabled() && - !isCustomKeyRouted(CUSTOM_KEY_KARAOKE)) { - SecModulePrimary::getInstance().setKaraokeDevice(); - } -#endif - if (mTag == Usecase::COMPRESS_CAPTURE) { - auto& compressCapture = std::get(mExt); - compressCapture.advanceReadCount(); - *latencyMs = compressCapture.getLatencyMs(); - } else if (mTag == Usecase::PCM_RECORD || mTag == Usecase::HOTWORD_RECORD) { - *latencyMs = PcmRecord::kCaptureDurationMs; - } - - if (bytesRead < 0) { - LOG(ERROR) << __func__ << mLogPrefix << " read failed, ret:" << std::to_string(bytesRead); -#ifdef SEC_AUDIO_ROUTING_NOISE - // P230608-00262 : TX buzzing sound occurs when EP was pulled right after answering the call - memset(palBuffer.buffer, 0, palBuffer.size); -#endif - *actualFrameCount = frameCount; - return onReadError(frameCount); - } - else { - *actualFrameCount = mFrameSizeBytes ? - (static_cast(bytesRead) / mFrameSizeBytes) : 0; - } - -#ifdef VERY_VERBOSE_LOGGING - LOG(VERBOSE) << __func__ << mLogPrefix << ": bytes read " << bytesRead << ", return frame count " - << *actualFrameCount; -#endif - - return ::android::OK; -} - -::android::status_t StreamInPrimary::refinePosition( - ::aidl::android::hardware::audio::core::StreamDescriptor::Reply* reply) { - if (mTag == Usecase::COMPRESS_CAPTURE) { - auto& compressCapture = std::get(mExt); - reply->observable.frames = compressCapture.getPositionInFrames(); - } else if (mTag == Usecase::MMAP_RECORD) { - if (int32_t ret = std::get(mExt).getMMapPosition(&(reply->hardware.frames), - &(reply->hardware.timeNs)); - ret != 0) { - return android::INVALID_OPERATION; - } - } - /* Adjustment accounts for A2dp decoder latency - * Note: Decoder latency is returned in ms, while platform_source_latency in us. - */ - pal_param_bta2dp_t* param_bt_a2dp_ptr, param_bt_a2dp; - param_bt_a2dp_ptr = ¶m_bt_a2dp; - size_t size = 0; - int32_t ret; - auto countBluetoothA2dpTXDevices = - std::count_if(mConnectedDevices.cbegin(), mConnectedDevices.cend(), - isBluetoothA2dpTXDevice); - auto countBluetoothLETXDevices = - std::count_if(mConnectedDevices.cbegin(), mConnectedDevices.cend(), - isBluetoothLETXDevice); - if (countBluetoothA2dpTXDevices > 0) { - param_bt_a2dp_ptr->dev_id = PAL_DEVICE_IN_BLUETOOTH_A2DP; - } else if (countBluetoothLETXDevices > 0) { - param_bt_a2dp_ptr->dev_id = PAL_DEVICE_IN_BLUETOOTH_BLE; - } else { - return ::android::OK; - } - ret = pal_get_param(PAL_PARAM_ID_BT_A2DP_DECODER_LATENCY, - (void**)¶m_bt_a2dp_ptr, &size, nullptr); - if (!ret && size && param_bt_a2dp_ptr && param_bt_a2dp_ptr->latency) { - reply->observable.timeNs -= param_bt_a2dp_ptr->latency * 1000000LL; - } - return ::android::OK; -} - -void StreamInPrimary::shutdown() { - return shutdown_I(); -} - -// end of driverInterface methods - -// start of StreamCommonInterface methods - -void StreamInPrimary::checkHearingAidRoutingForVoice(const Metadata& metadata, bool voiceActive) { - - if (!voiceActive) { - return; - } - - std::vector devices; - AudioDevice device; - - device.type.type = AudioDeviceType::OUT_HEARING_AID; - device.type.connection = AudioDeviceDescription::CONNECTION_WIRELESS; - devices.push_back(device); - - ::aidl::android::hardware::audio::common::SinkMetadata sinkMetadata = - std::get<::aidl::android::hardware::audio::common::SinkMetadata>(metadata); - - for (auto& item : sinkMetadata.tracks) { - if (item.destinationDevice.has_value()) { - if (item.destinationDevice.value().type.type == AudioDeviceType::OUT_HEARING_AID) { - if (auto telephony = mContext.getTelephony().lock()) { - LOG(DEBUG) << __func__ << " Hearing aid device , calling voice routing"; - telephony->setDevices(devices, true); - } - break; - } - } - } -} - -ndk::ScopedAStatus StreamInPrimary::updateMetadataCommon(const Metadata& metadata) { - if (!isClosed()) { - if (metadata.index() != mMetadata.index()) { - LOG(FATAL) << __func__ << mLogPrefix << ": changing metadata variant is not allowed"; - } - mMetadata = metadata; - } - int callState = mPlatform.getCallState(); - int callMode = mPlatform.getCallMode(); - bool voiceActive = ((callState == 2) || (callMode == 2)); - - /** - * Based on sink metadata of recording session, we might need - * to update the voice routing if dest device in metadata is - * hearing aid. - */ - checkHearingAidRoutingForVoice(metadata, voiceActive); - - StreamInPrimary::sinkMetadata_mutex_.lock(); - setAggregateSinkMetadata(voiceActive); - StreamInPrimary::sinkMetadata_mutex_.unlock(); - LOG(ERROR) << __func__ << mLogPrefix << ": stream was closed"; - // return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - return ndk::ScopedAStatus::ok(); -} - -int32_t StreamInPrimary::setAggregateSinkMetadata(bool voiceActive) { - ssize_t track_count_total = 0; - - std::vector total_tracks; - sink_metadata_t btSinkMetadata; - - ModulePrimary::inListMutex.lock(); - std::vector>& inStreams = ModulePrimary::getInStreams(); - // Dont send metadata if voice is active - if (voiceActive || inStreams.empty()) { - ModulePrimary::inListMutex.unlock(); - return 0; - } - auto removeStreams = [&](std::weak_ptr streamIn) -> bool { - if (!streamIn.lock()) return true; - return streamIn.lock()->isClosed(); - }; - - inStreams.erase(std::remove_if(inStreams.begin(), inStreams.end(), removeStreams), - inStreams.end()); - - for (auto it = inStreams.begin(); it < inStreams.end(); it++) { - if (it->lock() && !it->lock()->isClosed()) { - ::aidl::android::hardware::audio::common::SinkMetadata sinkMetadata; - it->lock()->getMetadata(sinkMetadata); - track_count_total += sinkMetadata.tracks.size(); - } else { - } - } - LOG(VERBOSE) << __func__ << mLogPrefix << " trackCount " << track_count_total << - " streamSize " << inStreams.size(); - if (track_count_total == 0) { - ModulePrimary::inListMutex.unlock(); - return 0; - } - - total_tracks.resize(track_count_total); - btSinkMetadata.track_count = track_count_total; - btSinkMetadata.tracks = total_tracks.data(); - - for (auto it = inStreams.begin(); it != inStreams.end(); it++) { - ::aidl::android::hardware::audio::common::SinkMetadata sinkMetadata; - if (it->lock()) { - it->lock()->getMetadata(sinkMetadata); - for (auto& item : sinkMetadata.tracks) { - btSinkMetadata.tracks->source = static_cast(item.source); - ++btSinkMetadata.tracks; - } - } - } - - btSinkMetadata.tracks = total_tracks.data(); - pal_set_param(PAL_PARAM_ID_SET_SINK_METADATA, (void*)&btSinkMetadata, 0); - ModulePrimary::inListMutex.unlock(); - return 0; -} - -ndk::ScopedAStatus StreamInPrimary::getVendorParameters( - const std::vector& in_ids, std::vector* _aidl_return) { - if (mTag == Usecase::COMPRESS_CAPTURE) { - auto& compressCapture = std::get(mExt); - return compressCapture.getVendorParameters(in_ids, _aidl_return); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamInPrimary::setVendorParameters( - const std::vector& in_parameters, bool in_async) { - if (mTag == Usecase::COMPRESS_CAPTURE) { - auto& compressCapture = std::get(mExt); - return compressCapture.setVendorParameters(in_parameters, in_async); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamInPrimary::addEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) { - if (in_effect == nullptr) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - ::aidl::android::hardware::audio::effect::Descriptor desc; - auto status = in_effect->getDescriptor(&desc); - if (!status.isOk()) { - LOG(ERROR) << __func__ << mLogPrefix << "error fetching descriptor"; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - const auto& typeUUID = desc.common.id.type; - - if (typeUUID == getEffectTypeUuidAcousticEchoCanceler()) { - if (!mAECEnabled) { - mAECEnabled = true; - applyEffects(); - } - } else if (typeUUID == getEffectTypeUuidNoiseSuppression()) { - if (!mNSEnabled) { - mNSEnabled = true; - applyEffects(); - } - } - - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamInPrimary::removeEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) { - if (in_effect == nullptr) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - ::aidl::android::hardware::audio::effect::Descriptor desc; - auto status = in_effect->getDescriptor(&desc); - if (!status.isOk()) { - LOG(ERROR) << __func__ << mLogPrefix << "error fetching descriptor"; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - const auto& typeUUID = desc.common.id.type; - - if (typeUUID == getEffectTypeUuidAcousticEchoCanceler()) { - if (mAECEnabled) { - mAECEnabled = false; - applyEffects(); - } - } else if (typeUUID == getEffectTypeUuidNoiseSuppression()) { - if (mNSEnabled) { - mNSEnabled = false; - applyEffects(); - } - } - - return ndk::ScopedAStatus::ok(); -} - -// end of StreamCommonInterface methods - -size_t StreamInPrimary::getPlatformDelay() const noexcept { - return 0; -} - -void StreamInPrimary::configure() { - - if(hasInputMMapFlag(mMixPortConfig.flags.value())){ - // this API doesn't handle for MMAP - return; - } - - const auto startTime = std::chrono::steady_clock::now(); - auto attr = mPlatform.getPalStreamAttributes(mMixPortConfig, true); - LOG(INFO) << __func__ << " : configure : Enter"; - auto palDevices = mPlatform.configureAndFetchPalDevices(mMixPortConfig, mTag, mConnectedDevices); - if (!attr) { - LOG(ERROR) << __func__ << mLogPrefix << " no pal attributes"; - return; - } - if (mTag == Usecase::PCM_RECORD) { - LOG(DEBUG) << __func__ << " : PCM_RECORD usecase"; - attr->type = PAL_STREAM_DEEP_BUFFER; - const auto& source = getAudioSource(mMixPortConfig); - if (source) { - if (source.value() == AudioSource::ECHO_REFERENCE) { - attr->type = PAL_STREAM_RAW; - LOG(INFO) << __func__ << mLogPrefix << ": echo reference capture"; - } else if (source.value() == AudioSource::UNPROCESSED) { - attr->type = PAL_STREAM_RAW; -#ifdef SEC_AUDIO_MMAP_NOIRQ - if (hasInputMMapFlag(mMixPortConfig.flags.value())) { - attr->type = PAL_STREAM_ULTRA_LOW_LATENCY; - } -#endif - LOG(INFO) << __func__ << mLogPrefix << ": unprocessed capture"; - } else if (source.value() == AudioSource::VOICE_RECOGNITION) { -#ifdef SEC_AUDIO_HOTWORD - attr->type = PAL_STREAM_DEEP_BUFFER; -#else - attr->type = PAL_STREAM_VOICE_RECOGNITION; -#endif - LOG(INFO) << __func__ << mLogPrefix << ": voice recognition capture"; - } else { - auto countTelephonyRxDevices = - std::count_if(mConnectedDevices.cbegin(), mConnectedDevices.cend(), - isTelephonyRXDevice); - if (countTelephonyRxDevices > 0) { - attr->type = PAL_STREAM_PROXY; - attr->info.opt_stream_info.tx_proxy_type = PAL_STREAM_PROXY_TX_TELEPHONY_RX; - LOG(DEBUG) << __func__ << mLogPrefix << ": proxy capture for telephony rx"; - } - } - } - if (mPlatform.getTranslationRecordState()) { - mPlatform.configurePalDevicesCustomKey(palDevices, "translate_record"); - LOG(INFO) << __func__ << ": setting custom key as translate_record"; - } - } else if (mTag == Usecase::COMPRESS_CAPTURE) { - attr->type = PAL_STREAM_COMPRESSED; - } else if (mTag == Usecase::VOIP_RECORD) { - attr->type = PAL_STREAM_VOIP_TX; - } else if (mTag == Usecase::VOICE_CALL_RECORD) { - attr->type = PAL_STREAM_VOICE_CALL_RECORD; - attr->info.voice_rec_info.record_direction = - std::get(mExt).getRecordDirection(mMixPortConfig); - } else if (mTag == Usecase::FAST_RECORD) { - if (std::get(mExt).mIsWFDCapture) { - attr->type = PAL_STREAM_PROXY; - attr->info.opt_stream_info.tx_proxy_type = PAL_STREAM_PROXY_TX_WFD; - } else { -#ifdef SEC_AUDIO_SAMSUNGRECORD - attr->type = PAL_STREAM_DEEP_BUFFER; -#else - attr->type = PAL_STREAM_LOW_LATENCY; -#endif - } - } else if (mTag == Usecase::ULTRA_FAST_RECORD) { - if (std::get(mExt).mIsWFDCapture) { - attr->type = PAL_STREAM_PROXY; - attr->info.opt_stream_info.tx_proxy_type = PAL_STREAM_PROXY_TX_WFD; - } else { - attr->type = PAL_STREAM_ULTRA_LOW_LATENCY; - attr->flags = PAL_STREAM_FLAG_MMAP; - } - } else if (mTag == Usecase::HOTWORD_RECORD) { -#ifdef SEC_AUDIO_SOUND_TRIGGER_TYPE - if(mPlatform.isSeamlessEnabled()) { - std::get(mExt).enableSeamless(true); - } -#endif - mPalHandle = std::get(mExt).getPalHandle(mMixPortConfig); - if (!mPalHandle) - attr->type = PAL_STREAM_DEEP_BUFFER; - else - return; - } else { - LOG(ERROR) << __func__ << mLogPrefix << " invalid usecase to configure"; - return; - } - - LOG(VERBOSE) << __func__ << mLogPrefix << " assigned pal stream type:" << attr->type; - - if (!palDevices.size()) { - LOG(ERROR) << __func__ << mLogPrefix << " no connected devices on stream!!"; - return; - } - - if (mTag == Usecase::PCM_RECORD || mTag == Usecase::COMPRESS_CAPTURE) { - LOG(DEBUG) << __func__ << mLogPrefix << " PalDevices is config"; - mPlatform.configurePalDevices(mMixPortConfig, palDevices); - } -#ifdef SEC_AUDIO_COMMON - const auto& source = getAudioSource(mMixPortConfig); -#endif -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - if (source && source.value() == AudioSource::CAMCORDER) { - AudioDevice dev; - audio_devices_t devices = static_cast(mPlatform.get_device_types(mConnectedDevices)); // SEC_AUDIO_SAMSUNGRECORD - - if (mPlatform.multidevice_rec && mPlatform.IsBtForMultiDevice(mConnectedDevices)) { - std::vector device_types; - if (audio_is_subset_device(devices, AUDIO_DEVICE_IN_BLE_HEADSET)) { - dev = AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_LE}; - device_types.push_back(dev); -#ifdef SEC_AUDIO_BLE_OFFLOAD - updateRecordMetadataForBLE(); -#endif - } else { - dev = AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_SCO}; - device_types.push_back(dev); - } - dev = AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_MULTI}; - device_types.push_back(dev); - setConnectedDevices(device_types); - } else if (mConnectedDevices.size() == 2 && !mPlatform.multidevice_rec) { - std::vector device_types; - if (audio_is_subset_device(devices, AUDIO_DEVICE_IN_BLE_HEADSET)) { - dev = AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_LE}; - device_types.push_back(dev); -#ifdef SEC_AUDIO_BLE_OFFLOAD - updateRecordMetadataForBLE(); -#endif - } else { - dev = AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_MULTI}; - device_types.push_back(dev); - } - setConnectedDevices(device_types); - } - } -#endif - -#ifdef SEC_AUDIO_COMMON - palDevices = mPlatform.configureSecPalDevicesForCapture(mMixPortConfig, mTag, mConnectedDevices); - - if (mSecFTM.getRMSTestMode() || mSecFTM.getLoopbackScoOn()) { - palDevices = mSecFTM.convertToPalDevices({mSecFTM.getTxFTMDevice()}); - } -#endif -#ifdef SEC_AUDIO_SAMSUNGRECORD - mDeviceChannels = getChannelCount(mMixPortConfig.channelMask.value()); -#if SEC_AUDIO_MULTI_MIC >= 3 || defined (SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO) - if (mPlatform.GetRecMultiMic(mMixPortConfig, mConnectedDevices, mTag)) { - if (mPlatform.multidevice_rec) { -#if (SEC_AUDIO_MULTI_MIC == 0) && defined(SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO) - mDeviceChannels = SEC_AUDIO_MULTI_MIC; -#else - mDeviceChannels = SEC_AUDIO_MULTI_MIC_CAPTURE_CHANNELS; -#endif - } else { - mDeviceChannels = SEC_AUDIO_MULTI_MIC; - } - auto palChannelInfo = PlatformConverter::getPalChannelInfoForChannelCount(mDeviceChannels); - attr->in_media_config.ch_info = *(palChannelInfo); - preprocess_->forced_channel = true; - LOG(DEBUG) << __func__ << mLogPrefix << " change pcm_ch " << mDeviceChannels; - } else if (preprocess_->forced_channel) { - LOG(DEBUG) << __func__ << mLogPrefix << " revert pcm_ch " << mDeviceChannels; - preprocess_->forced_channel = false; - } -#endif -#endif -#ifdef SEC_AUDIO_SUPPORT_UHQ_REC - mDeviceFormat = AUDIO_FORMAT_PCM_16_BIT; - pal_audio_fmt_t fmt_id = Platform::kDefaultPalPCMFormat; - if (mPlatform.GetRecFormat(mMixPortConfig, mConnectedDevices, mTag) == AUDIO_SUPPORTED_FORMAT_24) { - mDeviceFormat = AUDIO_FORMAT_PCM_8_24_BIT; - preprocess_->forced_format = true; - fmt_id = PAL_AUDIO_FMT_PCM_S24_LE; - LOG(DEBUG) << __func__ << mLogPrefix << " change format 8_24"; - } else if (preprocess_->forced_format) { - preprocess_->forced_format = false; - LOG(DEBUG) << __func__ << mLogPrefix << " revert format"; - } - attr->in_media_config.aud_fmt_id = fmt_id; - attr->in_media_config.bit_width = audio_bytes_per_sample(mDeviceFormat) * 8; -#endif - - uint64_t cookie = reinterpret_cast(this); - pal_stream_callback palFn = nullptr; - - const auto palOpenApiStartTime = std::chrono::steady_clock::now(); - if (int32_t ret = ::pal_stream_open(attr.get(), palDevices.size(), palDevices.data(), 0, - nullptr, palFn, cookie, &(mPalHandle)); - ret) { - LOG(ERROR) << __func__ << mLogPrefix << " pal_stream_open failed!!! ret:" << ret; - mPalHandle = nullptr; - return; - } -#ifdef SEC_AUDIO_COMMON - mPalDevices = palDevices; -#endif - const auto palOpenApiEndTime = std::chrono::steady_clock::now(); - - auto bufConfig = getBufferConfig(); - if (mTag == Usecase::ULTRA_FAST_RECORD) { - const size_t durationMs = 1; - size_t frameSizeInBytes = ::aidl::android::hardware::audio::common::getFrameSizeInBytes( - mMixPortConfig.format.value(), mMixPortConfig.channelMask.value()); - bufConfig.bufferSize = durationMs * - (mMixPortConfig.sampleRate.value().value /1000) * frameSizeInBytes; - } -#ifdef SEC_AUDIO_SAMSUNGRECORD - size_t ringBufSizeInBytes = bufConfig.bufferSize; - if (preprocess_->forced_format || preprocess_->forced_channel) { - size_t fcount = mPlatform.getFrameCount(mMixPortConfig); - size_t dev_size = fcount * mDeviceChannels * audio_bytes_per_sample(mDeviceFormat); - ringBufSizeInBytes = dev_size; - } -#else - const size_t ringBufSizeInBytes = bufConfig.bufferSize; -#endif - const size_t ringBufCount = bufConfig.bufferCount; - auto palBufferConfig = mPlatform.getPalBufferConfig(ringBufSizeInBytes, ringBufCount); - LOG(DEBUG) << __func__ << mLogPrefix << " set pal_stream_set_buffer_size to " << ringBufSizeInBytes - << " with count " << ringBufCount; - if (int32_t ret = ::pal_stream_set_buffer_size(mPalHandle, palBufferConfig.get(), nullptr); - ret) { - LOG(ERROR) << __func__ << mLogPrefix << " pal_stream_set_buffer_size failed!!! ret:" << ret; - ::pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return; - } - LOG(VERBOSE) << __func__ << mLogPrefix << " pal_stream_set_buffer_size successful"; - - if (mTag == Usecase::COMPRESS_CAPTURE) { - std::get(mExt).setPalHandle(mPalHandle); - if (bool isConfigured = std::get(mExt).configureCodecInfo(); - !isConfigured) { - ::pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return; - } - } - -#ifdef SEC_AUDIO_SAMSUNGRECORD - if (mPlatform.IsSupportPreprocess(mMixPortConfig, mTag)) { - preprocess_->SetParamPreProcessSolutions(mMixPortConfig, mDeviceFormat, mConnectedDevices, RECORD_PARAM_ALL); -#if defined(SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO) && defined(SEC_AUDIO_BLE_OFFLOAD) - if (mPlatform.multidevice_rec) { - for (auto& device : mConnectedDevices) { - if (device.type.type == AudioDeviceType::IN_HEADSET && device.type.connection == AudioDeviceDescription::CONNECTION_BT_LE) { - preprocess_->SetParamPreProcessSolutions(mMixPortConfig, mDeviceFormat, mConnectedDevices, RECORD_PARAM_BT_MIX_LATENCY); - break; - } - } - } -#endif - } -#ifdef SEC_AUDIO_LEVEL_DUMP - SEC_LEVEL_OPEN(mMixPortConfig.ext.get().handle, SEC_LEVEL_IN_PURE, - mMixPortConfig.sampleRate.value().value, mDeviceChannels, mDeviceFormat); - if (source) - SEC_LEVEL_SET_PARAM(mMixPortConfig.ext.get().handle, SEC_LEVEL_IN_PURE, - SEC_LEVEL_KEY_SOURCE, (int)source.value()); - if (mPlatform.IsSupportPreprocess(mMixPortConfig, mTag)) { - SEC_LEVEL_OPEN(mMixPortConfig.ext.get().handle, SEC_LEVEL_IN_LAST, - mMixPortConfig.sampleRate.value().value, - getChannelCount(mMixPortConfig.channelMask.value()), - (audio_format_t)PlatformConverter::getAudioFormatForAidlPCM(mMixPortConfig.format.value())); - if (source) - SEC_LEVEL_SET_PARAM(mMixPortConfig.ext.get().handle, SEC_LEVEL_IN_LAST, - SEC_LEVEL_KEY_SOURCE, (int)source.value()); - } -#endif -#endif - const auto palStartApiStartTime = std::chrono::steady_clock::now(); - if (int32_t ret = ::pal_stream_start(this->mPalHandle); ret) { - LOG(ERROR) << __func__ << mLogPrefix << " pal_stream_start failed!! ret:" << ret; - ::pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return; - } - - if (mPlatform.getMicMuteStatus() && !(mPlatform.getTranslationRecordState())) { - setStreamMicMute(true); - } - - const auto palStartApiEndTime = std::chrono::steady_clock::now(); - -#ifdef SEC_AUDIO_DYNAMIC_NREC - // not support dynamic nrec(not defined in audio_effects_sec.xml) : mic - if ((source && source.value() == AudioSource::MIC) - && (mPlatform.getCallMode() == AUDIO_MODE_IN_COMMUNICATION)) { - mAudioEffect.SetECNSForVoip(mTag, mPalHandle, true); - } -#endif -#ifdef SEC_AUDIO_CALL_VOIP - if (mTag == Usecase::VOIP_RECORD) { - mAudioEffect.SetVoipMicModeEffect(); - } -#endif - - if (!mEffectsApplied) - applyEffects(); - - LOG(DEBUG) << __func__ << mLogPrefix << " : stream is configured"; - - const auto endTime = std::chrono::steady_clock::now(); - using FloatMillis = std::chrono::duration; - const float palStreamOpenTimeTaken = - std::chrono::duration_cast(palOpenApiEndTime - palOpenApiStartTime) - .count(); - const float palStreamStartTimeTaken = - std::chrono::duration_cast(palStartApiEndTime - palStartApiStartTime) - .count(); - const float timeTaken = std::chrono::duration_cast(endTime - startTime).count(); - LOG(INFO) << __func__ << mLogPrefix << ": completed in " << timeTaken - << " ms [pal_stream_open: " << palStreamOpenTimeTaken - << ", ms pal_stream_start: " << palStreamStartTimeTaken << " ms]"; -} - -void StreamInPrimary::applyEffects() { - if (mPalHandle == nullptr) { - // try to applyEffects after pal_stream_start - mEffectsApplied = false; - return; - } - -#ifdef SEC_AUDIO_DYNAMIC_NREC - // support dynamic nrec(defined in audio_effects_sec.xml) - if (mPlatform.getCallMode() == AUDIO_MODE_IN_CALL) { - mAudioEffect.SetECNS(true); - } else { - mAudioEffect.SetECNSForVoip(mTag, mPalHandle, mAECEnabled); - } -#endif - - /* - * While enabling/ disabling AEC or NS check the other effect is enabled or not. - * Take action accordingly. In case AEC is disabled, but NS is still - * enabled then NS has to be enabled alone, otherwise disable both ECNS - * This can be decided based on the state of other effect. - */ - - pal_audio_effect_t type = PAL_AUDIO_EFFECT_ECNS; - bool enable = mAECEnabled || mNSEnabled; - - if (mAECEnabled && mNSEnabled) { - type = PAL_AUDIO_EFFECT_ECNS; - } else if (mAECEnabled) { - type = PAL_AUDIO_EFFECT_EC; - } else if (mNSEnabled) { - type = PAL_AUDIO_EFFECT_NS; - } - - LOG(DEBUG) << __func__ << mLogPrefix << " apply effects aec " << mAECEnabled << " ns " - << mNSEnabled << " type " << type << " enable " << enable; - int ret = pal_add_remove_effect(mPalHandle, type, enable); - mEffectsApplied = (ret == 0); -} - -void StreamInPrimary::shutdown_I() { - LOG(DEBUG) << __func__ << mLogPrefix; - - if (mTag == Usecase::MMAP_RECORD) { - std::get(mExt).setPalHandle(nullptr); - } - - mEffectsApplied = true; - if (mPalHandle != nullptr) { - if (mTag == Usecase::HOTWORD_RECORD && std::get(mExt).isStRecord()) { - if (std::get(mExt).getPalHandle(mMixPortConfig) == mPalHandle) - ::pal_stream_set_param(mPalHandle, PAL_PARAM_ID_STOP_BUFFERING, nullptr); - } else { - ::pal_stream_stop(mPalHandle); - ::pal_stream_close(mPalHandle); - } - } - if (mTag == Usecase::COMPRESS_CAPTURE) { - std::get(mExt).setPalHandle(nullptr); - } - mPalHandle = nullptr; -#ifndef SEC_AUDIO_COMMON - mPlatform.setMicMuteStatus(false); -#endif -} - -::android::status_t StreamInPrimary::burstZero() { - LOG(VERBOSE) << __func__ << mLogPrefix; - if (mTag == Usecase::MMAP_RECORD) { - return startMMAP(); - } - - return ::android::OK; -} - -::android::status_t StreamInPrimary::startMMAP() { - auto& mmap = std::get(mExt); - if (auto ret = mmap.start(); ret) { - LOG(ERROR) << __func__ << mLogPrefix << ": failed"; - return ret; - } - return ::android::OK; -} - -::android::status_t StreamInPrimary::stopMMAP() { - auto& mmap = std::get(mExt); - if (auto ret = mmap.stop(); ret) { - LOG(ERROR) << __func__ << mLogPrefix << ": failed"; - return ret; - } - return ::android::OK; -} - -#ifdef SEC_AUDIO_INTERPRETER_MODE -void StreamInPrimary::RerouteForInterpreter() { - if (mPlatform.getInterpreterMode() == INTERPRETER_LISTENING) { - if (mTag == Usecase::PCM_RECORD) { - const auto& source = getAudioSource(mMixPortConfig); - if (source && source.value() == AudioSource::SEC_BARGEIN_DRIVING) { - ForceSetDevices(mConnectedDevices); - } - } - } -} -#endif - -#ifdef SEC_AUDIO_BLE_OFFLOAD -void StreamInPrimary::updateRecordMetadataForBLE() -{ - int callState = mPlatform.getCallState(); - int callMode = mPlatform.getCallMode(); - bool voiceActive = ((callState == 2) || (callMode == 2)); - - StreamInPrimary::sinkMetadata_mutex_.lock(); - setAggregateSinkMetadata(voiceActive); - StreamInPrimary::sinkMetadata_mutex_.unlock(); -} -#endif - -#ifdef SEC_AUDIO_CAMCORDER -bool StreamInPrimary::isTxDataInvertable() { - const auto& source = getAudioSource(mMixPortConfig); - return source && source.value() == AudioSource::CAMCORDER && - getChannelCount(mMixPortConfig.channelMask.value()) == 2 && - (mPlatform.get_device_types(mConnectedDevices) & AUDIO_DEVICE_IN_2MIC) == AUDIO_DEVICE_IN_2MIC && - mPlatform.isTxDataInversionEnabled(); -} -#endif - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/StreamOutPrimary.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/StreamOutPrimary.cpp deleted file mode 100755 index b041fe28..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/StreamOutPrimary.cpp +++ /dev/null @@ -1,2235 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include - -#define LOG_TAG "AHAL_StreamOut_QTI" - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef SEC_AUDIO_COMMON -#include -#include -#include -using ::aidl::qti::audio::core::VString; -#endif - -using aidl::android::hardware::audio::common::AudioOffloadMetadata; -using aidl::android::hardware::audio::common::getFrameSizeInBytes; -using aidl::android::hardware::audio::common::SinkMetadata; -using aidl::android::hardware::audio::common::SourceMetadata; -using aidl::android::media::audio::common::AudioDevice; -using aidl::android::media::audio::common::AudioDualMonoMode; -using aidl::android::media::audio::common::AudioLatencyMode; -using aidl::android::media::audio::common::AudioOffloadInfo; -using aidl::android::media::audio::common::AudioPlaybackRate; -using aidl::android::media::audio::common::MicrophoneDynamicInfo; -using aidl::android::media::audio::common::MicrophoneInfo; -using aidl::android::media::audio::common::AudioLatencyMode; -using aidl::android::media::audio::common::AudioChannelLayout; -#ifdef SEC_AUDIO_SUPPORT_UHQ -using aidl::android::media::audio::common::PcmType; -#endif -using ::aidl::android::hardware::audio::common::getChannelCount; - -using ::aidl::android::hardware::audio::common::getFrameSizeInBytes; -using ::aidl::android::hardware::audio::common::getPcmSampleSizeInBytes; -using ::aidl::android::hardware::audio::core::IStreamCallback; -using ::aidl::android::hardware::audio::core::IStreamCommon; -using ::aidl::android::hardware::audio::core::StreamDescriptor; -using ::aidl::android::hardware::audio::core::VendorParameter; - -using aidl::android::media::audio::common::AudioPortExt; - -// uncomment this to enable logging of very verbose logs like burst commands. -// #define VERY_VERBOSE_LOGGING 1 - -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK -static bool karaoke = true; -#else -static bool karaoke = false; -#endif - -namespace qti::audio::core { - -std::mutex StreamOutPrimary::sourceMetadata_mutex_; - -StreamOutPrimary::StreamOutPrimary(StreamContext&& context, const SourceMetadata& sourceMetadata, - const std::optional& offloadInfo) - : StreamOut(std::move(context), offloadInfo), - StreamCommonImpl(&(StreamOut::mContext), sourceMetadata), - mTag(getUsecaseTag(getContext().getMixPortConfig())), - mTagName(getName(mTag)), - mFrameSizeBytes(getContext().getFrameSize()), - mMixPortConfig(getContext().getMixPortConfig()), - mPlaybackRate(sDefaultPlaybackRate) { - if (mTag == Usecase::PRIMARY_PLAYBACK) { - mExt.emplace(); - } else if (mTag == Usecase::DEEP_BUFFER_PLAYBACK) { - mExt.emplace(); - } else if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - mExt.emplace(offloadInfo.value(), this, - mMixPortConfig); - } else if (mTag == Usecase::PCM_OFFLOAD_PLAYBACK) { - mExt.emplace(mMixPortConfig); - } else if (mTag == Usecase::VOIP_PLAYBACK) { - mExt.emplace(); - } else if (mTag == Usecase::SPATIAL_PLAYBACK) { - mExt.emplace(); - } else if (mTag == Usecase::MMAP_PLAYBACK) { - mExt.emplace(); - } else if (mTag == Usecase::ULL_PLAYBACK) { - mExt.emplace(); - } else if (mTag == Usecase::IN_CALL_MUSIC) { - mExt.emplace(); - } else if (mTag == Usecase::HAPTICS_PLAYBACK) { - mExt.emplace(); - } - - mHwVolumeSupported = isHwVolumeSupported(); - mHwFlushSupported = isHwFlushSupported(); - mHwPauseSupported = isHwPauseSupported(); - if (mHwVolumeSupported) { - mVolumes.resize(getChannelCount(mMixPortConfig.channelMask.value())); - } - std::ostringstream os; - os << " : usecase: " << mTagName; - os << " IoHandle: " << mMixPortConfig.ext.get().handle << " "; - mLogPrefix = os.str(); - LOG(DEBUG) << __func__ << mLogPrefix; -} - -bool StreamOutPrimary::isHwVolumeSupported() { - switch (mTag) { - case Usecase::COMPRESS_OFFLOAD_PLAYBACK: - case Usecase::PCM_OFFLOAD_PLAYBACK: - case Usecase::MMAP_PLAYBACK: - case Usecase::VOIP_PLAYBACK: - return true; - default: - break; - } - return false; -} - -bool StreamOutPrimary::isHwFlushSupported() { - switch (mTag) { - case Usecase::COMPRESS_OFFLOAD_PLAYBACK: - case Usecase::PCM_OFFLOAD_PLAYBACK: - return true; - default: - break; - } - return false; -} - -bool StreamOutPrimary::isHwPauseSupported() { - switch (mTag) { - case Usecase::COMPRESS_OFFLOAD_PLAYBACK: - case Usecase::PCM_OFFLOAD_PLAYBACK: - return true; - default: - break; - } - return false; -} - -#if defined(SEC_AUDIO_DUAL_SPEAKER) || defined(SEC_AUDIO_MULTI_SPEAKER) -bool StreamOutPrimary::isSoundBoosterRotationSupported() { - switch (mTag) { -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP - case Usecase::COMPRESS_OFFLOAD_PLAYBACK: - case Usecase::DEEP_BUFFER_PLAYBACK: -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_MMAP_ON_DSP - case Usecase::ULL_PLAYBACK: -#endif - case Usecase::LOW_LATENCY_PLAYBACK: -#else - case Usecase::COMPRESS_OFFLOAD_PLAYBACK: -#endif - return true; - default: - break; - } - return false; -} -#endif - -#if defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP) || defined(SEC_AUDIO_PREVOLUME_SOUNDBOOSTER) -uint32_t StreamOutPrimary::getSoundBoosterVolumeMode() { - uint32_t mode = PARAM_VOLUME_NONE; - switch(mTag) { - case Usecase::COMPRESS_OFFLOAD_PLAYBACK: - mode = PARAM_VOLUME_OFFLOAD; - break; -#ifdef SEC_AUDIO_PREVOLUME_SOUNDBOOSTER - case Usecase::MMAP_PLAYBACK: - mode = PARAM_VOLUME_MMAP; - break; - case Usecase::PRIMARY_PLAYBACK: - mode = PARAM_VOLUME_GENERIC; - break; -#elif defined (SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP) - case Usecase::DEEP_BUFFER_PLAYBACK: - mode = PARAM_VOLUME_DEEP; - break; -#ifdef SEC_AUDIO_SUPPORT_LOWLATENCY_MEDIA - case Usecase::LOW_LATENCY_PLAYBACK: - mode = PARAM_VOLUME_FAST_MEDIA; - break; -#endif -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_MMAP_ON_DSP - case Usecase::MMAP_PLAYBACK: - mode = PARAM_VOLUME_MMAP; - break; -#endif -#endif - default: - break; - } - return mode; -} -#endif - -#ifdef SEC_AUDIO_PREVOLUME_SOUNDBOOSTER -void StreamOutPrimary::sendPrevolumeSoundbooster() { - bool sb_volume_on = false; - uint32_t sb_volume_mode = getSoundBoosterVolumeMode(); - - if (sb_volume_mode != PARAM_VOLUME_NONE) { - if (sb_volume_mode == PARAM_VOLUME_GENERIC) { - sb_volume_on = SecModulePrimary::CheckComboDevice(); - } else { - sb_volume_on = hasSpeakerDevice(mConnectedDevices); - } - mAudioEffect.send_soundbooster_on(sb_volume_mode, sb_volume_on); - } -} -#endif - -struct BufferConfig StreamOutPrimary::getBufferConfig() { -#ifdef SEC_AUDIO_SUPPORT_UHQ - return mPlatform.getBufferConfig(mMixPortConfig, mUhqConfig, mTag); -#else - return mPlatform.getBufferConfig(mMixPortConfig, mTag); -#endif -} - -#ifdef SEC_AUDIO_SUPPORT_UHQ -int32_t StreamOutPrimary::getSampleRate() { - if (mTag == Usecase::DEEP_BUFFER_PLAYBACK) { - if (mUhqConfig.has_value()) { - return (int32_t)mUhqConfig.value().second; - } - } - return (int32_t)mMixPortConfig.sampleRate.value().value; -} -#endif - -StreamOutPrimary::~StreamOutPrimary() { - shutdown_I(); - LOG(DEBUG) << __func__ << mLogPrefix; -} - -// start of methods called from IModule -ndk::ScopedAStatus StreamOutPrimary::setConnectedDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) { - mWorker->setIsConnected(!devices.empty()); -#ifdef SEC_AUDIO_HDMI // { SUPPORT_VOIP_VIA_SMART_MONITOR - if (devices.empty()) { - mPreviousDevices = mConnectedDevices; - } -#endif // } SUPPORT_VOIP_VIA_SMART_MONITOR -#ifdef SEC_AUDIO_CALL - // to fix an issue that incall music stream does not open because device is empty - if (!(mTag == Usecase::IN_CALL_MUSIC && devices.empty())) -#endif - mConnectedDevices = devices; - -#ifdef SEC_AUDIO_INTERPRETER_MODE - if (mTag == Usecase::DEEP_BUFFER_PLAYBACK) { - mPlatform.mOutDeepDevices = mConnectedDevices; - auto streamIn = SecModulePrimary::GetStreamIn(Usecase::PCM_RECORD); - if (streamIn) { - streamIn->RerouteForInterpreter(); - } - } -#endif - return configureConnectedDevices_I(); -} - -ndk::ScopedAStatus StreamOutPrimary::reconfigureConnectedDevices() { - return configureConnectedDevices_I(); -} - -ndk::ScopedAStatus StreamOutPrimary::configureConnectedDevices_I() { - if (mConnectedDevices.empty()) { - LOG(DEBUG) << __func__ << mLogPrefix << ": stream is not connected"; - return ndk::ScopedAStatus::ok(); - } - -#ifdef SEC_AUDIO_FMRADIO - RouteFMRadioStream(); -#endif - -#ifdef SEC_AUDIO_CALL - // to reduce call routing delay, call routing on primary routing case - if (mTag == Usecase::PRIMARY_PLAYBACK) -#else - if (mTag == Usecase::LOW_LATENCY_PLAYBACK) -#endif - { - if (auto telephony = mContext.getTelephony().lock()) { - telephony->onOutputPrimaryStreamDevices(mConnectedDevices); - } - } - -#ifdef SEC_AUDIO_CALL_VOIP - // call routing primary -> deep -> ... -> voip rx by audio_policy_configuration define - // to reduce voip routing delay, call voip routing on primary routing case - if (mTag == Usecase::PRIMARY_PLAYBACK) { - auto streamOut = SecModulePrimary::GetStreamOut(Usecase::VOIP_PLAYBACK); - if (streamOut && (streamOut->HasPalStreamHandle() || - mPlatform.getCallMode() == AUDIO_MODE_IN_COMMUNICATION)) { - LOG(DEBUG) << __func__ << mLogPrefix << ": Playback route for voip rx"; - streamOut->ForceSetDevices(mConnectedDevices); - - mAudioEffect.SetVoipMicModeEffect(); -#ifdef SEC_AUDIO_CALL_TRANSLATION - if (mPlatform.getCallTranslation()) { - mAudioEffect.SetVoiceRxEffectForTranslation(true); - } -#endif - } - } -#endif -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC - if (mPlatform.isAasEnabled() && (mTag == Usecase::PRIMARY_PLAYBACK)) { - pal_device_id_t deviceId = PAL_DEVICE_NONE; - auto palDevices = mPlatform.convertToPalDevices(mConnectedDevices); - deviceId = palDevices[0].id; - if (mAudExt.mAasExtension->updateAasStream(true, deviceId) == 0) { - mAudioEffect.setAASVolume(mPlatform.getAasVolume()); - } - } -#endif - - if (!mPalHandle) { - LOG(WARNING) << __func__ << mLogPrefix << ": stream is not configured"; - return ndk::ScopedAStatus::ok(); - } - - auto connectedPalDevices = - mPlatform.configureAndFetchPalDevices(mMixPortConfig, mTag, mConnectedDevices); - - if (connectedPalDevices.size() != mConnectedDevices.size()) { - LOG(ERROR) << __func__ << mLogPrefix << ": pal devices size != aidl devices size"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } -#ifdef SEC_AUDIO_COMMON - connectedPalDevices = mPlatform.configureSecPalDevicesForPlayback(mMixPortConfig, mTag, mConnectedDevices); - if (mSecFTM.getLoopbackScoOn() - || (mSecFTM.getFactoryMode() & SecFTM::FACTORY_ROUTE_ACTIVE)) { - connectedPalDevices = mSecFTM.convertToPalDevices({mSecFTM.getRxFTMDevice()}); - } -#endif -#ifdef SEC_AUDIO_HDMI // { SUPPORT_VOIP_VIA_SMART_MONITOR - RerouteForVoipSmartMonitor(mPreviousDevices); -#endif // } SUPPORT_VOIP_VIA_SMART_MONITOR -#ifdef SEC_AUDIO_CALL_VOIP - RerouteForVoipHeadphone(); -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - if (mPlatform.isListenBackEnabled()) { - auto deviceId = PlatformConverter::getPalDeviceId(mConnectedDevices[0].type); - - if (deviceId != mPlatform.getListenbackDevice() || - mPlatform.getCallMode() != AUDIO_MODE_NORMAL) { - checkAndSwitchListenbackMode(false); - } - - if (deviceId != mPlatform.getListenbackDevice() && - mTag == Usecase::DEEP_BUFFER_PLAYBACK) { - mPlatform.setListenBackEnabled(false); - } - } -#endif -#ifdef SEC_AUDIO_DSM_AMP - if (int32_t ret = (int32_t)mAudExt.mSpeakerFeedbackExtension->setDevice(mPalHandle, - connectedPalDevices.size(), - connectedPalDevices.data()); - !ret) { - LOG(INFO) << __func__ << mLogPrefix << ": set devices on stream for SpeakerFeedback"; - } else -#endif - if (int32_t ret = ::pal_stream_set_device(mPalHandle, connectedPalDevices.size(), - connectedPalDevices.data()); - ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed to set devices on stream, ret:" << ret; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - -#ifdef SEC_AUDIO_COMMON - mPalDevices = connectedPalDevices; -#endif -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_FOLD_PARAM_ON_DSP - mAudioEffect.updateSoundBoosterFoldDegree(); -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - checkAndSwitchListenbackMode(true); -#endif -#ifdef SEC_AUDIO_PREVOLUME_SOUNDBOOSTER - if (mPlatform.getFMRadioOn()) { - mAudioEffect.send_soundbooster_on(PARAM_VOLUME_FM, hasSpeakerDevice(mConnectedDevices)); - } else { - sendPrevolumeSoundbooster(); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_UHQ - if (mUpdateUhqAfterRoute) { - mUpdateUhqAfterRoute = false; - LOG(INFO) << __func__ << " re-open pcm stream for uhq after route"; - standby(); - configure(); - } -#endif - LOG(DEBUG) << __func__ << mLogPrefix << " connected to " << mConnectedDevices; - - return ndk::ScopedAStatus::ok(); -} - -#ifdef SEC_AUDIO_COMMON -ndk::ScopedAStatus StreamOutPrimary::ForceSetDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, bool force) { - - if (force && HasPalStreamHandle()) { - shutdown(); - } - - std::vector outDevices = devices; - if (devices.empty() || hasNoneDevice(devices)) { - outDevices = mConnectedDevices; - } - - if (outDevices.empty()) { - LOG(DEBUG) << __func__ << mLogPrefix << ": stream is not connected"; - return ndk::ScopedAStatus::ok(); - } - - if (!mPalHandle) { - LOG(WARNING) << __func__ << mLogPrefix << ": stream is not configured"; - return ndk::ScopedAStatus::ok(); - } - - auto connectedPalDevices = - mPlatform.configureAndFetchPalDevices(mMixPortConfig, mTag, outDevices); - - if (connectedPalDevices.size() != outDevices.size()) { - LOG(ERROR) << __func__ << mLogPrefix << ": pal devices size != aidl devices size"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - - connectedPalDevices = mPlatform.configureSecPalDevicesForPlayback(mMixPortConfig, mTag, outDevices); - if (mSecFTM.getLoopbackScoOn() - || (mSecFTM.getFactoryMode() & SecFTM::FACTORY_ROUTE_ACTIVE)) { - connectedPalDevices = mSecFTM.convertToPalDevices({mSecFTM.getRxFTMDevice()}); - } - - LOG(DEBUG) << __func__ << mLogPrefix << ": pal_stream_set_device"; - - if (int32_t ret = ::pal_stream_set_device(mPalHandle, connectedPalDevices.size(), - connectedPalDevices.data()); - ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed to set devices on stream, ret:" << ret; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } -#ifdef SEC_AUDIO_COMMON - mPalDevices = connectedPalDevices; -#endif -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_FOLD_PARAM_ON_DSP - mAudioEffect.updateSoundBoosterFoldDegree(); -#endif - - LOG(DEBUG) << __func__ << mLogPrefix << " connected to " << outDevices; - - return ndk::ScopedAStatus::ok(); -} - -bool StreamOutPrimary::isDeviceAvailable(pal_device_id_t pal_device) { - for (int i = 0; i < (int)mConnectedDevices.size(); i++) { - if (!mPalDevices.empty() && mPalDevices[i].id == pal_device) - return true; - } - return false; -} -#endif - -#ifdef SEC_AUDIO_HDMI // { SUPPORT_VOIP_VIA_SMART_MONITOR -void StreamOutPrimary::RerouteForVoipSmartMonitor( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& previousDevices) { - if (mTag == Usecase::VOIP_PLAYBACK) { - // when routing for voip_rx, ? <-> dp - if (hasHdmiOutputDevice(previousDevices) || hasHdmiOutputDevice(mConnectedDevices)) { - // update tx path with custom key if tx path is routed earlier than rx path. - auto streamIn = SecModulePrimary::GetStreamIn(Usecase::VOIP_RECORD); - if (streamIn) { - streamIn->ForceSetDevices(streamIn->getConnectedDevices()); - } - } - } -} -#endif // } SUPPORT_VOIP_VIA_SMART_MONITOR - -#ifdef SEC_AUDIO_CALL_VOIP -void StreamOutPrimary::RerouteForVoipHeadphone() { - if (mTag == Usecase::VOIP_PLAYBACK && mPlatform.getCallMode() == AUDIO_MODE_IN_COMMUNICATION) { - auto streamIn = SecModulePrimary::GetStreamIn(Usecase::VOIP_RECORD); - if (streamIn) { - streamIn->ForceSetDevices(streamIn->getConnectedDevices()); - } - } -} -#endif - -#ifdef SEC_AUDIO_FMRADIO -void StreamOutPrimary::RouteFMRadioStream() { - if (mTag == Usecase::PRIMARY_PLAYBACK && !mConnectedDevices.empty()) { - mPlatform.setFMRadioDevice(hasSpeakerDevice(mConnectedDevices) ? - AUDIO_DEVICE_OUT_SPEAKER : AUDIO_DEVICE_OUT_USB_HEADSET); - struct str_parms *fmParms = str_parms_create(); - str_parms_add_int(fmParms, kFMRouting.c_str(), - (int)(AUDIO_DEVICE_OUT_FM|mPlatform.getFMRadioDevice())); - mAudExt.mFmExtension->audio_extn_fm_set_parameters(fmParms); -#ifdef SEC_AUDIO_PREVOLUME_SOUNDBOOSTER - mAudioEffect.send_soundbooster_on(PARAM_VOLUME_FM, hasSpeakerDevice(mConnectedDevices)); -#endif - str_parms_destroy(fmParms); - } -} -#endif - -#ifdef SEC_AUDIO_DUAL_SPEAKER -bool StreamOutPrimary::isCallMode() -{ - auto curMode = mPlatform.getCallMode(); - if ((curMode == AUDIO_MODE_IN_CALL) || - (curMode == AUDIO_MODE_IN_COMMUNICATION) || - (curMode == AUDIO_MODE_CALL_SCREEN)) { - return true; - } - return false; -} - -bool StreamOutPrimary::isDualSpeakerRouting() { - if ((mConnectedDevices.size() == 1) - && hasSpeakerDevice(mConnectedDevices) - && !(mSecFTM.getFactoryMode() & (SecFTM::FACTORY_LOOPBACK_ACTIVE|SecFTM::FACTORY_ROUTE_ACTIVE))) - return true; - else - return false; -} - -void StreamOutPrimary::SetUpperAmpControl() { -#ifdef SEC_AUDIO_ENHANCED_DUAL_SPEAKER - // need to set mute or unmute in spekaer call mode excpet loopback case - bool mute = false; - if (isCallMode() && isDualSpeakerRouting()) { - mute = mPlatform.isSpeakerLeftAmpOff(); - } - // set mute or unmute for echo ref - if (mAudioEffect.GetEchoRefMuteStatus() != mute) { - if (isCallMode()) { - mAudioEffect.SetEchoRefMuteStatus(mute); - } else { - // mute(false) in case of ringtone and normal mode - mAudioEffect.SetEchoRefMuteStatus(false); - } - } - // set mute or unmute for upper spk - mAudioEffect.SetUpperSpeakerMute(mute); -#endif -} -#endif - -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK -void StreamOutPrimary::checkAndSwitchListenbackMode(bool on) { - - LOG(VERBOSE) << __func__ << " Enter: on " << on << ", isListenBackEnabled " << mPlatform.isListenBackEnabled() - << ", isKaraokeActive " << mAudExt.mKarokeExtension->isKaraokeActive(); - - if(mPlatform.isListenBackEnabled()) { - if (on) { - if (SecModulePrimary::isListenbackDevice(PlatformConverter::getPalDeviceId(mConnectedDevices[0].type)) && - SecModulePrimary::isListenbackUsecase(mTag) && - !mAudExt.mKarokeExtension->isKaraokeActive()) - SecModulePrimary::updateStreamListenbackMode(true); - } else { - if (!on && mAudExt.mKarokeExtension->isKaraokeActive()) - SecModulePrimary::updateStreamListenbackMode(false); - } - } -} - -int StreamOutPrimary::updateListenback(bool on) { - int ret = 0; - - LOG(DEBUG) << __func__ << " Enter: on " << on << ", listenback_on " << mPlatform.isListenBackEnabled(); - mPlatform.karaoke_mutex.lock(); - if (on) { - if (mPlatform.getCallMode() != AUDIO_MODE_NORMAL) { - LOG(ERROR) << __func__ << " Exit: cannot support audio mode " << mPlatform.getCallMode(); - mPlatform.karaoke_mutex.unlock(); - return -EINVAL; - } - - auto streamsIn = ModulePrimary::getInStreams(); - if (streamsIn.empty()) { - LOG(ERROR) << __func__ << " Exit: no active input"; - mPlatform.karaoke_mutex.unlock(); - return -EINVAL; - } - - auto attr = mPlatform.getPalStreamAttributes(mMixPortConfig, false); - if (mTag == Usecase::DEEP_BUFFER_PLAYBACK) { - attr->type = PAL_STREAM_DEEP_BUFFER; - } else if (mTag == Usecase::ULL_PLAYBACK) { - attr->type = PAL_STREAM_ULTRA_LOW_LATENCY; - } - - if (!(attr->direction == PAL_AUDIO_OUTPUT - && (attr->type == PAL_STREAM_DEEP_BUFFER || attr->type == PAL_STREAM_ULTRA_LOW_LATENCY))) { - LOG(ERROR) << __func__ << " Exit: invalid stream type " << attr->type; - mPlatform.karaoke_mutex.unlock(); - return -EINVAL; - } - - if (mAudExt.mKarokeExtension->isKaraokeActive()) { - LOG(DEBUG) << __func__ << " Exit: karaoke stream already open"; - mPlatform.karaoke_mutex.unlock(); - return -EINVAL; - } - pal_stream_callback palFn = nullptr; - pal_device_id_t deviceId = PlatformConverter::getPalDeviceId(mConnectedDevices.back().type); - - if (ret = mAudExt.mKarokeExtension->karaoke_open(deviceId, palFn, - attr->out_media_config.ch_info); - ret) { - LOG(ERROR) << __func__ << " karaoke stream open failed, ret = " << ret; - } else { - if (ret = mAudExt.mKarokeExtension->karaoke_start(); ret) { - LOG(ERROR) << __func__ << " karaoke stream start failed, ret = " << ret; - ret = mAudExt.mKarokeExtension->karaoke_close(); - } else { - LOG(DEBUG) << __func__ << " Karaoke stream start success"; - mPlatform.setListenbackDevice(deviceId); - mAudioEffect.setListenbackEffect(true); - } - } - } else { - if (!mAudExt.mKarokeExtension->isKaraokeActive()) { - LOG(ERROR) << __func__ << " Exit: karaoke stream is not active"; - mPlatform.karaoke_mutex.unlock(); - return -EINVAL; - } - - mAudioEffect.setListenbackEffect(false); - - if (ret = mAudExt.mKarokeExtension->karaoke_stop(); ret) { - LOG(ERROR) << __func__ <<" Failed to stop karaoke stream, ret = " << ret; - } else { - if (ret = mAudExt.mKarokeExtension->karaoke_close(); ret) { - LOG(ERROR) << __func__ << " Failed to close karaoke stream, ret = " << ret; - } else { - LOG(DEBUG) << __func__ << " Karaoke stream close success"; - } - } - } - mPlatform.karaoke_mutex.unlock(); - return ret; -} -#endif - -ndk::ScopedAStatus StreamOutPrimary::configureMMapStream(int32_t* fd, int64_t* burstSizeFrames, - int32_t* flags, - int32_t* bufferSizeFrames) { - if (mTag != Usecase::MMAP_PLAYBACK) { - LOG(ERROR) << __func__ << mLogPrefix << " cannot call on non-MMAP stream types"; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - auto attr = mPlatform.getPalStreamAttributes(mMixPortConfig, false); - if (!attr) { - LOG(ERROR) << __func__ << mLogPrefix << " can't get pal attributes"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - attr->type = PAL_STREAM_ULTRA_LOW_LATENCY; - auto palDevices = mPlatform.configureAndFetchPalDevices(mMixPortConfig, mTag, mConnectedDevices, - true /*dummyDevice*/); - - /* For MMAP playback usecase, audio framework updates track metadata to AHAL after - * CreateMmapBuffer(). In case of MMAP playback on BT, device starts well before - * track metadata updated to BT stack. Due to this, it requires unnecessary - * reconfig to change existing BT config to gaming config params. Thus to avoid - * extra reconfig event and ISO parameters error, HAL updates metadata to BT stack - * before MMAP stream opens. - */ - if (hasBluetoothLEDevice(mConnectedDevices)) { - ssize_t track_count = 1; - std::vector sourceTracks; - source_metadata_t btSourceMetadata; - sourceTracks.resize(track_count); - - btSourceMetadata.track_count = track_count; - btSourceMetadata.tracks = sourceTracks.data(); - btSourceMetadata.tracks->usage = AUDIO_USAGE_GAME; - btSourceMetadata.tracks->content_type = AUDIO_CONTENT_TYPE_MUSIC; - LOG(DEBUG) << __func__<< "Source metadata for mmap usage: " - << btSourceMetadata.tracks->usage << " content_type: " - << btSourceMetadata.tracks->content_type; - // Pass the source metadata to PAL - pal_set_param(PAL_PARAM_ID_SET_SOURCE_METADATA, (void*)&btSourceMetadata, 0); - } - uint64_t cookie = reinterpret_cast(this); - pal_stream_callback palFn = nullptr; - attr->flags = static_cast(PAL_STREAM_FLAG_MMAP_NO_IRQ); -#ifdef SEC_AUDIO_COMMON - palDevices = mPlatform.configureSecPalDevicesForPlayback(mMixPortConfig, mTag, mConnectedDevices); -#endif - if (int32_t ret = ::pal_stream_open(attr.get(), palDevices.size(), palDevices.data(), 0, - nullptr, palFn, cookie, &(this->mPalHandle)); - ret) { - LOG(ERROR) << __func__ << mLogPrefix - << " pal stream open failed, ret:" << std::to_string(ret); - mPalHandle = nullptr; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } -#ifdef SEC_AUDIO_COMMON - mPalDevices = palDevices; -#endif - auto bufConfig = getBufferConfig(); - const size_t ringBufSizeInBytes = bufConfig.bufferSize; - const size_t ringBufCount = bufConfig.bufferCount; - auto palBufferConfig = mPlatform.getPalBufferConfig(ringBufSizeInBytes, ringBufCount); - LOG(DEBUG) << __func__ << mLogPrefix << " set pal_stream_set_buffer_size to " - << std::to_string(ringBufSizeInBytes) << " with count " - << std::to_string(ringBufCount); - if (int32_t ret = - ::pal_stream_set_buffer_size(this->mPalHandle, nullptr, palBufferConfig.get()); - ret) { - LOG(ERROR) << __func__ << mLogPrefix - << " pal_stream_set_buffer_size failed!!! ret:" << std::to_string(ret); - ::pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - - std::get(mExt).setPalHandle(mPalHandle); - - const auto frameSize = ::aidl::android::hardware::audio::common::getFrameSizeInBytes( - mMixPortConfig.format.value(), mMixPortConfig.channelMask.value()); - int32_t ret = std::get(mExt).createMMapBuffer(frameSize, fd, burstSizeFrames, - flags, bufferSizeFrames); - if (ret != 0) { - LOG(ERROR) << __func__ << mLogPrefix << " create MMap buffer failed!"; - ::pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - - LOG(INFO) << __func__ << mLogPrefix << ": stream is configured"; - - setHwVolume(mVolumes); - -#ifdef SEC_AUDIO_PREVOLUME_SOUNDBOOSTER - sendPrevolumeSoundbooster(); -#endif - - return ndk::ScopedAStatus::ok(); -} - -// end of methods called from IModule - -// start of DriverInterface Methods - -::android::status_t StreamOutPrimary::init() { - return ::android::OK; -} - -::android::status_t StreamOutPrimary::drain(StreamDescriptor::DrainMode mode) { - if (!mPalHandle) { - LOG(WARNING) << __func__ << mLogPrefix << ": stream is not configured"; - return ::android::OK; - } - - if (mTag == Usecase::MMAP_PLAYBACK) { - // drain is stop for mmap - return stopMMAP(); - } - - auto palDrainMode = - mode == StreamDescriptor::DrainMode::DRAIN_ALL ? PAL_DRAIN : PAL_DRAIN_PARTIAL; - if (int32_t ret = ::pal_stream_drain(mPalHandle, palDrainMode); ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed to drain the stream, ret:" << ret; - return ret; - } - LOG(DEBUG) << __func__ << mLogPrefix << " drained "; - return ::android::OK; -} - -::android::status_t StreamOutPrimary::flush() { - if (!mPalHandle) { - LOG(WARNING) << __func__ << mLogPrefix << ": stream is not configured "; - return ::android::OK; - } - - if (mTag == Usecase::MMAP_PLAYBACK) { - // flush is stop for mmap - return stopMMAP(); - } - - if (!mHwFlushSupported) { - LOG(VERBOSE) << __func__ << mLogPrefix << " unsupported operation!!, Hence ignored"; - return ::android::OK; - } - - // to be precise or accurate w.r.t to frames consumed - // before flush operation, we would fetch latest frames - // and cache it. - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - std::get(mExt).getPositionInFrames(mPalHandle); - } else if (mTag == Usecase::PCM_OFFLOAD_PLAYBACK) { - std::get(mExt).getPositionInFrames(mPalHandle); - } - - if (int32_t ret = ::pal_stream_flush(mPalHandle); ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed to flush the stream, ret:" << ret; - return ret; - } - - // after flush operation - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - std::get(mExt).onFlush(); - } else if (mTag == Usecase::PCM_OFFLOAD_PLAYBACK) { - std::get(mExt).onFlush(); - } - - LOG(DEBUG) << __func__ << mLogPrefix; - return ::android::OK; -} - -::android::status_t StreamOutPrimary::pause() { - if (!mPalHandle) { - LOG(WARNING) << __func__ << mLogPrefix << ": stream is not configured "; - return ::android::OK; - } - - if (mTag == Usecase::MMAP_PLAYBACK) { - // pause is stop for mmap - return stopMMAP(); - } - - if (!mHwPauseSupported) { - LOG(VERBOSE) << __func__ << mLogPrefix << " unsupported operation!!, Hence ignored"; - return ::android::OK; - } - - if (int32_t ret = pal_stream_pause(mPalHandle); ret) { - LOG(ERROR) << __func__ << mLogPrefix - << " failed to pause the stream, ret:" << std::to_string(ret); - return ret; - } - mIsPaused = true; - LOG(DEBUG) << __func__ << mLogPrefix; - return ::android::OK; -} - -void StreamOutPrimary::resume() { - if (mTag == Usecase::MMAP_PLAYBACK) { - if (int32_t ret = pal_stream_start(mPalHandle); ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed to start the stream, ret:" << ret; - } - } else { - if (int32_t ret = ::pal_stream_resume(mPalHandle); ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed to resume the stream, ret:" << ret; - } - } - LOG(DEBUG) << __func__ << mLogPrefix; - mIsPaused = false; -} - -::android::status_t StreamOutPrimary::standby() { - if (!mPalHandle) { - LOG(WARNING) << __func__ << mLogPrefix << ": stream is not configured "; - return ::android::OK; - } - -#ifdef SEC_AUDIO_CALL_VOIP - if (mTag == Usecase::VOIP_PLAYBACK) { - mVoIPInSamplerate = 0; - if (mPlatform.getCngEnable()) { - mAudioEffect.SetCNGForEchoRefMute(false); - } -#ifdef SEC_AUDIO_CALL_TRANSLATION - if (mPlatform.getCallTranslation() && mPlatform.getCallState() != 2 /*CallState::ACTIVE*/) { - mAudioEffect.SetVoiceRxEffectForTranslation(false); - } -#endif - } -#endif - - shutdown_I(); - LOG(DEBUG) << __func__ << mLogPrefix; - return ::android::OK; -} - -::android::status_t StreamOutPrimary::start() { - // hardware is expected to up on start - // but we are doing on first write - LOG(DEBUG) << __func__ << mLogPrefix; - - if (mTag == Usecase::MMAP_PLAYBACK) { - return startMMAP(); - } - - if (mPalHandle && mIsPaused) { - resume(); - } - - if (hasOutputVoipRxFlag(mMixPortConfig.flags.value()) || - hasOutputDeepBufferFlag(mMixPortConfig.flags.value())) { - if (auto telephony = mContext.getTelephony().lock()) { - telephony->onPlaybackStart(); - } - } - return ::android::OK; -} - -::android::status_t StreamOutPrimary::transfer(void* buffer, size_t frameCount, - size_t* actualFrameCount, int32_t* latencyMs) { - if (!mPalHandle) { - // configure on first transfer or after stand by - configure(); - if (!mPalHandle) { - LOG(ERROR) << __func__ << mLogPrefix << ": failed to configure"; - *actualFrameCount = frameCount; - return onWriteError(frameCount); - } -#ifdef SEC_AUDIO_COMMON - else { - LOG(DEBUG) << __func__ << mLogPrefix << ": sucess to configure"; - } -#endif - } - - if (mIsPaused) { - resume(); - } - -#ifdef SEC_AUDIO_CALL_VOIP - if ((mTag == Usecase::VOIP_PLAYBACK) && - (mPlatform.getCallMode() != AUDIO_MODE_IN_COMMUNICATION)) { - if (isCustomKeyRouted(CUSTOM_KEY_VOIP_COMM)) { - ForceSetDevices(mConnectedDevices); - } - } -#endif -#ifdef SEC_AUDIO_KARAOKE - if (mPlatform.isKaraokeUsecases(mTag) && - isDeviceAvailable(PAL_DEVICE_OUT_SPEAKER)) { - if (mPlatform.isKaraokeEnabled() - && !isCustomKeyRouted(CUSTOM_KEY_KARAOKE)) { - SecModulePrimary::getInstance().setKaraokeDevice(); - } - } -#endif - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - /** - * upon partial drain, gapless metadata resets in tinycompress. - * if there is a write after that, we would need configure the gapless - * gain. - */ - auto& compressPlayback = std::get(mExt); - if (!(compressPlayback.isGaplessConfigured())) { - compressPlayback.configureGapless(mPalHandle); - } - } - - if (frameCount == 0) { - *actualFrameCount = 0; - return burstZero(); - } - - pal_buffer palBuffer{}; - palBuffer.buffer = static_cast(buffer); - palBuffer.size = frameCount * mFrameSizeBytes; - - ssize_t bytesWritten; - if (mBufferFormatConverter.has_value()) { - bytesWritten = convertBufferAndWrite(buffer, frameCount); - } else if (mTag == Usecase::HAPTICS_PLAYBACK && mHapticsPalHandle) { - bytesWritten = hapticsWrite(buffer, frameCount); - } else { -#ifdef SEC_AUDIO_CALL_VOIP - if (mTag == Usecase::VOIP_PLAYBACK) { - auto streamIn = SecModulePrimary::GetStreamIn(Usecase::VOIP_RECORD); - if (streamIn) { - auto attrStreamIn = mPlatform.getPalStreamAttributes(streamIn->getContext().getMixPortConfig(), true); - if (attrStreamIn->in_media_config.sample_rate != 0 && - attrStreamIn->in_media_config.sample_rate != mVoIPInSamplerate) { - standby(); - } - } - } -#endif - bytesWritten = ::pal_stream_write(mPalHandle, &palBuffer); - } - if (bytesWritten < 0) { - LOG(ERROR) << __func__ << mLogPrefix << " write failed, ret: " << bytesWritten; - *actualFrameCount = frameCount; - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - *actualFrameCount = 0; - } - return onWriteError(frameCount); - } - - *actualFrameCount = mFrameSizeBytes ? - static_cast(bytesWritten / mFrameSizeBytes) : 0; - -#ifdef VERY_VERBOSE_LOGGING - LOG(VERBOSE) << __func__ << mLogPrefix << ": byteswritten: " << bytesWritten; -#endif - - // Todo findout write latency - *latencyMs = mContext.getNominalLatencyMs(); - if (hasBluetoothDevice(mConnectedDevices)) { - const auto& btlatencyMs = mPlatform.getBluetoothLatencyMs(mConnectedDevices); - *latencyMs += btlatencyMs; - } - return ::android::OK; -} - -::android::status_t StreamOutPrimary::convertBufferAndWrite(const void* buffer, size_t frameCount) { - auto& converter = *mBufferFormatConverter.value(); - if (auto result = converter.convert(buffer, frameCount * mFrameSizeBytes)) { - pal_buffer palBuffer{}; - palBuffer.buffer = result->first; - palBuffer.size = result->second; - ssize_t bytesWritten = ::pal_stream_write(mPalHandle, &palBuffer); - if (bytesWritten >= 0) { - bytesWritten = (bytesWritten * converter.getInputBytesPerSample()) / - converter.getOutputBytesPerSample(); - return bytesWritten; - } - } - - return -EINVAL; -} -::android::status_t StreamOutPrimary::hapticsWrite(const void* buffer, size_t frameCount) { - int ret = 0; - bool allocHapticsBuffer = false; - struct pal_buffer audioBuf; - struct pal_buffer hapticsBuf; - size_t srcIndex = 0, audIndex = 0, hapIndex = 0; - uint8_t channelCount = getChannelCount(mMixPortConfig.channelMask.value()); - uint8_t bytesPerSample = getPcmSampleSizeInBytes(mMixPortConfig.format.value().pcm); - uint32_t frameSize = channelCount * bytesPerSample; - - // Calculate Haptics Buffer size - - uint32_t hapticsFrameSize = mHapticsChannelCount * bytesPerSample; - uint32_t audioFrameSize = frameSize - hapticsFrameSize; - uint32_t totalHapticsBufferSize = frameCount * hapticsFrameSize; - - - if (!mHapticsBuffer) { - allocHapticsBuffer = true; - } else if (mHapticsBufSize < totalHapticsBufferSize) { - allocHapticsBuffer = true; - mHapticsBufSize = 0; - } - - if (allocHapticsBuffer) { - mHapticsBuffer = std::make_unique(totalHapticsBufferSize); - if(!mHapticsBuffer) { - LOG(ERROR) << __func__ << ": Failed to allocate haptic buffer"; - return -ENOMEM; - } - mHapticsBufSize = totalHapticsBufferSize; - } - - audioBuf.buffer = (uint8_t *)buffer; - audioBuf.size = frameCount * audioFrameSize; - audioBuf.offset = 0; - hapticsBuf.buffer = reinterpret_cast(mHapticsBuffer.get()); - hapticsBuf.size = frameCount * hapticsFrameSize; - hapticsBuf.offset = 0; - - for (size_t i = 0; i < frameCount; i++) { - memcpy((uint8_t *)(audioBuf.buffer) + audIndex, (uint8_t *)(audioBuf.buffer) + srcIndex, - audioFrameSize); - audIndex += audioFrameSize; - srcIndex += audioFrameSize; - - memcpy((uint8_t *)(hapticsBuf.buffer) + hapIndex, (uint8_t *)(audioBuf.buffer) + srcIndex, - hapticsFrameSize); - hapIndex += hapticsFrameSize; - srcIndex += hapticsFrameSize; - } - - // write audio data - ret = ::pal_stream_write(mPalHandle, &audioBuf); - // write haptics data - ret = ::pal_stream_write(mHapticsPalHandle, &hapticsBuf); - - return (ret < 0 ? ret : (frameSize*frameCount)); -} - -::android::status_t StreamOutPrimary::refinePosition(StreamDescriptor::Reply* reply) { - - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - reply->observable.frames = std::get(mExt).getPositionInFrames(mPalHandle); - } else if (mTag == Usecase::PCM_OFFLOAD_PLAYBACK) { - reply->observable.frames = - std::get(mExt).getPositionInFrames(mPalHandle); - } else if (mTag == Usecase::MMAP_PLAYBACK) { - int32_t ret = std::get(mExt).getMMapPosition(&(reply->hardware.frames), - &(reply->hardware.timeNs)); - if (ret != 0) { - LOG(ERROR) << __func__ << mLogPrefix << ": mmap position failed"; - return android::INVALID_OPERATION; - } - - int64_t totalDelayFrames = 0; - totalDelayFrames = - mContext.getNominalLatencyMs() * mMixPortConfig.sampleRate.value().value / 1000; - reply->observable.frames = (reply->hardware.frames > totalDelayFrames) - ? (reply->hardware.frames - totalDelayFrames) - : 0; - reply->observable.timeNs = reply->hardware.timeNs; - LOG(VERBOSE) << __func__ << mLogPrefix << ": hw frames " << reply->hardware.frames - << " observable frames " << reply->observable.frames - << " time : " << reply->observable.timeNs; - return ::android::OK; - } else { - int64_t totalDelayFrames = 0; -#ifdef SEC_AUDIO_SUPPORT_UHQ - totalDelayFrames = mContext.getNominalLatencyMs() * - getSampleRate() / 1000; -#else - totalDelayFrames = mContext.getNominalLatencyMs() * - mMixPortConfig.sampleRate.value().value / 1000; -#endif - reply->observable.frames = (reply->observable.frames > totalDelayFrames) ? - (reply->observable.frames - totalDelayFrames) : 0; - } - - // if the stream is connected to any bluetooth device, consider bluetooth encoder latency - if (hasBluetoothDevice(mConnectedDevices)) { - const auto& latencyMs = mPlatform.getBluetoothLatencyMs(mConnectedDevices); -#ifdef SEC_AUDIO_SUPPORT_UHQ - const auto& sampleRate = getSampleRate(); -#else - const auto& sampleRate = mMixPortConfig.sampleRate.value().value; -#endif - const auto btExtraFrames = latencyMs * sampleRate / 1000; - // Todo, Check do we want to consider this for MMAP usecase - reply->observable.frames = (reply->observable.frames > btExtraFrames) ? - (reply->observable.frames - btExtraFrames) : 0; - reply->latencyMs += latencyMs; - } - reply->observable.timeNs = ::android::uptimeNanos(); - LOG(VERBOSE) <<__func__ << mLogPrefix << " observable.frames: " << reply->observable.frames; - - return ::android::OK; -} - -void StreamOutPrimary::shutdown() { - shutdown_I(); -} - -// end of DriverInterface Methods - -// start of PlatformStreamCallback methods -void StreamOutPrimary::onTransferReady() { - publishTransferReady(); -} - -void StreamOutPrimary::onDrainReady() { - publishDrainReady(); -} - -void StreamOutPrimary::onError() { - publishError(); -} - -// end of PlatformStreamCallback methods - -// start of IStreamOut Methods -ndk::ScopedAStatus StreamOutPrimary::updateOffloadMetadata( - const AudioOffloadMetadata& in_offloadMetadata) { - if (isClosed()) { - LOG(ERROR) << __func__ << mLogPrefix << ": stream was closed"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - if (!mOffloadInfo.has_value()) { - LOG(ERROR) << __func__ << mLogPrefix << ": not a compressed offload stream"; - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - if (in_offloadMetadata.sampleRate < 0) { - LOG(ERROR) << __func__ << mLogPrefix - << ": invalid sample rate value: " << in_offloadMetadata.sampleRate; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_offloadMetadata.averageBitRatePerSecond < 0) { - LOG(ERROR) << __func__ << mLogPrefix - << ": invalid average BPS value: " << in_offloadMetadata.averageBitRatePerSecond; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_offloadMetadata.delayFrames < 0) { - LOG(ERROR) << __func__ << mLogPrefix - << ": invalid delay frames value: " << in_offloadMetadata.delayFrames; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_offloadMetadata.paddingFrames < 0) { - LOG(ERROR) << __func__ << mLogPrefix - << ": invalid padding frames value: " << in_offloadMetadata.paddingFrames; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (mTag != Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - LOG(WARNING) << __func__ << mLogPrefix << ": expected CompressOffloadPlayback instead of " - << mTagName; - return ndk::ScopedAStatus::ok(); - } - - mOffloadMetadata = in_offloadMetadata; - - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - std::get(mExt).updateOffloadMetadata(mOffloadMetadata.value()); - } - - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamOutPrimary::getHwVolume(std::vector* _aidl_return) { - if (!mHwVolumeSupported) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - *_aidl_return = mVolumes; - LOG(VERBOSE) << __func__ << mLogPrefix << ::android::internal::ToString(mVolumes); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamOutPrimary::setHwVolume(const std::vector& in_channelVolumes) { - if (!mHwVolumeSupported) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - if (mVolumes.size() != in_channelVolumes.size()) { - LOG(ERROR) << __func__ << mLogPrefix << " channel count mismatch with port, expected " - << mVolumes.size() << " got " << in_channelVolumes.size(); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - auto isVolumeInRange = [](const std::vector& volumes) { - return std::all_of(volumes.begin(), volumes.end(), - [](float vol) { return (vol >= 0.0f && vol <= 1.0f); }); - }; - - if (!isVolumeInRange(in_channelVolumes)) { - LOG(ERROR) << __func__ << mLogPrefix << " out of range volume " - << ::android::internal::ToString(in_channelVolumes); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - if (!mPalHandle) { - mVolumes = in_channelVolumes; - LOG(DEBUG) << __func__ << mLogPrefix << " cache volume " - << ::android::internal::ToString(in_channelVolumes); - return ndk::ScopedAStatus::ok(); - } - -#ifdef SEC_AUDIO_COMMON - if (int32_t ret = setSecVolume(in_channelVolumes); ret) { - LOG(DEBUG) << __func__ << mLogPrefix << " skip pal_stream_set_volume()"; - } else -#endif - if (int32_t ret = mPlatform.setVolume(mPalHandle, in_channelVolumes); ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed to set volume"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - - mVolumes = in_channelVolumes; - - LOG(DEBUG) << __func__ << mLogPrefix << ::android::internal::ToString(mVolumes); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamOutPrimary::getPlaybackRateParameters(AudioPlaybackRate* _aidl_return) { -#if defined(SEC_AUDIO_OFFLOAD_COMPRESSED_OPUS) && defined(SEC_AUDIO_OFFLOAD_SOUNDSPEED) - if (!mPlatform.isSecSupportsOffloadSpeed(mOffloadInfo)) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } -#else - if (!mPlatform.usecaseSupportsOffloadSpeed(mTag)) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } -#endif - LOG(DEBUG) << __func__ << mPlaybackRate.toString(); - *_aidl_return = mPlaybackRate; - return ndk::ScopedAStatus::ok(); -} - -#ifdef SEC_AUDIO_COMMON -bool StreamOutPrimary::setSecVolume(const std::vector& volumes) { - bool ret = false; - - auto data = mPlatform.getPalVolume(volumes); - if (data.empty()) { - LOG(ERROR) << __func__ << ": failed to configure volume"; - return false; - } - auto palVolumeData = reinterpret_cast(data.data()); - -#if defined (SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP) || defined (SEC_AUDIO_PREVOLUME_SOUNDBOOSTER) // TEMP_FOR_SETUP_V - if (hasSpeakerDevice(mConnectedDevices)) { - uint32_t mode = getSoundBoosterVolumeMode(); - if (mode != PARAM_VOLUME_NONE) { - mAudioEffect.send_soundbooster_volume(palVolumeData, mode); -#if defined(SEC_AUDIO_DUAL_SPEAKER) || defined(SEC_AUDIO_MULTI_SPEAKER) - if (isSoundBoosterRotationSupported()) { - mAudioEffect.send_soundbooster_rotation(); - } -#endif - } -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP - mAudioEffect.send_soundbooster_flatmotion(); -#endif -#ifdef SEC_AUDIO_SUPPORT_SOUNDBOOSTER_FOLD_PARAM_ON_DSP - mAudioEffect.updateSoundBoosterFoldDegree(); -#endif - } -#endif - -#ifdef SEC_AUDIO_OFFLOAD - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - mAudioEffect.send_effect_volume(palVolumeData); - ret = true; - } -#endif -#ifdef SEC_AUDIO_CALL - else if (mTag == Usecase::VOIP_PLAYBACK) { - if (mPlatform.getCallMode() == AUDIO_MODE_IN_CALL) { - ret = true; - } -#ifdef SEC_AUDIO_SUPPORT_BT_RVC - else if (mAudioEffect.SetScoVolume(palVolumeData->volume_pair[0].vol) == 0) { - LOG(DEBUG) << __func__ << " sco volume applied on voip stream"; - ret = true; - } -#endif - } -#endif - return ret; -} -#endif - -ndk::ScopedAStatus StreamOutPrimary::setPlaybackRateParameters( - const AudioPlaybackRate& in_playbackRate) { -#if defined(SEC_AUDIO_OFFLOAD_COMPRESSED_OPUS) && defined(SEC_AUDIO_OFFLOAD_SOUNDSPEED) - AudioEffect audioEffect = mAudioEffect; - - auto command = [&audioEffect](const float& speed) { - audioEffect.set_soundspeed_value(speed); - audioEffect.send_soundspeed_value(); - }; - auto ret = mPlatform.setSecPlaybackRate(mPalHandle, mTag, in_playbackRate, mOffloadInfo, command); -#else - auto ret = mPlatform.setPlaybackRate(mPalHandle, mTag, in_playbackRate); -#endif - if (PlaybackRateStatus::SUCCESS == ret) { - mPlaybackRate = in_playbackRate; - LOG(DEBUG) << __func__ << mPlaybackRate.toString(); - return ndk::ScopedAStatus::ok(); - } else if (PlaybackRateStatus::UNSUPPORTED == ret) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); -} - -// end of IStreamOut Methods - -// start of StreamCommonInterface Methods - -ndk::ScopedAStatus StreamOutPrimary::updateMetadataCommon(const Metadata& metadata) { - if (isClosed()) { - LOG(ERROR) << __func__ << mLogPrefix << ": stream was closed"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - - if (metadata.index() != mMetadata.index()) { - LOG(FATAL) << __func__ << mLogPrefix << ": changing metadata variant is not allowed"; - } - mMetadata = metadata; - - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - auto& compressPlayback = std::get(mExt); - compressPlayback.updateSourceMetadata(std::get(mMetadata)); - } - int callState = mPlatform.getCallState(); - int callMode = mPlatform.getCallMode(); - bool voiceActive = ((callState == 2) || (callMode == 2)); - - StreamOutPrimary::sourceMetadata_mutex_.lock(); - setAggregateSourceMetadata(voiceActive); - StreamOutPrimary::sourceMetadata_mutex_.unlock(); - - return ndk::ScopedAStatus::ok(); -} - -int32_t StreamOutPrimary::setAggregateSourceMetadata(bool voiceActive) { - ssize_t track_count_total = 0; - - std::vector total_tracks; - source_metadata_t btSourceMetadata; - - ModulePrimary::outListMutex.lock(); - std::vector>& outStreams = ModulePrimary::getOutStreams(); - if (voiceActive || outStreams.empty()) { - ModulePrimary::outListMutex.unlock(); - return 0; - } - auto removeStreams = [&](std::weak_ptr streamOut) -> bool { - if (!streamOut.lock()) return true; - return streamOut.lock()->isClosed(); - }; - outStreams.erase(std::remove_if(outStreams.begin(), outStreams.end(), removeStreams), - outStreams.end()); - - LOG(VERBOSE) << __func__ << mLogPrefix << " out streams not empty size is " << outStreams.size(); - - for (auto it = outStreams.begin(); it < outStreams.end(); it++) { - if (it->lock() && !it->lock()->isClosed()) { - ::aidl::android::hardware::audio::common::SourceMetadata srcMetadata; - it->lock()->getMetadata(srcMetadata); - track_count_total += srcMetadata.tracks.size(); - } else { - } - } - LOG(VERBOSE) << __func__ << mLogPrefix << " out streams size after deleting : " << outStreams.size() - << " total track count " << track_count_total; - - if (track_count_total <= 0) { - ModulePrimary::outListMutex.unlock(); - return 0; - } - - total_tracks.resize(track_count_total); - btSourceMetadata.track_count = track_count_total; - btSourceMetadata.tracks = total_tracks.data(); - - for (auto it = outStreams.begin(); it != outStreams.end(); it++) { - ::aidl::android::hardware::audio::common::SourceMetadata srcMetadata; - if (it->lock()) { - it->lock()->getMetadata(srcMetadata); - for (auto& item : srcMetadata.tracks) { - /* currently after cs call ends, we are getting metadata as - * usage voice and content speech, this is causing BT to again - * open call session, so added below check to send metadata of - * voice only if call is active, else discard it - */ - if (!voiceActive && (mPlatform.getCallMode() != 3) && - (AUDIO_USAGE_VOICE_COMMUNICATION == static_cast(item.usage)) && - (AUDIO_CONTENT_TYPE_SPEECH == - static_cast(item.contentType))) { - btSourceMetadata.track_count--; - } else { - btSourceMetadata.tracks->usage = static_cast(item.usage); - btSourceMetadata.tracks->content_type = - static_cast(item.contentType); - LOG(VERBOSE) << __func__ << mLogPrefix << " source metadata usage is " - << btSourceMetadata.tracks->usage << " content is " - << btSourceMetadata.tracks->content_type; - ++btSourceMetadata.tracks; - } - } - } - } - btSourceMetadata.tracks = total_tracks.data(); - pal_set_param(PAL_PARAM_ID_SET_SOURCE_METADATA, (void*)&btSourceMetadata, 0); - ModulePrimary::outListMutex.unlock(); - return 0; -} - -ndk::ScopedAStatus StreamOutPrimary::getVendorParameters( - const std::vector& in_ids, std::vector* _aidl_return) { - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - auto& compressPlayback = std::get(mExt); - return compressPlayback.getVendorParameters(in_ids, _aidl_return); - } - - for (const auto& id : in_ids) { - if (id == Parameters::kSupportsHwSuspend) { - if (mTag == Usecase::LOW_LATENCY_PLAYBACK) { - _aidl_return->push_back(makeVendorParameter(id, "1")); - } - } else if (id == Parameters::kIsDirectPCMTrack) { - if (mTag == Usecase::PCM_OFFLOAD_PLAYBACK) { - _aidl_return->push_back(makeVendorParameter(id, "true")); - } - } - } - - if (in_ids.size() != _aidl_return->size()) - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamOutPrimary::setVendorParameters( - const std::vector& in_parameters, bool in_async) { - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - auto& compressPlayback = std::get(mExt); -#ifdef SEC_AUDIO_COMMON - // for process sec param, not to return here - compressPlayback.setVendorParameters(in_parameters, in_async); -#else - return compressPlayback.setVendorParameters(in_parameters, in_async); -#endif - } - -#ifdef SEC_AUDIO_COMMON -#ifdef SEC_AUDIO_SUPPORT_UHQ - std::optional uhqFormat; - std::optional wideRes; - audio_devices_t forceDevice = AUDIO_DEVICE_NONE; - std::optional upscalerMode; -#endif - - for (const auto& param : in_parameters) { - std::string paramValue{}; - if (!extractParameter(param, ¶mValue)) { - LOG(ERROR) << __func__ << ": extraction failed for " << param.id; - continue; - } - LOG(DEBUG) << __func__ << mLogPrefix << ": configured " << param.id; - -#ifdef SEC_AUDIO_CALL - if (SecParameters::kVolumeVoice == param.id) { - mPlatform.setVoiceVolume(getFloatFromString(paramValue)); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_HAPTIC_PLAYBACK - else if (SecParameters::kHapticsSource == param.id) { - if (mTag == Usecase::HAPTICS_PLAYBACK) { - const int hapticsSource = getInt64FromString(paramValue); - mPlatform.setHapticsSource(hapticsSource); - } - } -#endif -#if defined(SEC_AUDIO_DUAL_SPEAKER) && !defined(SEC_AUDIO_FACTORY_TEST_MODE) - else if (SecParameters::kDualSpeakerAmpLeftPowerEnable == param.id) { -#ifdef SEC_AUDIO_ENHANCED_DUAL_SPEAKER - //update speaker_left_amp_off status - bool prev_status = mPlatform.isSpeakerLeftAmpOff(); - mPlatform.setSpeakerLeftAmpOff(!getBoolFromString(paramValue)); - if (isCallMode()) { - if (prev_status != mPlatform.isSpeakerLeftAmpOff()) { - SetUpperAmpControl(); - } - } else if (mPalHandle - && !mPlatform.isSpeakerLeftAmpOff() - && isDualSpeakerRouting()) { - // change a device in case of only mono -> stereo - ForceSetDevices(mConnectedDevices); - LOG(DEBUG) << __func__ << mLogPrefix << ": ForceRouteStream for speaker amp status"; - } -#endif - } -#endif -#if defined(SEC_AUDIO_DUAL_SPEAKER) || defined(SEC_AUDIO_MULTI_SPEAKER) - else if (SecParameters::kHwDisplayRotation == param.id) { - mPlatform.updateRotationInfo(static_cast(getInt64FromString(paramValue))); - if (hasSpeakerDevice(mConnectedDevices) && isSoundBoosterRotationSupported()) { - mAudioEffect.send_soundbooster_rotation(); - } - } -#endif -#ifdef SEC_AUDIO_SUPPORT_UHQ - else if (SecParameters::kUhqUpdateFormat == param.id) { - uhqFormat = (int)getInt64FromString(paramValue); - } - else if (SecParameters::kSubkeyUhqWideResolution == param.id) { - wideRes = getBoolFromString(paramValue); - } - else if (SecParameters::kSubkeyUhqForceRouting == param.id) { - forceDevice = (audio_devices_t)getInt64FromString(paramValue); - } -#ifdef SEC_AUDIO_SUPPORT_UHQ_OFFLOAD - else if (SecParameters::kEffectUpscalerMode == param.id) { - upscalerMode = (int)getInt64FromString(paramValue); - } -#endif -#endif - } -#endif - -#ifdef SEC_AUDIO_SUPPORT_UHQ - if (uhqFormat.has_value() && wideRes.has_value()) { - updateUhqConfig(uhqFormat.value(), wideRes.value()); - pal_uhqa_state sampleRate = mUhqConfig.value().second; - - if (mTag == Usecase::DEEP_BUFFER_PLAYBACK) { - mPlatform.updateUHQA(sampleRate); - if (mPalHandle) { -#ifdef SEC_AUDIO_BLE_OFFLOAD - //it will be change configure after routing - if (mConnectedDevices.size() == 1 && - isDeviceAvailable(PAL_DEVICE_OUT_BLUETOOTH_A2DP) && - forceDevice == (audio_devices_t)AUDIO_DEVICE_OUT_BLE_HEADSET) { - // for a2dp(a2dp suspend) -> ble case, enable a2dp device unintentionally by standby&open - // that canbe cause of mute issue. - // so, just set flag and do standby&open after routing ble device - mUpdateUhqAfterRoute = true; - } else -#endif - { - mUpdateUhqAfterRoute = false; - standby(); - configure(); - } - } - } -#ifdef SEC_AUDIO_SUPPORT_UHQ_OFFLOAD - else if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - mPlatform.updateUHQA(sampleRate); - int mode = (sampleRate == PAL_UHQ_STATE_192KHZ) ? UPSCALER_HIGH : UPSCALER_MID; - mAudioEffect.setUpscalerMode(mode); - } -#endif - } -#ifdef SEC_AUDIO_SUPPORT_UHQ_OFFLOAD - if (upscalerMode.has_value()) { - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK && mPalHandle) { - int mode = upscalerMode.value(); - if (mode >= UPSCALER_OFF && mode <= UPSCALER_MID) { - mAudioEffect.setUpscalerMode(mode); - mAudioEffect.send_upscaler_enable_mode(); - } - } - } -#endif -#endif - -#ifdef SEC_AUDIO_COMMON - return ndk::ScopedAStatus::ok(); // always return ok -#else - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -#endif -} - -void StreamOutPrimary::updateUhqConfig(int formatInt, bool wideRes) { - // case 1. 'l_uhq_update_format == 3 && l_uhq_wide_resolution_enable == false' : 384K 32bit - // case 2. 'l_uhq_update_format == 4 && l_uhq_wide_resolution_enable == false' : 192K 24bit - // case 3. 'l_uhq_update_format == 4 && l_uhq_wide_resolution_enable == true' : 48K 24bit - // case 4. 'l_uhq_update_format == 1 && l_uhq_wide_resolution_enable == false' : 48K 16bit - - //default config - PcmType format = PcmType::FIXED_Q_8_24; - pal_uhqa_state sample = PAL_UHQ_STATE_NORMAL; - - if (!wideRes) { - if (formatInt == AUDIO_FORMAT_PCM_16_BIT) { - format = PcmType::INT_16_BIT; - sample = PAL_UHQ_STATE_NORMAL; - } else if (formatInt == AUDIO_FORMAT_PCM_8_24_BIT) { - format = PcmType::FIXED_Q_8_24; - sample = PAL_UHQ_STATE_192KHZ; - } else if (formatInt == AUDIO_FORMAT_PCM_32_BIT) { - format = PcmType::INT_32_BIT; - sample = PAL_UHQ_STATE_384KHZ; - } - } - mUhqConfig = std::make_pair(format, sample); -} - -ndk::ScopedAStatus StreamOutPrimary::addEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) { - if (in_effect == nullptr) { - LOG(VERBOSE) << __func__ << mLogPrefix << ": null effect"; - } else { - LOG(VERBOSE) << __func__ << mLogPrefix << ": effect Binder" << in_effect->asBinder().get(); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -ndk::ScopedAStatus StreamOutPrimary::removeEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) { - if (in_effect == nullptr) { - LOG(VERBOSE) << __func__ << mLogPrefix << ": null effect"; - } else { - LOG(VERBOSE) << __func__ << mLogPrefix << ": effect Binder" << in_effect->asBinder().get(); - } - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); -} - -// end of StreamCommonInterface Methods - -size_t StreamOutPrimary::getPlatformDelay() const noexcept { - return 0; -} - -::android::status_t StreamOutPrimary::onWriteError(const size_t sleepFrameCount) { - shutdown_I(); - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - // return error for offload, so that FW sends data again - LOG(ERROR) << __func__ << mLogPrefix << ": cannot afford write failure"; - return ::android::DEAD_OBJECT; - } -#ifdef SEC_AUDIO_SUPPORT_UHQ - auto sampleRate = getSampleRate(); -#else - auto& sampleRate = mMixPortConfig.sampleRate.value().value; -#endif - if (sampleRate == 0) { - LOG(ERROR) << __func__ << mLogPrefix << ": cannot afford write failure, sampleRate is zero"; - return ::android::UNEXPECTED_NULL; - } - std::this_thread::sleep_for(std::chrono::milliseconds((sleepFrameCount * 1000) / sampleRate)); - LOG(WARNING) << __func__ << mLogPrefix << ": ignoring this write"; - return ::android::OK; -} - -void StreamOutPrimary::configure() { - - if(hasOutputMMapFlag(mMixPortConfig.flags.value())){ - // this API doesn't handle for MMAP - return; - } - - const auto startTime = std::chrono::steady_clock::now(); - std::unique_ptr palNonHapticChannelInfo; - std::unique_ptr palHapticChannelInfo; - AudioChannelLayout channelLayout; - AudioChannelLayout hapticChannelLayout; -#ifdef SEC_AUDIO_SUPPORT_UHQ - auto attr = mPlatform.getPalStreamAttributes(mMixPortConfig, false, mUhqConfig); -#else - auto attr = mPlatform.getPalStreamAttributes(mMixPortConfig, false); -#endif - - if (!attr) { - LOG(ERROR) << __func__ << mLogPrefix << " no pal attributes found"; - return; - } - -#ifdef SEC_AUDIO_CALL_VOIP - if (mTag == Usecase::VOIP_PLAYBACK) { - auto streamIn = SecModulePrimary::GetStreamIn(Usecase::VOIP_RECORD); - if (streamIn) { - auto attrStreamIn = mPlatform.getPalStreamAttributes(streamIn->getContext().getMixPortConfig(), true); - attr->in_media_config.sample_rate = mVoIPInSamplerate = attrStreamIn->in_media_config.sample_rate; - } else { - attr->in_media_config.sample_rate = mVoIPInSamplerate = FB_SAMPLING_RATE; - if (mPlatform.getVoWiFiState()) { - if (mPlatform.getSecCallBand() == SWB) - attr->in_media_config.sample_rate = mVoIPInSamplerate = SWB_SAMPLING_RATE; - if (mPlatform.getSecCallBand() == WB) - attr->in_media_config.sample_rate = mVoIPInSamplerate = WB_SAMPLING_RATE; - if (mPlatform.getSecCallBand() == NB) - attr->in_media_config.sample_rate = mVoIPInSamplerate = NB_SAMPLING_RATE; - } - } - } -#endif - -#ifdef SEC_AUDIO_COMMON - if ((mSecFTM.getIncallmusicLoopbackType() != SecFTM::INCALLMUSIC_LOOPBACK_OFF) -#ifdef SEC_AUDIO_CALL_FORWARDING - || (mPlatform.isCallForwarding() && !mPlatform.getEnforcePlaybackState()) -#endif - ) { - attr->type = PAL_STREAM_VOICE_CALL_MUSIC; - } else -#endif -#ifdef SEC_AUDIO_SUPPORT_MEDIA_OUTPUT - if (mTag == Usecase::PRIMARY_PLAYBACK) { - attr->type = PAL_STREAM_GENERIC; - } else if (mTag == Usecase::DEEP_BUFFER_PLAYBACK) { - attr->type = PAL_STREAM_DEEP_BUFFER; - } else -#else // qc orig. - if (mTag == Usecase::DEEP_BUFFER_PLAYBACK || mTag == Usecase::PRIMARY_PLAYBACK) { - attr->type = PAL_STREAM_DEEP_BUFFER; - } else -#endif - if (mTag == Usecase::LOW_LATENCY_PLAYBACK) { - attr->type = PAL_STREAM_LOW_LATENCY; - - auto countProxyDevices = std::count_if(mConnectedDevices.cbegin(), mConnectedDevices.cend(), - isIPDevice); - if (countProxyDevices > 0) { - attr->type = PAL_STREAM_PROXY; - attr->info.opt_stream_info.rx_proxy_type = PAL_STREAM_PROXY_RX_WFD; - LOG(INFO) << __func__ << mLogPrefix << ": proxy playback on IPV4"; - } -#ifdef SEC_AUDIO_SUPPORT_LOWLATENCY_MEDIA - if (hasOutputFastMediaFlag(mMixPortConfig.flags.value())) { - attr->info.lowlatency_media.mode = true; - } else { - attr->info.lowlatency_media.mode = false; - } -#endif - } else if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - attr->type = PAL_STREAM_COMPRESSED; - } else if (mTag == Usecase::PCM_OFFLOAD_PLAYBACK) { - attr->type = PAL_STREAM_PCM_OFFLOAD; - } else if (mTag == Usecase::VOIP_PLAYBACK) { - attr->type = PAL_STREAM_VOIP_RX; - } else if (mTag == Usecase::SPATIAL_PLAYBACK) { - attr->type = PAL_STREAM_SPATIAL_AUDIO; - } else if (mTag == Usecase::ULL_PLAYBACK) { - attr->type = PAL_STREAM_ULTRA_LOW_LATENCY; - } else if (mTag == Usecase::IN_CALL_MUSIC) { - attr->type = PAL_STREAM_VOICE_CALL_MUSIC; - attr->info.incall_music_info.local_playback = mPlatform.getInCallMusicState(); - } else if (mTag == Usecase::HAPTICS_PLAYBACK) { -#ifdef SEC_AUDIO_SUPPORT_HAPTIC_PLAYBACK // Set the same as Generic - attr->type = PAL_STREAM_GENERIC; -#else - attr->type = PAL_STREAM_LOW_LATENCY; -#endif - channelLayout = AudioChannelLayout::make - (mMixPortConfig.channelMask.value().get() & ~ (AudioChannelLayout::LAYOUT_HAPTIC_AB)); - LOG(DEBUG) << __func__ << " pal channel info for haptics data stream " - << channelLayout.toString(); - palNonHapticChannelInfo = PlatformConverter::getPalChannelInfoForChannelCount( - getChannelCount(channelLayout)); - - if (palNonHapticChannelInfo == nullptr) { - LOG(ERROR) << __func__ << " failed to find corresponding pal channel info for " - << channelLayout.toString(); - return; - } else { - attr->out_media_config.ch_info = *palNonHapticChannelInfo; - } - } else { - LOG(ERROR) << __func__ << mLogPrefix << " invalid usecase to configure"; - return; - } - - LOG(VERBOSE) << __func__ << mLogPrefix << " assigned pal stream type:" << attr->type; - - auto palDevices = - mPlatform.configureAndFetchPalDevices(mMixPortConfig, mTag, mConnectedDevices); - if (!palDevices.size()) { - LOG(ERROR) << __func__ << mLogPrefix << " no connected devices on stream!!"; - return; - } - - uint64_t cookie = reinterpret_cast(this); - pal_stream_callback palFn = nullptr; - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - auto& compressPlayback = std::get(mExt); - cookie = reinterpret_cast(&compressPlayback); - palFn = CompressPlayback::palCallback; - /* TODO check any dynamic update as per offload metadata or source - * metadata */ - if (mOffloadInfo.value().bitWidth != 0) { - attr->out_media_config.bit_width = mOffloadInfo.value().bitWidth; - } - attr->flags = static_cast(PAL_STREAM_FLAG_NON_BLOCKING); - } - if (mTag == Usecase::ULL_PLAYBACK) { - attr->flags = static_cast(PAL_STREAM_FLAG_MMAP); - } - - const auto palOpenApiStartTime = std::chrono::steady_clock::now(); -#ifdef SEC_AUDIO_COMMON - palDevices = mPlatform.configureSecPalDevicesForPlayback(mMixPortConfig, mTag, mConnectedDevices); - if (mSecFTM.getLoopbackScoOn() - || (mSecFTM.getFactoryMode() & SecFTM::FACTORY_ROUTE_ACTIVE)) { - palDevices = mSecFTM.convertToPalDevices({mSecFTM.getRxFTMDevice()}); - } -#endif - if (int32_t ret = ::pal_stream_open(attr.get(), palDevices.size(), palDevices.data(), 0, - nullptr, palFn, cookie, &(this->mPalHandle)); - ret) { - LOG(ERROR) << __func__ << mLogPrefix << " pal stream open failed!!! ret:" << ret; - mPalHandle = nullptr; - return; - } -#ifdef SEC_AUDIO_COMMON - mPalDevices = palDevices; -#endif -#ifdef SEC_AUDIO_PREVOLUME_SOUNDBOOSTER - if (mPlatform.getFMRadioOn()) { - mAudioEffect.send_soundbooster_on(PARAM_VOLUME_FM, hasSpeakerDevice(mConnectedDevices)); - } else { - sendPrevolumeSoundbooster(); - } -#endif - setHwVolume(mVolumes); - - if (mTag == Usecase::HAPTICS_PLAYBACK) { - - hapticChannelLayout = AudioChannelLayout::make - (mMixPortConfig.channelMask.value().get() & (AudioChannelLayout::LAYOUT_HAPTIC_AB)); - - LOG(DEBUG) << __func__ << mLogPrefix << " pal channel info for haptics stream " - << hapticChannelLayout.toString(); - - palHapticChannelInfo = PlatformConverter::getPalChannelInfoForChannelCount( - getChannelCount(hapticChannelLayout)); - - if (palHapticChannelInfo == nullptr) { - LOG(ERROR) << __func__ << mLogPrefix << " failed to find pal channel info for haptics" - << hapticChannelLayout.toString(); - return ; - } - // set haptics stream attributes - struct pal_stream_attributes hapticsStreamAttributes {}; - hapticsStreamAttributes.type = PAL_STREAM_HAPTICS; - hapticsStreamAttributes.flags = static_cast(0); - hapticsStreamAttributes.direction = PAL_AUDIO_OUTPUT; - hapticsStreamAttributes.out_media_config.sample_rate = Platform::kDefaultOutputSampleRate; - hapticsStreamAttributes.out_media_config.bit_width = Platform::kDefaultPCMBidWidth; - hapticsStreamAttributes.out_media_config.aud_fmt_id = Platform::kDefaultPalPCMFormat; - hapticsStreamAttributes.out_media_config.ch_info = *(palHapticChannelInfo); - hapticsStreamAttributes.info.opt_stream_info.haptics_type = PAL_STREAM_HAPTICS_RINGTONE; - mHapticsChannelCount = hapticsStreamAttributes.out_media_config.ch_info.channels; - - // set haptics device - struct pal_device hapticsDevice {}; - hapticsDevice.id = PAL_DEVICE_OUT_HAPTICS_DEVICE; - hapticsDevice.config.sample_rate = Platform::kDefaultOutputSampleRate; - hapticsDevice.config.bit_width = Platform::kDefaultPCMBidWidth; - hapticsDevice.config.ch_info = hapticsStreamAttributes.out_media_config.ch_info; - hapticsDevice.config.aud_fmt_id = Platform::kDefaultPalPCMFormat; - - if (int32_t ret = ::pal_stream_open(&hapticsStreamAttributes, 1, &hapticsDevice, 0, - nullptr, palFn, cookie, &(this->mHapticsPalHandle))) { - LOG(ERROR) << __func__ << mLogPrefix << " pal_stream_open failed for haptics " << ret; - } - } - - const auto palOpenApiEndTime = std::chrono::steady_clock::now(); - -#ifndef SEC_AUDIO_COMMON - if (karaoke) { - int size = palDevices.size(); - mAudExt.mKarokeExtension->karaoke_open(palDevices[size - 1].id, palFn, - attr.get()->out_media_config.ch_info); - } -#endif - -#ifdef SEC_AUDIO_USB_GAIN_CONTROL - { - auto streamOut = SecModulePrimary::GetStreamOut(Usecase::DEEP_BUFFER_PLAYBACK); - if (mTag == Usecase::PRIMARY_PLAYBACK && - streamOut && streamOut->HasPalStreamHandle() && - mConnectedDevices.size() == 2 && - hasUsbHeadsetDevice(mConnectedDevices)) { - mPlatform.setUSBGainForCombo(true); - streamOut->ForceSetDevices(streamOut->getConnectedDevices()); - } - } -#endif - - auto bufConfig = getBufferConfig(); - if (mTag == Usecase::ULL_PLAYBACK) { - //The buffer size for ULL_PLAYBACK set to PAL should not be more than 2ms - const size_t durationMs = 1; // set to 1ms - size_t frameSizeInBytes = ::aidl::android::hardware::audio::common::getFrameSizeInBytes( - mMixPortConfig.format.value(), mMixPortConfig.channelMask.value()); - bufConfig.bufferSize = durationMs * - (mMixPortConfig.sampleRate.value().value /1000) * frameSizeInBytes; - } - size_t ringBufSizeInBytes = bufConfig.bufferSize; - const size_t ringBufCount = bufConfig.bufferCount; - - if (mTag == Usecase::HAPTICS_PLAYBACK && mHapticsPalHandle) { - size_t hapticsFrameSize = getFrameSizeInBytes(mMixPortConfig.format.value(), channelLayout); - ringBufSizeInBytes = HapticsPlayback::getFrameCount(mMixPortConfig) * hapticsFrameSize; - } - - if (auto converter = Platform::requiresBufferReformat(mMixPortConfig); - converter && !mBufferFormatConverter.has_value()) { - mBufferFormatConverter = std::make_unique( - converter->first, converter->second, ringBufSizeInBytes); - LOG(DEBUG) << __func__ << mLogPrefix << "created format converter from format " - << converter->first << " to format " << converter->second; - } - - auto palBufferConfig = mPlatform.getPalBufferConfig(ringBufSizeInBytes, ringBufCount); - LOG(DEBUG) << __func__ << mLogPrefix << "set pal_stream_set_buffer_size to " - << std::to_string(ringBufSizeInBytes) << " with count " - << std::to_string(ringBufCount); - if (int32_t ret = - ::pal_stream_set_buffer_size(this->mPalHandle, nullptr, palBufferConfig.get()); - ret) { - LOG(ERROR) << __func__ << mLogPrefix << " pal_stream_set_buffer_size failed!!! ret:" << ret; - ::pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return; - } - if (mTag == Usecase::HAPTICS_PLAYBACK && mHapticsPalHandle) { - const size_t hapticsRingBufCount = ringBufCount; - size_t hapticsFrameSize = getFrameSizeInBytes(mMixPortConfig.format.value(), hapticChannelLayout); - const size_t hapticsRingBufSizeInBytes = HapticsPlayback::getFrameCount(mMixPortConfig) * hapticsFrameSize; - - auto hapticsPalBufferConfig = mPlatform.getPalBufferConfig(hapticsRingBufSizeInBytes, hapticsRingBufCount); - if (int32_t ret = - ::pal_stream_set_buffer_size(this->mHapticsPalHandle, nullptr, hapticsPalBufferConfig.get()); - ret) { - LOG(ERROR) << __func__ << mLogPrefix << " pal_stream_set_buffer_size failed!!! ret:" << ret; - ::pal_stream_close(mHapticsPalHandle); - mHapticsPalHandle = nullptr; - return; - } - } - - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - // Must be before pal stream start - std::get(mExt).setAndConfigureCodecInfo(mPalHandle); - } - -#ifdef SEC_AUDIO_PREVOLUME_SOUNDBOOSTER - sendPrevolumeSoundbooster(); -#endif - - const auto palStartApiStartTime = std::chrono::steady_clock::now(); - if (int32_t ret = ::pal_stream_start(this->mPalHandle); ret) { - LOG(ERROR) << __func__ << mLogPrefix << " pal_stream_start failed, ret:" << ret; - ::pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return; - } - - if (mTag == Usecase::HAPTICS_PLAYBACK && mHapticsPalHandle) { - if (int32_t ret = ::pal_stream_start(this->mHapticsPalHandle); ret) { - LOG(ERROR) << __func__ << mLogPrefix << " failed to start haptics stream. ret:" << ret; - ::pal_stream_close(mHapticsPalHandle); - mHapticsPalHandle = nullptr; - return; - } - } - - const auto palStartApiEndTime = std::chrono::steady_clock::now(); - -#ifdef SEC_AUDIO_DSM_AMP - if (pal_active_device_count(PAL_DEVICE_OUT_SPEAKER) == 1) { - LOG(DEBUG) << __func__ << mLogPrefix << ": Open and start feedback stream for speaker"; - mAudExt.mSpeakerFeedbackExtension->start(); - } -#endif -#ifndef SEC_AUDIO_COMMON - if (karaoke) mAudExt.mKarokeExtension->karaoke_start(); -#endif - LOG(VERBOSE) << __func__ << mLogPrefix << " pal_stream_start successful"; - -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - checkAndSwitchListenbackMode(true); -#endif - -#ifdef SEC_AUDIO_COMMON - setHwVolume(mVolumes); -#endif - -#if (SEC_AUDIO_MULTI_SPEAKER == 4) && defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP) - if ((mSecFTM.getFactoryMode() & SecFTM::FACTORY_ROUTE_ACTIVE) && - (mSecFTM.isSpeakerFactoryRxDevice())) { - mAudioEffect.send_factory_soundbooster_mode(mSecFTM.getFactorySoundBoosterMode()); - } -#endif - -#ifdef SEC_AUDIO_HDMI // { SUPPORT_VOIP_VIA_SMART_MONITOR - RerouteForVoipSmartMonitor(); -#endif // } SUPPORT_VOIP_VIA_SMART_MONITOR -#ifdef SEC_AUDIO_CALL_VOIP - if (mTag == Usecase::VOIP_PLAYBACK && - mPlatform.getCallMode() == AUDIO_MODE_IN_COMMUNICATION) { - mAudioEffect.SetVoipMicModeEffect(); - if (mPlatform.getCngEnable()) { - mAudioEffect.SetCNGForEchoRefMute(true); - } -#ifdef SEC_AUDIO_CALL_TRANSLATION - if (mPlatform.getCallTranslation()) { - mAudioEffect.SetVoiceRxEffectForTranslation(true); - } -#endif - } -#endif - - if (mPlaybackRate != sDefaultPlaybackRate) { - LOG(DEBUG) << __func__ << mLogPrefix << ": using playspeed " << mPlaybackRate.speed; - mPlatform.setPlaybackRate(mPalHandle, mTag, mPlaybackRate); - } - - LOG(INFO) << __func__ << mLogPrefix << ": stream is configured"; - enableOffloadEffects(true); - const auto endTime = std::chrono::steady_clock::now(); - using FloatMillis = std::chrono::duration; - const float palStreamOpenTimeTaken = - std::chrono::duration_cast(palOpenApiEndTime - palOpenApiStartTime) - .count(); - const float palStreamStartTimeTaken = - std::chrono::duration_cast(palStartApiEndTime - palStartApiStartTime) - .count(); - const float timeTaken = std::chrono::duration_cast(endTime - startTime).count(); - LOG(INFO) << __func__ << mLogPrefix << ": completed in " << timeTaken - << " ms [pal_stream_open: " << palStreamOpenTimeTaken - << ", ms pal_stream_start: " << palStreamStartTimeTaken << " ms]"; -} - -void StreamOutPrimary::enableOffloadEffects(const bool enable) { - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK || mTag == Usecase::PCM_OFFLOAD_PLAYBACK) { - auto& ioHandle = mMixPortConfig.ext.get().handle; - if (enable) { -#ifdef SEC_AUDIO_OFFLOAD - mAudioEffect.send_soundalive_lrsm_value(); -#endif - mHalEffects.startEffect(ioHandle, mPalHandle); -#ifdef SEC_AUDIO_OFFLOAD_SOUNDSPEED - mAudioEffect.set_soundspeed_value(mPlaybackRate.speed); - mAudioEffect.send_soundspeed_value(); -#endif - LOG(VERBOSE) << __func__ << mLogPrefix; - } else { - mHalEffects.stopEffect(ioHandle); - } - } -#ifdef SEC_AUDIO_VOLUME_MONITOR - else if (mTag == Usecase::DEEP_BUFFER_PLAYBACK || mTag == Usecase::ULL_PLAYBACK) { - if (enable) { - // update volume monitor parameter for DSP - int updateType = 0x100000; - mHalEffects.updateEffect(mPalHandle, updateType); - LOG(VERBOSE) << __func__ << mLogPrefix; - } - } -#endif -} - -ndk::ScopedAStatus StreamOutPrimary::getRecommendedLatencyModes( - std::vector<::aidl::android::media::audio::common::AudioLatencyMode>* _aidl_return) { - - int ret = 0; - - if (!hasBluetoothA2dpDevice(mConnectedDevices)) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - ret = mPlatform.getRecommendedLatencyModes(_aidl_return); - if (ret) ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamOutPrimary::setLatencyMode( - ::aidl::android::media::audio::common::AudioLatencyMode in_mode) { - - LOG(DEBUG) << __func__ << mLogPrefix << ": latency mode " << toString(in_mode); - int ret = 0; - - if (!hasBluetoothA2dpDevice(mConnectedDevices)) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - - ret = mPlatform.setLatencyMode((uint32_t)in_mode); - if (ret) ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - - return ndk::ScopedAStatus::ok(); -} - -void StreamOutPrimary::shutdown_I() { - - if (mTag == Usecase::COMPRESS_OFFLOAD_PLAYBACK) { - std::get(mExt).setAndConfigureCodecInfo(nullptr); - } else if (mTag == Usecase::MMAP_PLAYBACK) { - std::get(mExt).setPalHandle(nullptr); - } - -#ifndef SEC_AUDIO_COMMON - if (karaoke) mAudExt.mKarokeExtension->karaoke_stop(); -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - if (((mTag == Usecase::DEEP_BUFFER_PLAYBACK) || (mTag == Usecase::ULL_PLAYBACK)) - && mAudExt.mKarokeExtension->isKaraokeActive() - && (SecModulePrimary::getListenbackOutputCount() == 1)) { - SecModulePrimary::updateStreamListenbackMode(false); - } -#endif - if (mPalHandle != nullptr) { - enableOffloadEffects(false); - ::pal_stream_stop(mPalHandle); -#ifdef SEC_AUDIO_DSM_AMP - if (pal_active_device_count(PAL_DEVICE_OUT_SPEAKER) == 0) { - LOG(DEBUG) << __func__ << mLogPrefix << ": stop feedback stream for speaker"; - mAudExt.mSpeakerFeedbackExtension->stop(); - } -#endif - ::pal_stream_close(mPalHandle); -#ifdef SEC_AUDIO_DSM_AMP - if (pal_active_device_count(PAL_DEVICE_OUT_SPEAKER) == 0) { - LOG(DEBUG) << __func__ << mLogPrefix << ": close feedback stream for speaker"; - mAudExt.mSpeakerFeedbackExtension->close(); - } -#endif - } - if (mHapticsPalHandle != nullptr) { - ::pal_stream_stop(mHapticsPalHandle); - ::pal_stream_close(mHapticsPalHandle); - if (mHapticsBuffer) { - mHapticsBuffer = nullptr; - } - mHapticsBufSize = 0; - } - - if (hasOutputVoipRxFlag(mMixPortConfig.flags.value()) || - hasOutputDeepBufferFlag(mMixPortConfig.flags.value())) { - if (auto telephony = mContext.getTelephony().lock()) { - telephony->onPlaybackClose(); - } - } - - mIsPaused = false; - mPalHandle = nullptr; - mHapticsPalHandle = nullptr; - LOG(VERBOSE) << __func__ << mLogPrefix; -} - -::android::status_t StreamOutPrimary::burstZero() { - LOG(VERBOSE) << __func__ << mLogPrefix; - if (mTag == Usecase::MMAP_PLAYBACK) { - return startMMAP(); - } - return ::android::OK; -} - -::android::status_t StreamOutPrimary::startMMAP() { - auto& mmap = std::get(mExt); - if (auto ret = mmap.start(); ret) { - LOG(ERROR) << __func__ << mLogPrefix << ": failed"; - return ret; - } - return ::android::OK; -} - -::android::status_t StreamOutPrimary::stopMMAP() { - auto& mmap = std::get(mExt); - if (auto ret = mmap.stop(); ret) { - LOG(ERROR) << __func__ << mLogPrefix << ": failed"; - return ret; - } - return ::android::OK; -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/StreamStub.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/StreamStub.cpp deleted file mode 100755 index 91cd9395..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/StreamStub.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2023 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. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include - -#define LOG_TAG "AHAL_StreamStub_QTI" - -#include -#include - -#include -#include - -using aidl::android::hardware::audio::common::SinkMetadata; -using aidl::android::hardware::audio::common::SourceMetadata; -using aidl::android::media::audio::common::AudioDevice; -using aidl::android::media::audio::common::AudioOffloadInfo; -using aidl::android::media::audio::common::MicrophoneInfo; - -namespace qti::audio::core { - -StreamStub::StreamStub(StreamContext* context, const Metadata& metadata) - : StreamCommonImpl(context, metadata), - mFrameSizeBytes(getContext().getFrameSize()), - mSampleRate(getContext().getSampleRate()), - mIsAsynchronous(!!getContext().getAsyncCallback()), - mIsInput(isInput(metadata)) {} - -::android::status_t StreamStub::init() { - mIsInitialized = true; - usleep(500); - return ::android::OK; -} - -::android::status_t StreamStub::drain( - ::aidl::android::hardware::audio::core::StreamDescriptor::DrainMode) { - if (!mIsInitialized) { - LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver"; - } - usleep(500); - return ::android::OK; -} - -::android::status_t StreamStub::flush() { - if (!mIsInitialized) { - LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver"; - } - usleep(500); - return ::android::OK; -} - -::android::status_t StreamStub::pause() { - if (!mIsInitialized) { - LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver"; - } - usleep(500); - return ::android::OK; -} - -::android::status_t StreamStub::standby() { - if (!mIsInitialized) { - LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver"; - } - usleep(500); - mIsStandby = true; - return ::android::OK; -} - -::android::status_t StreamStub::start() { - if (!mIsInitialized) { - LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver"; - } - usleep(500); - mIsStandby = false; - return ::android::OK; -} - -::android::status_t StreamStub::transfer(void* buffer, size_t frameCount, size_t* actualFrameCount, - int32_t* latencyMs) { - if (!mIsInitialized) { - LOG(FATAL) << __func__ << ": must not happen for an uninitialized driver"; - } - if (mIsStandby) { - LOG(FATAL) << __func__ << ": must not happen while in standby"; - } - static constexpr float kMicrosPerSecond = MICROS_PER_SECOND; - static constexpr float kScaleFactor = .8f; - if (mIsAsynchronous) { - usleep(500); - } else { - const size_t delayUs = static_cast( - std::roundf(kScaleFactor * frameCount * kMicrosPerSecond / mSampleRate)); - usleep(delayUs); - } - if (mIsInput) { - uint8_t* byteBuffer = static_cast(buffer); - for (size_t i = 0; i < frameCount * mFrameSizeBytes; ++i) { - byteBuffer[i] = std::rand() % 255; - } - } - *actualFrameCount = frameCount; - return ::android::OK; -} - -void StreamStub::shutdown() { - mIsInitialized = false; -} - -StreamInStub::StreamInStub(StreamContext&& context, const SinkMetadata& sinkMetadata, - const std::vector& microphones) - : StreamIn(std::move(context), microphones), StreamStub(&(StreamIn::mContext), sinkMetadata) {} - -StreamInStub::~StreamInStub() { - LOG(DEBUG) << __func__ << ": destroy"; -} - -StreamOutStub::StreamOutStub(StreamContext&& context, const SourceMetadata& sourceMetadata, - const std::optional& offloadInfo) - : StreamOut(std::move(context), offloadInfo), - StreamStub(&(StreamOut::mContext), sourceMetadata) {} - -StreamOutStub::~StreamOutStub() { - LOG(DEBUG) << __func__ << ": destroy"; -} -int32_t StreamOutStub::setAggregateSourceMetadata(bool value) { - return 0; -} -int32_t StreamInStub::setAggregateSinkMetadata(bool value) { - return 0; -} - -ndk::ScopedAStatus StreamInStub::reconfigureConnectedDevices() { - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus StreamOutStub::reconfigureConnectedDevices() { - return ndk::ScopedAStatus::ok(); -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/Telephony.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/Telephony.cpp deleted file mode 100755 index 9a176bae..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/Telephony.cpp +++ /dev/null @@ -1,1594 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_Telephony_QTI" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef SEC_AUDIO_FMRADIO -#include -#include -#endif -#ifdef SEC_AUDIO_CALL_VOIP -#include -#endif - -using aidl::android::hardware::audio::common::isValidAudioMode; -using aidl::android::media::audio::common::AudioDevice; -using aidl::android::media::audio::common::AudioDeviceAddress; -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; -using aidl::android::media::audio::common::AudioMode; -using aidl::android::media::audio::common::Boolean; -using aidl::android::media::audio::common::Float; - -namespace qti::audio::core { - -const AudioDevice Telephony::kDefaultRxDevice = - AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER_EARPIECE}; -const AudioDevice Telephony::kDefaultCRSRxDevice = - AudioDevice{.type.type = AudioDeviceType::OUT_SPEAKER}; - -Telephony::Telephony() { - mVoiceSession.session[VSID1_VOICE_SESSION].CallUpdate.mVSID = VSID::VSID_1; - mVoiceSession.session[VSID1_VOICE_SESSION].state.current_ = CallState::IN_ACTIVE; - mVoiceSession.session[VSID1_VOICE_SESSION].state.new_ = CallState::IN_ACTIVE; - mVoiceSession.session[VSID2_VOICE_SESSION].CallUpdate.mVSID = VSID::VSID_2; - mVoiceSession.session[VSID2_VOICE_SESSION].state.current_ = CallState::IN_ACTIVE; - mVoiceSession.session[VSID2_VOICE_SESSION].state.new_ = CallState::IN_ACTIVE; - mTelecomConfig.voiceVolume = Float{TelecomConfig::VOICE_VOLUME_MAX}; - mTelecomConfig.ttyMode = TelecomConfig::TtyMode::OFF; - mTelecomConfig.isHacEnabled = Boolean{false}; - // Todo check on default RX device - mRxDevice = kDefaultRxDevice; - mTxDevice = getMatchingTxDevice(mRxDevice); -#ifdef SEC_AUDIO_CALL - mPlatform.mTelephonyDevices = {kDefaultRxDevice}; -#endif -} - -Telephony::~Telephony() { - stopCall(); -} - -ndk::ScopedAStatus Telephony::getSupportedAudioModes(std::vector* _aidl_return) { - std::scoped_lock lock{mLock}; - - *_aidl_return = mSupportedAudioModes; - LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return); - return ndk::ScopedAStatus::ok(); -} - -void Telephony::VoiceStop() { - for (int i = 0; i < MAX_VOICE_SESSIONS; i++) { - mVoiceSession.session[i].CallUpdate.mCallState = CallState::IN_ACTIVE; - mVoiceSession.session[i].state.new_ = CallState::IN_ACTIVE; -#ifdef SEC_AUDIO_CALL - mPlatform.updateCallState((int)mVoiceSession.session[i].CallUpdate.mCallState); -#endif - } - mIsVoiceStarted = false; - updateCalls(); - - LOG(DEBUG) << __func__ << ": Exit"; -} - -ndk::ScopedAStatus Telephony::switchAudioMode(AudioMode newAudioMode) { - std::scoped_lock lock{mLock}; - - if (std::find(mSupportedAudioModes.begin(), mSupportedAudioModes.end(), newAudioMode) == - mSupportedAudioModes.end()) { - LOG(ERROR) << __func__ << ": illegal mode " << toString(newAudioMode); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - - mPlatform.updateCallMode((int)newAudioMode); - - if (mAudioMode == newAudioMode) { - LOG(VERBOSE) << __func__ << ": no change" << toString(newAudioMode); - return ndk::ScopedAStatus::ok(); - } -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - if ((newAudioMode != AudioMode::NORMAL) && mPlatform.isListenBackEnabled()) { - SecModulePrimary::updateStreamListenbackMode(false); - } -#endif -#ifdef SEC_AUDIO_CALL - if (newAudioMode == AudioMode::IN_CALL) { - mSetUpdates.mVSID = mCurVSID; - mSetUpdates.mCallState = CallState::ACTIVE; -#ifdef SEC_AUDIO_CALL_SATELLITE - if (mPlatform.getSatelliteCall()) { - mSetUpdates.mCallState = CallState::EXTMODEM_ACTIVE; - } -#endif - mLock.unlock(); - reconfigure(mSetUpdates); - mLock.lock(); - LOG(DEBUG) << __func__ << ": new call state is ACTIVE for vsid " << mSetUpdates.mVSID; - -#ifdef SEC_AUDIO_RECOVERY - if (mSecFTM.getFactoryMode() != SecFTM::FACTORY_TEST_INACTIVE) { - LOG(DEBUG) << __func__ << ": initialize factory state before starting call"; - stopCall(); - mSecFTM.initFTMConfig(); - } -#endif -#ifdef SEC_AUDIO_FMRADIO - if (mPlatform.getFMRadioOn()) { - LOG(DEBUG) << __func__ << " FM force stop for call"; - struct str_parms *fmParms = str_parms_create(); - str_parms_add_int(fmParms, kHandleFM.c_str(), - (int)(AUDIO_DEVICE_NONE|AUDIO_DEVICE_OUT_SPEAKER)); - mAudExt.mFmExtension->audio_extn_fm_set_parameters(fmParms); - str_parms_destroy(fmParms); - } -#endif - } -#ifdef SEC_AUDIO_CALL_VOIP - auto streamOut = SecModulePrimary::GetStreamOut(Usecase::VOIP_PLAYBACK); - if (mAudioMode == AudioMode::IN_COMMUNICATION) { - if (streamOut && streamOut->HasPalStreamHandle() && mPlatform.getCngEnable()) - mAudioEffect.SetCNGForEchoRefMute(false); -#ifdef SEC_AUDIO_RECOVERY - if (newAudioMode == AudioMode::NORMAL) { - initSecConfig(); - } -#endif - } - - if (newAudioMode == AudioMode::IN_COMMUNICATION) { - if (streamOut) { - if (streamOut->HasPalStreamHandle()) { - if (mPlatform.getCngEnable()) { - mAudioEffect.SetCNGForEchoRefMute(true); - } - } - /* duo mt call : voicestream > mode 3, hac custom key setting error */ - streamOut->ForceSetDevices(streamOut->getConnectedDevices()); - mAudioEffect.SetVoipMicModeEffect(); - } - } -#endif -#ifdef SEC_AUDIO_DUAL_SPEAKER - else if (newAudioMode == AudioMode::NORMAL) { - mAudioEffect.SetEchoRefMuteStatus(false); - mAudioEffect.SetUpperSpeakerMute(false); - } -#endif -#endif - - if (newAudioMode == AudioMode::NORMAL) { - // safe to stop now - VoiceStop(); - } else if (newAudioMode == AudioMode::RINGTONE && mSetUpdates.mIsCrsCall) { - if (!mIsCRSStarted && !isAnyCallActive()) { - updateCrsDevice(); - startCall(); - if (mRxDevice.type.type != AudioDeviceType::OUT_SPEAKER) { - startCrsLoopback(); - } - mIsCRSStarted = true; - mCRSVSID = mSetUpdates.mVSID; - LOG(DEBUG) << __func__ << " start CRS call"; - } - } - - mAudioMode = newAudioMode; - - LOG(DEBUG) << __func__ << ": switching to AudioMode:" << toString(mAudioMode); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Telephony::setTelecomConfig(const TelecomConfig& in_config, - TelecomConfig* _aidl_return) { - std::unique_lock lock{mLock}; - - if (in_config.voiceVolume.has_value() && - (in_config.voiceVolume.value().value < - static_cast(TelecomConfig::VOICE_VOLUME_MIN) || - in_config.voiceVolume.value().value > - static_cast(TelecomConfig::VOICE_VOLUME_MAX))) { - LOG(ERROR) << __func__ - << ": voice volume value is invalid: " << in_config.voiceVolume.value().value; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - if (in_config.voiceVolume.has_value()) { - mTelecomConfig.voiceVolume = in_config.voiceVolume; - // safe to update when there is volume provided -#ifdef SEC_AUDIO_CALL - if (mTelecomConfig.voiceVolume) { - mPlatform.setVoiceVolume(mTelecomConfig.voiceVolume.value().value); - } -#endif - updateVoiceVolume(); -#ifdef SEC_AUDIO_CALL_SATELLITE - updateExtModemCallVolume(); -#endif - } - if (in_config.ttyMode != TelecomConfig::TtyMode::UNSPECIFIED) { - mTelecomConfig.ttyMode = in_config.ttyMode; - // safe to update when there is ttymode is provided - updateTtyMode(); - } - if (in_config.isHacEnabled.has_value()) { - mTelecomConfig.isHacEnabled = in_config.isHacEnabled; -#ifdef SEC_AUDIO_CALL_HAC - bool newHacIncall = in_config.isHacEnabled.value().value; - if (mPlatform.getHacIncall() != newHacIncall) { - mPlatform.setHacIncall(newHacIncall); - if (mPlatform.getCallMode() == AUDIO_MODE_IN_COMMUNICATION) { - auto streamOut = SecModulePrimary::GetStreamOut(Usecase::VOIP_PLAYBACK); - if (streamOut && streamOut->HasPalStreamHandle()) { - streamOut->ForceSetDevices(streamOut->getConnectedDevices()); - } - } else { - if (isAnyCallActive()) { - mLock.unlock(); - setDevices(mPlatform.getTelephonyDevices(), true); - mLock.lock(); - } - } - } -#else //TEMP_FOR_SETUP_V QC patch in 240802 - mPlatform.setHACEnabled(mTelecomConfig.isHacEnabled.value().value); - /** - * TODO remove this unusual way with streams - * remove the telephony lock before handling the streams. - * unlocking the telephony is necessary because the stream already have telephony instance. - */ - - lock.unlock(); - triggerHACinVoipPlayback(); - lock.lock(); -#endif - } - *_aidl_return = mTelecomConfig; - LOG(DEBUG) << __func__ << ": received " << in_config.toString() << ", returning " - << _aidl_return->toString(); - return ndk::ScopedAStatus::ok(); -} - -void Telephony::setMicMute(const bool muted) { - std::scoped_lock lock{mLock}; -#ifdef SEC_AUDIO_CALL_SATELLITE - updateExtModemMicMute(); -#endif - if (mPalHandle == nullptr) { - return; - } - -#ifdef SEC_AUDIO_CALL_FORWARDING - if (!muted && - (mPlatform.getMicMuteStatus() || - (mPlatform.isCallForwarding() || mPlatform.getCallMemo() == CALLMEMO_REC))) { - LOG(DEBUG) << __func__ << " skip voice tx unmute on " - << (mPlatform.getMicMuteStatus()? "tx mute":"force mute"); - return; - } -#endif -#ifdef SEC_AUDIO_CALL - mPlatform.setVoiceMuteState(PAL_TX, muted); -#endif - - if (!mPlatform.setStreamMicMute(mPalHandle, muted)) { - LOG(ERROR) << __func__ << ": failed"; - } -} - -bool Telephony::isCrsCallSupported() { - std::scoped_lock lock{mLock}; - return true; -} - -bool Telephony::isAnyCallActive() { - for (int i = 0; i < MAX_VOICE_SESSIONS; i++) { - if (mVoiceSession.session[i].state.current_ == CallState::ACTIVE) { - return true; - } - } - return false; -} - -void Telephony::resetDevices(const bool resetRx) { - std::scoped_lock lock{mLock}; - LOG(VERBOSE) <<__func__<<": ignore reset device "; -} - -#ifdef SEC_AUDIO_LOOPBACK_TEST -void Telephony::updateLoopback(const std::vector& devices, bool loopbackon) { - std::scoped_lock lock{mLock}; - LOG(DEBUG) << __func__ << " Enter"; - - if (loopbackon) { - stopCall(); - int type = mSecFTM.getLoopbackType(); - if (type == SecFTM::LOOPBACK_PACKET - || type == SecFTM::LOOPBACK_PACKET_NODELAY) { - pal_param_loopback_t pal_param_loopback; - if (type == SecFTM::LOOPBACK_PACKET) { - pal_param_loopback.loopback_mode = PAL_LOOPBACK_PACKET_DELAY_MODE; - } else { - pal_param_loopback.loopback_mode = PAL_LOOPBACK_PACKET_NO_DELAY_MODE; - } - pal_set_param(PAL_PARAM_ID_LOOPBACK_MODE, - (void*)&pal_param_loopback, sizeof(pal_param_loopback_t)); - } - updateDevices(); - startCall(); - } else { - stopCall(); - } - - LOG(DEBUG) << __func__ << " Exit"; -} -#endif - -void Telephony::setDevices(const std::vector& devices, const bool updateRx) { - std::scoped_lock lock{mLock}; - - if (devices.size() != 1) { - LOG(ERROR) << __func__ << " invalid size / combo devices unsupported: " << devices; - return; - } - - LOG(DEBUG) << __func__ << (updateRx ? " Rx " : " Tx") << " devices : " << devices; - if (updateRx) { - mRxDevice = devices[0]; // expected to have 1 device. - mTxDevice = getMatchingTxDevice(mRxDevice); - updateDevices(); -#ifdef SEC_AUDIO_CALL - mPlatform.setTelephonyDevices({mRxDevice}); - if (!mSecFTM.getLoopbackMode()) { - configureMicMode(); - } -#endif -#ifdef SEC_AUDIO_CALL_TRANSLATION - if (mPlatform.getCallTranslation()) { - mAudioEffect.ControlTxVolumeDown(); - mAudioEffect.SetVoiceRxEffectForTranslation(true); - } -#endif - } else { - // mTxDevice = devices; - // /* update the voice call devices only on TX devices update. Because Rx - // * devices patch is followed by Tx Devices patch */ - // updateDevices(); - } -} - -void Telephony::updateVoiceMetadataForBT(bool call_active) { - ssize_t track_count = 1; - std::vector sourceTracks; - std::vector sinkTracks; - sourceTracks.resize(track_count); - sinkTracks.resize(track_count); - int32_t ret = 0; - - source_metadata_t btSourceMetadata; - sink_metadata_t btSinkMetadata; - - if (call_active) { - btSourceMetadata.track_count = track_count; - btSourceMetadata.tracks = sourceTracks.data(); - - btSourceMetadata.tracks->usage = AUDIO_USAGE_VOICE_COMMUNICATION; - btSourceMetadata.tracks->content_type = AUDIO_CONTENT_TYPE_SPEECH; - - LOG(DEBUG) << __func__ - << "Source metadata for voice call usage: " << btSourceMetadata.tracks->usage - << "content_type: " << btSourceMetadata.tracks->content_type; - // Pass the source metadata to PAL - pal_set_param(PAL_PARAM_ID_SET_SOURCE_METADATA, (void*)&btSourceMetadata, 0); - - btSinkMetadata.track_count = track_count; - btSinkMetadata.tracks = sinkTracks.data(); - - btSinkMetadata.tracks->source = AUDIO_SOURCE_VOICE_CALL; - - LOG(DEBUG) << __func__ - << "Sink metadata for voice call source: " << btSinkMetadata.tracks->source; - // Pass the sink metadata to PAL - pal_set_param(PAL_PARAM_ID_SET_SINK_METADATA, (void*)&btSinkMetadata, 0); - } else { - /* When voice call ends, we need to restore metadata configuration for - * source and sink sessions same as prior to the call. Send source - * and sink metadata separately to BT. - */ - if (mStreamOutPrimary.lock()) { - StreamOutPrimary::sourceMetadata_mutex_.lock(); - ret = mStreamOutPrimary.lock()->setAggregateSourceMetadata(false); - if (ret != 0) { - LOG(ERROR) << __func__ << " Set PAL_PARAM_ID_SET_SOURCE_METADATA for" << ret - << " failed"; - } - StreamOutPrimary::sourceMetadata_mutex_.unlock(); - } - - if (mStreamInPrimary.lock()) { - StreamInPrimary::sinkMetadata_mutex_.lock(); - ret = mStreamInPrimary.lock()->setAggregateSinkMetadata(false); - if (ret != 0) { - LOG(ERROR) << __func__ << " Set PAL_PARAM_ID_SET_SINK_METADATA for" << ret - << " failed"; - } - StreamInPrimary::sinkMetadata_mutex_.unlock(); - } - } -} - -void Telephony::onExternalDeviceConnectionChanged(const AudioDevice& extDevice, - const bool& connect) { - std::scoped_lock lock{mLock}; - // Placeholder for telephony to act upon external device connection - if (isBluetoothSCODevice(extDevice) || isBluetoothA2dpDevice(extDevice)) { - LOG(VERBOSE) << __func__ << ": sco/a2dp no change"; - return; - } - if (isAnyCallActive() || mAudioMode == AudioMode::IN_CALL) { - LOG(VERBOSE) << __func__ << ": voice call exist"; - return; - } - if (connect) { - if (isOutputDevice(extDevice)) { - mRxDevice = extDevice; - mTxDevice = getMatchingTxDevice(mRxDevice); - updateDevices(); - } else { - if (mTxDevice.type.type != extDevice.type.type) { - mTxDevice = getMatchingTxDevice(mRxDevice); - updateDevices(); - } - } - } else { - if (isOutputDevice(extDevice)) { - mRxDevice = kDefaultRxDevice; - mTxDevice = getMatchingTxDevice(mRxDevice); - updateDevices(); - } - } -} - -void Telephony::onOutputPrimaryStreamDevices(const std::vector& primaryStreamDevices) { - std::scoped_lock lock{mLock}; - - /** - * CRS ringtone routing piggybacks on output primary stream devices - **/ -#ifdef SEC_AUDIO_CALL - if (!mIsCRSStarted && !mIsVoiceStarted) { - return; - } -#else - if (!mIsCRSStarted) { - return; - } -#endif - if (primaryStreamDevices.size() == 1) {// combo devices unsupported. - mRxDevice = primaryStreamDevices[0]; // expected to have 1 device. - mTxDevice = getMatchingTxDevice(mRxDevice); - updateDevices(); -#ifdef SEC_AUDIO_CALL - mPlatform.setTelephonyDevices({mRxDevice}); - if (!mSecFTM.getLoopbackMode()) { - configureMicMode(); - } -#endif -#ifdef SEC_AUDIO_CALL_TRANSLATION - if (mPlatform.getCallTranslation()) { - mAudioEffect.ControlTxVolumeDown(); - mAudioEffect.SetVoiceRxEffectForTranslation(true); - } -#endif - } -} - -void Telephony::onBluetoothScoEvent(const bool& enable) { - std::scoped_lock lock{mLock}; - - if (isAnyCallActive() || mAudioMode == AudioMode::IN_CALL) { - LOG(VERBOSE) << __func__ << ": voice call exist"; - return; - } - - if (enable) { - if (mIsCRSStarted) { - mRxDevice = AudioDevice{.type.type = AudioDeviceType::OUT_DEVICE, - .type.connection = AudioDeviceDescription::CONNECTION_BT_SCO}; - mTxDevice = getMatchingTxDevice(mRxDevice); - updateDevices(); - } - } else { - if (isBluetoothSCODevice(mRxDevice) || isBluetoothA2dpDevice(mRxDevice)) { - mRxDevice = kDefaultRxDevice; - mTxDevice = getMatchingTxDevice(mRxDevice); - updateDevices(); - } - } -} - -void Telephony::updateCrsDevice() { - LOG(VERBOSE) << __func__ << ": Enter"; - if (hasValidPlaybackStream) { - return; - } - - if (mRxDevice.type.type == AudioDeviceType::OUT_SPEAKER_EARPIECE) { - mRxDevice = kDefaultCRSRxDevice; - mTxDevice = getMatchingTxDevice(mRxDevice); - LOG(VERBOSE) << __func__ << " force to speaker for CRS call"; - } -} - -AudioDevice Telephony::getMatchingTxDevice(const AudioDevice& rxDevice) { - if (rxDevice.type.type == AudioDeviceType::OUT_SPEAKER_EARPIECE) { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_SPEAKER) { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_BACK}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_HEADSET && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_ANALOG) { - return AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_ANALOG, - .address = rxDevice.address}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_HEADPHONE && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_ANALOG) { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_DEVICE && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_ANALOG) { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else if ((rxDevice.type.type == AudioDeviceType::OUT_DEVICE || - rxDevice.type.type == AudioDeviceType::OUT_HEADSET) && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_BT_SCO) { - return AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_SCO}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_HEADSET && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_BT_LE) { - return AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_LE}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_CARKIT && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_BT_SCO) { - return AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_SCO}; - } else if ((rxDevice.type.type == AudioDeviceType::OUT_DEVICE || - rxDevice.type.type == AudioDeviceType::OUT_HEADSET) && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_USB) { - if (mPlatform.getUSBCapEnable()) { - return AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_USB, - .address = rxDevice.address}; - } else { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } - } else if (rxDevice.type.type == AudioDeviceType::OUT_HEARING_AID) { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else { - LOG(ERROR) << __func__ << ": unable to find matching TX device for " << rxDevice.toString(); - } - return {}; -} - -void Telephony::reconfigure(const SetUpdates& newUpdates) { - std::scoped_lock lock{mLock}; - auto palDevices = mPlatform.convertToPalDevices({mRxDevice, mTxDevice}); - LOG(DEBUG) << __func__ << " : Enter : current setUpdates" << mSetUpdates.toString() << " new setUpdates" - << newUpdates.toString(); - // Todo Implement - mPlatform.updateCallState((int)mSetUpdates.mCallState); - - if (newUpdates.mIsCrsCall) { - mSetUpdates.mIsCrsCall = newUpdates.mIsCrsCall; - mSetUpdates.mVSID = newUpdates.mVSID; - if (!mIsCRSStarted && !isAnyCallActive() && - mAudioMode == AudioMode::RINGTONE) { - updateCrsDevice(); - startCall(); - if (mRxDevice.type.type != AudioDeviceType::OUT_SPEAKER) { - startCrsLoopback(); - } - mIsCRSStarted = true; - mCRSVSID = newUpdates.mVSID; - LOG(DEBUG) << __func__ << ": start CRS call"; - return; - } - } else { - if (mIsCRSStarted && mCRSVSID == newUpdates.mVSID) { - stopCall(); - if (mPalCrsHandle != nullptr) { - stopCrsLoopback(); - } - mSetUpdates.mIsCrsCall = newUpdates.mIsCrsCall; - mIsCRSStarted = false; - LOG(DEBUG) << __func__ << ": stop CRS call"; - } - } - - for (int i = 0; i < MAX_VOICE_SESSIONS; i++) { - if (newUpdates.mVSID == mVoiceSession.session[i].CallUpdate.mVSID) { - mVoiceSession.session[i].state.new_ = newUpdates.mCallState; - mVoiceSession.session[i].CallUpdate = newUpdates; - break; - } - } - if (isAnyCallActive() || - ((mAudioMode == AudioMode::IN_CALL) && mIsVoiceStarted)) { - updateCalls(); - } - - LOG(DEBUG) << __func__ << ": Exit"; -} - -void Telephony::updateCalls() { - auto status = ndk::ScopedAStatus::ok(); - auto palDevices = mPlatform.convertToPalDevices({mRxDevice, mTxDevice}); - for (int i = 0; i < MAX_VOICE_SESSIONS; i++) { - switch (mVoiceSession.session[i].state.new_) { - case CallState::ACTIVE: - switch (mVoiceSession.session[i].state.current_) { - case CallState::IN_ACTIVE: - LOG(DEBUG) << __func__ << " CallState: INACTIVE -> ACTIVE vsid:" << mVoiceSession.session[i].CallUpdate.mVSID; - if ((palDevices[0].id == PAL_DEVICE_OUT_BLUETOOTH_BLE) && - (palDevices[1].id == PAL_DEVICE_IN_BLUETOOTH_BLE)) { - updateVoiceMetadataForBT(true); - } - if (!isAnyCallActive() && !mIsCRSStarted) { - mSetUpdates = mVoiceSession.session[i].CallUpdate; - status = startCall(); - if (!status.isOk()) { - LOG(ERROR) << __func__ << ": start call failed"; - } else { - mIsVoiceStarted = true; - mVoiceSession.session[i].state.current_ = mVoiceSession.session[i].state.new_; - } - } else { - LOG(DEBUG) << __func__ << ": voice already started"; - } - break; - - default: - LOG(INFO) << __func__ << " CallState: ACTIVE cannot be handled in " - << "state " << mVoiceSession.session[i].state.current_ - << " vsid " << mVoiceSession.session[i].CallUpdate.mVSID; - break; - } - break; -#ifdef SEC_AUDIO_CALL_SATELLITE - case CallState::EXTMODEM_ACTIVE: - switch (mVoiceSession.session[i].state.current_) { - case CallState::IN_ACTIVE: - LOG(DEBUG) << __func__ << " CallState: INACTIVE -> EXTMODEM_ACTIVE vsid:" - << mVoiceSession.session[i].CallUpdate.mVSID; - if (!mAudExt.mExtModemCallExtension->isCallActive() && !mIsCRSStarted) { - mSetUpdates = mVoiceSession.session[i].CallUpdate; - mAudExt.mExtModemCallExtension->startCall( - reinterpret_cast(palDevices.data())); - if (mPlatform.getMicMuteStatus()) { - updateExtModemMicMute(); - } - updateExtModemCallVolume(); - mIsVoiceStarted = true; - mVoiceSession.session[i].state.current_ = mVoiceSession.session[i].state.new_; - } else { - LOG(DEBUG) << __func__ << ": extmodem call already started"; - } - break; - - default: - LOG(INFO) << __func__ << " CallState: EXTMODEM_ACTIVE cannot be handled in " - << "state " << mVoiceSession.session[i].state.current_ - << " vsid " << mVoiceSession.session[i].CallUpdate.mVSID; - break; - } - break; -#endif - case CallState::IN_ACTIVE: - switch (mVoiceSession.session[i].state.current_) { - case CallState::ACTIVE: - LOG(DEBUG) << __func__ << " CallState: ACTIVE -> INACTIVE vsid:" << mVoiceSession.session[i].CallUpdate.mVSID; - mSetUpdates = mVoiceSession.session[i].CallUpdate; - status = stopCall(); - if (!status.isOk()) { - LOG(ERROR) << __func__ << ": stop call failed"; - } else { - mVoiceSession.session[i].state.current_ = mVoiceSession.session[i].state.new_; - } - break; -#ifdef SEC_AUDIO_CALL_SATELLITE - case CallState::EXTMODEM_ACTIVE: - LOG(DEBUG) << __func__ << " CallState: EXTMODEM_ACTIVE -> INACTIVE vsid:" - << mVoiceSession.session[i].CallUpdate.mVSID; - mSetUpdates = mVoiceSession.session[i].CallUpdate; - if (mPlatform.getMicMuteStatus()) { - mAudioEffect.setExtModemMicMute( - mAudExt.mExtModemCallExtension->getTxStreamHandle(), false); - } - mAudExt.mExtModemCallExtension->stopCall(); - mVoiceSession.session[i].state.current_ = mVoiceSession.session[i].state.new_; - break; -#endif - default: - LOG(INFO) << __func__ << " CallState: Default cannot be handled in " - << "state " << mVoiceSession.session[i].state.current_ - << " vsid " << mVoiceSession.session[i].CallUpdate.mVSID; - break; - } - break; - default: - break; - } - } -} - -void Telephony::updateVolumeBoost(const bool enable) { - std::scoped_lock lock{mLock}; - mIsVolumeBoostEnabled = enable; - LOG(INFO) << __func__ << ": is enabled: " << mIsVolumeBoostEnabled; - configureVolumeBoost(); -} - -void Telephony::updateSlowTalk(const bool enable) { - std::scoped_lock lock{mLock}; - mIsSlowTalkEnabled = enable; - LOG(INFO) << __func__ << ": is enabled: " << mIsSlowTalkEnabled; - configureSlowTalk(); -} - -void Telephony::updateHDVoice(const bool enable) { - std::scoped_lock lock{mLock}; - mIsHDVoiceEnabled = enable; - LOG(INFO) << __func__ << ": is enabled: " << mIsHDVoiceEnabled; - configureHDVoice(); -} - -void Telephony::updateDeviceMute(const bool isMute, const std::string& muteDirection) { - std::scoped_lock lock{mLock}; - mIsDeviceMuted = isMute; - mMuteDirection = muteDirection; - LOG(INFO) << __func__ << ": is muted: " << mIsDeviceMuted - << ", mute direction: " << mMuteDirection; - configureDeviceMute(); -} - -#ifdef SEC_AUDIO_CALL -void Telephony::updateSecCallState(const int state) { - std::scoped_lock lock{mLock}; - LOG(INFO) << __func__ << ": CallState val: 0x" << std::hex << state; -#ifdef SEC_AUDIO_SUPPORT_PERSONAL_VIDEOCALL - // 1st : check volte status - if (state & CALL_STATUS_VOLTE) { - bool prevState = volte_vt; - mIsVolteVT = (state & CALL_STATUS_VOLTE_VIDEO) ? true : false; - - // volte vt <-> voice/off, rerouting for spk path - if ((mSetUpdates.mCallState == CallState::ACTIVE) - && (prevState != mIsVolteVT) - && (mRxDevice.type.type == AudioDeviceType::OUT_SPEAKER)) { - updateDevices(); - } - } -#endif -} - -void Telephony::updateSecVSID(const int vsid) { - std::scoped_lock lock{mLock}; - Telephony::SetUpdates newUpdates{}; - - if (vsid == SIM_FORCE_UPDATE) { - // For emergency call - if (mSetUpdates.mCallState == CallState::ACTIVE) { - newUpdates.mVSID = (mSetUpdates.mVSID == VSID::VSID_1)? - VSID::VSID_2: VSID::VSID_1; - LOG(DEBUG) << __func__ << ": change vsid to " << newUpdates.mVSID - << " by SIM_FORCE_UPDATE"; - } - } else if (vsid == SIM1_VSID1) { - newUpdates.mVSID = VSID::VSID_1; - } else if (vsid == SIM2_VSID2) { - newUpdates.mVSID = VSID::VSID_2; - } - - if ((mSetUpdates.mCallState == CallState::ACTIVE && mPalHandle != nullptr) - && (mPlatform.getCallMode() == AUDIO_MODE_IN_CALL) - && !(vsid & SIM_FORCE_UPDATE)) { - LOG(ERROR) << __func__ << ": skip to change vsid to " << newUpdates.mVSID - << " during call"; - } else { - if (mSetUpdates.mVSID != newUpdates.mVSID) { - if (mSetUpdates.mCallState == CallState::ACTIVE && mPalHandle != nullptr) { - // SIM_FORCE_UPDATE - mLock.unlock(); - mSetUpdates.mCallState = CallState::IN_ACTIVE; - reconfigure(mSetUpdates); - newUpdates.mCallState = CallState::ACTIVE; - reconfigure(newUpdates); - mLock.lock(); - } - mCurVSID = newUpdates.mVSID; - } - } -} - -void Telephony::updateSecCallBand(const int callBand) { - std::scoped_lock lock{mLock}; - if (callBand == -1) { - LOG(ERROR) << __func__ << ": invalid call band"; - return; - } - mCallBand = callBand; -#ifdef SEC_AUDIO_WB_AMR - mPlatform.updateSecCallBand(mCallBand); -#endif -} -#endif - -void Telephony::configureVolumeBoost() { - if (mPalHandle == nullptr) { - LOG(ERROR) << __func__ << ": invalid pal handle"; - return; - } - auto byteSize = sizeof(pal_param_payload) + sizeof(bool); - auto bytes = std::make_unique(byteSize); - auto palParamPayload = reinterpret_cast(bytes.get()); - palParamPayload->payload_size = sizeof(bool); - palParamPayload->payload[0] = mIsVolumeBoostEnabled; - if (int32_t ret = - ::pal_stream_set_param(mPalHandle, PAL_PARAM_ID_VOLUME_BOOST, palParamPayload); - ret) { - LOG(ERROR) << __func__ << ": failed to set PAL_PARAM_ID_VOLUME_BOOST"; - return; - } -} - -void Telephony::configureSlowTalk() { - if (mPalHandle == nullptr) { - LOG(ERROR) << __func__ << ": invalid pal handle"; - return; - } - auto byteSize = sizeof(pal_param_payload) + sizeof(bool); - auto bytes = std::make_unique(byteSize); - auto palParamPayload = reinterpret_cast(bytes.get()); - palParamPayload->payload_size = sizeof(bool); - palParamPayload->payload[0] = mIsSlowTalkEnabled; - if (int32_t ret = ::pal_stream_set_param(mPalHandle, PAL_PARAM_ID_SLOW_TALK, palParamPayload); - ret) { - LOG(ERROR) << __func__ << ": failed to set PAL_PARAM_ID_SLOW_TALK"; - return; - } -} - -void Telephony::configureHDVoice() { - if (mPalHandle == nullptr) { - LOG(ERROR) << __func__ << ": invalid pal handle"; - return; - } - auto byteSize = sizeof(pal_param_payload) + sizeof(bool); - auto bytes = std::make_unique(byteSize); - auto palParamPayload = reinterpret_cast(bytes.get()); - palParamPayload->payload_size = sizeof(bool); - palParamPayload->payload[0] = mIsHDVoiceEnabled; - if (int32_t ret = ::pal_stream_set_param(mPalHandle, PAL_PARAM_ID_HD_VOICE, palParamPayload); - ret) { - LOG(ERROR) << __func__ << ": failed to set PAL_PARAM_ID_HD_VOICE"; - return; - } -} - -void Telephony::configureDeviceMute() { - if (mPalHandle == nullptr) { - LOG(ERROR) << __func__ << ": invalid pal handle"; - return; - } - -#ifdef SEC_AUDIO_CALL_FORWARDING - if ((mMuteDirection == "rx") && !mIsDeviceMuted - && (mPlatform.getAllSoundMute() || mPlatform.getEnforcePlaybackState() - || (mPlatform.isCallForwarding() || mPlatform.getCallMemo() == CALLMEMO_REC) -#ifdef SEC_AUDIO_CALL_TRANSLATION - || (mPlatform.getVoiceRxControl() == TRANSLATION_MUTE) -#endif - )) { - LOG(DEBUG) << __func__ << " skip voice rx unmute on " - << (mPlatform.getAllSoundMute() ? "rx mute":"force mute"); - return; - } -#endif -#ifdef SEC_AUDIO_CALL - if (mMuteDirection == "rx") { - mPlatform.setVoiceMuteState(PAL_RX, mIsDeviceMuted); - } -#endif - - auto byteSize = sizeof(pal_param_payload) + sizeof(pal_device_mute_t); - auto bytes = std::make_unique(byteSize); - auto palParamPayload = reinterpret_cast(bytes.get()); - palParamPayload->payload_size = sizeof(pal_device_mute_t); - auto palDeviceMute = reinterpret_cast(palParamPayload->payload); - palDeviceMute->mute = mIsDeviceMuted; - if (mMuteDirection == "rx") { - palDeviceMute->dir = PAL_AUDIO_OUTPUT; - } else { - palDeviceMute->dir = PAL_AUDIO_INPUT; - } - if (int32_t ret = ::pal_stream_set_param(mPalHandle, PAL_PARAM_ID_DEVICE_MUTE, palParamPayload); - ret) { - LOG(ERROR) << __func__ << ": failed to set PAL_PARAM_ID_DEVICE_MUTE"; - return; - } -} - -void Telephony::setVoipPlaybackStream(std::weak_ptr voipStream) { - std::scoped_lock lock{mLock}; - mVoipStreamWptr = voipStream; -} - -void Telephony::triggerHACinVoipPlayback() { - auto voipStream = mVoipStreamWptr.lock(); - if (!voipStream) { - return; - } - const auto& voipConnectedDevices = voipStream->getConnectedDevices(); - if (hasOutputSpeakerEarpiece(voipConnectedDevices)) { - LOG(INFO) << __func__ << ": HAC status changed for VOIP playback"; - voipStream->reconfigureConnectedDevices(); - } -} - -void Telephony::onPlaybackStart() { - std::scoped_lock lock{mLock}; - hasValidPlaybackStream = true; - if (mIsCRSStarted) { - LOG(INFO) << __func__ << ": playback conc status changed for CRS call"; - updateDevices(); - } -} - -void Telephony::onPlaybackClose() { - std::scoped_lock lock{mLock}; - hasValidPlaybackStream = false; - if (mIsCRSStarted) { - LOG(INFO) << __func__ << ": playback conc status changed for CRS call"; - updateDevices(); - } -} - -#ifdef SEC_AUDIO_CALL -void Telephony::configureMicMode() { - if (mPalHandle == nullptr) { - LOG(ERROR) << __func__ << ": invalid pal handle"; - return; - } - - bool needToSetStandard = false; - auto palDevices = mPlatform.convertToPalDevices({mRxDevice, mTxDevice}); - if (!(palDevices[0].id == PAL_DEVICE_OUT_HANDSET && palDevices[1].id == PAL_DEVICE_IN_HANDSET_MIC) && - !(palDevices[0].id == PAL_DEVICE_OUT_SPEAKER && palDevices[1].id == PAL_DEVICE_IN_SPEAKER_MIC)){ - LOG(INFO) << __func__ << " device that support standard mode"; - needToSetStandard = true; - } - - int mode = mPlatform.getCallIsolationMode(); - if (mPlatform.getCallTranslation()) { - mode = EFFECTS_TRANSLATION; - } else if (mPlatform.getDexPadConnected() || needToSetStandard) { - mode = EFFECTS_MICMODE_STANDARD; - } - - auto byteSize = sizeof(pal_param_payload) + sizeof(bool); - auto bytes = std::make_unique(byteSize); - auto palParamPayload = reinterpret_cast(bytes.get()); - palParamPayload->payload_size = sizeof(int); - palParamPayload->payload[0] = getVoipMicMode.at(mode); - if (int32_t ret = ::pal_stream_set_param(mPalHandle, PAL_PARAM_ID_MIC_MODE, palParamPayload); - ret) { - LOG(ERROR) << __func__ << ": failed to set PAL_PARAM_ID_MIC_MODE"; - return; - } -} -#endif - -#ifdef SEC_AUDIO_CALL_FORWARDING -void Telephony::setCallForwarding(bool enable) { - if (mPalHandle == nullptr) { - LOG(ERROR) << __func__ << ": invalid pal handle"; - return; - } - - auto inCallMusicStreamOut = SecModulePrimary::GetStreamOut(Usecase::IN_CALL_MUSIC); - auto voipStreamOut = SecModulePrimary::GetStreamOut(Usecase::VOIP_PLAYBACK); - - if (inCallMusicStreamOut && inCallMusicStreamOut->HasPalStreamHandle()) { - inCallMusicStreamOut->forceShutdown(); - } - - if (voipStreamOut && voipStreamOut->HasPalStreamHandle()) { - voipStreamOut->forceShutdown(); - } - - updateDeviceMute(enable, std::string("rx")); - setMicMute(enable); -} -#endif - -#ifdef SEC_AUDIO_CALL_SATELLITE -void Telephony::configureExtModemCall() { - if ((mSetUpdates.mCallState == CallState::ACTIVE && mPalHandle != nullptr) - && (mPlatform.getCallMode() == AUDIO_MODE_IN_CALL) - && mPlatform.getSatelliteCall()) { - Telephony::SetUpdates newUpdates{}; - mSetUpdates.mCallState = CallState::IN_ACTIVE; - reconfigure(mSetUpdates); - newUpdates.mCallState = CallState::EXTMODEM_ACTIVE; - newUpdates.mVSID = mCurVSID; - reconfigure(newUpdates); - } -} -#endif - -void Telephony::setCRSVolumeFromIndex(const int index) { - std::scoped_lock lock{mLock}; - if (index <= MAX_CRS_VOL_INDEX && index >= MIN_CRS_VOL_INDEX) - mCRSVolume = index / 10.0; - else { - mCRSVolume = 0.4; - LOG(INFO) << __func__ << ": use defalut CRS volume: " << mCRSVolume; - } - updateVoiceVolume(); -} - -void Telephony::updateVoiceVolume() { - if (mPalHandle == nullptr) { - return; - } - float volumeFloat = 0.0f; - if (mSetUpdates.mIsCrsCall) { - volumeFloat = mCRSVolume; - } else if (mPlatform.getTranslationRxMuteState()) { - volumeFloat = 0.0f; - LOG(INFO) << __func__ << ": set voice volume to mute."; - } else { - volumeFloat = mTelecomConfig.voiceVolume ? mTelecomConfig.voiceVolume.value().value : 1.0; -#ifdef SEC_AUDIO_CALL - if ((mPlatform.getVoiceVolume() != -1.0f) && - (volumeFloat != mPlatform.getVoiceVolume())) { - LOG(DEBUG) << __func__ << " : apply mCallVolume " << mPlatform.getVoiceVolume() - << " instead of volumeFloat " << volumeFloat; - volumeFloat = mPlatform.getVoiceVolume(); - } -#endif - } - -#ifdef SEC_AUDIO_SUPPORT_BT_RVC - if (mAudioEffect.SetScoVolume(volumeFloat) == 0) { - LOG(DEBUG) << __func__ << " : sco volume applied on voice session, skip pal_stream_set_volume()"; - } else -#endif - if (int32_t ret = mPlatform.setVolume(mPalHandle, {volumeFloat}); ret) { - LOG(ERROR) << __func__ << ": pal stream set volume failed !!" << ret; - return; - } - LOG(DEBUG) << __func__ << ": updated voice volume value as " << volumeFloat; -} - -#ifdef SEC_AUDIO_CALL_SATELLITE -void Telephony::updateExtModemCallVolume() { - if (!mAudExt.mExtModemCallExtension->isCallActive()) { - LOG(VERBOSE) << __func__ << " ext modem call is not active"; - return; - } - float volumeFloat = 0.0f; - - volumeFloat = mTelecomConfig.voiceVolume ? mTelecomConfig.voiceVolume.value().value : 1.0; -#ifdef SEC_AUDIO_CALL - if ((mPlatform.getVoiceVolume() != -1.0f) && - (volumeFloat != mPlatform.getVoiceVolume())) { - LOG(DEBUG) << __func__ << " : apply mCallVolume " << mPlatform.getVoiceVolume() - << " instead of volumeFloat " << volumeFloat; - volumeFloat = mPlatform.getVoiceVolume(); - } -#endif - mAudioEffect.setExtModemCallVolume( - mAudExt.mExtModemCallExtension->getRxStreamHandle(), volumeFloat); -} - -void Telephony::updateExtModemMicMute() { - if (!mAudExt.mExtModemCallExtension->isCallActive()) { - LOG(VERBOSE) << __func__ << " ext modem call is not active"; - return; - } - - mAudioEffect.setExtModemMicMute( - mAudExt.mExtModemCallExtension->getTxStreamHandle(), mPlatform.getMicMuteStatus()); -} -#endif - -void Telephony::updateTtyMode() { - if (mPalHandle == nullptr) { - return; - } - // Todo fix this bad size conversion - const size_t ttyModeSizeInBytes = 4; - auto bytes = std::make_unique(sizeof(pal_param_payload) + ttyModeSizeInBytes); - auto paramPtr = reinterpret_cast(bytes.get()); - if (int32_t ret = ::pal_stream_set_param(mPalHandle, PAL_PARAM_ID_TTY_MODE, paramPtr); ret) { - LOG(ERROR) << __func__ << ": failed to set PAL_PARAM_ID_TTY_MODE"; - return; - } - LOG(VERBOSE) << __func__ << ": success"; - return; -} - -ndk::ScopedAStatus Telephony::startCall() { - LOG(DEBUG) << __func__ << ": Enter: " - << " Rx: " << mRxDevice.toString() << " Tx: " << mTxDevice.toString(); - auto attributes = mPlatform.getDefaultTelephonyAttributes(); - - auto palDevices = mPlatform.convertToPalDevices({mRxDevice, mTxDevice}); - - attributes->info.voice_call_info.VSID = static_cast(mSetUpdates.mVSID); - { - const auto ttyMode = mTtyMap.find(mTelecomConfig.ttyMode); - attributes->info.voice_call_info.tty_mode = - ttyMode != mTtyMap.cend() ? ttyMode->second : PAL_TTY_OFF; - } - - const size_t numDevices = 2; - //set custom key for hac mode - if (mTelecomConfig.isHacEnabled.has_value() && mTelecomConfig.isHacEnabled.value().value && - palDevices[0].id == PAL_DEVICE_OUT_HANDSET) { - strlcpy(palDevices[0].custom_config.custom_key, "HAC", - sizeof(palDevices[0].custom_config.custom_key)); - LOG(VERBOSE) << __func__ << "setting custom key as " << palDevices[0].custom_config.custom_key; - } - if (mSetUpdates.mIsCrsCall) { - strlcpy(palDevices[0].custom_config.custom_key, "crsCall", - sizeof(palDevices[0].custom_config.custom_key)); - LOG(VERBOSE) << __func__ << "setting custom key as " << palDevices[0].custom_config.custom_key; - } - -#ifdef SEC_AUDIO_CALL - palDevices = mPlatform.configureSecPalDevicesForTelephony({mRxDevice, mTxDevice}); -#endif -#ifdef SEC_AUDIO_LOOPBACK_TEST - if (mSecFTM.getLoopbackMode()) { - attributes->info.voice_call_info.VSID = static_cast(VSID::VSID_LB_1); - palDevices = mSecFTM.convertToPalDevices( - {mSecFTM.getRxFTMDevice(), mSecFTM.getTxFTMDevice()}); - } -#endif -#ifdef SEC_AUDIO_DUAL_SPEAKER - if (mPlatform.isSpeakerLeftAmpOff() - && (mSecFTM.getFactoryMode() & (SecFTM::FACTORY_LOOPBACK_ACTIVE|SecFTM::FACTORY_ROUTE_ACTIVE))) { - mAudioEffect.SetUpperSpeakerMute(false/*unmute*/, true/*force*/); - } -#endif - - if (int32_t ret = ::pal_stream_open( - attributes.get(), numDevices, reinterpret_cast(palDevices.data()), 0, - nullptr, nullptr, reinterpret_cast(this), &mPalHandle); - ret) { - LOG(ERROR) << __func__ << ": pal stream open failed !!" << ret; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } -#ifdef SEC_AUDIO_CALL - if (!mSecFTM.getLoopbackMode()) { - configureMicMode(); - } -#endif - if (int32_t ret = ::pal_stream_start(mPalHandle); ret) { - LOG(ERROR) << __func__ << ": pal stream start failed !!" << ret; - pal_stream_close(mPalHandle); - mPalHandle = nullptr; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - if (mPlatform.getMicMuteStatus()) { - mPlatform.setStreamMicMute(mPalHandle, true); - } - updateVoiceVolume(); -#ifdef SEC_AUDIO_ENFORCED_AUDIBLE - if (!mPlatform.getAllSoundMute() && mPlatform.getVoiceMuteState(PAL_RX) && !mPlatform.getEnforcePlaybackState()) { - mIsDeviceMuted = false; - mPlatform.setVoiceMuteState(PAL_RX, mIsDeviceMuted); - } -#endif - if (mIsDeviceMuted) { - configureDeviceMute(); - } - if (mSetUpdates.mIsCrsCall) { - mPlatform.setStreamMicMute(mPalHandle, true); - LOG(DEBUG) << __func__ << ": CRS usecase mute TX"; - } - -#ifdef SEC_AUDIO_CALL_TRANSLATION - if (mPlatform.getVoiceRxControl() == TRANSLATION_MUTE) { - mLock.unlock(); - updateDeviceMute(mPlatform.getVoiceRxControl(), std::string("rx")); - mLock.lock(); - } - - if (mPlatform.getCallTranslation()) { - mAudioEffect.ControlTxVolumeDown(); - mAudioEffect.SetVoiceRxEffectForTranslation(true); - } -#endif -#ifdef SEC_AUDIO_DYNAMIC_NREC - // reset dsp aec mixer when entering cp call - mAudioEffect.SetECNS(true); -#endif -#ifdef SEC_AUDIO_CALL - if (mSecFTM.getLoopbackType() == SecFTM::LOOPBACK_OFF) { - mAudioEffect.SetRingbackGain(); - mAudioEffect.SetNBQuality(); -#ifdef SEC_AUDIO_ADAPT_SOUND - mAudioEffect.SetDHAData(NULL, DHA_SET); -#endif - if (mPlatform.getCngEnable()) { - mAudioEffect.SetCNGForEchoRefMute(true); - } - mAudioEffect.SetDeviceInfo(palDevices[0].id); - } -#endif - - LOG(DEBUG) << __func__ << ": Exit : Voice Stream"; - return ndk::ScopedAStatus::ok(); -} - -void Telephony::startCrsLoopback() { - LOG(DEBUG) << __func__ << ": Enter"; - if (hasValidPlaybackStream) { - LOG(VERBOSE) << __func__ << ": block loopback start"; - return; - } - auto attributes = mPlatform.getDefaultCRSTelephonyAttributes(); - std::vector<::aidl::android::media::audio::common::AudioDevice> RxDevices; - RxDevices = {kDefaultCRSRxDevice}; - - auto palDevices = mPlatform.convertToPalDevices({RxDevices}); - palDevices[0].id = PAL_DEVICE_OUT_SPEAKER; - palDevices[0].config.sample_rate = Platform::kDefaultOutputSampleRate; - palDevices[0].config.bit_width = Platform::kDefaultPCMBidWidth; - palDevices[0].config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - attributes->info.voice_call_info.VSID = static_cast(mSetUpdates.mVSID); - if (mSetUpdates.mIsCrsCall) { - strlcpy(palDevices[0].custom_config.custom_key, "crsCall", - sizeof(palDevices[0].custom_config.custom_key)); - LOG(VERBOSE) << __func__ << " setting custom key as ", palDevices[0].custom_config.custom_key; - } else { - strlcpy(palDevices[0].custom_config.custom_key, "", - sizeof(palDevices[0].custom_config.custom_key)); - } - - const size_t numDevices = 1; - if (int32_t ret = ::pal_stream_open( - attributes.get(), numDevices, reinterpret_cast(palDevices.data()), 0, - nullptr, nullptr, reinterpret_cast(this), &mPalCrsHandle); - ret) { - LOG(ERROR) << __func__ << ": pal stream open failed !!" << ret; - return; - } - if (int32_t ret = ::pal_stream_start(mPalCrsHandle); ret) { - LOG(ERROR) << __func__ << ": pal stream open failed !!" << ret; - return; - } - updateVoiceVolume(); - LOG(DEBUG) << __func__ << ": Exit"; -} - -ndk::ScopedAStatus Telephony::stopCall() { - LOG(DEBUG) << __func__ << ": Enter"; - if (mPalHandle == nullptr) { - return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION); - } - int32_t ret = 0; - -#ifdef SEC_AUDIO_ADAPT_SOUND - if (mSecFTM.getLoopbackType() == SecFTM::LOOPBACK_OFF) { - mAudioEffect.SetDHAData(NULL, DHA_RESET); - } -#endif -#ifdef SEC_AUDIO_RECOVERY - initSecConfig(); -#endif -#ifdef SEC_AUDIO_CALL - if (mPlatform.getCngEnable()) { - mAudioEffect.SetCNGForEchoRefMute(false); - } -#endif - - auto palDevices = mPlatform.convertToPalDevices({mRxDevice, mTxDevice}); - if (mSetUpdates.mIsCrsCall) { - strlcpy(palDevices[0].custom_config.custom_key, "", - sizeof(palDevices[0].custom_config.custom_key)); - LOG(VERBOSE) << __func__ << "setting custom key as ", palDevices[0].custom_config.custom_key; - } - if (int32_t ret = pal_stream_stop(mPalHandle); ret) { - LOG(ERROR) << __func__ << ": pal stream stop failed !!" << ret; - } - if (int32_t ret = pal_stream_close(mPalHandle); ret) { - LOG(ERROR) << __func__ << ": pal stream stop failed !!" << ret; - } - if ((palDevices[0].id == PAL_DEVICE_OUT_BLUETOOTH_BLE) && - (palDevices[1].id == PAL_DEVICE_IN_BLUETOOTH_BLE)) { - updateVoiceMetadataForBT(false); - } - mPalHandle = nullptr; - if (mSetUpdates.mIsCrsCall && - mRxDevice.type.type == AudioDeviceType::OUT_SPEAKER) { - mRxDevice = kDefaultRxDevice; - mTxDevice = getMatchingTxDevice(mRxDevice); - } -#ifdef SEC_AUDIO_CALL - mPlatform.setDeviceInfo(VOICE_DEVICE_INVALID); -#endif - if (ret) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - LOG(DEBUG) << __func__ << ": EXIT"; - return ndk::ScopedAStatus::ok(); -} - -void Telephony::stopCrsLoopback() { - LOG(DEBUG) << __func__ << ": Enter"; - if (mPalCrsHandle == nullptr) { - return; - } - std::vector<::aidl::android::media::audio::common::AudioDevice> RxDevices; - RxDevices = {kDefaultCRSRxDevice}; - auto palDevices = mPlatform.convertToPalDevices({RxDevices}); - if (mSetUpdates.mIsCrsCall) { - strlcpy(palDevices[0].custom_config.custom_key, "", - sizeof(palDevices[0].custom_config.custom_key)); - LOG(VERBOSE) << __func__ << "setting custom key as ", palDevices[0].custom_config.custom_key; - } - ::pal_stream_stop(mPalCrsHandle); - ::pal_stream_close(mPalCrsHandle); - mPalCrsHandle = nullptr; - LOG(DEBUG) << __func__ << ": EXIT"; -} - -void Telephony::updateDevices() { - - auto palDevices = mPlatform.convertToPalDevices({mRxDevice, mTxDevice}); - - pal_param_bta2dp_t* param_bt_a2dp_ptr = nullptr; - bool a2dp_capture_suspended = false; - size_t bt_param_size = 0; - bool a2dp_suspended = false; - int ret = 0; - int retry_cnt = 20; - const int retry_period_ms = 100; - bool is_suspend_setparam = false; - LOG(DEBUG) << __func__ << ": Enter"; - - if (!isAnyCallActive()) { -#ifdef SEC_AUDIO_CALL_SATELLITE - if (mSetUpdates.mCallState == CallState::EXTMODEM_ACTIVE) { - LOG(DEBUG) << __func__ << " CallState: EXTMODEM_ACTIVE"; - } else -#endif - if (mAudioMode == AudioMode::IN_CALL && mPalHandle == nullptr) { -#ifndef SEC_AUDIO_COMMON - mIsVoiceStarted = true; -#endif - updateCalls(); -#ifdef SEC_AUDIO_CALL_FORWARDING /* || CscFeature_Audio_SupportAutoAnswer */ - if (!mPlatform.getEnforcePlaybackState()) { - mLock.unlock(); - if (mPlatform.isCallForwarding()) { - // if fwd or call_memo param sent before call setup, enable here - setCallForwarding(true); - } else if (mPlatform.getCallMemo() == CALLMEMO_REC) { - // if call_memo rec param sent before call setup, enable here - setMicMute(true); - updateDeviceMute(true, std::string("rx")); - } - mLock.lock(); - } -#endif - return; - } - } -#ifdef SEC_AUDIO_CALL_SATELLITE - if (!mAudExt.mExtModemCallExtension->isCallActive()) { - if (mAudioMode == AudioMode::IN_CALL - && (mSetUpdates.mCallState == CallState::EXTMODEM_ACTIVE)) { - mIsVoiceStarted = true; - updateCalls(); - return; - } - } -#endif - // TODO configure pal devices with custom key if any - if (mSetUpdates.mCallState == CallState::ACTIVE) { - /*In case of active LEA profile, if voice call accepted by an inactive legacy headset - * over SCO profile. APM is not aware about SCO active profile until BT_SCO=ON - * event triggers from BT. In meantime before BT_SCO=ON, when LEA is suspended via - * setparam call, APM tries to route voice call to BLE device. - * In RouteStream call, if suspended state for LEA is true it keep checks over a - * sleep of 2 secs. This causes timecheck issue in audioservice. Thus check for - * is_suspend_setparam flag to know whether BLE suspended due to the actual setparam - * or reconfig_cb(suspend->resume). - */ - if ((palDevices[0].id == PAL_DEVICE_OUT_BLUETOOTH_BLE) && - (palDevices[1].id == PAL_DEVICE_IN_BLUETOOTH_BLE)) { - updateVoiceMetadataForBT(true); - pal_param_bta2dp_t param_bt_a2dp; - do { - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - param_bt_a2dp_ptr = ¶m_bt_a2dp; - param_bt_a2dp_ptr->dev_id = PAL_DEVICE_OUT_BLUETOOTH_BLE; - - ret = pal_get_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED, (void**)¶m_bt_a2dp_ptr, - &bt_param_size, nullptr); - if (!ret && bt_param_size && param_bt_a2dp_ptr) { - a2dp_suspended = param_bt_a2dp_ptr->a2dp_suspended; - is_suspend_setparam = param_bt_a2dp_ptr->is_suspend_setparam; - } else { - LOG(ERROR) << __func__ << "getparam for PAL_PARAM_ID_BT_A2DP_SUSPENDED failed"; - } - param_bt_a2dp_ptr = ¶m_bt_a2dp; - param_bt_a2dp_ptr->dev_id = PAL_DEVICE_IN_BLUETOOTH_BLE; - bt_param_size = 0; - ret = pal_get_param(PAL_PARAM_ID_BT_A2DP_CAPTURE_SUSPENDED, - (void**)¶m_bt_a2dp_ptr, &bt_param_size, nullptr); - if (!ret && bt_param_size && param_bt_a2dp_ptr) - a2dp_capture_suspended = param_bt_a2dp_ptr->a2dp_capture_suspended; - else - LOG(ERROR) << __func__ << "getparam for BT_A2DP_CAPTURE_SUSPENDED failed"; - param_bt_a2dp_ptr = nullptr; - bt_param_size = 0; - } while (!is_suspend_setparam && (a2dp_suspended || a2dp_capture_suspended) && - retry_cnt-- && !usleep(retry_period_ms * 1000)); - LOG(INFO) << __func__ << "a2dp_suspended status: " << a2dp_suspended - << "and a2dp_capture_suspended status: " << a2dp_capture_suspended; - } - } - - //set or remove custom key for hac mode - if (mTelecomConfig.isHacEnabled.has_value() && mTelecomConfig.isHacEnabled.value().value && - palDevices[0].id == PAL_DEVICE_OUT_HANDSET) { - strlcpy(palDevices[0].custom_config.custom_key, "HAC", - sizeof(palDevices[0].custom_config.custom_key)); - LOG(VERBOSE) << __func__ << "setting custom key as " << palDevices[0].custom_config.custom_key; - } else { - strlcpy(palDevices[0].custom_config.custom_key, "", - sizeof(palDevices[0].custom_config.custom_key)); - } - - if (mSetUpdates.mIsCrsCall) { - if (mPalCrsHandle != nullptr) - stopCrsLoopback(); - updateCrsDevice(); - palDevices = mPlatform.convertToPalDevices({mRxDevice, mTxDevice}); - strlcpy(palDevices[0].custom_config.custom_key, "crsCall", - sizeof(palDevices[0].custom_config.custom_key)); - } -#ifdef SEC_AUDIO_CALL_SATELLITE - if (mAudExt.mExtModemCallExtension->isCallActive()) { - mAudExt.mExtModemCallExtension->setDevice( - reinterpret_cast(palDevices.data())); - updateExtModemCallVolume(); - } -#endif - - if (mPalHandle == nullptr) return; - -#ifdef SEC_AUDIO_SPK_AMP_MUTE - if ((mPlatform.mTelephonyDevices[0].type.type == AudioDeviceType::OUT_SPEAKER) - && (mRxDevice.type.type != AudioDeviceType::OUT_SPEAKER)) { - mPlatform.setSpeakerMute(true); - } -#endif -#ifdef SEC_AUDIO_CALL - palDevices = mPlatform.configureSecPalDevicesForTelephony({mRxDevice, mTxDevice}); -#endif -#ifdef SEC_AUDIO_LOOPBACK_TEST - if (mSecFTM.getLoopbackMode()) { - palDevices = mSecFTM.convertToPalDevices( - {mSecFTM.getRxFTMDevice(), mSecFTM.getTxFTMDevice()}); - } -#endif - -#ifdef SEC_AUDIO_DSM_AMP - if (int32_t ret = (int32_t)mAudExt.mSpeakerFeedbackExtension->setDevice(mPalHandle, 2, - reinterpret_cast(palDevices.data())); - !ret) { - LOG(INFO) << __func__ << ": set devices on stream for SpeakerFeedback"; - } else -#endif - if (int32_t ret = ::pal_stream_set_device(mPalHandle, 2, - reinterpret_cast(palDevices.data())); - ret) { - LOG(ERROR) << __func__ << ": failed to set devices"; - return; - } -#ifdef SEC_AUDIO_CALL - mAudioEffect.SetDeviceInfo(palDevices[0].id); -#endif - if (mSetUpdates.mIsCrsCall) { - if (mRxDevice.type.type != AudioDeviceType::OUT_SPEAKER) { - startCrsLoopback(); - } - } - updateVoiceVolume(); - if (mIsDeviceMuted) { - configureDeviceMute(); - } -#ifdef SEC_AUDIO_SPK_AMP_MUTE - mPlatform.setSpeakerMute(false); -#endif - LOG(DEBUG) << __func__ << ": Exit : Rx: " << mRxDevice.toString() << " Tx: " << mTxDevice.toString(); -} - -#ifdef SEC_AUDIO_RECOVERY -void Telephony::initSecConfig() { -#ifdef SEC_AUDIO_CALL - mPlatform.setRingbacktone(false); -#ifdef SEC_AUDIO_ENFORCED_AUDIBLE - mPlatform.updateEnforcePlaybackState(NOT_MUTE); -#endif -#ifdef SEC_AUDIO_CALL_FORWARDING - mPlatform.setCallMemo(CALLMEMO_OFF); - mPlatform.setCallForwarding(false); -#endif -#endif - LOG(DEBUG) << __func__ << ": initialize sec voice state"; -} -#endif - -std::ostream& operator<<(std::ostream& os, const Telephony::CallState& state) { - switch (state) { - case Telephony::CallState::IN_ACTIVE: - os << "IN_ACTIVE"; - break; - case Telephony::CallState::ACTIVE: - os << "ACTIVE"; - break; - default: - os << "UNKNOWN"; - break; - } - return os; -} - -std::ostream& operator<<(std::ostream& os, const Telephony::VSID& vsid) { - switch (vsid) { - case Telephony::VSID::VSID_1: - os << "VSID_1"; - break; - case Telephony::VSID::VSID_2: - os << "VSID_2"; - break; - default: - os << "UNKNOWN"; - break; - } - return os; -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/Android.mk deleted file mode 100755 index f72b9113..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/Android.mk +++ /dev/null @@ -1,170 +0,0 @@ -LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) -LOCAL_MODULE := libaudiocore.extension -LOCAL_VENDOR_MODULE := true - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/include \ - $(LOCAL_PATH)/../platform/include \ - $(LOCAL_PATH)/../utils/include - -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include - -LOCAL_CFLAGS := -Wall -Wextra -Werror -Wthread-safety - -LOCAL_SRC_FILES := \ - AudioExtension.cpp - -LOCAL_HEADER_LIBRARIES := \ - libaudioclient_headers \ - libmedia_helper_headers \ - libexpectedutils_headers - -LOCAL_SHARED_LIBRARIES := \ - libaudioaidlcommon \ - libbase \ - libbinder_ndk \ - libcutils \ - libfmq \ - liblog \ - libmedia_helper \ - libstagefright_foundation \ - libutils \ - libxml2 \ - android.hardware.common-V2-ndk \ - android.hardware.common.fmq-V1-ndk \ - android.media.audio.common.types-V3-ndk \ - android.hardware.audio.core-V2-ndk \ - qti-audio-types-aidl-V1-ndk \ - libar-pal - -# { SEC_AUDIO_COMMON -SEC_AUDIO_VARS := vendor/samsung/variant/audio/sec_audioreach_vars.mk -include $(SEC_AUDIO_VARS) -# } SEC_AUDIO_COMMON - -include $(BUILD_STATIC_LIBRARY) - -#------------------------------------------- -# Build HFP LIB -#------------------------------------------- -include $(CLEAR_VARS) - -LOCAL_MODULE := libhfp_pal -LOCAL_VENDOR_MODULE := true - -ifeq ($(TARGET_BOARD_AUTO),true) - LOCAL_CFLAGS += -DPLATFORM_AUTO -endif - -LOCAL_SRC_FILES:= Hfp.cpp - -LOCAL_CFLAGS += \ - -Wall \ - -Werror \ - -Wno-unused-function \ - -Wno-unused-variable - -LOCAL_CPPFLAGS += -fexceptions - -LOCAL_SHARED_LIBRARIES := \ - libaudioroute \ - libbase \ - liblog \ - libaudioutils \ - libcutils \ - libdl \ - libexpat \ - liblog \ - libar-pal - -LOCAL_C_INCLUDES := \ - $(TOP)/vendor/qcom/opensource/pal \ - $(TOP)/vendor/qcom/opensource/audio-hal/primary-hal/hal \ - $(TOP)/external/expat/lib \ - $(TOP)/system/media/audio_utils/include \ - $(call include-path-for, audio-route) \ - -LOCAL_HEADER_LIBRARIES += libhardware_headers -LOCAL_HEADER_LIBRARIES += libsystem_headers -include $(BUILD_SHARED_LIBRARY) - -#------------------------------------------- -# Build FM LIB -#------------------------------------------- -include $(CLEAR_VARS) - -LOCAL_MODULE := libfmpal -LOCAL_VENDOR_MODULE := true - -LOCAL_SRC_FILES:= FM.cpp - -LOCAL_CFLAGS += \ - -Wall \ - -Werror \ - -Wno-unused-function \ - -Wno-unused-variable - -LOCAL_SHARED_LIBRARIES := \ - libaudioroute \ - libbase \ - liblog \ - libaudioutils \ - libcutils \ - libdl \ - libexpat \ - liblog \ - libar-pal - -LOCAL_C_INCLUDES := \ - $(TOP)/vendor/qcom/opensource/pal \ - $(TOP)/vendor/qcom/opensource/audio-hal/primary-hal/hal \ - $(TOP)/vendor/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/include \ - $(TOP)/external/expat/lib \ - $(TOP)/system/media/audio_utils/include \ - $(call include-path-for, audio-route) \ - -# { SEC_AUDIO_COMMON -SEC_AUDIO_VARS := vendor/samsung/variant/audio/sec_audioreach_vars.mk -include $(SEC_AUDIO_VARS) -# } SEC_AUDIO_COMMON - -LOCAL_HEADER_LIBRARIES += libhardware_headers -LOCAL_HEADER_LIBRARIES += libsystem_headers -include $(BUILD_SHARED_LIBRARY) - -#------------------------------------------- -# Build BATTERY_LISTENER -#------------------------------------------- -include $(CLEAR_VARS) - -LOCAL_MODULE := libbatterylistener -LOCAL_VENDOR_MODULE := true - -LOCAL_SRC_FILES:= battery_listener.cpp -LOCAL_C_INCLUDES := $(LOCAL_PATH)/include - -LOCAL_CFLAGS := \ - -Wall \ - -Werror \ - -Wno-unused-function \ - -Wno-unused-variable - -LOCAL_SHARED_LIBRARIES := \ - android.hardware.health@1.0 \ - android.hardware.health@2.0 \ - android.hardware.health@2.1 \ - android.hardware.power@1.2 \ - android.hardware.health-V1-ndk \ - libbinder_ndk \ - libaudioutils \ - libbase \ - libcutils \ - libdl \ - libhidlbase \ - liblog \ - libutils \ - -LOCAL_STATIC_LIBRARIES := libhealthhalutils - -include $(BUILD_SHARED_LIBRARY) - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/AudioExtension.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/AudioExtension.cpp deleted file mode 100755 index 29db63fd..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/AudioExtension.cpp +++ /dev/null @@ -1,1269 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_AudioExtension_QTI" - -#include -#include -#include -#include -#include -#include -#include "PalApi.h" -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC -#include -#endif -#ifdef SEC_AUDIO_COMMON -#include "SecPalDefs.h" -#endif - -#define DEFAULT_OUTPUT_SAMPLING_RATE 48000 -#define CODEC_BACKEND_DEFAULT_BIT_WIDTH 16 -#define AFS_PARAMETER_QVA_VERSION "qva.version" - -#define AUDIO_PARAMETER_KEY_CAN_OPEN_PROXY "can_open_proxy" - -#define AFS_QVA_FILE_NAME "/data/vendor/audio/adc_qva_version.txt" - -using ::aidl::android::media::audio::common::AudioDevice; -using ::aidl::android::media::audio::common::AudioDeviceType; -using ::aidl::android::media::audio::common::AudioDeviceDescription; - -namespace qti::audio::core { - -std::mutex AudioExtension::reconfig_wait_mutex_; -bool BatteryListenerExtension::isCharging; -#ifdef SEC_AUDIO_SUPPORT_USB_OFFLOAD -struct pal_usb_device_address AudioExtensionBase::mUsbAddr; -#endif - -AudioExtensionBase::AudioExtensionBase(std::string library, bool enabled) - : mLibraryName(library), mEnabled(enabled) { - LOG(INFO) << __func__ << " opening " << mLibraryName.c_str() << " enabled " << enabled; - if (mEnabled) { - mHandle = dlopen(mLibraryName.c_str(), RTLD_LAZY); - if (mHandle == nullptr) { - const char *error = dlerror(); - LOG(INFO) << __func__ << " Failed to dlopen " << mLibraryName.c_str() << " error " - << error; - } - } -#ifdef SEC_AUDIO_SUPPORT_USB_OFFLOAD - mUsbAddr.card_id = -1; - mUsbAddr.device_num = -1; -#endif -} - -AudioExtensionBase::~AudioExtensionBase() { - cleanUp(); -} - -void AudioExtension::audio_extn_get_parameters(struct str_parms *query, struct str_parms *reply) { - char *kv_pairs = NULL; - char value[32] = {0}; - int ret, val = 0; -} -void AudioExtension::audio_extn_set_parameters(struct str_parms *params) { - mHfpExtension->audio_extn_hfp_set_parameters(params); - mFmExtension->audio_extn_fm_set_parameters(params); - audio_feature_stats_set_parameters(params); -} - -void AudioExtension::audio_feature_stats_set_parameters(struct str_parms *params) { - FILE *fp; - int status = 0; - char value[50] = {0}; - - status = str_parms_get_str(params, AFS_PARAMETER_QVA_VERSION, value, sizeof(value)); - if (status >= 0) { - fp = fopen(AFS_QVA_FILE_NAME, "w"); - if (!fp) { - LOG(ERROR) << __func__ << " File open failed for write"; - } else { - char qva_version[50] = "qva_version="; - strlcat(qva_version, value, sizeof(qva_version)); - LOG(DEBUG) << __func__ << " QVA Version : " << qva_version; - fprintf(fp, "%s", qva_version); - fclose(fp); - } - } -} - -void AudioExtensionBase::cleanUp() { - if (mHandle != nullptr) { - dlclose(mHandle); - } -} - -void BatteryListenerExtension::setChargingMode(bool is_charging) { - int32_t result = 0; - pal_param_charging_state_t charge_state; - - LOG(DEBUG) << __func__ << " enter, is_charging " << is_charging; - isCharging = is_charging; - charge_state.charging_state = is_charging; - - result = pal_set_param(PAL_PARAM_ID_CHARGING_STATE, (void *)&charge_state, - sizeof(pal_param_charging_state_t)); - if (result) LOG(DEBUG) << __func__ << " error while handling charging event result " << result; - - LOG(DEBUG) << __func__ << " exit"; -} - -void on_battery_status_changed(bool charging) { - LOG(DEBUG) << __func__ << " battery status changed to " << charging; - BatteryListenerExtension::setChargingMode(charging); -} - -BatteryListenerExtension::~BatteryListenerExtension() { - battery_properties_listener_deinit(); -} - -void BatteryListenerExtension::battery_properties_listener_deinit() { - if (batt_listener_deinit) batt_listener_deinit(); -} - -bool BatteryListenerExtension::battery_properties_is_charging() { - return (batt_prop_is_charging) ? batt_prop_is_charging() : false; -} - -void BatteryListenerExtension::battery_properties_listener_init() { - if (batt_listener_init) batt_listener_init(on_battery_status_changed); -} - -BatteryListenerExtension::BatteryListenerExtension() - : AudioExtensionBase(kBatteryListenerLibrary, isExtensionEnabled(kBatteryListenerProperty)) { - LOG(INFO) << __func__ << " Enter"; - if (mHandle != nullptr) { - if (!(batt_listener_init = - (batt_listener_init_t)dlsym(mHandle, "battery_properties_listener_init")) || - !(batt_listener_deinit = (batt_listener_deinit_t)dlsym( - mHandle, "battery_properties_listener_deinit")) || - !(batt_prop_is_charging = - (batt_prop_is_charging_t)dlsym(mHandle, "battery_properties_is_charging"))) { - LOG(ERROR) << __func__ << "dlsym failed"; - goto feature_disabled; - } - LOG(INFO) << __func__ << "----- Feature BATTERY_LISTENER is enabled ----"; - battery_properties_listener_init(); - setChargingMode(battery_properties_is_charging()); - return; - } - -feature_disabled: - if (mHandle) { - dlclose(mHandle); - mHandle = NULL; - } - - batt_listener_init = NULL; - batt_listener_deinit = NULL; - batt_prop_is_charging = NULL; - LOG(INFO) << __func__ << "----- Feature BATTERY_LISTENER is disabled ----"; -} - -static int reconfig_cb(tSESSION_TYPE session_type, int state) { - int ret = 0; - pal_param_bta2dp_t param_bt_a2dp; - LOG(DEBUG) << __func__ << " reconfig_cb enter with state " - << reconfigStateName.at(state).c_str() << " for " - << deviceNameLUT.at(SessionTypePalDevMap.at(session_type)).c_str(); - - /* If reconfiguration is in progress state (state = 0), perform a2dp suspend. - * If reconfiguration is in complete state (state = 1), perform a2dp resume. - * Set LC3 channel mode as mono (state = 2). - * Set LC3 channel mode as stereo (state = 3). - */ - if (session_type == LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH) { - if ((tRECONFIG_STATE)state == SESSION_SUSPEND) { - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - param_bt_a2dp.a2dp_suspended = true; - param_bt_a2dp.is_suspend_setparam = false; - param_bt_a2dp.dev_id = PAL_DEVICE_OUT_BLUETOOTH_BLE; - - ret = pal_set_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED, (void *)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } else if ((tRECONFIG_STATE)state == SESSION_RESUME) { - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - param_bt_a2dp.a2dp_suspended = false; - param_bt_a2dp.is_suspend_setparam = false; - param_bt_a2dp.dev_id = PAL_DEVICE_OUT_BLUETOOTH_BLE; - - ret = pal_set_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED, (void *)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } else if ((tRECONFIG_STATE)state == CHANNEL_MONO) { - param_bt_a2dp.is_lc3_mono_mode_on = true; - - ret = pal_set_param(PAL_PARAM_ID_BT_A2DP_LC3_CONFIG, (void *)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } else if ((tRECONFIG_STATE)state == CHANNEL_STEREO) { - param_bt_a2dp.is_lc3_mono_mode_on = false; - - ret = pal_set_param(PAL_PARAM_ID_BT_A2DP_LC3_CONFIG, (void *)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } - } else if (session_type == LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH) { - if ((tRECONFIG_STATE)state == SESSION_SUSPEND) { - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - param_bt_a2dp.a2dp_capture_suspended = true; - param_bt_a2dp.is_suspend_setparam = false; - param_bt_a2dp.dev_id = PAL_DEVICE_IN_BLUETOOTH_BLE; - - ret = pal_set_param(PAL_PARAM_ID_BT_A2DP_CAPTURE_SUSPENDED, (void *)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } else if ((tRECONFIG_STATE)state == SESSION_RESUME) { - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - param_bt_a2dp.a2dp_capture_suspended = false; - param_bt_a2dp.is_suspend_setparam = false; - param_bt_a2dp.dev_id = PAL_DEVICE_IN_BLUETOOTH_BLE; - - ret = pal_set_param(PAL_PARAM_ID_BT_A2DP_CAPTURE_SUSPENDED, (void *)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } - } else if (session_type == A2DP_HARDWARE_OFFLOAD_DATAPATH) { - if ((tRECONFIG_STATE)state == SESSION_SUSPEND) { - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - param_bt_a2dp.a2dp_suspended = true; - param_bt_a2dp.is_suspend_setparam = false; - param_bt_a2dp.dev_id = PAL_DEVICE_OUT_BLUETOOTH_A2DP; - - ret = pal_set_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED, (void *)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } else if ((tRECONFIG_STATE)state == SESSION_RESUME) { - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - param_bt_a2dp.a2dp_suspended = false; - param_bt_a2dp.is_suspend_setparam = false; - param_bt_a2dp.dev_id = PAL_DEVICE_OUT_BLUETOOTH_A2DP; - - ret = pal_set_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED, (void *)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } - } - LOG(DEBUG) << __func__ << " reconfig_cb exit with state " << reconfigStateName.at(state).c_str() - << " for " << deviceNameLUT.at(SessionTypePalDevMap.at(session_type)).c_str(); - return ret; -} - -A2dpExtension::~A2dpExtension() {} -A2dpExtension::A2dpExtension() - : AudioExtensionBase(kBluetoothIpcLibrary, isExtensionEnabled(kBluetoothProperty)) { - LOG(INFO) << __func__ << " Enter"; - if (mHandle != nullptr) { - if (!(a2dp_bt_audio_pre_init = - (a2dp_bt_audio_pre_init_t)dlsym(mHandle, "bt_audio_pre_init"))) { - LOG(ERROR) << __func__ << " dlsym failed"; - goto feature_disabled; - } - - if (mHandle && a2dp_bt_audio_pre_init) { - LOG(VERBOSE) << __func__ << " calling BT module preinit"; - // fwk related check's will be done in the BT layer - a2dp_bt_audio_pre_init(); - } - - if (!(register_reconfig_cb = - (register_reconfig_cb_t)dlsym(mHandle, "register_reconfig_cb"))) { - LOG(ERROR) << __func__ << " dlsym failed for reconfig"; - goto feature_disabled; - } - - if (mHandle && register_reconfig_cb) { - LOG(VERBOSE) << __func__ << " calling BT module register reconfig"; - int (*reconfig_cb_ptr)(tSESSION_TYPE, int) = &reconfig_cb; - register_reconfig_cb(reconfig_cb_ptr); - } - - LOG(VERBOSE) << __func__ << "---- Feature A2DP offload is Enabled ---"; - return; - } - -feature_disabled: - if (mHandle) { - dlclose(mHandle); - mHandle = NULL; - } - - a2dp_bt_audio_pre_init = nullptr; - LOG(VERBOSE) << __func__ << "---- Feature A2DP offload is disabled ---"; -} - -AudioDevice HfpExtension::audio_extn_hfp_get_matching_tx_device(const AudioDevice& rxDevice) { - if (rxDevice.type.type == AudioDeviceType::OUT_SPEAKER_EARPIECE) { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_SPEAKER) { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_BACK}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_HEADSET && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_ANALOG) { - return AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_ANALOG, - .address = rxDevice.address}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_HEADPHONE && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_ANALOG) { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else if ((rxDevice.type.type == AudioDeviceType::OUT_DEVICE || - rxDevice.type.type == AudioDeviceType::OUT_HEADSET) && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_BT_SCO) { - return AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_SCO}; - } else if (rxDevice.type.type == AudioDeviceType::OUT_HEADSET && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_BT_LE) { - return AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_BT_LE}; - } else if ((rxDevice.type.type == AudioDeviceType::OUT_DEVICE || - rxDevice.type.type == AudioDeviceType::OUT_HEADSET) && - rxDevice.type.connection == AudioDeviceDescription::CONNECTION_USB) { - if (mPlatform.getUSBCapEnable()) { - return AudioDevice{.type.type = AudioDeviceType::IN_HEADSET, - .type.connection = AudioDeviceDescription::CONNECTION_USB, - .address = rxDevice.address}; - } else { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } - } else if (rxDevice.type.type == AudioDeviceType::OUT_HEARING_AID) { - return AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE}; - } else { - LOG(ERROR) << __func__ << ": unable to find matching TX device for " << rxDevice.toString(); - } - return {}; -} - -void HfpExtension::audio_extn_hfp_set_device(const std::vector& devices, - const bool updateRx) { - AudioDevice rxDevice; - AudioDevice txDevice; - if (devices.size() != 1) { - LOG(ERROR) << __func__ << " invalid size / combo devices unsupported: " << devices; - return; - } - - LOG(DEBUG) << __func__ << (updateRx ? " Rx " : " Tx") << " devices : " << devices; - if (updateRx) { - rxDevice = devices[0]; - txDevice = audio_extn_hfp_get_matching_tx_device(rxDevice); - if (hfp_set_device) { - auto palDevices = mPlatform.convertToPalDevices({rxDevice, txDevice}); - hfp_set_device(reinterpret_cast(palDevices.data())); - } - } -} - -void HfpExtension::audio_extn_hfp_set_parameters(struct str_parms *params) { - if (hfp_set_parameters) hfp_set_parameters(micMute, params); -} - -int HfpExtension::audio_extn_hfp_set_mic_mute(bool state) { - if (audio_extn_hfp_is_active()) { - micMute = state; - return ((hfp_set_mic_mute) ? hfp_set_mic_mute(state) : -1); - } - return -1; -} - -bool HfpExtension::audio_extn_hfp_is_active() { - return ((hfp_is_active) ? hfp_is_active() : false); -} - -HfpExtension::~HfpExtension() {} -HfpExtension::HfpExtension() : AudioExtensionBase(kHfpLibrary, isExtensionEnabled(kHfpProperty)) { - LOG(INFO) << __func__ << " Enter"; - if (mHandle != nullptr) { - if (!(hfp_init = (hfp_init_t)dlsym(mHandle, "hfp_init")) || - !(hfp_is_active = (hfp_is_active_t)dlsym(mHandle, "hfp_is_active")) || - !(hfp_set_mic_mute = (hfp_set_mic_mute_t)dlsym(mHandle, "hfp_set_mic_mute")) || - !(hfp_set_mic_mute2 = (hfp_set_mic_mute2_t)dlsym(mHandle, "hfp_set_mic_mute2")) || - !(hfp_set_parameters = (hfp_set_parameters_t)dlsym(mHandle, "hfp_set_parameters")) || - !(hfp_set_device = (hfp_set_device_t)dlsym(mHandle, "hfp_set_device"))) { - LOG(ERROR) << __func__ << " dlsym failed"; - goto feature_disabled; - } - LOG(DEBUG) << __func__ << "---- Feature HFP is Enabled ----"; - return; - } - -feature_disabled: - if (mHandle) { - dlclose(mHandle); - mHandle = NULL; - } - - hfp_init = NULL; - hfp_is_active = NULL; - hfp_get_usecase = NULL; - hfp_set_mic_mute = NULL; - hfp_set_mic_mute2 = NULL; - hfp_set_parameters = NULL; -} - -#ifdef SEC_AUDIO_CALL_SATELLITE -bool ExtModemCallExtension::isValidOutDevice(pal_device_id_t id) { - switch (id) { - case PAL_DEVICE_OUT_HANDSET: - case PAL_DEVICE_OUT_SPEAKER: - case PAL_DEVICE_OUT_WIRED_HEADSET: - case PAL_DEVICE_OUT_WIRED_HEADPHONE: - case PAL_DEVICE_OUT_BLUETOOTH_SCO: - case PAL_DEVICE_OUT_USB_DEVICE: - case PAL_DEVICE_OUT_USB_HEADSET: - return true; - default: - return false; - } -} - -bool ExtModemCallExtension::isValidInDevice(pal_device_id_t id) { - switch (id) { - case PAL_DEVICE_IN_HANDSET_MIC: - case PAL_DEVICE_IN_SPEAKER_MIC: - case PAL_DEVICE_IN_WIRED_HEADSET: - case PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET: - case PAL_DEVICE_IN_USB_DEVICE: - case PAL_DEVICE_IN_USB_HEADSET: - return true; - default: - return false; - } -} - -bool ExtModemCallExtension::isUsbDevice(pal_device_id_t id) { - switch (id) { - case PAL_DEVICE_OUT_USB_DEVICE: - case PAL_DEVICE_OUT_USB_HEADSET: - case PAL_DEVICE_IN_USB_DEVICE: - case PAL_DEVICE_IN_USB_HEADSET: - return true; - default: - return false; - } -} - -void ExtModemCallExtension::setCustomKey(pal_device& palDevice, const pal_device_id_t outDeviceId) { - int customKeyId = CUSTOM_KEY_EXT_MODEM; - memset(palDevice.custom_config.custom_key, 0, PAL_MAX_CUSTOM_KEY_SIZE); - - if (isValidInDevice(palDevice.id)) { - if ((palDevice.id == PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET) - && !mPlatform.isBtNrecOn()) { - customKeyId = CUSTOM_KEY_BT_HEADSET_NREC; - } else if (palDevice.id == PAL_DEVICE_IN_HANDSET_MIC) { - if (outDeviceId == PAL_DEVICE_OUT_WIRED_HEADPHONE) { - customKeyId = CUSTOM_KEY_HEADPHONE_MIC; - } else if ((outDeviceId == PAL_DEVICE_OUT_USB_HEADSET) - && !mPlatform.getUSBCapEnable()) { - customKeyId = CUSTOM_KEY_USB_HEADPHONE_MIC; - } - } - } - strcpy(palDevice.custom_config.custom_key, ck_table[customKeyId]); - LOG(INFO) << __func__ << " Setting custom key for call pal_devs : " - << palDevice.custom_config.custom_key; -} - -std::unique_ptr ExtModemCallExtension::getExtModemCallAttributes( - pal_stream_loopback_type_t type) { - auto attributes = std::make_unique(); - struct pal_channel_info channelInfo; - channelInfo.channels = 1; - channelInfo.ch_map[0] = PAL_CHMAP_CHANNEL_FL; - - attributes->type = PAL_STREAM_LOOPBACK; - attributes->info.opt_stream_info.loopback_type = type; - attributes->direction = PAL_AUDIO_INPUT_OUTPUT; - attributes->in_media_config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - attributes->in_media_config.ch_info = channelInfo; - attributes->in_media_config.bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH; - attributes->in_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - attributes->out_media_config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - attributes->out_media_config.bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH; - attributes->out_media_config.ch_info = channelInfo; - attributes->out_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - return std::move(attributes); -} - -void ExtModemCallExtension::configurePalDevices(struct pal_device *palDevices, const pal_device_id_t callRxDeviceId) { - const int num_pal_devs = 2; - struct pal_channel_info channelInfo; - channelInfo.channels = 1; - channelInfo.ch_map[0] = PAL_CHMAP_CHANNEL_FL; - - for (int i = 0; i < num_pal_devs; ++i) { - if ((palDevices[i].id == PAL_DEVICE_OUT_EXT_MODEM || - palDevices[i].id == PAL_DEVICE_IN_EXT_MODEM_MIC)) { - palDevices[i].config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - palDevices[i].config.bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH; - palDevices[i].config.ch_info = channelInfo; - palDevices[i].config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - } else { - // call devices - setCustomKey(palDevices[i], callRxDeviceId); -#ifdef SEC_AUDIO_SUPPORT_USB_OFFLOAD - if (isUsbDevice(palDevices[i].id)) { - // Configure USB Digital Headset parameters - pal_param_device_capability_t *device_cap_query = - (pal_param_device_capability_t *)malloc(sizeof(pal_param_device_capability_t)); - if (!device_cap_query) { - LOG(ERROR) << __func__ << " Failed to allocate mem for device_cap_query"; - return; - } - dynamic_media_config_t dynamic_media_config; - size_t payload_size = 0; - if (isValidOutDevice(palDevices[i].id) && isUsbDevice(palDevices[i].id)) { - device_cap_query->id = PAL_DEVICE_OUT_USB_DEVICE; - device_cap_query->is_playback = true; - } else { - device_cap_query->id = PAL_DEVICE_IN_USB_DEVICE; - device_cap_query->is_playback = false; - } - // get usb details - device_cap_query->addr.card_id = AudioExtensionBase::mUsbAddr.card_id; - device_cap_query->addr.device_num = AudioExtensionBase::mUsbAddr.device_num; - device_cap_query->config = &dynamic_media_config; - pal_get_param(PAL_PARAM_ID_DEVICE_CAPABILITY, (void **)&device_cap_query, &payload_size, - nullptr); - palDevices[i].address.card_id = AudioExtensionBase::mUsbAddr.card_id; - palDevices[i].address.device_num = AudioExtensionBase::mUsbAddr.device_num; - palDevices[i].config.sample_rate = dynamic_media_config.sample_rate[0]; - palDevices[i].config.ch_info = channelInfo; - palDevices[i].config.aud_fmt_id = (pal_audio_fmt_t)dynamic_media_config.format[0]; - free(device_cap_query); - } -#endif - } - - } -} - -int32_t ExtModemCallExtension::startCall(struct pal_device *callDevices) { - int32_t ret = 0; - uint32_t no_of_devices = 2; - struct pal_device devices[2] = {}; - - LOG(DEBUG) << __func__ << ": Enter"; - if (rxStreamHandle || txStreamHandle) { - // external modem call already running; - LOG(DEBUG) << __func__ << " ext modem call already running"; - return 0; - } - - if (!isValidOutDevice(callDevices[0].id)) { - LOG(ERROR) << __func__ << " invalid call device id: " << callDevices[0].id; - return -EINVAL; - } - - /* ExtModemCall Tx -> Call Rx */ - auto stream_attr = getExtModemCallAttributes(PAL_STREAM_LOOPBACK_EXT_MODEM_RX); - devices[0].id = PAL_DEVICE_IN_EXT_MODEM_MIC; - devices[1].id = callDevices[0].id; - configurePalDevices(devices, callDevices[0].id); - - if (ret = ::pal_stream_open(stream_attr.get(), no_of_devices, devices, 0, NULL, NULL, 0, - &rxStreamHandle); - ret) { - LOG(ERROR) << __func__ << " rx stream (ExtModemCall Tx->Call Rx) open failed, rc " << ret; - rxStreamHandle = nullptr; - return ret; - } - - if (ret = ::pal_stream_start(rxStreamHandle); ret) { - LOG(ERROR) << __func__ << " rx stream (ExtModemCall Tx->Call Rx) start failed, rc " << ret; - pal_stream_close(rxStreamHandle); - rxStreamHandle = nullptr; - return ret; - } - - /* Call Tx -> ExtModemCall Rx */ - auto stream_tx_attr = getExtModemCallAttributes(PAL_STREAM_LOOPBACK_EXT_MODEM_TX); - devices[0].id = PAL_DEVICE_OUT_EXT_MODEM; - devices[1].id = callDevices[1].id; - configurePalDevices(devices, callDevices[0].id); - - if (ret = ::pal_stream_open(stream_tx_attr.get(), no_of_devices, devices, 0, NULL, NULL, 0, - &txStreamHandle); - ret) { - LOG(ERROR) << __func__ << " tx stream (Call Tx->ExtModemCall Rx) open failed, rc " << ret; - pal_stream_stop(rxStreamHandle); - pal_stream_close(rxStreamHandle); - rxStreamHandle = nullptr; - return ret; - } - - if (ret = ::pal_stream_start(txStreamHandle); ret) { - LOG(ERROR) << __func__ << " tx stream (Call Tx->ExtModemCall Rx) start failed, rc " << ret; - pal_stream_close(txStreamHandle); - pal_stream_stop(rxStreamHandle); - pal_stream_close(rxStreamHandle); - rxStreamHandle = nullptr; - txStreamHandle = nullptr; - return ret; - } - - isExtModemCallRunning = true; - - LOG(DEBUG) << __func__ << ": Exit"; - return ret; -} - -void ExtModemCallExtension::stopCall() { - LOG(DEBUG) << __func__ << ": Enter"; - isExtModemCallRunning = false; - if (rxStreamHandle) { - pal_stream_stop(rxStreamHandle); - pal_stream_close(rxStreamHandle); - rxStreamHandle = nullptr; - } - if (txStreamHandle) { - pal_stream_stop(txStreamHandle); - pal_stream_close(txStreamHandle); - txStreamHandle = nullptr; - } - - LOG(DEBUG) << __func__ << ": Exit"; -} - -void ExtModemCallExtension::setDevice(struct pal_device *devices) { - int32_t rc = 0; - - if (isExtModemCallRunning && hasValidStreamHandle() && - isValidOutDevice(devices[0].id) && isValidInDevice(devices[1].id)) { - setCustomKey(devices[0], devices[0].id); - rc = pal_stream_set_device(rxStreamHandle, 1, &devices[0]); - if (!rc) { - setCustomKey(devices[1], devices[0].id); - rc = pal_stream_set_device(txStreamHandle, 1, &devices[1]); - } - } - - if (rc) { - LOG(ERROR) << __func__ << ": failed to set devices"; - } - return; -} - -ExtModemCallExtension::~ExtModemCallExtension() {} -ExtModemCallExtension::ExtModemCallExtension() : AudioExtensionBase(kDummyLibrary) { - isExtModemCallRunning = false; - rxStreamHandle = nullptr; - txStreamHandle = nullptr; -} -#endif - -FmExtension::~FmExtension() {} - -bool FmExtension::audio_extn_fm_get_status() { - if (fm_running_status) return fm_running_status; - - return false; -} - -void FmExtension::audio_extn_fm_set_parameters(struct str_parms *params) { -#ifdef SEC_AUDIO_FMRADIO - char value[32] = {0}; - int ret = str_parms_get_str(params, "handle_fm", value, sizeof(value)); - if (ret >= 0) { - str_parms_add_int(params, "usb_card_id", AudioExtensionBase::mUsbAddr.card_id); - str_parms_add_int(params, "usb_device_num", AudioExtensionBase::mUsbAddr.device_num); - } -#endif - if (fm_set_params) fm_set_params(params); -} -FmExtension::FmExtension() : AudioExtensionBase(kFmLibrary) { - LOG(INFO) << __func__ << " Enter"; - if (mHandle != nullptr) { - fm_set_params = (set_parameters_t)dlsym(mHandle, "fm_set_parameters"); - fm_running_status = (fm_running_status_t)dlsym(mHandle, "fm_get_running_status"); - if (!fm_set_params || !fm_running_status) { - LOG(ERROR) << "error " << dlerror(); - dlclose(mHandle); - fm_set_params = NULL; - fm_running_status = NULL; - } - } else { - fm_set_params = NULL; - fm_running_status = NULL; - } -} - -int KarokeExtension::karaoke_open(pal_device_id_t device_out, pal_stream_callback pal_callback, -pal_channel_info ch_info) { -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - if (karaoke_stream_handle != NULL) { - if (int ret = karaoke_stop(); ret) { - LOG(ERROR) << __func__ <<" Failed to stop karaoke stream, ret = " << ret; - return 0; - } else { - if (int ret = karaoke_close(); ret) { - LOG(ERROR) << __func__ << " Failed to close karaoke stream, ret = " << ret; - return 0; - } else { - LOG(DEBUG) << __func__ << " Karaoke stream close success"; - } - } - } -#endif - const int num_pal_devs = 2; - struct pal_device pal_devs[num_pal_devs]; - karaoke_stream_handle = NULL; - pal_device_id_t device_in; - dynamic_media_config_t dynamic_media_config; - size_t payload_size = 0; - - // Configuring Hostless Loopback - if (device_out == PAL_DEVICE_OUT_WIRED_HEADSET) - device_in = PAL_DEVICE_IN_WIRED_HEADSET; -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - else if (device_out == PAL_DEVICE_OUT_WIRED_HEADPHONE) { - device_in = PAL_DEVICE_IN_HANDSET_MIC; - } -#endif - else if (device_out == PAL_DEVICE_OUT_USB_HEADSET) { -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - if (!mPlatform.getUSBCapEnable()) { - device_in = PAL_DEVICE_IN_HANDSET_MIC; - } else -#endif - device_in = PAL_DEVICE_IN_USB_HEADSET; - // get capability from device of USB - } else - return 0; - - sattr.type = PAL_STREAM_LOOPBACK; - sattr.info.opt_stream_info.loopback_type = PAL_STREAM_LOOPBACK_KARAOKE; - sattr.direction = PAL_AUDIO_INPUT_OUTPUT; - sattr.in_media_config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - sattr.in_media_config.bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH; - sattr.in_media_config.ch_info = ch_info; - sattr.in_media_config.aud_fmt_id = PAL_AUDIO_FMT_DEFAULT_PCM; - sattr.out_media_config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - sattr.out_media_config.bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH; - sattr.out_media_config.ch_info = ch_info; - sattr.out_media_config.aud_fmt_id = PAL_AUDIO_FMT_DEFAULT_PCM; - for (int i = 0; i < num_pal_devs; ++i) { - pal_devs[i].id = i ? device_in : device_out; -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - memset(pal_devs[i].custom_config.custom_key, 0, PAL_MAX_CUSTOM_KEY_SIZE); -#endif - if (device_out == PAL_DEVICE_OUT_USB_HEADSET || device_in == PAL_DEVICE_IN_USB_HEADSET) { - // Configure USB Digital Headset parameters - pal_param_device_capability_t *device_cap_query = - (pal_param_device_capability_t *)malloc(sizeof(pal_param_device_capability_t)); - if (!device_cap_query) { - LOG(ERROR) << __func__ << " Failed to allocate mem for device_cap_query"; - return 0; - } - - if (pal_devs[i].id == PAL_DEVICE_OUT_USB_HEADSET) { - device_cap_query->id = PAL_DEVICE_OUT_USB_DEVICE; - device_cap_query->is_playback = true; - } else { - device_cap_query->id = PAL_DEVICE_IN_USB_DEVICE; - device_cap_query->is_playback = false; - } - // TODO: //get usb details -#ifdef SEC_AUDIO_SUPPORT_USB_OFFLOAD - device_cap_query->addr.card_id = AudioExtensionBase::mUsbAddr.card_id; // adevice->usb_card_id_; - device_cap_query->addr.device_num = AudioExtensionBase::mUsbAddr.device_num; // adevice->usb_dev_num_; -#else - device_cap_query->addr.card_id = 0; // adevice->usb_card_id_; - device_cap_query->addr.device_num = 0; // adevice->usb_dev_num_; -#endif - device_cap_query->config = &dynamic_media_config; - pal_get_param(PAL_PARAM_ID_DEVICE_CAPABILITY, (void **)&device_cap_query, &payload_size, - nullptr); -#ifdef SEC_AUDIO_SUPPORT_USB_OFFLOAD - pal_devs[i].address.card_id = AudioExtensionBase::mUsbAddr.card_id; // adevice->usb_card_id_; - pal_devs[i].address.device_num = AudioExtensionBase::mUsbAddr.device_num; // adevice->usb_dev_num_; -#else - pal_devs[i].address.card_id = 0; // adevice->usb_card_id_; - pal_devs[i].address.device_num = 0; // adevice->usb_dev_num_; -#endif - pal_devs[i].config.sample_rate = dynamic_media_config.sample_rate[0]; - pal_devs[i].config.ch_info = ch_info; - pal_devs[i].config.aud_fmt_id = (pal_audio_fmt_t)dynamic_media_config.format[0]; - free(device_cap_query); - } else { - pal_devs[i].config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - pal_devs[i].config.bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH; - pal_devs[i].config.ch_info = ch_info; - pal_devs[i].config.aud_fmt_id = PAL_AUDIO_FMT_DEFAULT_PCM; - } - } -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - //Configure custom config key for karaoke listenback - strcpy(pal_devs[0].custom_config.custom_key, ck_table[CUSTOM_KEY_LISTENBACK]); - LOG(INFO) << __func__ << " Setting custom key for rx pal_devs : " << pal_devs[0].custom_config.custom_key; - - if (isVoiceRecognitionStreamCreated()) { - strcpy(pal_devs[1].custom_config.custom_key, ck_table[CUSTOM_KEY_VR]); - LOG(INFO) << __func__ << " Setting custom key for tx pal_devs : " << pal_devs[1].custom_config.custom_key; - } -#endif - return pal_stream_open(&sattr, num_pal_devs, pal_devs, 0, NULL, pal_callback, (uint64_t)this, - &karaoke_stream_handle); -} - -int KarokeExtension::karaoke_start() { - return pal_stream_start(karaoke_stream_handle); -} - -int KarokeExtension::karaoke_stop() { - return pal_stream_stop(karaoke_stream_handle); -} - -int KarokeExtension::karaoke_close() { -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - int ret = pal_stream_close(karaoke_stream_handle); - karaoke_stream_handle = NULL; - return ret; -#else - return pal_stream_close(karaoke_stream_handle); -#endif -} - -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK -bool KarokeExtension::isKaraokeActive() { - if (karaoke_stream_handle != NULL) - return true; - - return false; -} - -void KarokeExtension::init() { - karaoke_stream_handle = NULL; -} -#endif - -KarokeExtension::~KarokeExtension() {} -KarokeExtension::KarokeExtension() : AudioExtensionBase(kKarokeLibrary) { - LOG(INFO) << __func__ << " Enter"; - if (mHandle != nullptr) { - } -} - -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC -const std::unordered_set validAasDevices = { - PAL_DEVICE_OUT_WIRED_HEADSET, - PAL_DEVICE_OUT_WIRED_HEADPHONE, - PAL_DEVICE_OUT_BLUETOOTH_SCO, - PAL_DEVICE_OUT_USB_HEADSET -}; - -bool AasExtension::isAasDeviceAvailable(const pal_device_id_t deviceId) { - return (validAasDevices.find(deviceId) != validAasDevices.end()); -} - -bool AasExtension::isValidStatusForAas(const pal_device_id_t outDeviceId) { - if (mPlatform.getCallMode() == AUDIO_MODE_IN_CALL) { - /* on - support only Normal Mode. off - working all audio mode */ - LOG(ERROR) << __func__ << ": Not support AAS during call mode"; - return false; - } - if (!isAasDeviceAvailable(outDeviceId) - || (!mPlatform.isBtScoOn() && (outDeviceId == PAL_DEVICE_OUT_BLUETOOTH_SCO))) { - LOG(ERROR) << __func__ << ": Invalid device state " << outDeviceId; - return false; - } - return true; -} - -void AasExtension::setAasCustomKey(pal_device& palDevice, const pal_device_id_t outDeviceId) { - int customKeyId = CUSTOM_KEY_INVALID; - if (palDevice.id == outDeviceId) { - customKeyId = CUSTOM_KEY_AAS; - } else { - // In device refers to out device ID for custom key. - switch (outDeviceId) { - case PAL_DEVICE_OUT_WIRED_HEADSET: - case PAL_DEVICE_OUT_WIRED_HEADPHONE: - customKeyId = CUSTOM_KEY_AAS_HEADSET; - break; - case PAL_DEVICE_OUT_BLUETOOTH_SCO: - customKeyId = CUSTOM_KEY_AAS_BT_HEADSET; - break; - case PAL_DEVICE_OUT_USB_HEADSET: - customKeyId = CUSTOM_KEY_AAS_USB_HEADSET; - break; - default: - break; - } - } - if (customKeyId != CUSTOM_KEY_INVALID) { - strcpy(palDevice.custom_config.custom_key, ck_table[customKeyId]); - LOG(INFO) << __func__ << " Setting custom key for " - << ((palDevice.id == outDeviceId) ? "out" : "in") - << " pal_devs : " << palDevice.custom_config.custom_key; - } -} - -int AasExtension::updateAasStream(const bool enable, const pal_device_id_t outDeviceId) { - int ret = 0; - LOG(DEBUG) << __func__ << " Enter : enable " << enable; - - if (enable) { - if (!isValidStatusForAas(outDeviceId)) { - return stopAasStream(); - } - ret = startAasStream(outDeviceId); - if (ret) { - LOG(ERROR) << __func__ << ": Failed to start AAS stream ret = " << ret; - stopAasStream(); - } else { - LOG(DEBUG) << __func__ << ": Start AAS stream success"; - } - } else { - // Disable - ret = stopAasStream(); - } - LOG(DEBUG) << __func__ << " Exit: ret " << ret; - return ret; -} - -int AasExtension::startAasStream(const pal_device_id_t outDeviceId) -{ - const int num_pal_devs = 2; - struct pal_device pal_devs[num_pal_devs]; - pal_device_id_t inDeviceId; - struct pal_stream_attributes aasStreamAttributes; - pal_channel_info ch_info = {0, {0}}; - int ret = 0; - - if (isAasActive()) { - if (outDeviceId != mAasOutDeviceId) { - LOG(DEBUG) << __func__ - << ": Re-open AAS stream due to device change from " - << mAasOutDeviceId << " to " << outDeviceId; - stopAasStream(); // close the existing stream - } else { - LOG(DEBUG) << __func__ - << ": skip to setAASMode enable for same device id " << outDeviceId; - return ret; - } - } - // Configuring Hostless Loopback - if (isAasDeviceAvailable(outDeviceId)) { - inDeviceId = PAL_DEVICE_IN_SPEAKER_MIC; - } else { - LOG(ERROR) << __func__ << ": Invalid device " << outDeviceId; - return -EINVAL; - } - - ch_info.channels = 2; - ch_info.ch_map[0] = PAL_CHMAP_CHANNEL_FL; - ch_info.ch_map[1] = PAL_CHMAP_CHANNEL_FR; - - memset(&aasStreamAttributes, 0, sizeof(aasStreamAttributes)); - aasStreamAttributes.type = PAL_STREAM_LOOPBACK; - aasStreamAttributes.info.opt_stream_info.loopback_type = PAL_STREAM_LOOPBACK_KARAOKE; - aasStreamAttributes.direction = PAL_AUDIO_INPUT_OUTPUT; - aasStreamAttributes.in_media_config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - aasStreamAttributes.in_media_config.bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH; - aasStreamAttributes.in_media_config.ch_info = ch_info; - aasStreamAttributes.in_media_config.aud_fmt_id = PAL_AUDIO_FMT_DEFAULT_PCM; - aasStreamAttributes.out_media_config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - aasStreamAttributes.out_media_config.bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH; - aasStreamAttributes.out_media_config.ch_info = ch_info; - aasStreamAttributes.out_media_config.aud_fmt_id = PAL_AUDIO_FMT_DEFAULT_PCM; - - for (int i = 0; i < num_pal_devs; ++i) { - pal_devs[i].id = i ? inDeviceId : outDeviceId; - memset(pal_devs[i].custom_config.custom_key, 0, PAL_MAX_CUSTOM_KEY_SIZE); - if (outDeviceId == PAL_DEVICE_OUT_USB_HEADSET) { - //Configure USB Digital Headset parameters -#ifdef SEC_AUDIO_SUPPORT_USB_OFFLOAD - pal_param_device_capability_t *device_cap_query = (pal_param_device_capability_t *) - malloc(sizeof(pal_param_device_capability_t)); - if (!device_cap_query) { - LOG(ERROR) << __func__ << ": Failed to allocate mem for device_cap_query"; - return -ENOMEM; - } - dynamic_media_config_t dynamic_media_config; - size_t payload_size = 0; - if (pal_devs[i].id == PAL_DEVICE_OUT_USB_HEADSET) { - device_cap_query->id = PAL_DEVICE_OUT_USB_DEVICE; - device_cap_query->is_playback = true; - } - device_cap_query->addr.card_id = AudioExtensionBase::mUsbAddr.card_id; - device_cap_query->addr.device_num = AudioExtensionBase::mUsbAddr.device_num; - device_cap_query->config = &dynamic_media_config; - pal_get_param(PAL_PARAM_ID_DEVICE_CAPABILITY, - (void **)&device_cap_query, - &payload_size, nullptr); - pal_devs[i].address.card_id = AudioExtensionBase::mUsbAddr.card_id; - pal_devs[i].address.device_num = AudioExtensionBase::mUsbAddr.device_num; - pal_devs[i].config.sample_rate = dynamic_media_config.sample_rate[0]; - pal_devs[i].config.ch_info = ch_info; - pal_devs[i].config.aud_fmt_id = (pal_audio_fmt_t)dynamic_media_config.format[0]; - free(device_cap_query); -#endif - } else { - pal_devs[i].config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - pal_devs[i].config.bit_width = CODEC_BACKEND_DEFAULT_BIT_WIDTH; - pal_devs[i].config.ch_info = ch_info; - pal_devs[i].config.aud_fmt_id = PAL_AUDIO_FMT_DEFAULT_PCM; - } - - setAasCustomKey(pal_devs[i], pal_devs[0].id); // Set AAS custom key for the device - } - - mAasOutDeviceId = outDeviceId; - - ret = pal_stream_open(&aasStreamAttributes, - num_pal_devs, pal_devs, - 0, - NULL, - NULL, //callback - (uint64_t) this, - &(mAasStreamHandle)); - - if (ret) { - LOG(ERROR) << __func__ << ": Failed to open AAS stream ret = " << ret; - mAasStreamHandle = nullptr; - return ret; - } - - LOG(DEBUG) << __func__ << ": AAS stream open success"; - - return pal_stream_start(mAasStreamHandle); -} - -int AasExtension::stopAasStream() -{ - if (!isAasActive()) { - LOG(ERROR) << __func__ << ": AAS is not active state"; - return -EINVAL; - } - - int ret = pal_stream_stop(mAasStreamHandle); - if (ret) - LOG(ERROR) << __func__ << ": Failed to stop AAS Stream ret = " << ret; - - ret = pal_stream_close(mAasStreamHandle); - if (ret) { - LOG(ERROR) << __func__ << ": Failed to close AAS stream ret = " << ret; - } else { - LOG(DEBUG) << __func__ << ": AAS stream close success"; - } - mAasStreamHandle = nullptr; - return ret; -} - -AasExtension::~AasExtension() {} -AasExtension::AasExtension() : AudioExtensionBase(kDummyLibrary) { - LOG(INFO) << __func__ << " Enter"; - mAasOutDeviceId = PAL_DEVICE_NONE; - mAasStreamHandle = nullptr; -} -#endif - -#ifdef SEC_AUDIO_DSM_AMP -// START: FEEDBACK ======================================================= -void SpeakerFeedbackExtension::init() -{ -#ifdef SEC_AUDIO_DUMP - char property_value[PROPERTY_VALUE_MAX] = {0}; -#endif -#ifdef SEC_AUDIO_VI_FEEDBACK - // use vi feedback stream for vi sensing - mSupportViFeedback = true; -#else - mSupportViFeedback = false; -#ifdef SEC_AUDIO_DUMP - if (property_get("vendor.audio.vifeedback.dump", property_value, NULL) > 0) { - mSupportViFeedback = atoi(property_value); - } -#endif // SEC_AUDIO_DUMP -#endif // SEC_AUDIO_VI_FEEDBACK - mFeedbackStreamHandle = NULL; -} - -void SpeakerFeedbackExtension::start() -{ - int ret = 0; - - if (!mSupportViFeedback) { - LOG(DEBUG) << __func__ << " : SpeakerFeedbackExtension is not supported"; - return; - } - - std::unique_lock guard(mFeedbackMutex); - - if (mFeedbackStreamHandle) { - LOG(DEBUG) << __func__ << " : SpeakerFeedbackExtension is already opened"; - return; - } - - struct pal_stream_attributes feedbackStreamAttr; - struct pal_device device; - device.id = PAL_DEVICE_IN_VI_FEEDBACK; - - struct pal_channel_info out_ch_info = {2, {PAL_CHMAP_CHANNEL_FL, PAL_CHMAP_CHANNEL_FR}}; - - feedbackStreamAttr.type = PAL_STREAM_LOOPBACK; - feedbackStreamAttr.flags = (pal_stream_flags_t)0; - feedbackStreamAttr.direction = PAL_AUDIO_INPUT_OUTPUT; - feedbackStreamAttr.out_media_config.sample_rate = DEFAULT_OUTPUT_SAMPLING_RATE; - feedbackStreamAttr.out_media_config.bit_width = CODEC_BACKEND_FEEDBACK_BIT_WIDTH; - feedbackStreamAttr.out_media_config.aud_fmt_id = PAL_AUDIO_FMT_DEFAULT_PCM; - feedbackStreamAttr.out_media_config.ch_info = out_ch_info; - feedbackStreamAttr.info.opt_stream_info.loopback_type = PAL_STREAM_LOOPBACK_CAPTURE_ONLY; - - ret = pal_stream_open(&feedbackStreamAttr, - 1/* Single device */, - &device, - 0, - NULL, - nullptr, - (uint64_t) this, - &mFeedbackStreamHandle); - if (ret) { - LOG(ERROR) << __func__ << " : Feedback Stream Open Error(" << ret << ")"; - // Not fatal so ignoring the error. - return; - } else { - LOG(DEBUG) << __func__ << " : SpeakerFeedbackExtension is opened"; - } - - ret = pal_stream_start(mFeedbackStreamHandle); - if (ret) { - LOG(ERROR) << __func__ << " : failed to start feedback stream(" << ret << ")"; - pal_stream_close(mFeedbackStreamHandle); - mFeedbackStreamHandle = NULL; - - } else { - LOG(DEBUG) << __func__ << " : SpeakerFeedbackExtension is started"; - } - - return; -} - -int SpeakerFeedbackExtension::setDevice(pal_stream_handle_t *stream_handle, - uint32_t no_of_devices, struct pal_device *devices) { - int ret = 0; - bool hasSpeakerPALDevice = false; - - if (!mSupportViFeedback) { - LOG(DEBUG) << __func__ << " : SpeakerFeedbackExtension is not supported"; - return ret; - } - - if (devices[0].id == PAL_DEVICE_OUT_SPEAKER) { - hasSpeakerPALDevice = true; - } - - if (!mFeedbackStreamHandle && - hasSpeakerPALDevice && - (pal_active_device_count(PAL_DEVICE_OUT_SPEAKER) >= 0)) { - // start feedback when routing spk -> other device - // in case of playback && call - // new device is speaker and current device count is 0 -> 1 - LOG(DEBUG) << __func__ << ": Open and start feedback stream for speaker"; - start(); - } - - if (int ret = ::pal_stream_set_device(stream_handle, no_of_devices, devices); - ret) { - LOG(ERROR) << __func__ << ": failed to set devices"; - return ret; - } - - if(mFeedbackStreamHandle && - pal_active_device_count(PAL_DEVICE_OUT_SPEAKER) == 0) { - // stop feedback when routing spk -> other device - // in case of playback && call - // and current spk count is 1 -> 0 - LOG(DEBUG) << __func__ << ": stop and close feedback stream for speaker"; - stop(); - close(); - } - - return ret; -} - -void SpeakerFeedbackExtension::stop() -{ - int ret = 0; - - if (!mSupportViFeedback) { - LOG(DEBUG) << __func__ << " : SpeakerFeedbackExtension is not supported"; - return; - } - - std::unique_lock guard(mFeedbackMutex); - if (mFeedbackStreamHandle) { - ret = pal_stream_stop(mFeedbackStreamHandle); - if (ret) { - LOG(ERROR) << __func__ << " : failed to stop feedback path"; - } else { - LOG(DEBUG) << __func__ << " : SpeakerFeedbackExtension is stopped"; - } - } - return; -} - -void SpeakerFeedbackExtension::close() -{ - int ret = 0; - - if (!mSupportViFeedback) { - LOG(DEBUG) << __func__ << " : SpeakerFeedbackExtension is not supported"; - return; - } - - std::unique_lock guard(mFeedbackMutex); - if (mFeedbackStreamHandle) { - ret = pal_stream_close(mFeedbackStreamHandle); - if (ret) { - LOG(ERROR) << __func__ << " : failed to stop feedback path"; - } else { - LOG(DEBUG) << __func__ << " : SpeakerFeedbackExtension is closed"; - } - mFeedbackStreamHandle = NULL; - } - return; -} - -SpeakerFeedbackExtension::~SpeakerFeedbackExtension() {} -SpeakerFeedbackExtension::SpeakerFeedbackExtension() : AudioExtensionBase(kDummyLibrary) { - LOG(INFO) << __func__ << " Enter"; - mFeedbackStreamHandle = nullptr; - mSupportViFeedback = false; -} -// END: FEEDBACK ======================================================= -#endif - -void GefExtension::gef_interface_init() { - if (gef_init) gef_init(); -} - -void GefExtension::gef_interface_deinit() { - if (gef_deinit) gef_deinit(); -} - -GefExtension::~GefExtension() { - gef_interface_deinit(); -} - -GefExtension::GefExtension() : AudioExtensionBase(kGefLibrary, true) { - LOG(INFO) << __func__ << " Enter"; - if (mHandle != nullptr) { - if (!(gef_init = (gef_init_t)dlsym(mHandle, "gef_interface_init")) || - !(gef_deinit = (gef_deinit_t)dlsym(mHandle, "gef_interface_deinit"))) { - LOG(ERROR) << __func__ << "dlsym failed"; - goto feature_disabled; - } - LOG(INFO) << __func__ << "----- GEF interface is initialized ----"; - gef_interface_init(); - return; - } - -feature_disabled: - if (mHandle) { - dlclose(mHandle); - mHandle = NULL; - } - - gef_init = NULL; - gef_deinit = NULL; -} -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/FM.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/FM.cpp deleted file mode 100755 index 847f5aa5..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/FM.cpp +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Copyright (c) 2012-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_FM_QTI" -#define LOG_NDDEBUG 0 - -#include -#include -#include -#include -#include -#include -#include -#include "PalApi.h" - -#ifdef DYNAMIC_LOG_ENABLED -#include -#define LOG_MASK HAL_MOD_FILE_FM -#include -#endif - -#ifdef SEC_AUDIO_FMRADIO -#include "SecPalDefs.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#define AUDIO_PARAMETER_KEY_HANDLE_FM "handle_fm" -#define AUDIO_PARAMETER_KEY_FM_VOLUME "fm_volume" -#define AUDIO_PARAMETER_KEY_REC_PLAY_CONC "rec_play_conc_on" -#define AUDIO_PARAMETER_KEY_FM_MUTE "fm_mute" -#define AUDIO_PARAMETER_KEY_FM_RESTORE_VOLUME "fm_restore_volume" -#define AUDIO_PARAMETER_KEY_FM_ROUTING "fm_routing" -#define AUDIO_PARAMETER_KEY_FM_STATUS "fm_status" -#define FM_LOOPBACK_DRAIN_TIME_MS 2 - -#define CHANNELS 2 -#define BIT_WIDTH 16 -#define SAMPLE_RATE 48000 - -struct fm_module { - bool running; - bool muted; - bool restart; - float volume; - // audio_devices_t device; - pal_stream_handle_t *stream_handle; -}; - -#ifdef SEC_AUDIO_FMRADIO -static int usb_card_id = -1; -static int usb_device_num = -1; -#endif - -static struct fm_module fm = {.running = 0, - .muted = 0, - .restart = 0, - .volume = 0, - //.device = (audio_devices_t)0, - .stream_handle = 0}; - -int32_t fm_set_volume(float value, bool persist = false) { - int32_t ret = 0; - struct pal_volume_data *pal_volume = NULL; - -#if defined(SEC_AUDIO_FMRADIO) && \ - (defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP) || defined(SEC_AUDIO_PREVOLUME_SOUNDBOOSTER)) - LOG(VERBOSE) << __func__ << " Enter: volume = " << value << " persist: " << persist; - return ret; -#else - LOG(DEBUG) << __func__ << " Enter: volume = " << value << " persist: " << persist; -#endif - - if (value < 0.0) { - LOG(DEBUG) << __func__ << " Under 0.0, assuming 0.0" << value; - value = 0.0; - } else if (value > 1.0) { - LOG(DEBUG) << __func__ << " Over 0.0, assuming 0.0" << value; - value = 1.0; - } - - if (persist) fm.volume = value; - - if (fm.muted && value > 0) { - LOG(DEBUG) << __func__ << " fm is muted, applying '0' volume instead of " << value; - value = 0; - } - - if (!fm.running) { - LOG(VERBOSE) << __func__ << " FM not active, ignoring set_volume call"; - return -EIO; - } - - LOG(DEBUG) << __func__ << " Setting FM volume to " << value; - - pal_volume = (struct pal_volume_data *)malloc(sizeof(struct pal_volume_data) + - sizeof(struct pal_channel_vol_kv)); - - if (!pal_volume) return -ENOMEM; - - pal_volume->no_of_volpair = 1; - pal_volume->volume_pair[0].channel_mask = 0x03; - pal_volume->volume_pair[0].vol = value; - - ret = pal_stream_set_volume(fm.stream_handle, pal_volume); - if (ret) LOG(ERROR) << __func__ << " set volume failed: " << ret; - - free(pal_volume); - LOG(DEBUG) << __func__ << " exit"; - return ret; -} - -int32_t fm_start(int device_id) { - int32_t ret = 0; - const int num_pal_devs = 2; - struct pal_stream_attributes stream_attr; - struct pal_channel_info ch_info; - struct pal_device pal_devs[num_pal_devs]; - pal_device_id_t pal_device_id = PAL_DEVICE_OUT_SPEAKER; - - LOG(DEBUG) << __func__ << " Enter"; - -#ifdef SEC_AUDIO_FMRADIO - fm.running = false; - if (device_id == AUDIO_DEVICE_OUT_USB_HEADSET) { - pal_param_fmradio_usb_gain_t param_fmradio_usb_gain; - param_fmradio_usb_gain.enable = true; - pal_set_param(PAL_PARAM_ID_FMRADIO_USB_GAIN, (void *)¶m_fmradio_usb_gain, - sizeof(pal_param_fmradio_usb_gain_t)); - - fm.running = true; - LOG(DEBUG) << __func__ << " Exit"; - return ret; - } -#endif - - if (device_id == 2) // AUDIO_DEVICE_OUT_SPEAKER) - pal_device_id = PAL_DEVICE_OUT_SPEAKER; - else if (device_id == 4) // AUDIO_DEVICE_OUT_WIRED_HEADSET) - pal_device_id = PAL_DEVICE_OUT_WIRED_HEADSET; - else if (device_id == 8) // AUDIO_DEVICE_OUT_WIRED_HEADPHONE) - pal_device_id = PAL_DEVICE_OUT_WIRED_HEADPHONE; - else { - LOG(DEBUG) << __func__ << " Unsupported device_id " << device_id; - return -EINVAL; - } - - ch_info.channels = CHANNELS; - ch_info.ch_map[0] = PAL_CHMAP_CHANNEL_FL; - ch_info.ch_map[1] = PAL_CHMAP_CHANNEL_FR; - - stream_attr.type = PAL_STREAM_LOOPBACK; - stream_attr.info.opt_stream_info.loopback_type = PAL_STREAM_LOOPBACK_FM; - stream_attr.direction = PAL_AUDIO_INPUT_OUTPUT; - stream_attr.in_media_config.sample_rate = SAMPLE_RATE; - stream_attr.in_media_config.bit_width = BIT_WIDTH; - stream_attr.in_media_config.ch_info = ch_info; - stream_attr.in_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - stream_attr.out_media_config.sample_rate = SAMPLE_RATE; - stream_attr.out_media_config.bit_width = BIT_WIDTH; - stream_attr.out_media_config.ch_info = ch_info; - stream_attr.out_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - for (int i = 0; i < 2; ++i) { - // TODO: remove hardcoded device id & pass adev to getPalDeviceIds instead - pal_devs[i].id = i ? PAL_DEVICE_IN_FM_TUNER : pal_device_id; - pal_devs[i].config.sample_rate = SAMPLE_RATE; - pal_devs[i].config.bit_width = BIT_WIDTH; - pal_devs[i].config.ch_info = ch_info; - pal_devs[i].config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - } - -#ifdef SEC_AUDIO_FMRADIO - if (pal_devs[0].id == PAL_DEVICE_OUT_SPEAKER) { - strcpy(pal_devs[0].custom_config.custom_key, ck_table[CUSTOM_KEY_SPEAKER_FM]); - pal_devs[1].id = PAL_DEVICE_IN_USB_HEADSET; - - //Configure USB Digital Headset parameters - pal_param_device_capability_t *device_cap_query = (pal_param_device_capability_t *) - malloc(sizeof(pal_param_device_capability_t)); - if (!device_cap_query) { - LOG(ERROR) << __func__ << "Failed to allocate mem for device_cap_query"; - return -ENOMEM; - } - dynamic_media_config_t dynamic_media_config; - size_t payload_size = 0; - device_cap_query->id = PAL_DEVICE_IN_USB_HEADSET; - device_cap_query->is_playback = false; - device_cap_query->addr.card_id = usb_card_id; - device_cap_query->addr.device_num = usb_device_num; - device_cap_query->config = &dynamic_media_config; - pal_get_param(PAL_PARAM_ID_DEVICE_CAPABILITY, - (void **)&device_cap_query, - &payload_size, nullptr); - pal_devs[1].address.card_id = usb_card_id; - pal_devs[1].address.device_num = usb_device_num; - pal_devs[1].config.sample_rate = dynamic_media_config.sample_rate[0]; - pal_devs[1].config.ch_info = ch_info; - pal_devs[1].config.aud_fmt_id = (pal_audio_fmt_t)dynamic_media_config.format[0]; - strcpy(pal_devs[1].custom_config.custom_key, ck_table[CUSTOM_KEY_SPEAKER_FM]); - free(device_cap_query); - } -#endif - - ret = pal_stream_open(&stream_attr, num_pal_devs, pal_devs, 0, NULL, NULL, 0, - &fm.stream_handle); - - if (ret) { - LOG(ERROR) << __func__ << " stream open failed with: " << ret; - return ret; - } - - ret = pal_stream_start(fm.stream_handle); - if (ret) { - LOG(ERROR) << __func__ << " stream start failed with: " << ret; - pal_stream_close(fm.stream_handle); -#ifdef SEC_AUDIO_FMRADIO - fm.stream_handle = NULL; -#endif - return ret; - } - - fm.running = true; - fm_set_volume(fm.volume, true); - LOG(DEBUG) << __func__ << " Exit"; - return ret; -} - -int32_t fm_stop() { - LOG(DEBUG) << __func__ << " enter"; - - if (!fm.running) { - LOG(ERROR) << __func__ << " FM not in running state..."; - return -EINVAL; - } - - if (fm.stream_handle) { - pal_stream_stop(fm.stream_handle); - pal_stream_close(fm.stream_handle); - } -#ifdef SEC_AUDIO_FMRADIO - else { // if fm radio is playing via usb headset, fm.stream_handle is not created. - pal_param_fmradio_usb_gain_t param_fmradio_usb_gain; - param_fmradio_usb_gain.enable = false; - pal_set_param(PAL_PARAM_ID_FMRADIO_USB_GAIN, (void *)¶m_fmradio_usb_gain, - sizeof(pal_param_fmradio_usb_gain_t)); - } -#endif - - fm.stream_handle = NULL; - fm.running = false; - LOG(DEBUG) << __func__ << " Exit"; - return 0; -} - -bool fm_get_running_status() { - LOG(DEBUG) << __func__ << " enter"; - return fm.running; - LOG(DEBUG) << __func__ << " Exit"; -} - -void fm_set_parameters(struct str_parms *parms) { - int ret, val, num_pal_devs; - pal_device_id_t *pal_devs; - char value[32] = {0}; - float vol = 0.0; - - ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_HANDLE_FM, value, sizeof(value)); - if (ret >= 0) { - val = atoi(value); - LOG(DEBUG) << __func__ << " FM usecase"; - if (val) { -#ifdef SEC_AUDIO_FMRADIO - ret = str_parms_get_str(parms, "usb_card_id", value, sizeof(value)); - if (ret >= 0) { - usb_card_id = atoi(value); - ret = str_parms_get_str(parms, "usb_device_num", value, sizeof(value)); - if (ret >= 0) { - usb_device_num = atoi(value); - } - } -#endif - if (val & 0x00100000 /*AUDIO_DEVICE_OUT_FM*/ && !fm.running) - fm_start(val & ~(0x00100000) /*AUDIO_DEVICE_OUT_FM*/); - else if (!(val & 0x00100000 /*AUDIO_DEVICE_OUT_FM*/) && fm.running) { - fm_set_volume(0, false); - usleep(FM_LOOPBACK_DRAIN_TIME_MS * 1000); - fm_stop(); - } - } - } - - ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FM_ROUTING, value, sizeof(value)); - if (ret >= 0 && fm.running) { - val = atoi(value); -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - LOG(DEBUG) << __func__ << " Param: routing"; -#else - LOG(DEBUG) << __func__ << " FM usecase"; -#endif - if (val && (val & 0x00100000 /*AUDIO_DEVICE_OUT_FM*/)) { - fm_set_volume(0, false); - fm_stop(); - fm_start(val & ~(0x00100000) /*AUDIO_DEVICE_OUT_FM*/); - } - } - memset(value, 0, sizeof(value)); - - ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FM_VOLUME, value, sizeof(value)); - if (ret >= 0) { - LOG(DEBUG) << __func__ << " Param: set volume"; - if (sscanf(value, "%f", &vol) != 1) { - LOG(ERROR) << __func__ << " error in retrieving fm volume"; - return; - } - fm_set_volume(vol, true); - } - - ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FM_MUTE, value, sizeof(value)); - if (ret >= 0) { - LOG(DEBUG) << __func__ << " Param: mute"; - fm.muted = (value[0] == '1'); - if (fm.muted) - fm_set_volume(0); - else - fm_set_volume(fm.volume); - } - - ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_FM_RESTORE_VOLUME, value, sizeof(value)); - if (ret >= 0) { - LOG(DEBUG) << __func__ << " Param: restore volume"; - if (value[0] == '1') fm_set_volume(fm.volume); - } - -} - -#ifdef __cplusplus -} -#endif diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/Hfp.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/Hfp.cpp deleted file mode 100755 index 24de6d0b..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/Hfp.cpp +++ /dev/null @@ -1,506 +0,0 @@ -/* - * Copyright (c) 2012-2020, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear -*/ - -#define LOG_TAG "AHAL_HFP_QTI" -#define LOG_NDDEBUG 0 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "PalApi.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define AUDIO_PARAMETER_HFP_ENABLE "hfp_enable" -#define AUDIO_PARAMETER_HFP_SET_SAMPLING_RATE "hfp_set_sampling_rate" -#define AUDIO_PARAMETER_KEY_HFP_VOLUME "hfp_volume" -#define AUDIO_PARAMETER_HFP_PCM_DEV_ID "hfp_pcm_dev_id" - -#define AUDIO_PARAMETER_KEY_HFP_MIC_VOLUME "hfp_mic_volume" - -struct hfp_module { - bool is_hfp_running; - float hfp_volume; - float mic_volume; - bool mic_mute; - uint32_t sample_rate; - pal_stream_handle_t *rx_stream_handle; - pal_stream_handle_t *tx_stream_handle; -}; - -#define PLAYBACK_VOLUME_MAX 0x2000 -#define CAPTURE_VOLUME_DEFAULT (15.0) -static struct hfp_module hfpmod = { - .is_hfp_running = 0, - .hfp_volume = 0, - .mic_volume = CAPTURE_VOLUME_DEFAULT, - .mic_mute = 0, - .sample_rate = 16000, -}; - -static int32_t hfp_set_volume(float value) { - int32_t vol, ret = 0; - struct pal_volume_data *pal_volume = NULL; - - LOG(VERBOSE) << __func__ << " entry"; - - hfpmod.hfp_volume = value; - - if (!hfpmod.is_hfp_running) { - LOG(VERBOSE) << __func__ << " HFP not active, ignoring set_hfp_volume call"; - return -EIO; - } - - LOG(DEBUG) << __func__ << " Setting HFP volume to " << value; - - pal_volume = (struct pal_volume_data *)malloc(sizeof(struct pal_volume_data) + - sizeof(struct pal_channel_vol_kv)); - - if (!pal_volume) return -ENOMEM; - - pal_volume->no_of_volpair = 1; - pal_volume->volume_pair[0].channel_mask = 0x03; - pal_volume->volume_pair[0].vol = value; - ret = pal_stream_set_volume(hfpmod.rx_stream_handle, pal_volume); - if (ret) LOG(ERROR) << __func__ << " set volume failed: " << ret; - - free(pal_volume); - LOG(VERBOSE) << __func__ << " exit"; - return ret; -} - -/*Set mic volume to value. - * - * This interface is used for mic volume control, set mic volume as value(range 0 ~ 15). - * -*/ -static int hfp_set_mic_volume(float value) { - int volume, ret = 0; - struct pal_volume_data *pal_volume = NULL; - - LOG(DEBUG) << __func__ << " enter value= " << value; - - if (!hfpmod.is_hfp_running) { - LOG(ERROR) << __func__ << " HFP not active, ignoring set_hfp_mic_volume call"; - return -EIO; - } - - if (value < 0.0) { - LOG(DEBUG) << __func__ << " " << value << " Under 0.0, assuming 0.0"; - value = 0.0; - } else if (value > CAPTURE_VOLUME_DEFAULT) { - value = CAPTURE_VOLUME_DEFAULT; - LOG(DEBUG) << __func__ << " Volume brought within range " << value; - } - - value = value / CAPTURE_VOLUME_DEFAULT; - - volume = (int)(value * PLAYBACK_VOLUME_MAX); - - pal_volume = (struct pal_volume_data *)malloc(sizeof(struct pal_volume_data) + - sizeof(struct pal_channel_vol_kv)); - if (!pal_volume) { - LOG(ERROR) << __func__ << " Failed to allocate memory for pal_volume"; - return -ENOMEM; - } - pal_volume->no_of_volpair = 1; - pal_volume->volume_pair[0].channel_mask = 0x03; - pal_volume->volume_pair[0].vol = value; - if (pal_stream_set_volume(hfpmod.tx_stream_handle, pal_volume) < 0) { - LOG(ERROR) << __func__ << " Couldn't set HFP Volume " << volume; - free(pal_volume); - pal_volume = NULL; - return -EINVAL; - } - - free(pal_volume); - pal_volume = NULL; - - return ret; -} - -static float hfp_get_mic_volume(void) { - return hfpmod.mic_volume; -} - -static int32_t start_hfp(struct str_parms *parms __unused) { - int32_t ret = 0; - uint32_t no_of_devices = 2; - struct pal_stream_attributes stream_attr = {}; - struct pal_stream_attributes stream_tx_attr = {}; - struct pal_device devices[2] = {}; - struct pal_channel_info ch_info; - - LOG(DEBUG) << __func__ << " HFP start enter"; - if (hfpmod.rx_stream_handle || hfpmod.tx_stream_handle) return 0; // hfp already running; - - pal_param_device_connection_t param_device_connection; - - param_device_connection.id = PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET; - param_device_connection.connection_state = true; - ret = pal_set_param(PAL_PARAM_ID_DEVICE_CONNECTION, (void *)¶m_device_connection, - sizeof(pal_param_device_connection_t)); - if (ret != 0) { - LOG(ERROR) << __func__ << " Set PAL_PARAM_ID_DEVICE_CONNECTION for " - << param_device_connection.id << " failed"; - return ret; - } - - param_device_connection.id = PAL_DEVICE_OUT_BLUETOOTH_SCO; - param_device_connection.connection_state = true; - ret = pal_set_param(PAL_PARAM_ID_DEVICE_CONNECTION, (void *)¶m_device_connection, - sizeof(pal_param_device_connection_t)); - if (ret != 0) { - LOG(ERROR) << __func__ << " Set PAL_PARAM_ID_DEVICE_CONNECTION for " - << param_device_connection.id << " failed"; - return ret; - } - - pal_param_btsco_t param_btsco; - - param_btsco.is_bt_hfp = true; - param_btsco.bt_sco_on = true; - ret = pal_set_param(PAL_PARAM_ID_BT_SCO, (void *)¶m_btsco, sizeof(pal_param_btsco_t)); - if (ret != 0) { - LOG(ERROR) << __func__ << " Set PAL_PARAM_ID_BT_SCO failed"; - return ret; - } - - if (hfpmod.sample_rate == 16000) { - param_btsco.bt_wb_speech_enabled = true; - } else { - param_btsco.bt_wb_speech_enabled = false; - } - - ret = pal_set_param(PAL_PARAM_ID_BT_SCO_WB, (void *)¶m_btsco, sizeof(pal_param_btsco_t)); - if (ret != 0) { - LOG(ERROR) << __func__ << " Set PAL_PARAM_ID_BT_SCO_WB failed"; - return ret; - } - - ch_info.channels = 1; - ch_info.ch_map[0] = PAL_CHMAP_CHANNEL_FL; - - /* BT SCO -> Spkr */ - stream_attr.type = PAL_STREAM_LOOPBACK; - stream_attr.info.opt_stream_info.loopback_type = PAL_STREAM_LOOPBACK_HFP_RX; - stream_attr.direction = PAL_AUDIO_INPUT_OUTPUT; - stream_attr.in_media_config.sample_rate = hfpmod.sample_rate; - stream_attr.in_media_config.bit_width = 16; - stream_attr.in_media_config.ch_info = ch_info; - stream_attr.in_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - stream_attr.out_media_config.sample_rate = 48000; - stream_attr.out_media_config.bit_width = 16; - stream_attr.out_media_config.ch_info = ch_info; - stream_attr.out_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - devices[0].id = PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET; - devices[0].config.sample_rate = hfpmod.sample_rate; - devices[0].config.bit_width = 16; - devices[0].config.ch_info = ch_info; - devices[0].config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - devices[1].id = PAL_DEVICE_OUT_SPEAKER; - - ret = pal_stream_open(&stream_attr, no_of_devices, devices, 0, NULL, NULL, 0, - &hfpmod.rx_stream_handle); - if (ret != 0) { - LOG(ERROR) << __func__ << " HFP rx stream (BT SCO->Spkr) open failed, rc " << ret; - return ret; - } - ret = pal_stream_start(hfpmod.rx_stream_handle); - if (ret != 0) { - LOG(ERROR) << __func__ << " HFP rx stream (BT SCO->Spkr) open failed, rc " << ret; - pal_stream_close(hfpmod.rx_stream_handle); - return ret; - } - - /* Mic -> BT SCO */ - stream_tx_attr.type = PAL_STREAM_LOOPBACK; - stream_tx_attr.info.opt_stream_info.loopback_type = PAL_STREAM_LOOPBACK_HFP_TX; - stream_tx_attr.direction = PAL_AUDIO_INPUT_OUTPUT; - stream_tx_attr.in_media_config.sample_rate = hfpmod.sample_rate; - stream_tx_attr.in_media_config.bit_width = 16; - stream_tx_attr.in_media_config.ch_info = ch_info; - stream_tx_attr.in_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - stream_tx_attr.out_media_config.sample_rate = 48000; - stream_tx_attr.out_media_config.bit_width = 16; - stream_tx_attr.out_media_config.ch_info = ch_info; - stream_tx_attr.out_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - devices[0].id = PAL_DEVICE_OUT_BLUETOOTH_SCO; - devices[0].config.sample_rate = hfpmod.sample_rate; - devices[0].config.bit_width = 16; - devices[0].config.ch_info = ch_info; - devices[0].config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - devices[1].id = PAL_DEVICE_IN_SPEAKER_MIC; - - ret = pal_stream_open(&stream_tx_attr, no_of_devices, devices, 0, NULL, NULL, 0, - &hfpmod.tx_stream_handle); - if (ret != 0) { - LOG(ERROR) << __func__ << " HFP tx stream (Mic->BT SCO) open failed, rc " << ret; - pal_stream_stop(hfpmod.rx_stream_handle); - pal_stream_close(hfpmod.rx_stream_handle); - hfpmod.rx_stream_handle = NULL; - return ret; - } - ret = pal_stream_start(hfpmod.tx_stream_handle); - if (ret != 0) { - LOG(ERROR) << __func__ << " HFP tx stream (Mic->BT SCO) open failed, rc " << ret; - pal_stream_close(hfpmod.tx_stream_handle); - pal_stream_stop(hfpmod.rx_stream_handle); - pal_stream_close(hfpmod.rx_stream_handle); - hfpmod.rx_stream_handle = NULL; - hfpmod.tx_stream_handle = NULL; - return ret; - } - hfpmod.mic_mute = false; - hfpmod.is_hfp_running = true; - hfp_set_volume(hfpmod.hfp_volume); - - LOG(DEBUG) << __func__ << " HFP start end"; - return ret; -} - -static int32_t stop_hfp() { - int32_t ret = 0; - - LOG(DEBUG) << __func__ << " HFP stop enter"; - hfpmod.is_hfp_running = false; - if (hfpmod.rx_stream_handle) { - pal_stream_stop(hfpmod.rx_stream_handle); - pal_stream_close(hfpmod.rx_stream_handle); - hfpmod.rx_stream_handle = NULL; - } - if (hfpmod.tx_stream_handle) { - pal_stream_stop(hfpmod.tx_stream_handle); - pal_stream_close(hfpmod.tx_stream_handle); - hfpmod.tx_stream_handle = NULL; - } - - pal_param_btsco_t param_btsco; - - param_btsco.is_bt_hfp = true; - param_btsco.bt_sco_on = true; - ret = pal_set_param(PAL_PARAM_ID_BT_SCO, (void *)¶m_btsco, sizeof(pal_param_btsco_t)); - if (ret != 0) { - LOG(DEBUG) << __func__ << " Set PAL_PARAM_ID_BT_SCO failed"; - } - - pal_param_device_connection_t param_device_connection; - - param_device_connection.id = PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET; - param_device_connection.connection_state = false; - ret = pal_set_param(PAL_PARAM_ID_DEVICE_CONNECTION, (void *)¶m_device_connection, - sizeof(pal_param_device_connection_t)); - if (ret != 0) { - LOG(ERROR) << __func__ << " Set PAL_PARAM_ID_DEVICE_DISCONNECTION for " - << param_device_connection.id << " failed"; - } - - param_device_connection.id = PAL_DEVICE_OUT_BLUETOOTH_SCO; - param_device_connection.connection_state = false; - ret = pal_set_param(PAL_PARAM_ID_DEVICE_CONNECTION, (void *)¶m_device_connection, - sizeof(pal_param_device_connection_t)); - if (ret != 0) { - LOG(ERROR) << __func__ << " Set PAL_PARAM_ID_DEVICE_DISCONNECTION for " - << param_device_connection.id << " failed"; - } - - LOG(DEBUG) << __func__ << "HFP stop end"; - return ret; -} - -void hfp_init() { - return; -} - -bool hfp_is_active() { - return hfpmod.is_hfp_running; -} - -bool is_valid_out_device(pal_device_id_t id) { - switch (id) { - case PAL_DEVICE_OUT_HANDSET: - case PAL_DEVICE_OUT_SPEAKER: - case PAL_DEVICE_OUT_WIRED_HEADSET: - case PAL_DEVICE_OUT_WIRED_HEADPHONE: - case PAL_DEVICE_OUT_USB_DEVICE: - case PAL_DEVICE_OUT_USB_HEADSET: - return true; - default: - return false; - } -} - -bool is_valid_in_device(pal_device_id_t id) { - switch (id) { - case PAL_DEVICE_IN_HANDSET_MIC: - case PAL_DEVICE_IN_SPEAKER_MIC: - case PAL_DEVICE_IN_WIRED_HEADSET: - case PAL_DEVICE_IN_USB_DEVICE: - case PAL_DEVICE_IN_USB_HEADSET: - return true; - default: - return false; - } -} - -bool has_valid_stream_handle() { - return (hfpmod.rx_stream_handle && hfpmod.tx_stream_handle); -} - -void hfp_set_device(struct pal_device *devices) { - int rc = 0; - - if (hfpmod.is_hfp_running && has_valid_stream_handle() && - is_valid_out_device(devices[0].id) && is_valid_in_device(devices[1].id)) { - rc = pal_stream_set_device(hfpmod.rx_stream_handle, 1, &devices[0]); - if (!rc) { - rc = pal_stream_set_device(hfpmod.tx_stream_handle, 1, &devices[1]); - } - } - - if (rc) { - LOG(ERROR) << __func__ << ": failed to set devices for hfp"; - } - return; -} - -/*Set mic mute state. - * * - * * This interface is used for mic mute state control - * */ -int hfp_set_mic_mute(bool state) { - int rc = 0; - - if (state == hfpmod.mic_mute) { - LOG(DEBUG) << __func__ << " mic mute already " << state; - return rc; - } - rc = hfp_set_mic_volume((state == true) ? 0.0 : hfpmod.mic_volume); - if (rc == 0) hfpmod.mic_mute = state; - LOG(DEBUG) << __func__ << " Setting mute state " << state << " rc " << rc; - return rc; -} - -int hfp_set_mic_mute2(bool state __unused) { - LOG(DEBUG) << __func__ << " Unsupported"; - return 0; -} - -void hfp_set_parameters(bool adev_mute, struct str_parms *parms) { - int status = 0; - char value[32] = {0}; - float vol; - int val; - int rate; - - LOG(DEBUG) << __func__ << " enter"; - - status = str_parms_get_str(parms, AUDIO_PARAMETER_HFP_ENABLE, value, sizeof(value)); - if (status >= 0) { - if (!strncmp(value, "true", sizeof(value)) && !hfpmod.is_hfp_running) { - status = start_hfp(parms); - /* - * Sync to adev mic mute state if hfpmod.mic_mute state is lost due - * to HFP session tear down during device switch on companion device. - */ - if (hfpmod.mic_mute != adev_mute) { - LOG(DEBUG) << __func__ << " update mic mute with latest mute state " << adev_mute; - hfp_set_mic_mute(adev_mute); - } - } else if (!strncmp(value, "false", sizeof(value)) && hfpmod.is_hfp_running) { - stop_hfp(); - } else { - LOG(ERROR) << __func__ << " hfp_enable " << value << " is unsupported"; - } - } - - memset(value, 0, sizeof(value)); - status = str_parms_get_str(parms, AUDIO_PARAMETER_HFP_SET_SAMPLING_RATE, value, sizeof(value)); - if (status >= 0) { - rate = atoi(value); - if (rate == 8000) { - hfpmod.sample_rate = (uint32_t)rate; - } else if (rate == 16000) { - hfpmod.sample_rate = (uint32_t)rate; - } else - LOG(ERROR) << __func__ << " Unsupported rate.. " << rate; - } - - memset(value, 0, sizeof(value)); - status = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_HFP_VOLUME, value, sizeof(value)); - if (status >= 0) { - if (sscanf(value, "%f", &vol) != 1) { - LOG(ERROR) << __func__ << " error in retrieving hfp volume"; - status = -EIO; - goto exit; - } - LOG(DEBUG) << __func__ << " set_hfp_volume usecase, Vol: " << vol; - hfp_set_volume(vol); - } - - memset(value, 0, sizeof(value)); - status = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_HFP_MIC_VOLUME, value, sizeof(value)); - if (status >= 0) { - if (sscanf(value, "%f", &vol) != 1) { - LOG(ERROR) << __func__ << " error in retrieving hfp mic volume"; - status = -EIO; - goto exit; - } - LOG(DEBUG) << __func__ << " set_hfp_mic_volume usecase, Vol: " << vol; - if (hfp_set_mic_volume(vol) == 0) hfpmod.mic_volume = vol; - } - -exit: - LOG(DEBUG) << __func__ << " Exit"; -} - -#ifdef __cplusplus -} -#endif diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/battery_listener.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/battery_listener.cpp deleted file mode 100755 index 21a98ba9..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/battery_listener.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/* -* Copyright (c) 2019, 2021 The Linux Foundation. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following -* disclaimer in the documentation and/or other materials provided -* with the distribution. -* * Neither the name of The Linux Foundation nor the names of its -* contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -* Changes from Qualcomm Innovation Center are provided under the following license: -* -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -#define LOG_TAG "AHAL_BatteryListener_QTI" -#include "extensions/battery_listener.h" -#include -#include -#include -#include -#include -#include - -using aidl::android::hardware::health::BatteryStatus; -using aidl::android::hardware::health::HealthInfo; -using aidl::android::hardware::health::IHealthInfoCallback; -using aidl::android::hardware::health::BnHealthInfoCallback; -using aidl::android::hardware::health::IHealth; -using namespace std::literals::chrono_literals; - -namespace android { - -#define GET_HEALTH_SVC_RETRY_CNT 5 -#define GET_HEALTH_SVC_WAIT_TIME_MS 500 - -struct BatteryListenerImpl : public BnHealthInfoCallback { - typedef std::function cb_fn_t; - BatteryListenerImpl(cb_fn_t cb); - ~BatteryListenerImpl(); - ndk::ScopedAStatus healthInfoChanged(const HealthInfo &info) override; - static void serviceDied(void *cookie); - bool isCharging() { - std::lock_guard _l(mLock); - return statusToBool(mStatus); - } - void reset(); - status_t init(); - - private: - std::shared_ptr mHealth; - BatteryStatus mStatus; - cb_fn_t mCb; - std::mutex mLock; - std::condition_variable mCond; - std::unique_ptr mThread; - ndk::ScopedAIBinder_DeathRecipient mDeathRecipient; - bool mDone; - bool statusToBool(const BatteryStatus &s) const { - return (s == BatteryStatus::CHARGING) || (s == BatteryStatus::FULL); - } -}; - -static std::shared_ptr batteryListener; - -status_t BatteryListenerImpl::init() { - int tries = 0; - auto service_name = std::string() + IHealth::descriptor + "/default"; - - if (mHealth != NULL) return INVALID_OPERATION; - - do { - mHealth = IHealth::fromBinder( - ndk::SpAIBinder(AServiceManager_getService(service_name.c_str()))); - if (mHealth != NULL) break; - usleep(GET_HEALTH_SVC_WAIT_TIME_MS * 1000); - tries++; - } while (tries < GET_HEALTH_SVC_RETRY_CNT); - - if (mHealth == NULL) { - ALOGE("no health service found, retries %d", tries); - return NO_INIT; - } else { - ALOGI("Get health service in %d tries", tries); - } - mStatus = BatteryStatus::UNKNOWN; - auto ret = mHealth->getChargeStatus(&mStatus); - if (!ret.isOk()) ALOGE("batterylistener: get charge status transaction error"); - - if (mStatus == BatteryStatus::UNKNOWN) ALOGW("batterylistener: init: invalid battery status"); - mDone = false; - mThread = std::make_unique([this]() { - std::unique_lock l(mLock); - BatteryStatus local_status = mStatus; - while (!mDone) { - if (local_status == mStatus) { - mCond.wait(l); - continue; - } - local_status = mStatus; - switch (local_status) { - // NOT_CHARGING is a special event that indicates, a battery is connected, - // but not charging. This is seen for approx a second - // after charger is plugged in. A charging event is eventually received. - // We must try to avoid an unnecessary cb to HAL - // only to call it again shortly. - // An option to deal with this transient event would be to ignore this. - // Or process this event with a slight delay (i.e cancel this event - // if a different event comes in within a timeout - case BatteryStatus::NOT_CHARGING: { - auto mStatusnot_ncharging = [this, local_status]() { - return mStatus != local_status; - }; - mCond.wait_for(l, 3s, mStatusnot_ncharging); - if (mStatusnot_ncharging()) // i.e event changed - break; - } - [[fallthrough]]; - default: - bool c = statusToBool(local_status); - ALOGI("healthInfo cb thread: cb %s", c ? "CHARGING" : "NOT CHARGING"); - l.unlock(); - mCb(c); - l.lock(); - break; - } - } - }); - mHealth->registerCallback(batteryListener); - binder_status_t binder_status = - AIBinder_linkToDeath(mHealth->asBinder().get(), mDeathRecipient.get(), this); - if (binder_status != STATUS_OK) { - ALOGE("Failed to link to death, status %d", static_cast(binder_status)); - return NO_INIT; - } - return NO_ERROR; -} - -BatteryListenerImpl::BatteryListenerImpl(cb_fn_t cb) - : mCb(cb), mDeathRecipient(AIBinder_DeathRecipient_new(BatteryListenerImpl::serviceDied)) {} - -BatteryListenerImpl::~BatteryListenerImpl() { - { - std::lock_guard _l(mLock); - mDone = true; - mCond.notify_one(); - } - mThread->join(); -} - -void BatteryListenerImpl::reset() { - std::lock_guard _l(mLock); - if (mHealth != nullptr) { - mHealth->unregisterCallback(batteryListener); - binder_status_t status = - AIBinder_unlinkToDeath(mHealth->asBinder().get(), mDeathRecipient.get(), this); - if (status != STATUS_OK && status != STATUS_DEAD_OBJECT) ALOGE("Cannot unlink to death"); - } - mStatus = BatteryStatus::UNKNOWN; - mDone = true; - mCond.notify_one(); -} -void BatteryListenerImpl::serviceDied(void *cookie) { - BatteryListenerImpl *listener = reinterpret_cast(cookie); - { - std::lock_guard _l(listener->mLock); - if (listener->mHealth == NULL) { - ALOGE("health not initialized"); - return; - } - ALOGI("health service died, reinit"); - listener->mDone = true; - listener->mCond.notify_one(); - } - listener->mThread->join(); - std::lock_guard _l(listener->mLock); - listener->mHealth = NULL; - listener->init(); -} - -// this callback seems to be a SYNC callback and so -// waits for return before next event is issued. -// therefore we need not have a queue to process -// NOT_CHARGING and CHARGING concurrencies. -// Replace single var by a list if this assumption is broken -ndk::ScopedAStatus BatteryListenerImpl::healthInfoChanged(const HealthInfo &info) { - ALOGV("healthInfoChanged: %d", info.batteryStatus); - std::unique_lock l(mLock); - if (info.batteryStatus != mStatus) { - mStatus = info.batteryStatus; - mCond.notify_one(); - } - return ndk::ScopedAStatus::ok(); -} - -status_t batteryPropertiesListenerInit(BatteryListenerImpl::cb_fn_t cb) { - batteryListener = ndk::SharedRefBase::make(cb); - return batteryListener->init(); -} - -status_t batteryPropertiesListenerDeinit() { - batteryListener->reset(); - return OK; -} - -bool batteryPropertiesListenerIsCharging() { - return batteryListener->isCharging(); -} - -} // namespace android - -extern "C" { -void battery_properties_listener_init(battery_status_change_fn_t fn) { - android::batteryPropertiesListenerInit([=](bool charging) { fn(charging); }); -} - -void battery_properties_listener_deinit() { - android::batteryPropertiesListenerDeinit(); -} - -bool battery_properties_is_charging() { - return android::batteryPropertiesListenerIsCharging(); -} - -} // extern C diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/include/extensions/AudioExtension.h b/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/include/extensions/AudioExtension.h deleted file mode 100755 index 1decfdb0..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/include/extensions/AudioExtension.h +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include "extensions/battery_listener.h" - -#ifdef SEC_AUDIO_DSM_AMP -#ifdef SEC_AUDIO_VI_FEEDBACK -#define CODEC_BACKEND_FEEDBACK_BIT_WIDTH 24 -#else -#define CODEC_BACKEND_FEEDBACK_BIT_WIDTH 16 -#endif -#endif - -typedef enum { - SESSION_UNKNOWN, - /** A2DP legacy that AVDTP media is encoded by Bluetooth Stack */ - A2DP_SOFTWARE_ENCODING_DATAPATH, - /** The encoding of AVDTP media is done by HW and there is control only */ - A2DP_HARDWARE_OFFLOAD_DATAPATH, - /** Used when encoded by Bluetooth Stack and streaming to Hearing Aid */ - HEARING_AID_SOFTWARE_ENCODING_DATAPATH, - /** Used when encoded by Bluetooth Stack and streaming to LE Audio device */ - LE_AUDIO_SOFTWARE_ENCODING_DATAPATH, - /** Used when decoded by Bluetooth Stack and streaming to audio framework */ - LE_AUDIO_SOFTWARE_DECODED_DATAPATH, - /** Encoding is done by HW an there is control only */ - LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH, - /** Decoding is done by HW an there is control only */ - LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH, - /** SW Encoding for LE Audio Broadcast */ - LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH, - /** HW Encoding for LE Audio Broadcast */ - LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH, - MAX, -} tSESSION_TYPE; - -namespace qti::audio::core { -// RAII based classes to dlopen/dysym on init and dlclose on dest. - -#ifdef __LP64__ -static std::string kBluetoothIpcLibrary = "/vendor/lib64/btaudio_offload_if.so"; -#else -static std::string kBluetoothIpcLibrary = "/vendor/lib/btaudio_offload_if.so"; -#endif -static std::string kBatteryListenerLibrary = std::string("libbatterylistener.so"); -static std::string kHfpLibrary = "libhfp_pal.so"; -static std::string kFmLibrary = "libfmpal.so"; -static std::string kKarokeLibrary = "dummy.so"; // TODO -static std::string kGefLibrary = "libqtigefar.so"; -#ifdef SEC_AUDIO_COMMON -static std::string kDummyLibrary = "dummy.so"; -#endif - -static std::string kBatteryListenerProperty = "vendor.audio.feature.battery_listener.enable"; -static std::string kHfpProperty = "vendor.audio.feature.hfp.enable"; -static std::string kBluetoothProperty = "vendor.audio.feature.a2dp_offload.enable"; - -const std::map SessionTypePalDevMap{ - {A2DP_HARDWARE_OFFLOAD_DATAPATH, PAL_DEVICE_OUT_BLUETOOTH_A2DP}, - {LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH, PAL_DEVICE_OUT_BLUETOOTH_BLE}, - {LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH, PAL_DEVICE_IN_BLUETOOTH_BLE}, - {LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH, - PAL_DEVICE_OUT_BLUETOOTH_BLE_BROADCAST}, -}; - -typedef enum { - /**If reconfiguration is in progress state */ - SESSION_SUSPEND, - /**If reconfiguration is in complete state */ - SESSION_RESUME, - /**To set Lc3 channel mode as Mono */ - CHANNEL_MONO, - /**To set LC3 channel mode as Stereo */ - CHANNEL_STEREO, -} tRECONFIG_STATE; - -const std::map reconfigStateName{ - {SESSION_SUSPEND, std::string{"SESSION_SUSPEND"}}, - {SESSION_RESUME, std::string{"SESSION_RESUME"}}, - {CHANNEL_MONO, std::string{"CHANNEL_MONO"}}, - {CHANNEL_STEREO, std::string{"CHANNEL_STEREO"}}, -}; - -typedef void (*batt_listener_init_t)(battery_status_change_fn_t); -typedef void (*batt_listener_deinit_t)(); -typedef bool (*batt_prop_is_charging_t)(); - -typedef void (*set_parameters_t)(struct str_parms*); -typedef void (*hfp_set_parameters_t)(bool val, struct str_parms*); -typedef void (*get_parameters_t)(struct str_parms*, struct str_parms*); -typedef bool (*fm_running_status_t)(); - -typedef void (*hfp_init_t)(); -typedef bool (*hfp_is_active_t)(); -typedef int (*hfp_get_usecase_t)(); -typedef int (*hfp_set_mic_mute_t)(bool state); -typedef int (*hfp_set_mic_mute2_t)(bool state); -typedef void (*hfp_set_device_t)(struct pal_device *devices); - -typedef void (*a2dp_bt_audio_pre_init_t)(void); -typedef void (*register_reconfig_cb_t)(int (*reconfig_cb)(tSESSION_TYPE, int)); - -typedef void (*gef_init_t)(void); -typedef void (*gef_deinit_t)(void); - -static bool isExtensionEnabled(std::string property) { - return property_get_bool(property.c_str(), false); -} -class AudioExtensionBase { - public: - AudioExtensionBase(std::string library, bool enabled = true); - ~AudioExtensionBase(); -#ifdef SEC_AUDIO_SUPPORT_USB_OFFLOAD - static void setUSBCardConfig(pal_usb_device_address addr) { mUsbAddr = addr; } -#endif - protected: - void* mHandle = nullptr; - bool mEnabled; -#ifdef SEC_AUDIO_SUPPORT_USB_OFFLOAD - static struct pal_usb_device_address mUsbAddr; -#endif - std::string mLibraryName; - Platform& mPlatform{Platform::getInstance()}; - - private: - void cleanUp(); -}; - -class BatteryListenerExtension : public AudioExtensionBase { - public: - BatteryListenerExtension(); - ~BatteryListenerExtension(); - void battery_properties_listener_init(); - void battery_properties_listener_deinit(); - bool battery_properties_is_charging(); - static void setChargingMode(bool is_charging); - static bool isCharging; - // void on_battery_status_changed(bool charging); - private: - batt_listener_init_t batt_listener_init; - batt_listener_deinit_t batt_listener_deinit; - batt_prop_is_charging_t batt_prop_is_charging; -}; - -class A2dpExtension : public AudioExtensionBase { - public: - A2dpExtension(); - ~A2dpExtension(); - - a2dp_bt_audio_pre_init_t a2dp_bt_audio_pre_init = nullptr; - register_reconfig_cb_t register_reconfig_cb = nullptr; -}; - -class HfpExtension : public AudioExtensionBase { - public: - HfpExtension(); - ~HfpExtension(); - bool audio_extn_hfp_is_active(); - int audio_extn_hfp_set_mic_mute(bool state); - int audio_extn_hfp_set_mic_mute2(bool state); - void audio_extn_hfp_set_parameters(struct str_parms* params); - void audio_extn_hfp_set_device(const std::vector<::aidl::android::media::audio::common::AudioDevice>& - devices, const bool updateRx); - ::aidl::android::media::audio::common::AudioDevice audio_extn_hfp_get_matching_tx_device( - const ::aidl::android::media::audio::common::AudioDevice& rxDevice); - - private: - hfp_init_t hfp_init; - hfp_is_active_t hfp_is_active; - hfp_get_usecase_t hfp_get_usecase; - hfp_set_mic_mute_t hfp_set_mic_mute; - hfp_set_parameters_t hfp_set_parameters; - hfp_set_mic_mute2_t hfp_set_mic_mute2; - hfp_set_device_t hfp_set_device; - bool micMute; -}; - -#ifdef SEC_AUDIO_CALL_SATELLITE -class ExtModemCallExtension : public AudioExtensionBase { - public: - ExtModemCallExtension(); - ~ExtModemCallExtension(); - int32_t startCall(struct pal_device *callDevices); - void stopCall(); - void setDevice(struct pal_device *devices); - bool isCallActive() { return isExtModemCallRunning; } - pal_stream_handle_t* getRxStreamHandle() { return rxStreamHandle; }; - pal_stream_handle_t* getTxStreamHandle() { return txStreamHandle; }; - - private: - bool hasValidStreamHandle() { return (rxStreamHandle && txStreamHandle); } - bool isValidOutDevice(pal_device_id_t id); - bool isValidInDevice(pal_device_id_t id); - bool isUsbDevice(pal_device_id_t id); - void setCustomKey(pal_device& palDevice, const pal_device_id_t outDeviceId); - void configurePalDevices(struct pal_device *palDevices, const pal_device_id_t callRxDeviceId); - std::unique_ptr getExtModemCallAttributes( - pal_stream_loopback_type_t type); - bool isExtModemCallRunning; - pal_stream_handle_t *rxStreamHandle; - pal_stream_handle_t *txStreamHandle; -}; -#endif - -class FmExtension : public AudioExtensionBase { - public: - FmExtension(); - ~FmExtension(); - set_parameters_t fm_set_params; - fm_running_status_t fm_running_status; - void audio_extn_fm_set_parameters(struct str_parms* params); - bool audio_extn_fm_get_status(); -}; - -class KarokeExtension : public AudioExtensionBase { - public: - KarokeExtension(); - ~KarokeExtension(); -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - void init(); - bool isKaraokeActive(); - bool isVoiceRecognitionStreamCreated() { return mIsVoiceRecognitionStreamCreated; } - void setVoiceRecognitionStreamCreated(bool on) { mIsVoiceRecognitionStreamCreated = on; } -#endif - int karaoke_open(pal_device_id_t device_out, pal_stream_callback pal_callback, - pal_channel_info ch_info); - int karaoke_start(); - int karaoke_stop(); - int karaoke_close(); - protected: - pal_stream_handle_t* karaoke_stream_handle; - struct pal_stream_attributes sattr; -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - bool mIsVoiceRecognitionStreamCreated = false; -#endif -}; - -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC -class AasExtension : public AudioExtensionBase { - public: - AasExtension(); - ~AasExtension(); - int startAasStream(const pal_device_id_t outDeviceId); - int stopAasStream(); - int updateAasStream(const bool enable, const pal_device_id_t outDeviceId); - protected: - bool isAasActive() { return (mAasStreamHandle != nullptr) ? true : false; } - bool isAasDeviceAvailable(const pal_device_id_t deviceId); - bool isValidStatusForAas(const pal_device_id_t outDeviceId); - void setAasCustomKey(pal_device& palDevice, const pal_device_id_t outDeviceId); - pal_device_id_t mAasOutDeviceId; - pal_stream_handle_t *mAasStreamHandle; -}; -#endif - -#ifdef SEC_AUDIO_DSM_AMP -class SpeakerFeedbackExtension : public AudioExtensionBase { -public: - SpeakerFeedbackExtension(); - ~SpeakerFeedbackExtension(); - void init(); - void start(); - int setDevice(pal_stream_handle_t *stream_handle, - uint32_t no_of_devices, struct pal_device *devices); - void stop(); - void close(); -protected: - pal_stream_handle_t *mFeedbackStreamHandle; - bool mSupportViFeedback; - std::mutex mFeedbackMutex; -}; -#endif - -class GefExtension : public AudioExtensionBase { - public: - GefExtension(); - ~GefExtension(); - void gef_interface_init(); - void gef_interface_deinit(); - - private: - gef_init_t gef_init; - gef_deinit_t gef_deinit; -}; - -class AudioExtension { - public: - static AudioExtension& getInstance() { - static const auto kAudioExtension = []() { - std::unique_ptr audioExt{new AudioExtension()}; - return std::move(audioExt); - }(); - return *(kAudioExtension.get()); - } - void audio_extn_set_parameters(struct str_parms* params); - void audio_extn_get_parameters(struct str_parms* params, struct str_parms* reply); - void audio_feature_stats_set_parameters(struct str_parms* params); - explicit AudioExtension() = default; - AudioExtension(const AudioExtension&) = delete; - AudioExtension& operator=(const AudioExtension& x) = delete; - - AudioExtension(AudioExtension&& other) = delete; - AudioExtension& operator=(AudioExtension&& other) = delete; - std::unique_ptr mBatteryListenerExtension = - std::make_unique(); - std::unique_ptr mA2dpExtension = std::make_unique(); - std::unique_ptr mHfpExtension = std::make_unique(); -#ifdef SEC_AUDIO_CALL_SATELLITE - std::unique_ptr mExtModemCallExtension = std::make_unique(); -#endif - std::unique_ptr mFmExtension = std::make_unique(); - std::unique_ptr mKarokeExtension = std::make_unique(); -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC - std::unique_ptr mAasExtension = std::make_unique(); -#endif -#ifdef SEC_AUDIO_DSM_AMP - std::unique_ptr mSpeakerFeedbackExtension - = std::make_unique(); -#endif - std::unique_ptr mGefExtension = std::make_unique(); - static std::mutex reconfig_wait_mutex_; -}; -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/include/extensions/battery_listener.h b/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/include/extensions/battery_listener.h deleted file mode 100755 index c31687ce..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/extensions/include/extensions/battery_listener.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* Copyright (c) 2019, 2021 The Linux Foundation. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following -* disclaimer in the documentation and/or other materials provided -* with the distribution. -* * Neither the name of The Linux Foundation nor the names of its -* contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -* Changes from Qualcomm Innovation Center are provided under the following license: -* -* Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. -* SPDX-License-Identifier: BSD-3-Clause-Clear -*/ -#ifdef __cplusplus -extern "C" { -#endif -typedef void (*battery_status_change_fn_t)(bool); -void battery_properties_listener_init(battery_status_change_fn_t fn); -void battery_properties_listener_deinit(void); -bool battery_properties_is_charging(void); -#ifdef __cplusplus -} -#endif diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/fuzzer/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/core/fuzzer/Android.mk deleted file mode 100755 index 0ecb279e..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/fuzzer/Android.mk +++ /dev/null @@ -1,63 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) -LOCAL_MODULE := aidl_fuzzer_audio_core_hal -LOCAL_VENDOR_MODULE := true - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \ - $(TOP)/system/media/audio/include \ - $(TOP)/hardware/libhardware/include - -LOCAL_CFLAGS := -DBACKEND_NDK - -LOCAL_SRC_FILES := \ - fuzzer.cpp \ - -LOCAL_HEADER_LIBRARIES := \ - libxsdc-utils \ - libaudioeffects \ - liberror_headers \ - libaudioclient_headers \ - libaudio_system_headers \ - libmedia_helper_headers - -LOCAL_STATIC_LIBRARIES := \ - libaudiohalutils.qti \ - libaudio_module_config.qti \ - libaudiocore.extension - -LOCAL_WHOLE_STATIC_LIBRARIES := \ - libaudioplatform.qti - -LOCAL_SHARED_LIBRARIES := \ - libaudioaidlcommon \ - libbase \ - libbinder_ndk \ - libcutils \ - liblog \ - libdl \ - libhidlbase \ - libhardware \ - libfmq \ - libmedia_helper \ - libstagefright_foundation \ - libutils \ - libaudioutils \ - libxml2 \ - android.hardware.common-V2-ndk \ - android.media.audio.common.types-V3-ndk \ - android.hardware.audio.core-V2-ndk \ - $(LATEST_ANDROID_HARDWARE_AUDIO_EFFECT) \ - android.hardware.audio.core.sounddose-V1-ndk \ - libar-pal \ - libaudioserviceexampleimpl \ - libaudioplatformconverter.qti \ - qti-audio-types-aidl-V1-ndk \ - libbinder \ - libaudiocorehal.qti \ - libaudiocorehal.default \ - libclang_rt.ubsan_standalone - -LOCAL_STATIC_LIBRARIES += libbinder_random_parcel - -include $(BUILD_FUZZ_TEST) \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/fuzzer/fuzzer.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/fuzzer/fuzzer.cpp deleted file mode 100755 index 09d7add7..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/fuzzer/fuzzer.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -#include -#include -#include -#include -#include - -#include -#include - -#define LOG_TAG "AIDL_FUZZER_AUDIO_CORE_HAL" - -using aidl::android::hardware::audio::core::internal::AudioPolicyConfigXmlConverter; - -extern AudioPolicyConfigXmlConverter gAudioPolicyConverter; -extern std::shared_ptr<::aidl::android::hardware::audio::core::Config> gConfigDefaultAosp; -extern std::shared_ptr<::qti::audio::core::ModulePrimary> gModuleDefaultQti; - -// init -extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) { - gConfigDefaultAosp = ndk::SharedRefBase::make<::aidl::android::hardware::audio::core::Config>(gAudioPolicyConverter); - gModuleDefaultQti = ndk::SharedRefBase::make<::qti::audio::core::ModulePrimary>(); - - return 0; -} - -// one fuzzing test case -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - FuzzedDataProvider provider(data, size); - - uint32_t index = provider.ConsumeIntegralInRange(1, 2); - - if (index == 2 && gModuleDefaultQti != nullptr) { - android::fuzzService(gModuleDefaultQti->asBinder().get(), std::move(provider)); - } - - if (index == 1 && gConfigDefaultAosp != nullptr) { - android::fuzzService(gConfigDefaultAosp->asBinder().get(), std::move(provider)); - } - - return 0; -} \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Bluetooth.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Bluetooth.h deleted file mode 100755 index b3425af3..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Bluetooth.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once -#include -#include -#include -#include -#include - -namespace qti::audio::core { - -class Bluetooth : public ::aidl::android::hardware::audio::core::BnBluetooth { - public: - Bluetooth(); - - private: - ndk::ScopedAStatus setScoConfig(const ScoConfig& in_config, ScoConfig* _aidl_return) override; - ndk::ScopedAStatus setHfpConfig(const HfpConfig& in_config, HfpConfig* _aidl_return) override; - - ScoConfig mScoConfig; - HfpConfig mHfpConfig; - Platform& mPlatform{Platform::getInstance()}; - AudioExtension& mAudExt{AudioExtension::getInstance()}; -}; - -class BluetoothA2dp : public ::aidl::android::hardware::audio::core::BnBluetoothA2dp { - public: - BluetoothA2dp() = default; - - private: - ndk::ScopedAStatus isEnabled(bool* _aidl_return) override; - ndk::ScopedAStatus setEnabled(bool in_enabled) override; - ndk::ScopedAStatus supportsOffloadReconfiguration(bool* _aidl_return) override; - ndk::ScopedAStatus reconfigureOffload( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters) override; - - bool mEnabled = false; - Platform& mPlatform{Platform::getInstance()}; -}; - -class BluetoothLe : public ::aidl::android::hardware::audio::core::BnBluetoothLe { - public: - BluetoothLe() = default; - - private: - ndk::ScopedAStatus isEnabled(bool* _aidl_return) override; - ndk::ScopedAStatus setEnabled(bool in_enabled) override; - ndk::ScopedAStatus supportsOffloadReconfiguration(bool* _aidl_return) override; - ndk::ScopedAStatus reconfigureOffload( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters) override; - - bool mEnabled = false; - Platform& mPlatform{Platform::getInstance()}; -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/ChildInterface.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/ChildInterface.h deleted file mode 100755 index 39219fff..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/ChildInterface.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2023 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. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include - -#include -#include - -namespace qti::audio::core { - -// Helper used for interfaces that require a persistent instance. We hold them -// via a strong pointer. The binder token is retained for a call to -// 'setMinSchedulerPolicy'. -template -struct ChildInterface : private std::pair, ndk::SpAIBinder> { - ChildInterface() = default; - ChildInterface& operator=(const std::shared_ptr& c) { - return operator=(std::shared_ptr(c)); - } - ChildInterface& operator=(std::shared_ptr&& c) { - this->first = std::move(c); - return *this; - } - explicit operator bool() const { return !!this->first; } - C& operator*() const { return *(this->first); } - C* operator->() const { return this->first.get(); } - // Use 'getInstance' when returning the interface instance. - std::shared_ptr getInstance() { - if (this->second.get() == nullptr) { - const auto binder = this->second = this->first->asBinder(); - AIBinder_setMinSchedulerPolicy(binder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO); - AIBinder_setInheritRt(binder.get(), true); - } - return this->first; - } -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/HalOffloadEffects.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/HalOffloadEffects.h deleted file mode 100755 index 8978f276..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/HalOffloadEffects.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include - -namespace qti::audio::core { - -#ifdef __LP64__ -#define OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH "/vendor/lib64/soundfx/libqcompostprocbundle.so" -#define VISUALIZER_LIBRARY_PATH "/vendor/lib64/soundfx/libqcomvisualizer.so" -#else -#define OFFLOAD_EFFECTS_BUNDLE_LIBRARY_PATH "/vendor/lib/soundfx/libqcompostprocbundle.so" -#define VISUALIZER_LIBRARY_PATH "/vendor/lib/soundfx/libqcomvisualizer.so" -#endif - -// { SEC_AUDIO_SUPPORT_AIDL_EFFECT -#ifdef __LP64__ -#define OFFLOAD_EFFECT_LIBRARY_PATH "/vendor/lib64/soundfx/libaudioeffectoffload_aidl.so" -#else -#define OFFLOAD_EFFECT_LIBRARY_PATH "/vendor/lib/soundfx/libaudioeffectoffload_aidl.so" -#endif -// } SEC_AUDIO_SUPPORT_AIDL_EFFECT - -/* -* All libraries implementing post processing effect should expose -* startEffect(int, pal_stream_handle_t*) -* stopEffect(int) -*/ -using pal_stream_handle_t = uint64_t; - -using StartEffectFptr = void (*)(int, uint64_t*); -using StopEffectFptr = void (*)(int); -// { SEC_AUDIO_VOLUME_MONITOR -using UpdateEffectFptr = void (*)(uint64_t*, int); -// } SEC_AUDIO_VOLUME_MONITOR -struct OffloadEffectLibIntf { - StartEffectFptr mStartEffect; - StopEffectFptr mStopEffect; -// { SEC_AUDIO_VOLUME_MONITOR - UpdateEffectFptr mUpdateEffect; -// } SEC_AUDIO_VOLUME_MONITOR -}; - -/* Pair of libhandle, and function pointers*/ -using EffectLibInfo = std::pair>, - std::unique_ptr>; - -class HalOffloadEffects { - private: -#ifdef __LP64__ - const std::string kOffloadVisualizerPath = "/vendor/lib64/soundfx/libqcomvisualizer.so"; - const std::string kOffloadPostProcBundlePath = "/vendor/lib64/soundfx/libqcompostprocbundle.so"; -#else - const std::string kOffloadVisualizerPath = "/vendor/lib/soundfx/libqcomvisualizer.so"; - const std::string kOffloadPostProcBundlePath = "/vendor/lib/soundfx/libqcompostprocbundle.so"; -#endif - -// { SEC_AUDIO_SUPPORT_AIDL_EFFECT -#ifdef __LP64__ - const std::string kSecOffloadEffectLibraryPath = "/vendor/lib64/soundfx/libaudioeffectoffload_aidl.so"; -#else - const std::string kSecOffloadEffectLibraryPath = "/vendor/lib/soundfx/libaudioeffectoffload_aidl.so"; -#endif -// } SEC_AUDIO_SUPPORT_AIDL_EFFECT - - std::vector mEffects; - - HalOffloadEffects(); - void loadLibrary(std::string path); - - public: - static HalOffloadEffects& getInstance() { - static HalOffloadEffects halEffects; - return halEffects; - } - - void startEffect(int ioHandle, pal_stream_handle_t* palHandle); - void stopEffect(int ioHandle); -// { SEC_AUDIO_VOLUME_MONITOR - void updateEffect(pal_stream_handle_t* palHandle, int updateType); -// } SEC_AUDIO_VOLUME_MONITOR -}; - -} // qti::audio::core \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Module.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Module.h deleted file mode 100755 index f9d2ca67..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Module.h +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace qti::audio::core { - -class Module : public ::aidl::android::hardware::audio::core::BnModule, - public std::enable_shared_from_this { - public: - enum Type : int { DEFAULT, R_SUBMIX, STUB, USB }; - - explicit Module(Type type); - - // #################### start of overriding APIs from IModule #################### - ndk::ScopedAStatus setModuleDebug( - const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) override; - ndk::ScopedAStatus getTelephony( - std::shared_ptr<::aidl::android::hardware::audio::core::ITelephony>* _aidl_return) - override; - ndk::ScopedAStatus getBluetooth( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetooth>* _aidl_return) - override; - ndk::ScopedAStatus getBluetoothA2dp( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothA2dp>* _aidl_return) - override; - ndk::ScopedAStatus getBluetoothLe( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothLe>* _aidl_return) - override; - ndk::ScopedAStatus prepareToDisconnectExternalDevice(int32_t in_portId) override; - ndk::ScopedAStatus connectExternalDevice( - const ::aidl::android::media::audio::common::AudioPort& in_templateIdAndAdditionalData, - ::aidl::android::media::audio::common::AudioPort* _aidl_return) override; - ndk::ScopedAStatus disconnectExternalDevice(int32_t in_portId) override; - ndk::ScopedAStatus getAudioPatches( - std::vector<::aidl::android::hardware::audio::core::AudioPatch>* _aidl_return) override; - ndk::ScopedAStatus getAudioPort( - int32_t in_portId, - ::aidl::android::media::audio::common::AudioPort* _aidl_return) override; - ndk::ScopedAStatus getAudioPortConfigs( - std::vector<::aidl::android::media::audio::common::AudioPortConfig>* _aidl_return) - override; - ndk::ScopedAStatus getAudioPorts( - std::vector<::aidl::android::media::audio::common::AudioPort>* _aidl_return) override; - ndk::ScopedAStatus getAudioRoutes( - std::vector<::aidl::android::hardware::audio::core::AudioRoute>* _aidl_return) override; - ndk::ScopedAStatus getAudioRoutesForAudioPort( - int32_t in_portId, - std::vector<::aidl::android::hardware::audio::core::AudioRoute>* _aidl_return) override; - ndk::ScopedAStatus openInputStream( - const ::aidl::android::hardware::audio::core::IModule::OpenInputStreamArguments& - in_args, - ::aidl::android::hardware::audio::core::IModule::OpenInputStreamReturn* _aidl_return) - override; - ndk::ScopedAStatus openOutputStream( - const ::aidl::android::hardware::audio::core::IModule::OpenOutputStreamArguments& - in_args, - ::aidl::android::hardware::audio::core::IModule::OpenOutputStreamReturn* _aidl_return) - override; - ndk::ScopedAStatus getSupportedPlaybackRateFactors( - SupportedPlaybackRateFactors* _aidl_return) override; - ndk::ScopedAStatus setAudioPatch( - const ::aidl::android::hardware::audio::core::AudioPatch& in_requested, - ::aidl::android::hardware::audio::core::AudioPatch* _aidl_return) override; - ndk::ScopedAStatus setAudioPortConfig( - const ::aidl::android::media::audio::common::AudioPortConfig& in_requested, - ::aidl::android::media::audio::common::AudioPortConfig* out_suggested, - bool* _aidl_return) override; - ndk::ScopedAStatus resetAudioPatch(int32_t in_patchId) override; - ndk::ScopedAStatus resetAudioPortConfig(int32_t in_portConfigId) override; - ndk::ScopedAStatus getMasterMute(bool* _aidl_return) override; - ndk::ScopedAStatus setMasterMute(bool in_mute) override; - ndk::ScopedAStatus getMasterVolume(float* _aidl_return) override; - ndk::ScopedAStatus setMasterVolume(float in_volume) override; - ndk::ScopedAStatus getMicMute(bool* _aidl_return) override; - ndk::ScopedAStatus setMicMute(bool in_mute) override; - ndk::ScopedAStatus getMicrophones( - std::vector<::aidl::android::media::audio::common::MicrophoneInfo>* _aidl_return) - override; - ndk::ScopedAStatus updateAudioMode( - ::aidl::android::media::audio::common::AudioMode in_mode) override; - ndk::ScopedAStatus updateScreenRotation( - ::aidl::android::hardware::audio::core::IModule::ScreenRotation in_rotation) override; - ndk::ScopedAStatus updateScreenState(bool in_isTurnedOn) override; - ndk::ScopedAStatus getSoundDose( - std::shared_ptr<::aidl::android::hardware::audio::core::sounddose::ISoundDose>* - _aidl_return) override; - ndk::ScopedAStatus generateHwAvSyncId(int32_t* _aidl_return) override; - ndk::ScopedAStatus getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return) - override; - ndk::ScopedAStatus setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async) override; - ndk::ScopedAStatus addDeviceEffect( - int32_t in_portConfigId, - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override; - ndk::ScopedAStatus removeDeviceEffect( - int32_t in_portConfigId, - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override; - ndk::ScopedAStatus getMmapPolicyInfos( - ::aidl::android::media::audio::common::AudioMMapPolicyType mmapPolicyType, - std::vector<::aidl::android::media::audio::common::AudioMMapPolicyInfo>* _aidl_return) - override; - ndk::ScopedAStatus supportsVariableLatency(bool* _aidl_return) override; - ndk::ScopedAStatus getAAudioMixerBurstCount(int32_t* _aidl_return) override; - ndk::ScopedAStatus getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) override; - // #################### end of overriding APIs from IModule #################### - - // This value is used for all AudioPatches. - static constexpr int32_t kMinimumStreamBufferSizeFrames = 48; - // The maximum stream buffer size is 1 GiB = 2 ** 30 bytes; - static constexpr int32_t kMaximumStreamBufferSizeBytes = 1 << 30; - - protected: - struct VendorDebug { - static const std::string kForceTransientBurstName; - static const std::string kForceSynchronousDrainName; - bool forceTransientBurst = false; - bool forceSynchronousDrain = false; - }; - - // ids of device ports created at runtime via 'connectExternalDevice'. - // Also stores a list of ids of mix ports with dynamic profiles that were populated from - // the connected port. This list can be empty, thus an int->int multimap can't be used. - using ConnectedDevicePorts = std::map>; - // Maps port ids and port config ids to patch ids. - // Multimap because both ports and configs can be used by multiple patches. - using Patches = std::multimap; - - const Type mType; - std::unique_ptr mConfig; - ::aidl::android::hardware::audio::core::ModuleDebug mDebug; - VendorDebug mVendorDebug; - ConnectedDevicePorts mConnectedDevicePorts; - Streams mStreams; - Patches mPatches; - bool mMasterMute = false; - float mMasterVolume = 1.0f; - ChildInterface<::aidl::android::hardware::audio::core::sounddose::ISoundDose> mSoundDose; - std::optional mIsMmapSupported; - - protected: - // #################### start of virtual APIs to be implemented by children #################### - virtual ndk::ScopedAStatus createInputStream( - StreamContext&& context, - const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata, - const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones, - std::shared_ptr* result) = 0; - virtual ndk::ScopedAStatus createOutputStream( - StreamContext&& context, - const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata, - const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>& - offloadInfo, - std::shared_ptr* result) = 0; - virtual std::vector<::aidl::android::media::audio::common::AudioProfile> getDynamicProfiles( - const ::aidl::android::media::audio::common::AudioPort& audioPort); - - virtual void onNewPatchCreation( - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sources, - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sinks, - ::aidl::android::hardware::audio::core::AudioPatch& newPatch); - virtual void onPrepareToDisconnectExternalDevice( - const ::aidl::android::media::audio::common::AudioPort& audioPort); - - virtual void setAudioPatchTelephony( - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sources, - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sinks, - const ::aidl::android::hardware::audio::core::AudioPatch& patch); - virtual void resetAudioPatchTelephony( - const ::aidl::android::hardware::audio::core::AudioPatch&); - virtual std::string toStringInternal() { return std::string("No-op implementation"); } - /** - * Call this API only for debugging purpose - **/ - virtual void dumpInternal(const std::string& identifier = "no_id"){}; - - // If the module is unable to populate the connected device port correctly, - // the returned error code must correspond to the errors of - // `IModule.connectedExternalDevice` method. - virtual ndk::ScopedAStatus populateConnectedDevicePort( - ::aidl::android::media::audio::common::AudioPort* connectedDevicePort, - const int32_t templateDevicePortId); - // If the module finds that the patch endpoints configurations are not - // matched, the returned error code must correspond to the errors of - // `IModule.setAudioPatch` method. - virtual ndk::ScopedAStatus checkAudioPatchEndpointsMatch( - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sources, - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sinks); - virtual int onExternalDeviceConnectionChanged( - const ::aidl::android::media::audio::common::AudioPort& audioPort, bool connected); - virtual ndk::ScopedAStatus onMasterMuteChanged(bool mute); - virtual ndk::ScopedAStatus onMasterVolumeChanged(float volume); - virtual std::unique_ptr initializeConfig(); - /* fetch the nominal latency for the given mix port config */ - virtual int32_t getNominalLatencyMs( - const ::aidl::android::media::audio::common::AudioPortConfig&); - // #################### end of virtual APIs to be implemented by children #################### - - // Utility and helper functions accessible to subclasses. - void cleanUpPatch(int32_t patchId); - ndk::ScopedAStatus createStreamContext( - int32_t in_portConfigId, int64_t in_bufferSizeFrames, - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCallback> asyncCallback, - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamOutEventCallback> - outEventCallback, - StreamContext* out_context); - std::vector<::aidl::android::media::audio::common::AudioDevice> findConnectedDevices( - int32_t portConfigId); - std::set findConnectedPortConfigIds(int32_t portConfigId); - ndk::ScopedAStatus findPortIdForNewStream( - int32_t in_portConfigId, ::aidl::android::media::audio::common::AudioPort** port); - ModuleConfig& getConfig(); - const ConnectedDevicePorts& getConnectedDevicePorts() const { return mConnectedDevicePorts; } - bool getMasterMute() const { return mMasterMute; } - bool getMasterVolume() const { return mMasterVolume; } - const Patches& getPatches() const { return mPatches; } - const Streams& getStreams() const { return mStreams; } - Type getType() const { return mType; } - bool isMmapSupported(); - void populateConnectedProfiles(); - template - std::set portIdsFromPortConfigIds(C portConfigIds); - - // helper functions to print human readable string for portconfig names and routes - std::string portNameFromPortConfigIds(int portConfigId); - std::string getPatchDetails(const ::aidl::android::hardware::audio::core::AudioPatch& patch); - - void registerPatch(const ::aidl::android::hardware::audio::core::AudioPatch& patch); - ndk::ScopedAStatus updateStreamsConnectedState( - const ::aidl::android::hardware::audio::core::AudioPatch& oldPatch, - const ::aidl::android::hardware::audio::core::AudioPatch& newPatch); - - ChildInterface mTelephony; -}; - -std::ostream& operator<<(std::ostream& os, Module::Type t); - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/ModulePrimary.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/ModulePrimary.h deleted file mode 100755 index 15d088e0..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/ModulePrimary.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (C) 2023 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. - */ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#ifdef SEC_AUDIO_COMMON -#include -#include "SecFTM.h" -#include "AudioEffect.h" -#endif - -namespace qti::audio::core { - -class ModulePrimary final : public Module { - public: - ModulePrimary(); - - // #################### start of overriding APIs from IModule #################### - binder_status_t dump(int fd, const char** args, uint32_t numArgs) override; - ndk::ScopedAStatus getBluetooth( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetooth>* _aidl_return) - override; - ndk::ScopedAStatus getBluetoothA2dp( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothA2dp>* _aidl_return) - override; - ndk::ScopedAStatus getBluetoothLe( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothLe>* _aidl_return) - override; - ndk::ScopedAStatus getTelephony( - std::shared_ptr<::aidl::android::hardware::audio::core::ITelephony>* _aidl_return) - override; - ndk::ScopedAStatus setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async) override; - ndk::ScopedAStatus getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return) - override; - ndk::ScopedAStatus getMicMute(bool* _aidl_return) override; - ndk::ScopedAStatus setMicMute(bool in_mute) override; - ndk::ScopedAStatus getMicrophones( - std::vector<::aidl::android::media::audio::common::MicrophoneInfo>* _aidl_return) - override; - ndk::ScopedAStatus updateScreenState(bool in_isTurnedOn) override; - ndk::ScopedAStatus updateScreenRotation( - ::aidl::android::hardware::audio::core::IModule::ScreenRotation in_rotation) override; - ndk::ScopedAStatus getSupportedPlaybackRateFactors( - SupportedPlaybackRateFactors* _aidl_return) override; - // #################### end of overriding APIs from IModule #################### - - // Mutex for stream lists protection - static std::mutex outListMutex; - static std::mutex inListMutex; - - static std::vector>& getOutStreams() { return mStreamsOut; } - static std::vector>& getInStreams() { return mStreamsIn; } - -#ifdef SEC_AUDIO_COMMON - public: - SecModulePrimary& mSecModulePrimary{SecModulePrimary::getInstance()}; -#endif - - protected: - // #################### start of overriding APIs from Module #################### - std::string toStringInternal() override; - void dumpInternal(const std::string& identifier = "no_id") override; - ndk::ScopedAStatus createInputStream( - StreamContext&& context, - const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata, - const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones, - std::shared_ptr* result) override; - ndk::ScopedAStatus createOutputStream( - StreamContext&& context, - const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata, - const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>& - offloadInfo, - std::shared_ptr* result) override; - std::vector<::aidl::android::media::audio::common::AudioProfile> getDynamicProfiles( - const ::aidl::android::media::audio::common::AudioPort& audioPort) override; - void onNewPatchCreation( - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sources, - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sinks, - ::aidl::android::hardware::audio::core::AudioPatch& newPatch) override; - void setAudioPatchTelephony( - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sources, - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sinks, - const ::aidl::android::hardware::audio::core::AudioPatch& newPatch) override; - void resetAudioPatchTelephony( - const ::aidl::android::hardware::audio::core::AudioPatch&) override; - int onExternalDeviceConnectionChanged( - const ::aidl::android::media::audio::common::AudioPort& audioPort, - bool connected) override; - int32_t getNominalLatencyMs( - const ::aidl::android::media::audio::common::AudioPortConfig&) override; - // #################### end of overriding APIs from Module #################### - - // start of Module Parameters - - /** - * Features to be provided by Set/Get Parameters. - * Each Feature can be associated to one or more semantically related Parameters id's. - * Each Feature has atmost one set handler or atmost one get handler or both. - * Such a group of Parameters acquires a Feature enum and will be - * dealt either by set or get or both handlers. - * - * Example: - * {k1,k2,k3} => F1 => SH,GH - * {k3,k5} => F2 => SH - * {k7} => F3 => GH - * - * k* -> parameter's Ids, - * F* -> Feature enums, - * SH -> SetHandler - * GH -> GetHandler - **/ - enum class Feature : uint16_t { - GENERIC = 0, // this enum groups much generic parameters - TELEPHONY, - BLUETOOTH, - HDR, - WFD, - FTM, // Factory Test Mode - AUDIOEXTENSION, - HAPTICS - }; - - // For set parameters - using SetHandler = std::function&)>; - using SetParameterToFeatureMap = std::map; - using FeatureToSetHandlerMap = std::map; - static SetParameterToFeatureMap fillSetParameterToFeatureMap(); - static FeatureToSetHandlerMap fillFeatureToSetHandlerMap(); - using FeatureToVendorParametersMap = - std::map>; - - // For get parameters - using GetHandler = - std::function( - ModulePrimary*, const std::vector&)>; - using GetParameterToFeatureMap = std::map; - using FeatureToGetHandlerMap = std::map; - static GetParameterToFeatureMap fillGetParameterToFeatureMap(); - static FeatureToGetHandlerMap fillFeatureToGetHandlerMap(); - using FeatureToStringMap = std::map>; - - // end of Module Parameters - static std::vector> mStreamsOut; - static std::vector> mStreamsIn; - - static void updateStreamOutList(const std::shared_ptr streamOut) { - mStreamsOut.push_back(streamOut); - } - static void updateStreamInList(const std::shared_ptr streamIn) { - mStreamsIn.push_back(streamIn); - } - - // start of module parameters handling - bool processSetVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>&); - // setHandler for Generic - void onSetGenericParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>&); - // SetHandler For HDR - void onSetHDRParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>&); - // SetHandler For Telephony - void onSetTelephonyParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>&); - // SetHandler For WFD - void onSetWFDParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>&); - // SetHandler For FTM - void onSetFTMParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>&); - // SetHandler For Haptics - void onSetHapticsParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>&); - - std::vector<::aidl::android::hardware::audio::core::VendorParameter> processGetVendorParameters( - const std::vector&); - // GetHandler for HDR - std::vector<::aidl::android::hardware::audio::core::VendorParameter> onGetHDRParameters( - const std::vector&); - // GetHandler for Telephony - std::vector<::aidl::android::hardware::audio::core::VendorParameter> onGetTelephonyParameters( - const std::vector&); - // GetHandler for WFD - std::vector<::aidl::android::hardware::audio::core::VendorParameter> onGetWFDParameters( - const std::vector&); - // GetHandler for FTM - std::vector<::aidl::android::hardware::audio::core::VendorParameter> onGetFTMParameters( - const std::vector&); - std::vector<::aidl::android::hardware::audio::core::VendorParameter> onGetAudioExtnParams( - const std::vector&); - std::vector<::aidl::android::hardware::audio::core::VendorParameter> onGetBluetoothParams( - const std::vector&); - std::vector<::aidl::android::hardware::audio::core::VendorParameter> onGetGenericParams( - const std::vector&); - // end of module parameters handling - - - protected: - const SetParameterToFeatureMap mSetParameterToFeatureMap{fillSetParameterToFeatureMap()}; - const FeatureToSetHandlerMap mFeatureToSetHandlerMap{fillFeatureToSetHandlerMap()}; - const GetParameterToFeatureMap mGetParameterToFeatureMap{fillGetParameterToFeatureMap()}; - const FeatureToGetHandlerMap mFeatureToGetHandlerMap{fillFeatureToGetHandlerMap()}; - ChildInterface<::aidl::android::hardware::audio::core::IBluetooth> mBluetooth; - ChildInterface<::aidl::android::hardware::audio::core::IBluetoothA2dp> mBluetoothA2dp; - ChildInterface<::aidl::android::hardware::audio::core::IBluetoothLe> mBluetoothLe; - Platform& mPlatform{Platform::getInstance()}; - AudioExtension& mAudExt{AudioExtension::getInstance()}; - - private: - bool mOffloadSpeedSupported; -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/ModuleStub.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/ModuleStub.h deleted file mode 100755 index 2210a9e1..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/ModuleStub.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2023 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. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include - -namespace qti::audio::core { - -class ModuleStub final : public Module { - public: - ModuleStub() : Module(Type::STUB) {} - - protected: - ndk::ScopedAStatus getBluetooth( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetooth>* _aidl_return) - override; - ndk::ScopedAStatus getBluetoothA2dp( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothA2dp>* _aidl_return) - override; - ndk::ScopedAStatus getBluetoothLe( - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothLe>* _aidl_return) - override; - ndk::ScopedAStatus createInputStream( - StreamContext&& context, - const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata, - const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones, - std::shared_ptr* result) override; - ndk::ScopedAStatus createOutputStream( - StreamContext&& context, - const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata, - const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>& - offloadInfo, - std::shared_ptr* result) override; - - private: - ChildInterface<::aidl::android::hardware::audio::core::IBluetooth> mBluetooth; - ChildInterface<::aidl::android::hardware::audio::core::IBluetoothA2dp> mBluetoothA2dp; - ChildInterface<::aidl::android::hardware::audio::core::IBluetoothLe> mBluetoothLe; -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Parameters.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Parameters.h deleted file mode 100755 index 7e1c660a..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Parameters.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#ifdef ENABLE_TAS_SPK_PROT -#include "TISpeakerProtDefs.h" -#endif - -namespace qti::audio::core::Parameters { - -/** - * Since the parameters from the Android framework enables or disables features - * which would impact small to big level, It is highly recommended to write - * verbose comments for each parameter. As Parameter is composition 'id' and 'its - * possibles values', hence list all the values with verbose explaination - **/ - -// HDR Recording -const static std::string kHdrRecord{"hdr_record_on"}; -const static std::string kHdrChannelCount{"hdr_audio_channel_count"}; -const static std::string kHdrSamplingRate{"hdr_audio_sampling_rate"}; -const static std::string kWnr{"wnr_on"}; -const static std::string kAns{"ans_on"}; -const static std::string kOrientation{"orientation"}; -const static std::string kInverted{"inverted"}; -const static std::string kFacing{"facing"}; - - -// voice -const static std::string kVoiceCallState{"call_state"}; -const static std::string kVoiceCallType{"call_type"}; -const static std::string kVoiceVSID{"vsid"}; -const static std::string kVoiceDeviceMute{"device_mute"}; -const static std::string kVolumeBoost{"volume_boost"}; -const static std::string kVoiceDirection{"direction"}; -const static std::string kVoiceSlowTalk{"st_enable"}; -const static std::string kVoiceHDVoice{"hd_voice"}; -const static std::string kVoiceIsCRsSupported{"isCRSsupported"}; -const static std::string kVoiceCRSCall{"crs_call"}; -const static std::string kVoiceCRSVolume{"CRS_volume"}; -const static std::string kVoiceTranslationRxMute{"voice_translation_rx_mute"}; -/** kVoiceTranslationRxMute : helps to set the Voice Rx Volume -* to mute when the param is set to enabled during the -* voice call translation usecase running. -**/ - - -// WFD -const static std::string kCanOpenProxy{"can_open_proxy"}; -const static std::string kWfdChannelMap{"wfd_channel_cap"}; -const static std::string kWfdProxyRecordActive{"proxyRecordActive"}; - -/** - * USE_IP_IN_DEVICE_FOR_PROXY_RECORD: Use this parameter to set/unset if ip-v4 in device - * in getting used a proxy device. Set it before making the device available and unset - * it while making device unavailable. - **/ -const static std::string kWfdIPAsProxyDevConnected{"USE_IP_IN_DEVICE_FOR_PROXY_RECORD"}; -/** - * clients have need to hardcode - * frame count requirement per read. - * Ideally, client should be able read - * as AHAL provided. Still, AHAL supports - * this way to set module vendor parameter - * to request a custom FMQ size from client - * FMQ size. - * example: - * As the session starts, client sets - * proxy_record_fmq_size = 480 - - * As session ends, client unsets - * proxy_record_fmq_size = 0 - - * After the session of proxy record finishes, - * client is resposible to unset the module - * vendor parameter. - - * For upcoming requirements, this way is - * depreciated. - **/ -const static std::string kProxyRecordFMQSize{"proxy_record_fmq_size"}; - -// Generic -const static std::string kInCallMusic{"icmd_playback"}; -const static std::string kUHQA{"UHQA"}; -const static std::string kOffloadPlaySpeedSupported{"offloadVariableRateSupported"}; -const static std::string kSupportsHwSuspend{"supports_hw_suspend"}; -const static std::string kIsDirectPCMTrack{"is_direct_pcm_track"}; -const static std::string kTranslateRecord{"translate_record"}; -#ifdef ENABLE_TAS_SPK_PROT -const static std::string kTiSmartPaKey{AUDIO_PARAM_TI_SMARTPA}; -#endif -/** - * translate_record : AUDIO_FLUENCE_FFECNS PCM_RECORD - * Use this parameter to for the Voice Translation usecase. - * Set param support for APK to select FFECNS record and populate - * custom key for FFECNS record based on the setparam. - **/ - -// FTM -const static std::string kFbspCfgWaitTime{"fbsp_cfg_wait_time"}; -const static std::string kFbspFTMWaitTime{"fbsp_cfg_ftm_time"}; -const static std::string kFbspValiWaitTime{"fbsp_v_vali_wait_time"}; -const static std::string kFbspValiValiTime{"fbsp_v_vali_vali_time"}; -const static std::string kTriggerSpeakerCall{"trigger_spkr_cal"}; -const static std::string kFTMParam{"get_ftm_param"}; -const static std::string kFTMSPKRParam{"get_spkr_cal"}; - -// Audio Extn -const static std::string kFMStatus{"fm_status"}; - -// Bluetooth -const static std::string kA2dpSuspended{"A2dpSuspended"}; - -// Haptics -const static std::string kHapticsVolume{"haptics_volume"}; -const static std::string kHapticsIntensity{"haptics_intensity"}; - -}; // namespace qti::audio::core::Parameters diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/SecModulePrimary.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/SecModulePrimary.h deleted file mode 100755 index 736370f1..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/SecModulePrimary.h +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2023 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 -#include -#include - -#include "AudioEffect.h" -#include "SecFTM.h" -#include - -using ::aidl::android::hardware::audio::core::VendorParameter; -using ::aidl::qti::audio::core::VString; - -namespace qti::audio::core { - -class SecModulePrimary { - public: - SecModulePrimary(); - - static SecModulePrimary& getInstance(); - // For set parameters - using SetHandler = std::function&)>; - using SetParameterToFeatureMap = std::map; - using FeatureToSetHandlerMap = std::map; - - static SetParameterToFeatureMap fillSetParameterToFeatureMap(); - static FeatureToSetHandlerMap fillFeatureToSetHandlerMap(); - using FeatureToVendorParametersMap = - std::map>; - - // For get parameters - using GetHandler = - std::function( - SecModulePrimary*, const std::vector&)>; - using GetParameterToFeatureMap = std::map; - using FeatureToGetHandlerMap = std::map; - static GetParameterToFeatureMap fillGetParameterToFeatureMap(); - static FeatureToGetHandlerMap fillFeatureToGetHandlerMap(); - using FeatureToStringMap = std::map>; -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION - using CalValueToGetParameterMap = std::map; - static CalValueToGetParameterMap fillCalValueToGetParameterMap(); -#endif - // start of module parameters handling - bool processSetVendorParameters(const std::vector& parameters); -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION - void processCalibrationParameters(const std::vector& parameters); - std::string getCalibrationResults(std::string calValue, std::string ampType); -#endif -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_PROVIDEO - void SetProVideoState(int mode); -#endif -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC - pal_device_id_t getPrimaryOutPalDeviceId(); -#endif -#ifdef SEC_AUDIO_COMMON - static bool CheckComboDevice(); -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - static bool isListenbackDevice(pal_device_id_t deviceId); - static bool isListenbackUsecase(Usecase usecase); - static int getListenbackOutputCount(); - static void updateStreamListenbackMode(bool enable); -#endif -#ifdef SEC_AUDIO_USB_GAIN_CONTROL - static void updateUsbAudioGain(); -#endif -#ifdef SEC_AUDIO_KARAOKE - void setKaraokeDevice(); -#endif - // setHandler for Samsung Generic - void onSetSECGenericParameters(const std::vector& parameters); - // SetHandler For Samsung Telephony - void onSetSECTelephonyParameters(const std::vector& parameters); - // SetHandler For Samsung Factory - void onSetSECFTMParameters(const std::vector& parameters); - // SetHandler For Samsung Parameters using Subkey - void onSetSECSubkeyParameters(const std::vector& parameters); - - std::vector processGetVendorParameters(const std::vector&); - // GetHandler for Samsung Generic - std::vector onGetSECGenericParameters(const std::vector&); - // GetHandler For Samsung Telephony - std::vector onGetSECTelephonyParameters(const std::vector&); - // GetHandler For Samsung Factory - std::vector onGetSECFTMParameters(const std::vector&); - - static ndk::ScopedAStatus ForceSetOutDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, - bool force = false); - static ndk::ScopedAStatus ForceSetInDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices); - static std::shared_ptr GetStreamOut(Usecase tag); - static std::shared_ptr GetStreamIn(Usecase tag); -#ifdef SEC_AUDIO_SAMSUNGRECORD - static std::shared_ptr getHighestPriorityStreamIn(); -#endif - void setTelephony(ChildInterface tel) { mTelephony = tel; } - - std::string toString() const { - std::ostringstream os; - os << std::endl << " --- SecModulePrimary ---" << std::endl; - os << mSecFTM.toString(); - os << " --- SecModulePrimary end ---" << std::endl << std::endl; - return os.str(); - } - - protected: - ChildInterface mTelephony; - - const SetParameterToFeatureMap mSetParameterToFeatureMap_SEC{fillSetParameterToFeatureMap()}; - const FeatureToSetHandlerMap mFeatureToSetHandlerMap{fillFeatureToSetHandlerMap()}; - const GetParameterToFeatureMap mGetParameterToFeatureMap{fillGetParameterToFeatureMap()}; - const FeatureToGetHandlerMap mFeatureToGetHandlerMap{fillFeatureToGetHandlerMap()}; -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION - const CalValueToGetParameterMap mCalValueToGetParameterMap{fillCalValueToGetParameterMap()}; -#endif - -#ifdef SEC_AUDIO_CALL_VOIP - ndk::ScopedAStatus RerouteForVoip(); -#endif -#ifdef SEC_AUDIO_SCREEN_MIRRORING // { SUPPORT_VOIP_VIA_SMART_VIEW - ndk::ScopedAStatus UpdateSmartViewState(bool newVoipViaSmartView); -#endif // } SUPPORT_VOIP_VIA_SMART_VIEW -#if defined(SEC_AUDIO_SUPPORT_FLIP_CALL) || defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_FOLD_PARAM_ON_DSP) - void SetFolderState(int state); -#endif -#ifdef SEC_AUDIO_BLE_OFFLOAD - void UpdateSCOdeviceState(); -#endif - - Platform& mPlatform{Platform::getInstance()}; - AudioExtension& mAudExt{AudioExtension::getInstance()}; - AudioEffect& mAudioEffect{AudioEffect::getInstance()}; - SecFTM& mSecFTM{SecFTM::getInstance()}; - - }; -} // namespace qti::audio::core::SecModulePrimary diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/SecParameters.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/SecParameters.h deleted file mode 100755 index 538b89f5..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/SecParameters.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2023 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 -#include -#include - -namespace qti::audio::core::SecParameters { - -enum class Feature_SEC : uint16_t { - SEC_GENERIC = 0, - SEC_TELEPHONY, - SEC_FTM, - SEC_SUBKEY, -}; - -// Voice -const static std::string kFactoryEchoRefMuteDetect{AUDIO_PARAMETER_SEC_GLOBAL_FACTORY_ECHOREF_MUTE_DETECT}; -const static std::string kFactoryEchoRefMuteValue{AUDIO_PARAMETER_SEC_GLOBAL_FACTORY_ECHOREF_MUTE_VALUE}; -const static std::string kTtyMode{AUDIO_PARAMETER_KEY_TTY_MODE}; -const static std::string kVoiceCallBand{AUDIO_PARAMETER_SEC_GLOBAL_CALL_BAND}; -const static std::string kVoiceCallForwardingEnable{AUDIO_PARAMETER_SEC_GLOBAL_CALL_FORWARDING_ENABLE}; -const static std::string kVoiceCallMemoState{AUDIO_PARAMETER_SEC_GLOBAL_CALL_MEMO_STATE}; -const static std::string kVoiceCallNBQualityEnable{AUDIO_PARAMETER_SEC_LOCAL_CALL_NB_QUALITY_ENABLE}; -const static std::string kVoiceCallRingbacktoneState{AUDIO_PARAMETER_SEC_GLOBAL_CALL_RINGBACKTONE_STATE}; -const static std::string kVoiceCallSatelliteEnable{AUDIO_PARAMETER_SEC_GLOBAL_CALL_SATELLITE_ENABLE}; -const static std::string kVoiceCallState{AUDIO_PARAMETER_SEC_GLOBAL_CALL_STATE}; -const static std::string kVoiceCallTranslationMode{AUDIO_PARAMETER_SEC_LOCAL_CALL_TRANSLATION_MODE}; -const static std::string kVoiceEffectDVAdaptSound{AUDIO_PARAMETER_SEC_GLOBAL_EFFECT_DV_ADAPT_SOUND}; -const static std::string kVoiceEffectDVAdaptSoundCallPatam{AUDIO_PARAMETER_SEC_LOCAL_EFFECT_DV_ADAPT_SOUND_CALL_PARAM}; -const static std::string kVoiceFactoryEchoRefMuteCNGEnable{AUDIO_PARAMETER_SEC_GLOBAL_FACTORY_ECHOREF_MUTE_CNG_ENABLE}; -const static std::string kVoiceHAC{AUDIO_PARAMETER_KEY_HAC}; -const static std::string kVoiceHACMode{AUDIO_PARAMETER_SEC_LOCAL_CALL_HAC_MODE}; -const static std::string kVoiceScreenCall{AUDIO_PARAMETER_SEC_LOCAL_SCREEN_CALL}; -const static std::string kVoiceStreamEnforcedActiveInCall{AUDIO_PARAMETER_SEC_LOCAL_STREAM_ENFORCED_ACTIVE_IN_CALL}; -const static std::string kVoiceTxControlMode{AUDIO_PARAMETER_SEC_LOCAL_VOICE_TX_CONTROL_MODE}; -const static std::string kVoiceRxControlMode{AUDIO_PARAMETER_SEC_LOCAL_VOICE_RX_CONTROL_MODE}; -const static std::string kVoiceMicInputControlMode{AUDIO_PARAMETER_SEC_LOCAL_MIC_INPUT_CONTROL_MODE}; -const static std::string kVoiceMicInputControlModeCall{AUDIO_PARAMETER_SEC_LOCAL_MIC_INPUT_CONTROL_MODE_CALL}; -const static std::string kVoiceVSID{AUDIO_PARAMETER_SEC_GLOBAL_CALL_SIM_SLOT}; - -// Factory Test -const static std::string kFactoryTestLoopback{AUDIO_PARAMETER_FACTORY_TEST_LOOPBACK}; -const static std::string kFactoryTestMicPath{AUDIO_PARAMETER_KEY_FACTORY_RMS_TEST}; -const static std::string kFactoryTestPath{AUDIO_PARAMETER_FACTORY_TEST_PATH}; -const static std::string kFactoryTestRoute{AUDIO_PARAMETER_FACTORY_TEST_ROUTE}; -const static std::string kFactoryTestType{AUDIO_PARAMETER_FACTORY_TEST_TYPE}; -const static std::string kFactoryTestSpkPath{AUDIO_PARAMETER_FACTORY_TEST_SPKPATH}; -const static std::string kFactoryTestCalibration{AUDIO_PARAMETER_SEC_GLOBAL_FACTORY_CALIBRATION_KEY}; -const static std::string kFactoryTestCalAmpType{AUDIO_PARAMETER_SUBKEY_FACTORY_CALIBRATION_AMP}; -const static std::string kFactoryTestCalTarget{AUDIO_PARAMETER_SUBKEY_FACTORY_CALIBRATION_TARGET}; -const static std::string kFactoryTestCalStatus{AUDIO_PARAMETER_SEC_GLOBAL_FACTORY_CALIBRATION_STATUS}; -const static std::string kFactoryTestCalOff{AUDIO_PARAMETER_SEC_GLOBAL_FACTORY_CALIBRATION_OFF}; -const static std::string kFactoryTestCalRead{AUDIO_PARAMETER_SEC_GLOBAL_FACTORY_CALIBRATION_READ}; -const static std::string kFactoryTestCalAmpTI{AUDIO_PARAMETER_VALUE_TAS_V2}; -const static std::string kVoiceFactoryEchoRefStatus{AUDIO_PARAMETER_SEC_GLOBAL_FACTORY_ECHOREF_STATUS}; -const static std::string kVoiceFactoryEchoRefValue{AUDIO_PARAMETER_SEC_GLOBAL_FACTORY_ECHOREF_VALUE}; - -// Effect -const static std::string kEffectOffloadVSPParam{AUDIO_PARAMETER_SEC_GLOBAL_EFFECT_OFFLOAD_VSP_PARAM}; -const static std::string kEffectSoundBalanceValue{AUDIO_PARAMETER_SEC_GLOBAL_EFFECT_SOUND_BALANCE_VALUE}; -const static std::string kEffectToMonoEnable{AUDIO_PARAMETER_SEC_GLOBAL_EFFECT_TO_MONO_ENABLE}; -const static std::string kRecordConversationEnergyKey{AUDIO_PARAMETER_SEC_GLOBAL_RECORD_CONVERSATION_ENERGY_KEY}; - -// Generic -const static std::string kAllSoundMuteEnable{AUDIO_PARAMETER_SEC_LOCAL_ALL_SOUND_MUTE_ENABLE}; -const static std::string kA2dpFormat{AUDIO_PARAMETER_SEC_LOCAL_A2DP_FORMAT}; -const static std::string kA2dpSuspendForBle{AUDIO_PARAMETER_SEC_LOCAL_A2DP_SUSPEND_FOR_BLE}; -const static std::string kBargeinMode{AUDIO_PARAMETER_SEC_GLOBAL_BARGEIN_MODE}; -const static std::string kBtScoCodecType{AUDIO_PARAMETER_SEC_GLOBAL_BT_SCO_CODEC_TYPE}; -const static std::string kEffectSoundBoosterDspSupport{AUDIO_PARAMETER_SEC_LOCAL_EFFECT_SOUNDBOOSTER_DSP_SUPPORT}; -const static std::string kFMRadioMode{AUDIO_PARAMETER_SEC_LOCAL_FMRADIO_MODE}; -const static std::string kFMRadioVolume{AUDIO_PARAMETER_SEC_LOCAL_FMRADIO_VOLUME}; -const static std::string kFMRadioMute{AUDIO_PARAMETER_SEC_GLOBAL_FMRADIO_MUTE}; -const static std::string kGameChatEnable{AUDIO_PARAMETER_SEC_LOCAL_GAME_CHAT_ENABLE}; -const static std::string kHwDisplayRotation{AUDIO_PARAMETER_SEC_GLOBAL_HW_DISPLAY_ROTATION}; -const static std::string kHwFlatMotionState{AUDIO_PARAMETER_SEC_LOCAL_HW_FLAT_MOTION_STATE}; -const static std::string kHwFolderState{AUDIO_PARAMETER_SEC_LOCAL_HW_FOLDER_STATE}; -const static std::string kHwInterfaceTestcase{AUDIO_PARAMETER_SEC_LOCAL_HW_INTERFACE_TESTCASE}; -const static std::string kHwSpeakerAmpBigData{AUDIO_PARAMETER_SEC_LOCAL_HW_SPEAKER_AMP_BIGDATA}; -const static std::string kHwSpeakerAmpBigDataSupport{AUDIO_PARAMETER_SEC_LOCAL_HW_SPEAKER_AMP_BIGDATA_SUPPORT}; -const static std::string kHwSpeakerAmpMaxTemperature{AUDIO_PARAMETER_SEC_GLOBAL_HW_SPEAKER_AMP_MAX_TEMPERATURE}; -const static std::string kHwSpeakerAmpTemperatureRCV{AUDIO_PARAMETER_SEC_GLOBAL_HW_SPEAKER_AMP_TEMPERATURE_RCV}; -const static std::string kHwSpeakerAmpTemperatureSPK{AUDIO_PARAMETER_SEC_GLOBAL_HW_SPEAKER_AMP_TEMPERATURE_SPK}; -const static std::string kInterpreterMode{AUDIO_PARAMETER_SEC_GLOBAL_INTERPRETER_MODE}; -const static std::string kKaraokeEnable{AUDIO_PARAMETER_SEC_LOCAL_KARAOKE_ENABLE}; -const static std::string kOffloadVariableRateSupported{"offloadVariableRateSupported"}; -const static std::string kPcmDumpApCallState{AUDIO_PARAMETER_SEC_GLOBAL_PCM_DUMP_AP_CALL_STATE}; -const static std::string kPcmDumpRecordState{AUDIO_PARAMETER_SEC_LOCAL_PCM_DUMP_RECORD_STATE}; -const static std::string kPcmDumpState{AUDIO_PARAMETER_SEC_GLOBAL_PCM_DUMP_STATE}; -const static std::string kRecordBeamformingMode{AUDIO_PARAMETER_SEC_GLOBAL_RECORD_BEAMFORMING_MODE}; -const static std::string kRecordInputLatency{AUDIO_PARAMETER_SEC_GLOBAL_RECORD_INPUT_LATENCY}; -const static std::string kRecordNSRISecurityEnable{AUDIO_PARAMETER_SEC_GLOBAL_RECORD_NSRI_SECURITY_ENABLE}; -const static std::string kRecordSecVoiceRecorderEnable{AUDIO_PARAMETER_SEC_GLOBAL_RECORD_SEC_VOICE_RECORDER_ENABLE}; -const static std::string kRecordTxInversion{AUDIO_PARAMETER_SEC_GLOBAL_RECORD_TX_INVERSION}; -const static std::string kRemoteMicEnable{AUDIO_PARAMETER_SEC_LOCAL_REMOTE_MIC_ENABLE}; -const static std::string kRemoteMicVolume{AUDIO_PARAMETER_SEC_LOCAL_REMOTE_MIC_VOLUME}; -const static std::string kScoRvcSupport{AUDIO_PARAMETER_SEC_GLOBAL_SCO_RVC_SUPPORT}; -const static std::string kSetupTestcase{AUDIO_PARAMETER_SEC_GLOBAL_SETUP_TESTCASE}; -const static std::string kSupportSecAudioFeature{AUDIO_PARAMETER_SEC_LOCAL_SUPPORT_SEC_AUDIO_FEATURE}; -const static std::string kVoiceWakeupRegisterVoiceKeyword{AUDIO_PARAMETER_SEC_GLOBAL_VOICE_WAKEUP_REGISTER_VOICE_KEYWORD}; -const static std::string kVoiceWakeupSeamlessEnable{AUDIO_PARAMETER_SEC_GLOBAL_VOICE_WAKEUP_SEAMLESS_ENABLE}; -const static std::string kVoipViaSmartView{AUDIO_PARAMETER_SEC_LOCAL_VOIP_VIA_SMART_VIEW}; -const static std::string kMultiMicMode{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_MODE}; -const static std::string kInputFlag{AUDIO_PARAMETER_SEC_LOCAL_RECORD_INPUT_FLAG}; - -// Stream Out -const static std::string kDualSpeakerAmpLeftPowerEnable{AUDIO_PARAMETER_SEC_LOCAL_DUAL_SPEAKER_AMP_LEFT_POWER_ENABLE}; -const static std::string kEffectUpscalerMode{AUDIO_PARAMETER_SEC_LOCAL_EFFECT_UPSCALER_MODE}; -const static std::string kHapticsSource{AUDIO_PARAMETER_SEC_LOCAL_HAPTIC_SOURCE}; -const static std::string kUhqUpdateFormat{AUDIO_PARAMETER_SEC_LOCAL_UHQ_UPDATE_FORMAT}; -const static std::string kVolumeVoice{AUDIO_PARAMETER_SEC_LOCAL_VOLUME_VOICE}; - -// Stream In - -// Subkey -const static std::string kDexKey{AUDIO_PARAMETER_SEC_LOCAL_DEX_KEY}; -const static std::string kSubkeyDexType{AUDIO_PARAMETER_SUBKEY_DEX_TYPE}; -const static std::string kSubkeyDexConnected{AUDIO_PARAMETER_SUBKEY_DEX_CONNECTED}; -const static std::string kEffectListenBackKey{AUDIO_PARAMETER_SEC_LOCAL_EFFECT_LISTENBACK_KEY}; -const static std::string kSubkeyEffectListenBackState{AUDIO_PARAMETER_SUBKEY_EFFECT_LISTENBACK_STATE}; -const static std::string kMultiMicKey{AUDIO_PARAMETER_SEC_LOCAL_MULTI_MIC_KEY}; -const static std::string kSubkeyMultiMicAudioFocusEnable{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_AUDIO_FOCUS_ENABLE}; -const static std::string kSubkeyMultiMicCameraDirection{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_CAMERA_DIRECTION}; -const static std::string kSubkeyMultiMicFocusCoordinate{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_FOCUS_COORDINATE}; -const static std::string kSubkeyMultiMicMode{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_MODE}; -const static std::string kSubkeyMultiMicPhoneOrientation{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_PHONE_ORIENTATION}; -const static std::string kSubkeyMultiMicSensitivityLevel{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_SENSITIVITY_LEVEL}; -const static std::string kSubkeyMultiMicZoomLevel{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_ZOOM_LEVEL}; -const static std::string kSubkeyMultiMicZoomMax{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_ZOOM_MAX}; -const static std::string kSubkeyMultiMicZoomMin{AUDIO_PARAMETER_SUBKEY_MULTI_MIC_ZOOM_MIN}; -const static std::string kSubkeyUhqWideResolution{AUDIO_PARAMETER_SEC_LOCAL_UHQ_WIDE_RESOLUTION_ENABLE}; -const static std::string kSubkeyUhqForceRouting{AUDIO_PARAMETER_SEC_LOCAL_UHQ_FORCE_ROUTING}; - -}; // namespace qti::audio::core::SecParameters diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/SoundDose.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/SoundDose.h deleted file mode 100755 index f82f4851..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/SoundDose.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include - -#include - -using aidl::android::media::audio::common::AudioDevice; - -namespace qti::audio::core { - -class SoundDose : public ::aidl::android::hardware::audio::core::sounddose::BnSoundDose { - public: - SoundDose() : mRs2Value(DEFAULT_MAX_RS2){}; - - ndk::ScopedAStatus setOutputRs2UpperBound(float in_rs2ValueDbA) override; - ndk::ScopedAStatus getOutputRs2UpperBound(float* _aidl_return) override; - ndk::ScopedAStatus registerSoundDoseCallback( - const std::shared_ptr& in_callback) override; - - private: - std::shared_ptr mCallback; - float mRs2Value; -}; - -} // namespace qti::audio::core \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Stream.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Stream.h deleted file mode 100755 index ff2de762..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Stream.h +++ /dev/null @@ -1,846 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#ifdef SEC_AUDIO_SAMSUNGRECORD -#include "AudioPreProcess.h" -#endif - -namespace qti::audio::core { - -class Telephony; - -// This class is similar to StreamDescriptor, but unlike -// the descriptor, it actually owns the objects implementing -// data exchange: FMQs etc, whereas StreamDescriptor only -// contains their descriptors. -class StreamContext { - public: - typedef ::android::AidlMessageQueue< - ::aidl::android::hardware::audio::core::StreamDescriptor::Command, - ::aidl::android::hardware::common::fmq::SynchronizedReadWrite> - CommandMQ; - typedef ::android::AidlMessageQueue< - ::aidl::android::hardware::audio::core::StreamDescriptor::Reply, - ::aidl::android::hardware::common::fmq::SynchronizedReadWrite> - ReplyMQ; - typedef ::android::AidlMessageQueue< - int8_t, ::aidl::android::hardware::common::fmq::SynchronizedReadWrite> - DataMQ; - - // Ensure that this value is not used by any of - // ::aidl::android::hardware::audio::core::StreamDescriptor.State enums - static constexpr int32_t STATE_CLOSED = -1; - - struct DebugParameters { - // An extra delay for transient states, in ms. - int transientStateDelayMs = 0; - // Force the "burst" command to move the SM to the TRANSFERRING state. - bool forceTransientBurst = false; - // Force the "drain" command to be synchronous, going directly to the - // IDLE state. - bool forceSynchronousDrain = false; - }; - - StreamContext() = default; - StreamContext( - std::unique_ptr commandMQ, std::unique_ptr replyMQ, - const ::aidl::android::media::audio::common::AudioFormatDescription& format, - const ::aidl::android::media::audio::common::AudioChannelLayout& channelLayout, - int sampleRate, std::unique_ptr dataMQ, - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCallback> asyncCallback, - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamOutEventCallback> - outEventCallback, - ::aidl::android::media::audio::common::AudioPortConfig mixPortConfig, - DebugParameters debugParameters, const int nominalLatency, - std::weak_ptr telephony) - : mCommandMQ(std::move(commandMQ)), - mInternalCommandCookie(std::rand()), - mReplyMQ(std::move(replyMQ)), - mFormat(format), - mChannelLayout(channelLayout), - mSampleRate(sampleRate), - mDataMQ(std::move(dataMQ)), - mAsyncCallback(asyncCallback), - mOutEventCallback(outEventCallback), - mMixPortConfig(mixPortConfig), - mNominalLatency(nominalLatency), - mDebugParameters(debugParameters), - mTelephony(telephony) {} - StreamContext(StreamContext&& other) - : mCommandMQ(std::move(other.mCommandMQ)), - mInternalCommandCookie(other.mInternalCommandCookie), - mReplyMQ(std::move(other.mReplyMQ)), - mFormat(other.mFormat), - mChannelLayout(other.mChannelLayout), - mSampleRate(other.mSampleRate), - mDataMQ(std::move(other.mDataMQ)), - mAsyncCallback(std::move(other.mAsyncCallback)), - mOutEventCallback(std::move(other.mOutEventCallback)), - mMixPortConfig(std::move(other.mMixPortConfig)), - mDebugParameters(std::move(other.mDebugParameters)), - mFrameCount(other.mFrameCount), - mNominalLatency(other.mNominalLatency), - mTelephony(other.mTelephony) {} - StreamContext& operator=(StreamContext&& other) { - mCommandMQ = std::move(other.mCommandMQ); - mInternalCommandCookie = other.mInternalCommandCookie; - mReplyMQ = std::move(other.mReplyMQ); - mFormat = std::move(other.mFormat); - mChannelLayout = std::move(other.mChannelLayout); - mSampleRate = other.mSampleRate; - mDataMQ = std::move(other.mDataMQ); - mAsyncCallback = std::move(other.mAsyncCallback); - mOutEventCallback = std::move(other.mOutEventCallback); - mMixPortConfig = std::move(other.mMixPortConfig); - mDebugParameters = std::move(other.mDebugParameters); - mFrameCount = other.mFrameCount; - mNominalLatency = other.mNominalLatency; - mTelephony = other.mTelephony; - return *this; - } - - void fillDescriptor(::aidl::android::hardware::audio::core::StreamDescriptor* desc); - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCallback> getAsyncCallback() - const { - return mAsyncCallback; - } - size_t getBufferSizeInFrames() const; - ::aidl::android::media::audio::common::AudioChannelLayout getChannelLayout() const { - return mChannelLayout; - } - CommandMQ* getCommandMQ() const { return mCommandMQ.get(); } - DataMQ* getDataMQ() const { return mDataMQ.get(); } - ::aidl::android::media::audio::common::AudioFormatDescription getFormat() const { - return mFormat; - } - ::aidl::android::media::audio::common::AudioIoFlags getFlags() const { - return mMixPortConfig.flags.value(); - } -#ifdef SEC_AUDIO_SAMSUNGRECORD - void setFlags(::aidl::android::media::audio::common::AudioIoFlags flags) { - mMixPortConfig.flags.value() = flags; - } -#endif - bool getForceTransientBurst() const { return mDebugParameters.forceTransientBurst; } - bool getForceSynchronousDrain() const { return mDebugParameters.forceSynchronousDrain; } - size_t getFrameSize() const; - int getInternalCommandCookie() const { return mInternalCommandCookie; } - int32_t getMixPortHandle() const { - return mMixPortConfig.ext.get<::aidl::android::media::audio::common::AudioPortExt::mix>() - .handle; - } - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamOutEventCallback> - getOutEventCallback() const { - return mOutEventCallback; - } - int getPortId() const { return mMixPortConfig.portId; } - ReplyMQ* getReplyMQ() const { return mReplyMQ.get(); } - int getTransientStateDelayMs() const { return mDebugParameters.transientStateDelayMs; } - int getSampleRate() const { return mSampleRate; } - bool isValid() const; - // 'reset' is called on a Binder thread when closing the stream. Does not use - // locking because it only cleans MQ pointers which were also set on the Binder thread. - void reset(); - // 'advanceFrameCount' and 'getFrameCount' are only called on the worker thread. - long advanceFrameCount(size_t increase) { return mFrameCount += increase; } - long getFrameCount() const { return mFrameCount; } - const ::aidl::android::media::audio::common::AudioPortConfig& getMixPortConfig() const { - return mMixPortConfig; - } - int32_t getNominalLatencyMs() const { return mNominalLatency; } - std::weak_ptr getTelephony() { return mTelephony; } - - private: - std::unique_ptr mCommandMQ; - int mInternalCommandCookie; // The value used to confirm that the command - // was posted internally - std::unique_ptr mReplyMQ; - ::aidl::android::media::audio::common::AudioFormatDescription mFormat; - ::aidl::android::media::audio::common::AudioChannelLayout mChannelLayout; - int mSampleRate; - ::aidl::android::media::audio::common::AudioPortConfig mMixPortConfig; - std::unique_ptr mDataMQ; - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCallback> mAsyncCallback; - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamOutEventCallback> - mOutEventCallback; // Only used by output streams - DebugParameters mDebugParameters; - long mFrameCount = 0; - int32_t mNominalLatency = 0; - std::weak_ptr mTelephony; -}; - -// This interface provides operations of the stream which are executed on the worker thread. -struct DriverInterface { - virtual ~DriverInterface() = default; - // All the methods below are called on the worker thread. - // This function is only called once. - virtual ::android::status_t init() = 0; - virtual ::android::status_t drain( - ::aidl::android::hardware::audio::core::StreamDescriptor::DrainMode mode) = 0; - virtual ::android::status_t flush() = 0; - virtual ::android::status_t pause() = 0; - virtual ::android::status_t standby() = 0; - virtual ::android::status_t start() = 0; - virtual ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount, - int32_t* latencyMs) = 0; - // No need to implement 'refinePosition' unless the driver can provide more precise - // data than just total frame count. For example, the driver may correctly account - // for any intermediate buffers. - virtual ::android::status_t refinePosition( - ::aidl::android::hardware::audio::core::StreamDescriptor::Reply* /*reply*/) { - return ::android::OK; - } - - // This function is only called once. - // Implementers must provide implementation to shutdown the platform resources - virtual void shutdown() { return;} -}; - -class StreamWorkerCommonLogic : public ::android::hardware::audio::common::StreamLogic { - public: - bool isClosed() const { - return static_cast(mState.load()) == StreamContext::STATE_CLOSED; - } - void setClosed() { - mState = static_cast<::aidl::android::hardware::audio::core::StreamDescriptor::State>( - StreamContext::STATE_CLOSED); - } - void setIsConnected(bool connected) { mIsConnected = connected; } - - /** - * IStreamCallback equivalents for StreamWorker - **/ - virtual void publishTransferReady() {} - virtual void publishDrainReady() {} - virtual void publishError() {} - - protected: - using DataBufferElement = int8_t; - - StreamWorkerCommonLogic(StreamContext* context, DriverInterface* driver) - : mContext(context), - mDriver(driver), - mTransientStateDelayMs(context->getTransientStateDelayMs()) {} - pid_t getTid() const; - std::string init() override; - void populateReply(::aidl::android::hardware::audio::core::StreamDescriptor::Reply* reply, - bool isConnected) const; - void populateReplyWrongState( - ::aidl::android::hardware::audio::core::StreamDescriptor::Reply* reply, - const ::aidl::android::hardware::audio::core::StreamDescriptor::Command& command) const; - void switchToTransientState( - ::aidl::android::hardware::audio::core::StreamDescriptor::State state) { - mState = state; - mTransientStateStart = std::chrono::steady_clock::now(); - } - - // The context is only used for reading, except for updating the frame count, - // which happens on the worker thread only. - StreamContext* const mContext; - DriverInterface* const mDriver; - // Atomic fields are used both by the main and worker threads. - std::atomic mIsConnected = false; - static_assert(std::atomic<::aidl::android::hardware::audio::core::StreamDescriptor::State>:: - is_always_lock_free); - std::atomic<::aidl::android::hardware::audio::core::StreamDescriptor::State> mState = - ::aidl::android::hardware::audio::core::StreamDescriptor::State::STANDBY; - std::atomic<::aidl::android::hardware::audio::core::StreamDescriptor::DrainMode> - mRecentDrainMode = - ::aidl::android::hardware::audio::core::StreamDescriptor::DrainMode::DRAIN_UNSPECIFIED; - // All fields below are used on the worker thread only. - const std::chrono::duration mTransientStateDelayMs; - std::chrono::time_point mTransientStateStart; - // We use an array and the "size" field instead of a vector to be able to - // detect memory allocation issues. - std::unique_ptr mDataBuffer; - size_t mDataBufferSize; - /** - * only used in Asynchrous Stream(In|Out) context, to synchronize the - * callbacks from the hardware. - * Hardware sends callback any time irrespective of the Stream State. - * Hence the synchronization. - **/ - std::mutex mAsyncMutex; - enum StreamCallbackType { - TR = 1, // TransferReady - DR = 2, // DrainReady - ER = 3, // Error - }; - std::optional mPendingCallBack = std::nullopt; - std::condition_variable mPendingCV; -}; - -// This interface is used to decouple stream implementations from a concrete -// StreamWorker implementation. -struct StreamWorkerInterface { - using CreateInstance = - std::function; - virtual ~StreamWorkerInterface() = default; - virtual bool isClosed() const = 0; - virtual void setIsConnected(bool isConnected) = 0; - virtual void setClosed() = 0; - virtual bool start() = 0; - virtual pid_t getTid() = 0; - virtual void join() = 0; - virtual void publishTransferReady() = 0; - virtual void publishDrainReady() = 0; - virtual void publishError() = 0; -}; - -template -class StreamWorkerImpl : public StreamWorkerInterface, - public ::android::hardware::audio::common::StreamWorker { - using WorkerImpl = ::android::hardware::audio::common::StreamWorker; - - public: - StreamWorkerImpl(StreamContext* context, DriverInterface* driver) - : WorkerImpl(context, driver) {} - bool isClosed() const override { return WorkerImpl::isClosed(); } - void setIsConnected(bool isConnected) override { WorkerImpl::setIsConnected(isConnected); } - void setClosed() override { WorkerImpl::setClosed(); } - bool start() override { - // This is an "audio service thread," must have elevated priority. - return WorkerImpl::start(WorkerImpl::kThreadName, ANDROID_PRIORITY_URGENT_AUDIO); - } - pid_t getTid() override { return WorkerImpl::getTid(); } - void join() override { return WorkerImpl::join(); } - void publishTransferReady() override { return WorkerImpl::publishTransferReady(); }; - void publishDrainReady() override { return WorkerImpl::publishDrainReady(); } - void publishError() override { return WorkerImpl::publishError(); } -}; - -class StreamInWorkerLogic : public StreamWorkerCommonLogic { - public: - static const std::string kThreadName; - StreamInWorkerLogic(StreamContext* context, DriverInterface* driver) - : StreamWorkerCommonLogic(context, driver) {} - - protected: - Status cycle() override; - - private: - bool read(size_t clientSize, - ::aidl::android::hardware::audio::core::StreamDescriptor::Reply* reply); -}; -using StreamInWorker = StreamWorkerImpl; - -class StreamOutWorkerLogic : public StreamWorkerCommonLogic { - public: - static const std::string kThreadName; - StreamOutWorkerLogic(StreamContext* context, DriverInterface* driver) - : StreamWorkerCommonLogic(context, driver), - mEventCallback(context->getOutEventCallback()) {} - void publishTransferReady() override; - void publishDrainReady() override; - void publishError() override; - - protected: - Status cycle() override; - - private: - bool write(size_t clientSize, - ::aidl::android::hardware::audio::core::StreamDescriptor::Reply* reply); - - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamOutEventCallback> mEventCallback; -}; -using StreamOutWorker = StreamWorkerImpl; - -// This interface provides operations of the stream which are executed on a Binder pool thread. -// These methods originate both from the AIDL interface and its implementation. -struct StreamCommonInterface { - using ConnectedDevices = std::vector<::aidl::android::media::audio::common::AudioDevice>; - using Metadata = - std::variant<::aidl::android::hardware::audio::common::SinkMetadata /*IStreamIn*/, - ::aidl::android::hardware::audio::common::SourceMetadata /*IStreamOut*/>; - - static constexpr bool isInput(const Metadata& metadata) { return metadata.index() == 0; } - - virtual ~StreamCommonInterface() = default; - // Methods below originate from the 'IStreamCommon' interface. - // This is semantically equivalent to inheriting from 'IStreamCommon' with a benefit - // that concrete stream implementations can inherit both from this interface and IStreamIn/Out. - virtual ndk::ScopedAStatus close() = 0; - virtual ndk::ScopedAStatus prepareToClose() = 0; - virtual ndk::ScopedAStatus updateHwAvSyncId(int32_t in_hwAvSyncId) = 0; - virtual ndk::ScopedAStatus getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return) = 0; - virtual ndk::ScopedAStatus setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async) = 0; - virtual ndk::ScopedAStatus addEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& - in_effect) = 0; - virtual ndk::ScopedAStatus removeEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& - in_effect) = 0; - - // Methods below are common for both 'IStreamIn' and 'IStreamOut'. Note that - // 'updateMetadata' in them uses an individual structure which is wrapped here. - // The 'Common' suffix is added to distinguish them from the methods from 'IStreamIn/Out'. - virtual ndk::ScopedAStatus getStreamCommonCommon( - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCommon>* - _aidl_return) = 0; - virtual ndk::ScopedAStatus updateMetadataCommon(const Metadata& metadata) = 0; - virtual Metadata getMetadataCommon() = 0; - - // Methods below are called by implementation of 'IModule', 'IStreamIn' and 'IStreamOut'. - virtual ndk::ScopedAStatus initInstance( - const std::shared_ptr& delegate) = 0; - virtual const StreamContext& getContext() const = 0; - virtual bool isClosed() const = 0; - virtual const ConnectedDevices& getConnectedDevices() const = 0; - virtual ndk::ScopedAStatus setConnectedDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) = 0; - /** - * API to configure the connected devices based on the latest platform configuration - * Example: whenever there is a HAC enabled on the platform, we would want to reconfigure - * VOIP playback stream with HAC enabled Handset speaker. - */ - virtual ndk::ScopedAStatus reconfigureConnectedDevices() = 0; - virtual ndk::ScopedAStatus configureMMapStream(int32_t* fd, int64_t* burstSizeFrames, - int32_t* flags, int32_t* bufferSizeFrames) = 0; - virtual void setStreamMicMute(const bool muted) = 0; -#ifdef SEC_AUDIO_COMMON - virtual ndk::ScopedAStatus ForceSetDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, - bool force = false) = 0; - virtual bool isStreamUsecase(Usecase tag) = 0; - virtual bool isDeviceAvailable(pal_device_id_t pal_device) = 0; - virtual bool HasPalStreamHandle() = 0; - virtual void forceShutdown() = 0; -#endif -#ifdef SEC_AUDIO_INTERPRETER_MODE - virtual void RerouteForInterpreter() = 0; -#endif -}; - -// This is equivalent to automatically generated 'IStreamCommonDelegator' but uses -// a weak pointer to avoid creating a reference loop. The loop will occur because -// 'IStreamIn/Out.getStreamCommon' must return the same instance every time, thus -// the stream implementation must hold a strong pointer to an instance of 'IStreamCommon'. -// Also, we use 'StreamCommonInterface' here instead of 'IStreamCommon'. -class StreamCommonDelegator : public ::aidl::android::hardware::audio::core::BnStreamCommon { - public: - explicit StreamCommonDelegator(const std::shared_ptr& delegate) - : mDelegate(delegate) {} - - private: - ndk::ScopedAStatus close() override { - auto delegate = mDelegate.lock(); - return delegate != nullptr ? delegate->close() - : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - ndk::ScopedAStatus prepareToClose() override { - auto delegate = mDelegate.lock(); - return delegate != nullptr ? delegate->prepareToClose() - : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - ndk::ScopedAStatus updateHwAvSyncId(int32_t in_hwAvSyncId) override { - auto delegate = mDelegate.lock(); - return delegate != nullptr ? delegate->updateHwAvSyncId(in_hwAvSyncId) - : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - ndk::ScopedAStatus getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return) - override { - auto delegate = mDelegate.lock(); - return delegate != nullptr ? delegate->getVendorParameters(in_ids, _aidl_return) - : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - ndk::ScopedAStatus setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async) override { - auto delegate = mDelegate.lock(); - return delegate != nullptr ? delegate->setVendorParameters(in_parameters, in_async) - : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - ndk::ScopedAStatus addEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override { - auto delegate = mDelegate.lock(); - return delegate != nullptr ? delegate->addEffect(in_effect) - : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - ndk::ScopedAStatus removeEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override { - auto delegate = mDelegate.lock(); - return delegate != nullptr ? delegate->removeEffect(in_effect) - : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - // It is possible that on the client side the proxy for IStreamCommon will - // outlive the IStream* instance, and the server side IStream* instance will - // get destroyed while this IStreamCommon instance is still alive. - std::weak_ptr mDelegate; -}; - -// The implementation of DriverInterface must be provided by each concrete stream implementation. -// Note that StreamCommonImpl does not own the context. This is to support swapping on the fly -// implementations of the stream while keeping the same IStreamIn/Out instance. It's that instance -// who must be owner of the context. -class StreamCommonImpl : virtual public StreamCommonInterface, virtual public DriverInterface { - public: - StreamCommonImpl(StreamContext* context, const Metadata& metadata, - const StreamWorkerInterface::CreateInstance& createWorker) - : mContextRef(*context), mMetadata(metadata), mWorker(createWorker(context, this)) {} - StreamCommonImpl(StreamContext* context, const Metadata& metadata) - : StreamCommonImpl(context, metadata, isInput(metadata) ? getDefaultInWorkerCreator() - : getDefaultOutWorkerCreator()) {} - virtual ~StreamCommonImpl() override; - ndk::ScopedAStatus close() override; - ndk::ScopedAStatus prepareToClose() override; - ndk::ScopedAStatus updateHwAvSyncId(int32_t in_hwAvSyncId) override; - ndk::ScopedAStatus getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return) - override; - ndk::ScopedAStatus setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async) override; - ndk::ScopedAStatus addEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override; - ndk::ScopedAStatus removeEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override; - - ndk::ScopedAStatus getStreamCommonCommon( - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCommon>* _aidl_return) - override; - ndk::ScopedAStatus updateMetadataCommon(const Metadata& metadata) override; - Metadata getMetadataCommon() { return mMetadata; } - - ndk::ScopedAStatus initInstance( - const std::shared_ptr& delegate) override; - const StreamContext& getContext() const override { return mContextRef; } - bool isClosed() const override { return mWorker->isClosed(); } - const ConnectedDevices& getConnectedDevices() const override { return mConnectedDevices; } - ndk::ScopedAStatus setConnectedDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) - override; - void setStreamMicMute(const bool muted) override; - ndk::ScopedAStatus configureMMapStream(int32_t* fd, int64_t* burstSizeFrames, int32_t* flags, - int32_t* bufferSizeFrames) override; -#ifdef SEC_AUDIO_COMMON - ndk::ScopedAStatus ForceSetDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, - bool force = false) override; - bool isStreamUsecase(Usecase tag) override; - bool isDeviceAvailable(pal_device_id_t pal_device) override; - bool HasPalStreamHandle() override; - void forceShutdown() override; - bool isCustomKeyRouted(const int ck_id); -#endif -#ifdef SEC_AUDIO_INTERPRETER_MODE - void RerouteForInterpreter() override; -#endif - - // start of Equivalent of IStreamCallbacks - void publishTransferReady() { mWorker->publishTransferReady(); } - - void publishDrainReady() { mWorker->publishDrainReady(); } - - void publishError() { mWorker->publishError(); } - // end of Equivalent of IStreamCallbacks - - protected: - static StreamWorkerInterface::CreateInstance getDefaultInWorkerCreator() { - return [](StreamContext* ctx, DriverInterface* driver) -> StreamWorkerInterface* { - return new StreamInWorker(ctx, driver); - }; - } - static StreamWorkerInterface::CreateInstance getDefaultOutWorkerCreator() { - return [](StreamContext* ctx, DriverInterface* driver) -> StreamWorkerInterface* { - return new StreamOutWorker(ctx, driver); - }; - } - virtual void onClose() = 0; - void stopWorker(); - - const StreamContext& mContextRef; - Metadata mMetadata; - std::unique_ptr mWorker; - ChildInterface mCommon; - ConnectedDevices mConnectedDevices; -#ifdef SEC_AUDIO_COMMON - ConnectedDevices mPreviousDevices; - std::vector mPalDevices{}; -#endif -}; - -// Note: 'StreamIn/Out' can not be used on their own. Instead, they must be used for defining -// concrete input/output stream implementations. -class StreamIn : virtual public StreamCommonInterface, - public ::aidl::android::hardware::audio::core::BnStreamIn { - public: - virtual ~StreamIn() override = default; - ndk::ScopedAStatus getMetadata( - ::aidl::android::hardware::audio::common::SinkMetadata& out_sinkMetadata) { - out_sinkMetadata = std::get<::aidl::android::hardware::audio::common::SinkMetadata>( - getMetadataCommon()); - return ndk::ScopedAStatus::ok(); - } - virtual int32_t setAggregateSinkMetadata(bool) { return 0; } -#ifdef SEC_AUDIO_SAMSUNGRECORD - std::shared_ptr PreProcessInit(); -#endif - - protected: - void defaultOnClose(); - - ndk::ScopedAStatus getStreamCommon( - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCommon>* _aidl_return) - override { - return getStreamCommonCommon(_aidl_return); - } - ndk::ScopedAStatus updateMetadata(const ::aidl::android::hardware::audio::common::SinkMetadata& - in_sinkMetadata) override { - return updateMetadataCommon(in_sinkMetadata); - } - ndk::ScopedAStatus getActiveMicrophones( - std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo>* _aidl_return) - override; - ndk::ScopedAStatus getMicrophoneDirection(MicrophoneDirection* _aidl_return) override; - ndk::ScopedAStatus setMicrophoneDirection(MicrophoneDirection in_direction) override; - ndk::ScopedAStatus getMicrophoneFieldDimension(float* _aidl_return) override; - ndk::ScopedAStatus setMicrophoneFieldDimension(float in_zoom) override; - ndk::ScopedAStatus getHwGain(std::vector* _aidl_return) override; - ndk::ScopedAStatus setHwGain(const std::vector& in_channelGains) override; - - friend class ndk::SharedRefBase; - - StreamIn(StreamContext&& context, - const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones); - - StreamContext mContext; - const std::map<::aidl::android::media::audio::common::AudioDevice, std::string> mMicrophones; -#ifdef SEC_AUDIO_SAMSUNGRECORD - std::shared_ptr preprocess_; - friend class AudioPreProcess; -#endif -}; - -class StreamOut : virtual public StreamCommonInterface, - public ::aidl::android::hardware::audio::core::BnStreamOut { - public: - virtual ~StreamOut() override = default; - ndk::ScopedAStatus getMetadata( - ::aidl::android::hardware::audio::common::SourceMetadata& out_sourceMetadata) { - out_sourceMetadata = std::get<::aidl::android::hardware::audio::common::SourceMetadata>( - getMetadataCommon()); - return ndk::ScopedAStatus::ok(); - } - virtual int32_t setAggregateSourceMetadata(bool) { return 0; } -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - virtual int updateListenback(bool on) { return 0; } -#endif - protected: - void defaultOnClose(); - ndk::ScopedAStatus getStreamCommon( - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCommon>* _aidl_return) - override { - return getStreamCommonCommon(_aidl_return); - } - ndk::ScopedAStatus updateMetadata( - const ::aidl::android::hardware::audio::common::SourceMetadata& in_sourceMetadata) - override { - return updateMetadataCommon(in_sourceMetadata); - } - ndk::ScopedAStatus updateOffloadMetadata( - const ::aidl::android::hardware::audio::common::AudioOffloadMetadata& - in_offloadMetadata) override; - ndk::ScopedAStatus getHwVolume(std::vector* _aidl_return) override; - ndk::ScopedAStatus setHwVolume(const std::vector& in_channelVolumes) override; - ndk::ScopedAStatus getAudioDescriptionMixLevel(float* _aidl_return) override; - ndk::ScopedAStatus setAudioDescriptionMixLevel(float in_leveldB) override; - ndk::ScopedAStatus getDualMonoMode( - ::aidl::android::media::audio::common::AudioDualMonoMode* _aidl_return) override; - ndk::ScopedAStatus setDualMonoMode( - ::aidl::android::media::audio::common::AudioDualMonoMode in_mode) override; - ndk::ScopedAStatus getRecommendedLatencyModes( - std::vector<::aidl::android::media::audio::common::AudioLatencyMode>* _aidl_return) - override; - ndk::ScopedAStatus setLatencyMode( - ::aidl::android::media::audio::common::AudioLatencyMode in_mode) override; - ndk::ScopedAStatus getPlaybackRateParameters( - ::aidl::android::media::audio::common::AudioPlaybackRate* _aidl_return) override; - ndk::ScopedAStatus setPlaybackRateParameters( - const ::aidl::android::media::audio::common::AudioPlaybackRate& in_playbackRate) - override; - ndk::ScopedAStatus selectPresentation(int32_t in_presentationId, int32_t in_programId) override; - - friend class ndk::SharedRefBase; - - StreamOut(StreamContext&& context, - const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>& - offloadInfo); - - StreamContext mContext; - const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo> mOffloadInfo; - std::optional<::aidl::android::hardware::audio::common::AudioOffloadMetadata> mOffloadMetadata; -}; - -// The recommended way to create a stream instance. -// 'StreamImpl' is the concrete stream implementation, 'StreamInOrOut' is either 'StreamIn' or -// 'StreamOut', the rest are the arguments forwarded to the constructor of 'StreamImpl'. -template -ndk::ScopedAStatus createStreamInstance(std::shared_ptr* result, Args&&... args) { - std::shared_ptr stream = - ::ndk::SharedRefBase::make(std::forward(args)...); - RETURN_STATUS_IF_ERROR(stream->initInstance(stream)); - *result = std::move(stream); - return ndk::ScopedAStatus::ok(); -} - -class StreamWrapper { - public: - explicit StreamWrapper(const std::shared_ptr& streamIn) - : mStream(streamIn), mStreamBinder(streamIn->asBinder()) {} - explicit StreamWrapper(const std::shared_ptr& streamOut) - : mStream(streamOut), mStreamBinder(streamOut->asBinder()) {} - ndk::SpAIBinder getBinder() const { return mStreamBinder; } - bool isStreamOpen() const { - auto s = mStream.lock(); - return s && !s->isClosed(); - } - ndk::ScopedAStatus setConnectedDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) { - auto s = mStream.lock(); - if (s) return s->setConnectedDevices(devices); - return ndk::ScopedAStatus::ok(); - } - - void setStreamMicMute(const bool muted) { - auto s = mStream.lock(); - if (s) return s->setStreamMicMute(muted); - return; - } - - ndk::ScopedAStatus configureMMapStream(int32_t* fd, int64_t* burstSizeFrames, int32_t* flags, - int32_t* bufferSizeFrames) { - auto s = mStream.lock(); - if (s) return s->configureMMapStream(fd, burstSizeFrames, flags, bufferSizeFrames); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - -#ifdef SEC_AUDIO_COMMON - ndk::ScopedAStatus ForceSetDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, - bool force = false) { - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE); - } - bool isStreamUsecase(Usecase tag) { return false; }; - bool isDeviceAvailable(pal_device_id_t pal_device) { return false; }; - bool HasPalStreamHandle() { return false; }; - void forceShutdown() { return; }; -#endif - - private: - std::weak_ptr mStream; - ndk::SpAIBinder mStreamBinder; -}; - -class Streams { - public: - Streams() = default; - Streams(const Streams&) = delete; - Streams& operator=(const Streams&) = delete; - size_t count(int32_t id) { - // Streams do not remove themselves from the collection on close. - erase_if(mStreams, [](const auto& pair) { return !pair.second.isStreamOpen(); }); - return mStreams.count(id); - } - void insert(int32_t portId, int32_t portConfigId, StreamWrapper sw) { - mStreams.insert(std::pair{portConfigId, sw}); - mStreams.insert(std::pair{portId, std::move(sw)}); - } - ndk::ScopedAStatus setStreamConnectedDevices( - int32_t portConfigId, - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) { - if (auto it = mStreams.find(portConfigId); it != mStreams.end()) { - return it->second.setConnectedDevices(devices); - } - return ndk::ScopedAStatus::ok(); - } - void setStreamMicMute(int32_t portConfigId, const bool muted) { - if (auto it = mStreams.find(portConfigId); it != mStreams.end()) { - return it->second.setStreamMicMute(muted); - } - return; - } - std::string toString() const { - std::ostringstream os; - os << std::endl << " --- mStreams ---" << std::endl; - std::for_each(mStreams.cbegin(), mStreams.cend(), [&](const auto& pair) { - os << "PortConfigId/PortId:" << pair.first << std::endl; - }); - os << std::endl << " --- mStreams end ---" << std::endl << std::endl; - return os.str(); - } - - private: - // Maps port ids and port config ids to streams. Multimap because a port - // (not port config) can have multiple streams opened on it. - std::multimap mStreams; -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/StreamInPrimary.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/StreamInPrimary.h deleted file mode 100755 index 18283d7b..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/StreamInPrimary.h +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include - -#ifdef SEC_AUDIO_COMMON -#include "SecFTM.h" -#endif -#ifdef SEC_AUDIO_DYNAMIC_NREC -#include "AudioEffect.h" -#endif - -namespace qti::audio::core { - -class StreamInPrimary : public StreamIn, public StreamCommonImpl { - public: - friend class ndk::SharedRefBase; - StreamInPrimary( - StreamContext&& context, - const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata, - const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones); - - virtual ~StreamInPrimary() override; - - int32_t setAggregateSinkMetadata(bool voiceActive) override; - // Methods of 'DriverInterface'. - ::android::status_t init() override; - ::android::status_t drain( - ::aidl::android::hardware::audio::core::StreamDescriptor::DrainMode) override; - ::android::status_t flush() override; - ::android::status_t pause() override; - ::android::status_t standby() override; - ::android::status_t start() override; - ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount, - int32_t* latencyMs) override; - ::android::status_t refinePosition( - ::aidl::android::hardware::audio::core::StreamDescriptor::Reply* - /*reply*/) override; - void shutdown() override; - - // methods of StreamCommonInterface - - ndk::ScopedAStatus getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return) - override; - ndk::ScopedAStatus setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async) override; - ndk::ScopedAStatus addEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override; - ndk::ScopedAStatus removeEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override; - - ndk::ScopedAStatus updateMetadataCommon(const Metadata& metadata) override; - - ndk::ScopedAStatus getActiveMicrophones( - std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo>* _aidl_return) - override; - - // Methods called IModule - ndk::ScopedAStatus setConnectedDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) - override; - ndk::ScopedAStatus reconfigureConnectedDevices() override; - void setStreamMicMute(const bool muted) override; - ndk::ScopedAStatus configureMMapStream(int32_t* fd, int64_t* burstSizeFrames, int32_t* flags, - int32_t* bufferSizeFrames) override; -#ifdef SEC_AUDIO_COMMON - ndk::ScopedAStatus ForceSetDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, - bool force = false) override; - bool isStreamUsecase(Usecase tag) override { return (mTag == tag); } - bool isDeviceAvailable(pal_device_id_t pal_device) override; - bool HasPalStreamHandle() override { return (mPalHandle != nullptr) ? true : false; } - void forceShutdown() override { return shutdown(); } -#endif -#ifdef SEC_AUDIO_INTERPRETER_MODE - void RerouteForInterpreter() override; -#endif -#ifdef SEC_AUDIO_CAMCORDER - bool isTxDataInvertable(); -#endif - void onClose() override { defaultOnClose(); } - static std::mutex sinkMetadata_mutex_; - void checkHearingAidRoutingForVoice(const Metadata& metadata, bool voiceActive); - - protected: - /* - * This API opens, configures and starts pal stream. - * also responsible for validity of pal handle. - */ - void configure(); - void resume(); - void shutdown_I(); - /* burst zero indicates that burst command with zero bytes issued from framework */ - ::android::status_t burstZero(); - ::android::status_t startMMAP(); - ::android::status_t stopMMAP(); - size_t getPlatformDelay() const noexcept; - - // API which are *_I are internal - ndk::ScopedAStatus configureConnectedDevices_I(); - -#ifdef SEC_AUDIO_BLE_OFFLOAD - void updateRecordMetadataForBLE(); -#endif - - const Usecase mTag; - const std::string mTagName; - const size_t mFrameSizeBytes; - - // All the public must check the validity of this resource, if using - pal_stream_handle_t* mPalHandle{nullptr}; - - std::variant mExt; - - // references - Platform& mPlatform{Platform::getInstance()}; - const ::aidl::android::media::audio::common::AudioPortConfig& mMixPortConfig; -#ifdef SEC_AUDIO_SAMSUNGRECORD - unsigned int mDeviceChannels; - audio_format_t mDeviceFormat; -#endif -#ifdef SEC_AUDIO_COMMON - SecFTM& mSecFTM{SecFTM::getInstance()}; -#endif -#ifdef SEC_AUDIO_DYNAMIC_NREC - AudioEffect& mAudioEffect{AudioEffect::getInstance()}; -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - AudioExtension& mAudExt{AudioExtension::getInstance()}; -#endif - private: - ::android::status_t onReadError(const size_t sleepFrameCount); - struct BufferConfig getBufferConfig(); - void applyEffects(); - - bool mAECEnabled = false; - bool mNSEnabled = false; - bool mEffectsApplied = true; - std::string mLogPrefix = ""; -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/StreamOutPrimary.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/StreamOutPrimary.h deleted file mode 100755 index c29ed81f..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/StreamOutPrimary.h +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include - -#ifdef SEC_AUDIO_COMMON -#include "SecFTM.h" -#endif - -namespace qti::audio::core { - -class StreamOutPrimary : public StreamOut, public StreamCommonImpl, public PlatformStreamCallback { - public: - friend class ndk::SharedRefBase; - StreamOutPrimary(StreamContext&& context, - const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata, - const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>& - offloadInfo); - - virtual ~StreamOutPrimary() override; - int32_t setAggregateSourceMetadata(bool voiceActive) override; - - // Methods of 'DriverInterface'. - ::android::status_t init() override; - ::android::status_t drain( - ::aidl::android::hardware::audio::core::StreamDescriptor::DrainMode) override; - ::android::status_t flush() override; - ::android::status_t pause() override; - ::android::status_t standby() override; - ::android::status_t start() override; - ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount, - int32_t* latencyMs) override; - ::android::status_t refinePosition( - ::aidl::android::hardware::audio::core::StreamDescriptor::Reply* - /*reply*/) override; - void shutdown() override; - - // methods of StreamCommonInterface - - ndk::ScopedAStatus getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return) - override; - ndk::ScopedAStatus setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async) override; - ndk::ScopedAStatus addEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override; - ndk::ScopedAStatus removeEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) - override; - - ndk::ScopedAStatus updateMetadataCommon(const Metadata& metadata) override; - - // Methods of IStreamOut - ndk::ScopedAStatus updateOffloadMetadata( - const ::aidl::android::hardware::audio::common::AudioOffloadMetadata& - in_offloadMetadata) override; - - ndk::ScopedAStatus getHwVolume(std::vector* _aidl_return) override; - ndk::ScopedAStatus setHwVolume(const std::vector& in_channelVolumes) override; - - ndk::ScopedAStatus getPlaybackRateParameters( - ::aidl::android::media::audio::common::AudioPlaybackRate* _aidl_return) override; - ndk::ScopedAStatus setPlaybackRateParameters( - const ::aidl::android::media::audio::common::AudioPlaybackRate& in_playbackRate) - override; - // Methods called IModule - ndk::ScopedAStatus setConnectedDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) - override; - ndk::ScopedAStatus reconfigureConnectedDevices() override; - -#ifdef SEC_AUDIO_COMMON - ndk::ScopedAStatus ForceSetDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, - bool force = false) override; - bool isStreamUsecase(Usecase tag) override { return (mTag == tag); } - bool isDeviceAvailable(pal_device_id_t pal_device) override; - bool HasPalStreamHandle() override { return (mPalHandle != nullptr) ? true : false; } - bool setSecVolume(const std::vector& volumes); - void forceShutdown() override { return shutdown(); } -#endif -#ifdef SEC_AUDIO_HDMI // { SUPPORT_VOIP_VIA_SMART_MONITOR - void RerouteForVoipSmartMonitor( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& previousDevices = {}); -#endif // } SUPPORT_VOIP_VIA_SMART_MONITOR -#ifdef SEC_AUDIO_CALL_VOIP - void RerouteForVoipHeadphone(); -#endif -#ifdef SEC_AUDIO_FMRADIO - void RouteFMRadioStream(); -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - void checkAndSwitchListenbackMode(bool on); - int updateListenback(bool on); -#endif - - ndk::ScopedAStatus configureMMapStream(int32_t* fd, int64_t* burstSizeFrames, int32_t* flags, - int32_t* bufferSizeFrames) override; - - void onClose() override { defaultOnClose(); } - - ndk::ScopedAStatus setLatencyMode( - ::aidl::android::media::audio::common::AudioLatencyMode in_mode) override; - ndk::ScopedAStatus getRecommendedLatencyModes( - std::vector<::aidl::android::media::audio::common::AudioLatencyMode>* _aidl_return) override; - - bool isStreamOutPrimary() { return (mTag == Usecase::PRIMARY_PLAYBACK) ? true : false; } - static std::mutex sourceMetadata_mutex_; - - // Methods from PlatformStreamCallback - void onTransferReady() override; - void onDrainReady() override; - void onError() override; - - protected: - /* - * opens, configures and starts pal stream, also validates the pal handle. - */ - void configure(); - void resume(); - void shutdown_I(); - /* burst zero indicates that burst command with zero bytes issued from framework */ - ::android::status_t burstZero(); - ::android::status_t startMMAP(); - ::android::status_t stopMMAP(); - size_t getPlatformDelay() const noexcept; - ::android::status_t onWriteError(const size_t sleepFrameCount); - - // This API calls startEffect/stopEffect only on offload/pcm offload outputs. - void enableOffloadEffects(const bool enable); - - // API which are *_I are internal - ndk::ScopedAStatus configureConnectedDevices_I(); - - const Usecase mTag; - const std::string mTagName; - const size_t mFrameSizeBytes; - bool mIsPaused{false}; - std::vector mVolumes{}; - bool mHwVolumeSupported = false; - bool mHwFlushSupported = false; - bool mHwPauseSupported = false; - // check validaty of mPalHandle before use - pal_stream_handle_t* mPalHandle{nullptr}; - pal_stream_handle_t* mHapticsPalHandle{nullptr}; - static constexpr ::aidl::android::media::audio::common::AudioPlaybackRate sDefaultPlaybackRate = - {.speed = 1.0f, - .pitch = 1.0f, - .fallbackMode = ::aidl::android::media::audio::common::AudioPlaybackRate:: - TimestretchFallbackMode::FAIL}; - - ::aidl::android::media::audio::common::AudioPlaybackRate mPlaybackRate; - - //Haptics Usecase - int mHapticsChannelCount = 1; - std::unique_ptr mHapticsBuffer{nullptr}; - size_t mHapticsBufSize{0}; - ::android::status_t convertBufferAndWrite(const void* buffer, size_t frameCount); - // This API splits and writes audio and haptics streams - ::android::status_t hapticsWrite(const void *buffer, size_t frameCount); - -#ifdef SEC_AUDIO_CALL_VOIP - uint32_t mVoIPInSamplerate{0}; -#endif - - std::variant - mExt; - // references - Platform& mPlatform{Platform::getInstance()}; - const ::aidl::android::media::audio::common::AudioPortConfig& mMixPortConfig; - HalOffloadEffects& mHalEffects{HalOffloadEffects::getInstance()}; - AudioExtension& mAudExt{AudioExtension::getInstance()}; -#ifdef SEC_AUDIO_COMMON - SecFTM& mSecFTM{SecFTM::getInstance()}; - AudioEffect& mAudioEffect{AudioEffect::getInstance()}; -#endif - - private: - std::string mLogPrefix = ""; - bool isHwVolumeSupported(); - bool isHwFlushSupported(); - bool isHwPauseSupported(); - struct BufferConfig getBufferConfig(); - - // optional buffer format converter, if stream input and output formats are different - std::optional> mBufferFormatConverter; - -#if defined(SEC_AUDIO_DUAL_SPEAKER) || defined(SEC_AUDIO_MULTI_SPEAKER) - bool isSoundBoosterRotationSupported(); -#endif -#if defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_ON_DSP) || defined(SEC_AUDIO_PREVOLUME_SOUNDBOOSTER) - uint32_t getSoundBoosterVolumeMode(); -#endif -#ifdef SEC_AUDIO_PREVOLUME_SOUNDBOOSTER - void sendPrevolumeSoundbooster(); -#endif -#ifdef SEC_AUDIO_DUAL_SPEAKER - bool isCallMode(); - bool isDualSpeakerRouting(); - void SetUpperAmpControl(); -#endif -#ifdef SEC_AUDIO_SUPPORT_UHQ - int32_t getSampleRate(); - void updateUhqConfig(int format, bool wideRes); - std::optional> mUhqConfig = std::nullopt; - bool mUpdateUhqAfterRoute = false; -#endif -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/StreamStub.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/StreamStub.h deleted file mode 100755 index 899c5cf2..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/StreamStub.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2023 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. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include - -namespace qti::audio::core { - -class StreamStub : public StreamCommonImpl { - public: - StreamStub(StreamContext* context, const Metadata& metadata); - // Methods of 'DriverInterface'. - ::android::status_t init() override; - ::android::status_t drain( - ::aidl::android::hardware::audio::core::StreamDescriptor::DrainMode) override; - ::android::status_t flush() override; - ::android::status_t pause() override; - ::android::status_t standby() override; - ::android::status_t start() override; - ::android::status_t transfer(void* buffer, size_t frameCount, size_t* actualFrameCount, - int32_t* latencyMs) override; - void shutdown() override; - - private: - const size_t mFrameSizeBytes; - const int mSampleRate; - const bool mIsAsynchronous; - const bool mIsInput; - bool mIsInitialized = false; // Used for validating the state machine logic. - bool mIsStandby = true; // Used for validating the state machine logic. -}; - -class StreamInStub final : public StreamIn, public StreamStub { - public: - friend class ndk::SharedRefBase; - StreamInStub( - StreamContext&& context, - const ::aidl::android::hardware::audio::common::SinkMetadata& sinkMetadata, - const std::vector<::aidl::android::media::audio::common::MicrophoneInfo>& microphones); - ~StreamInStub() override; - int32_t setAggregateSinkMetadata(bool) override; - ndk::ScopedAStatus reconfigureConnectedDevices() override; - - private: - void onClose() override { defaultOnClose(); } -}; - -class StreamOutStub final : public StreamOut, public StreamStub { - public: - friend class ndk::SharedRefBase; - StreamOutStub(StreamContext&& context, - const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetadata, - const std::optional<::aidl::android::media::audio::common::AudioOffloadInfo>& - offloadInfo); - ~StreamOutStub() override; - int32_t setAggregateSourceMetadata(bool) override; - ndk::ScopedAStatus reconfigureConnectedDevices() override; - - private: - void onClose() override { defaultOnClose(); } -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Telephony.h b/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Telephony.h deleted file mode 100755 index d4137cc1..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/include/qti-audio-core/Telephony.h +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include - -#include - -#ifdef SEC_AUDIO_COMMON -#include "SecFTM.h" -#include "AudioEffect.h" -#endif - -namespace qti::audio::core { - -class Telephony : public ::aidl::android::hardware::audio::core::BnTelephony { - public: - Telephony(); - virtual ~Telephony() override; - - enum class CallState : uint8_t { - IN_ACTIVE = 1, - ACTIVE = 2, -#ifdef SEC_AUDIO_CALL_SATELLITE - EXTMODEM_ACTIVE = 3, -#endif - }; - friend std::ostream& operator<<(std::ostream& os, const CallState& state); - enum class VSID : int64_t { - VSID_1 = 0x11C05000, - VSID_2 = 0x11DC5000, -#ifdef SEC_AUDIO_COMMON - VSID_LB_1 = 0x12006000, - VSID_LB_2 = 0x121C6000, -#endif - }; - friend std::ostream& operator<<(std::ostream& os, const VSID& vsid); - using CallType = std::string; - - struct SetUpdates { - /* - call state is key the set update which decides validity or need of - other parameters. - */ - CallState mCallState{CallState::IN_ACTIVE}; - CallType mCallType{""}; - bool mIsCrsCall{false}; - VSID mVSID{VSID::VSID_1}; - std::string toString() const { - std::ostringstream os; - os << "{ mCallState:" << mCallState << ", mVSID:" << mVSID - << ", mIsCrsCall:" << mIsCrsCall << ", mCallType:" << mCallType << "}"; - return os.str(); - } - }; - - struct CallStatus { - CallState current_; - CallState new_; - }; - - float mCRSVolume = 0.4f; //default CRS call volume - bool mIsCRSStarted{false}; - VSID mCRSVSID{VSID::VSID_1}; - constexpr static size_t KCodecBackendDefaultBitWidth = 16; - const static ::aidl::android::media::audio::common::AudioDevice kDefaultRxDevice; - const static ::aidl::android::media::audio::common::AudioDevice kDefaultCRSRxDevice; - static constexpr int32_t VSID1_VOICE_SESSION = 0; - static constexpr int32_t VSID2_VOICE_SESSION = 1; - static constexpr int32_t MAX_VOICE_SESSIONS = 2; - static constexpr int32_t MIN_CRS_VOL_INDEX = 0; - static constexpr int32_t MAX_CRS_VOL_INDEX = 7; - struct SetUpdateSession { - CallStatus state; - SetUpdates CallUpdate; - }; - - struct VoiceSession { - SetUpdateSession session[MAX_VOICE_SESSIONS]; - }; - VoiceSession mVoiceSession; - -#ifdef SEC_AUDIO_CALL - VSID mCurVSID{VSID::VSID_1}; - bool mIsVolteVT{false}; - bool mIsVoWiFi{false}; - int mCallBand = WB; -#endif - - /* All the public APIs are guarded by mLock, Hence never call a public - * API from anther public API */ - public: - ndk::ScopedAStatus getSupportedAudioModes( - std::vector<::aidl::android::media::audio::common::AudioMode>* _aidl_return) override; - ndk::ScopedAStatus switchAudioMode( - ::aidl::android::media::audio::common::AudioMode in_mode) override; - ndk::ScopedAStatus setTelecomConfig(const TelecomConfig& in_config, - TelecomConfig* _aidl_return) override; - - /* This API is called when there are "TELEPHONY related set parameters" - on the primary module */ - void reconfigure(const SetUpdates& setUpdates); - - void updateVolumeBoost(const bool enable); - void updateSlowTalk(const bool enable); - void updateHDVoice(const bool enable); - void updateDeviceMute(const bool isMute, const std::string& muteDirection); -#ifdef SEC_AUDIO_CALL - void updateSecCallState(const int state); - void updateSecVSID(const int vsid); - void updateSecCallBand(const int band); - void configureMicMode(); - void setCallForwarding(bool enable); -#endif -#ifdef SEC_AUDIO_CALL_SATELLITE - void configureExtModemCall(); -#endif - bool isCrsCallSupported(); - void setCRSVolumeFromIndex(const int index); - void updateVoiceVolume(); -#ifdef SEC_AUDIO_CALL_SATELLITE - void updateExtModemCallVolume(); - void updateExtModemMicMute(); -#endif - void setMicMute(const bool muted); - void updateCalls(); - - // The following below API are both aimed to solve routing on telephony - /** - * brief sets Rx and Tx devices from device to device patch. - * @param devices devices obtained from the patch - * @param updateRx whether device update is for rx devices or tx devices. - * true in case when rx devices needs updation, false otherwise. - */ - void setDevices(const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, - const bool updateRx); - /** - * The following API resets the RX and TX device - * @param resetRx, indicates device to reset, true for RX, false for TX - **/ - void resetDevices(const bool resetRx); - -#ifdef SEC_AUDIO_COMMON - void updateLoopback(const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices, - const bool loopbackon); -#endif - - // Telephony to decide its strategy where there is external device connection change - void onExternalDeviceConnectionChanged( - const ::aidl::android::media::audio::common::AudioDevice& extDevice, - const bool& connect); - - /* Telephony to act on primary stream devices change */ - void onOutputPrimaryStreamDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>&); - - /* Telephony to act upon bluetooth sco enabled or disabled */ - void onBluetoothScoEvent(const bool& enable); - - /* set the voip stream */ - void setVoipPlaybackStream(std::weak_ptr voipStream); - - /* called on playback stream start/close */ - void onPlaybackStart(); - void onPlaybackClose(); - - void updateVoiceMetadataForBT(bool call_active); - std::weak_ptr mStreamOutPrimary; - std::weak_ptr mStreamInPrimary; - - protected: - ndk::ScopedAStatus startCall(); - ndk::ScopedAStatus stopCall(); - void VoiceStop(); - void configureVolumeBoost(); - void configureSlowTalk(); - void configureHDVoice(); - void configureDeviceMute(); - void updateDevices(); - void updateTtyMode(); - void updateCrsDevice(); - void startCrsLoopback(); - void stopCrsLoopback(); - void triggerHACinVoipPlayback(); - ::aidl::android::media::audio::common::AudioDevice getMatchingTxDevice( - const ::aidl::android::media::audio::common::AudioDevice & rxDevice); - bool isAnyCallActive(); - -#ifdef SEC_AUDIO_RECOVERY - void initSecConfig(); -#endif - - protected: - // Gaurd all the public APIs - std::mutex mLock; - TelecomConfig mTelecomConfig; - const std::vector<::aidl::android::media::audio::common::AudioMode> mSupportedAudioModes = { - ::aidl::android::media::audio::common::AudioMode::NORMAL, - ::aidl::android::media::audio::common::AudioMode::RINGTONE, - ::aidl::android::media::audio::common::AudioMode::IN_CALL, - ::aidl::android::media::audio::common::AudioMode::IN_COMMUNICATION, - ::aidl::android::media::audio::common::AudioMode::CALL_SCREEN, - }; - - ::aidl::android::media::audio::common::AudioMode mAudioMode{ - ::aidl::android::media::audio::common::AudioMode::NORMAL}; - - SetUpdates mSetUpdates{}; - bool mIsVolumeBoostEnabled{false}; - bool mIsSlowTalkEnabled{false}; - bool mIsHDVoiceEnabled{false}; - bool mIsDeviceMuted{false}; - bool hasValidPlaybackStream{false}; - bool mIsVoiceStarted{false}; - std::string mMuteDirection{""}; - - using TtyMap = std::map; - const TtyMap mTtyMap{ - {TelecomConfig::TtyMode::OFF, PAL_TTY_OFF}, - {TelecomConfig::TtyMode::FULL, PAL_TTY_FULL}, - {TelecomConfig::TtyMode::HCO, PAL_TTY_HCO}, - {TelecomConfig::TtyMode::VCO, PAL_TTY_VCO}, - }; - - ::aidl::android::media::audio::common::AudioDevice mRxDevice; // speaker, earpiece - ::aidl::android::media::audio::common::AudioDevice mTxDevice; // mic, speaker mic - pal_stream_handle_t* mPalCrsHandle{nullptr}; - pal_stream_handle_t* mPalHandle{nullptr}; - // Stream Handle for VOIP Playback - std::weak_ptr mVoipStreamWptr; - Platform& mPlatform{Platform::getInstance()}; -#ifdef SEC_AUDIO_COMMON - SecFTM& mSecFTM{SecFTM::getInstance()}; - AudioEffect& mAudioEffect{AudioEffect::getInstance()}; - AudioExtension& mAudExt{AudioExtension::getInstance()}; -#endif -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/manifest_audiocoreservices_qti.xml b/qcom/opensource/audio-hal/primary-hal/hal/core/manifest_audiocoreservices_qti.xml deleted file mode 100755 index b5d5e84d..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/manifest_audiocoreservices_qti.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - android.hardware.audio.core - 2 - IModule/default - - - android.hardware.audio.core - 2 - IModule/r_submix - - - android.hardware.audio.core - 2 - IModule/usb - - - android.hardware.audio.core - 2 - IConfig/default - - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/Android.bp b/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/Android.bp deleted file mode 100755 index 53c7d926..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/Android.bp +++ /dev/null @@ -1,36 +0,0 @@ -cc_library_static { - name: "libaudio_module_config.qti", - vendor: true, - export_include_dirs: ["include"], - srcs: [ - "ModuleConfig.cpp", - ], - shared_libs: [ - "libaudioaidlcommon", - "libbase", - "libcutils", - "liblog", - "libstagefright_foundation", - "libutils", - "libxml2", - "android.media.audio.common.types-V3-ndk", - "android.hardware.audio.core-V2-ndk", - ], - header_libs: [ - "libxsdc-utils", - "libaudio_system_headers", - ], - generated_headers: [ - "audio_module_config_qti", - ], - generated_sources: [ - "audio_module_config_qti", - ], - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - "-Wthread-safety", - ], -} - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/ModuleConfig.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/ModuleConfig.cpp deleted file mode 100755 index 35282d04..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/ModuleConfig.cpp +++ /dev/null @@ -1,757 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -// { SEC_AUDIO_COMMON -#include -// } SEC_AUDIO_COMMON - -using ::aidl::android::hardware::audio::common::makeBitPositionFlagMask; -using ::aidl::android::hardware::audio::core::AudioPatch; -using ::aidl::android::hardware::audio::core::AudioRoute; -using ::aidl::android::media::audio::common::AudioChannelLayout; -using ::aidl::android::media::audio::common::AudioDeviceAddress; -using ::aidl::android::media::audio::common::AudioDeviceDescription; -using ::aidl::android::media::audio::common::AudioDeviceType; -using ::aidl::android::media::audio::common::AudioEncapsulationType; -using ::aidl::android::media::audio::common::AudioFormatDescription; -using ::aidl::android::media::audio::common::AudioFormatType; -using ::aidl::android::media::audio::common::AudioGain; -using ::aidl::android::media::audio::common::AudioGainConfig; -using ::aidl::android::media::audio::common::AudioIoFlags; -using ::aidl::android::media::audio::common::AudioOutputFlags; -using ::aidl::android::media::audio::common::AudioPort; -using ::aidl::android::media::audio::common::AudioPortConfig; -using ::aidl::android::media::audio::common::AudioPortDeviceExt; -using ::aidl::android::media::audio::common::AudioPortExt; -using ::aidl::android::media::audio::common::AudioPortMixExt; -using ::aidl::android::media::audio::common::AudioProfile; -using ::aidl::android::media::audio::common::Int; -using ::aidl::android::media::audio::common::MicrophoneInfo; -using ::aidl::android::media::audio::common::PcmType; - -namespace xsd = ::audio_module_config_qti; - -namespace qti::audio::core { - -const static char kRouteDelimiter = ','; -const static std::string kDefaultOutputDevice = "speaker"; - -const static std::unordered_map XsdToPcmType = { - {xsd::AudioPcmType::DEFAULT, PcmType::DEFAULT}, - {xsd::AudioPcmType::UINT_8_BIT, PcmType::UINT_8_BIT}, - {xsd::AudioPcmType::INT_16_BIT, PcmType::INT_16_BIT}, - {xsd::AudioPcmType::INT_32_BIT, PcmType::INT_32_BIT}, - {xsd::AudioPcmType::FIXED_Q_8_24, PcmType::FIXED_Q_8_24}, - {xsd::AudioPcmType::FLOAT_32_BIT, PcmType::FLOAT_32_BIT}, - {xsd::AudioPcmType::INT_24_BIT, PcmType::INT_24_BIT}, -}; - -const static std::unordered_map XsdToAudioDeviceType = { - {xsd::AudioDeviceType::NONE, AudioDeviceType::NONE}, - {xsd::AudioDeviceType::IN_DEFAULT, AudioDeviceType::IN_DEFAULT}, - {xsd::AudioDeviceType::IN_ACCESSORY, AudioDeviceType::IN_ACCESSORY}, - {xsd::AudioDeviceType::IN_AFE_PROXY, AudioDeviceType::IN_AFE_PROXY}, - {xsd::AudioDeviceType::IN_DEVICE, AudioDeviceType::IN_DEVICE}, - {xsd::AudioDeviceType::IN_ECHO_REFERENCE, AudioDeviceType::IN_ECHO_REFERENCE}, - {xsd::AudioDeviceType::IN_FM_TUNER, AudioDeviceType::IN_FM_TUNER}, - {xsd::AudioDeviceType::IN_HEADSET, AudioDeviceType::IN_HEADSET}, - {xsd::AudioDeviceType::IN_LOOPBACK, AudioDeviceType::IN_LOOPBACK}, - {xsd::AudioDeviceType::IN_MICROPHONE, AudioDeviceType::IN_MICROPHONE}, - {xsd::AudioDeviceType::IN_MICROPHONE_BACK, AudioDeviceType::IN_MICROPHONE_BACK}, - {xsd::AudioDeviceType::IN_SUBMIX, AudioDeviceType::IN_SUBMIX}, - {xsd::AudioDeviceType::IN_TELEPHONY_RX, AudioDeviceType::IN_TELEPHONY_RX}, - {xsd::AudioDeviceType::IN_TV_TUNER, AudioDeviceType::IN_TV_TUNER}, - {xsd::AudioDeviceType::IN_DOCK, AudioDeviceType::IN_DOCK}, -#ifdef SEC_AUDIO_COMMON - {xsd::AudioDeviceType::IN_MICROPHONE_MULTI, AudioDeviceType::IN_MICROPHONE_MULTI}, -#endif - {xsd::AudioDeviceType::OUT_DEFAULT, AudioDeviceType::OUT_DEFAULT}, - {xsd::AudioDeviceType::OUT_ACCESSORY, AudioDeviceType::OUT_ACCESSORY}, - {xsd::AudioDeviceType::OUT_AFE_PROXY, AudioDeviceType::OUT_AFE_PROXY}, - {xsd::AudioDeviceType::OUT_CARKIT, AudioDeviceType::OUT_CARKIT}, - {xsd::AudioDeviceType::OUT_DEVICE, AudioDeviceType::OUT_DEVICE}, - {xsd::AudioDeviceType::OUT_ECHO_CANCELLER, AudioDeviceType::OUT_ECHO_CANCELLER}, - {xsd::AudioDeviceType::OUT_FM, AudioDeviceType::OUT_FM}, - {xsd::AudioDeviceType::OUT_HEADPHONE, AudioDeviceType::OUT_HEADPHONE}, - {xsd::AudioDeviceType::OUT_HEADSET, AudioDeviceType::OUT_HEADSET}, - {xsd::AudioDeviceType::OUT_HEARING_AID, AudioDeviceType::OUT_HEARING_AID}, - {xsd::AudioDeviceType::OUT_LINE_AUX, AudioDeviceType::OUT_LINE_AUX}, - {xsd::AudioDeviceType::OUT_SPEAKER, AudioDeviceType::OUT_SPEAKER}, - {xsd::AudioDeviceType::OUT_SPEAKER_EARPIECE, AudioDeviceType::OUT_SPEAKER_EARPIECE}, - {xsd::AudioDeviceType::OUT_SPEAKER_SAFE, AudioDeviceType::OUT_SPEAKER_SAFE}, - {xsd::AudioDeviceType::OUT_SUBMIX, AudioDeviceType::OUT_SUBMIX}, - {xsd::AudioDeviceType::OUT_TELEPHONY_TX, AudioDeviceType::OUT_TELEPHONY_TX}, - {xsd::AudioDeviceType::OUT_DOCK, AudioDeviceType::OUT_DOCK}, - {xsd::AudioDeviceType::OUT_BROADCAST, AudioDeviceType::OUT_BROADCAST}, -}; - -const static std::unordered_map XsdToAudioChannelLayout = { - {xsd::AudioChannelLayout::LAYOUT_MONO, AudioChannelLayout::LAYOUT_MONO}, - {xsd::AudioChannelLayout::LAYOUT_STEREO, AudioChannelLayout::LAYOUT_STEREO}, - {xsd::AudioChannelLayout::LAYOUT_2POINT1, AudioChannelLayout::LAYOUT_2POINT1}, - {xsd::AudioChannelLayout::LAYOUT_TRI, AudioChannelLayout::LAYOUT_TRI}, - {xsd::AudioChannelLayout::LAYOUT_TRI_BACK, AudioChannelLayout::LAYOUT_TRI_BACK}, - {xsd::AudioChannelLayout::LAYOUT_3POINT1, AudioChannelLayout::LAYOUT_3POINT1}, - {xsd::AudioChannelLayout::LAYOUT_2POINT0POINT2, AudioChannelLayout::LAYOUT_2POINT0POINT2}, - {xsd::AudioChannelLayout::LAYOUT_2POINT1POINT2, AudioChannelLayout::LAYOUT_2POINT1POINT2}, - {xsd::AudioChannelLayout::LAYOUT_3POINT0POINT2, AudioChannelLayout::LAYOUT_3POINT0POINT2}, - {xsd::AudioChannelLayout::LAYOUT_3POINT1POINT2, AudioChannelLayout::LAYOUT_3POINT1POINT2}, - {xsd::AudioChannelLayout::LAYOUT_QUAD, AudioChannelLayout::LAYOUT_QUAD}, - {xsd::AudioChannelLayout::LAYOUT_QUAD_SIDE, AudioChannelLayout::LAYOUT_QUAD_SIDE}, - {xsd::AudioChannelLayout::LAYOUT_SURROUND, AudioChannelLayout::LAYOUT_SURROUND}, - {xsd::AudioChannelLayout::LAYOUT_PENTA, AudioChannelLayout::LAYOUT_PENTA}, - {xsd::AudioChannelLayout::LAYOUT_5POINT1, AudioChannelLayout::LAYOUT_5POINT1}, - {xsd::AudioChannelLayout::LAYOUT_5POINT1_SIDE, AudioChannelLayout::LAYOUT_5POINT1_SIDE}, - {xsd::AudioChannelLayout::LAYOUT_5POINT1POINT2, AudioChannelLayout::LAYOUT_5POINT1POINT2}, - {xsd::AudioChannelLayout::LAYOUT_5POINT1POINT4, AudioChannelLayout::LAYOUT_5POINT1POINT4}, - {xsd::AudioChannelLayout::LAYOUT_6POINT1, AudioChannelLayout::LAYOUT_6POINT1}, - {xsd::AudioChannelLayout::LAYOUT_7POINT1, AudioChannelLayout::LAYOUT_7POINT1}, - {xsd::AudioChannelLayout::LAYOUT_7POINT1POINT2, AudioChannelLayout::LAYOUT_7POINT1POINT2}, - {xsd::AudioChannelLayout::LAYOUT_7POINT1POINT4, AudioChannelLayout::LAYOUT_7POINT1POINT4}, - {xsd::AudioChannelLayout::LAYOUT_9POINT1POINT4, AudioChannelLayout::LAYOUT_9POINT1POINT4}, - {xsd::AudioChannelLayout::LAYOUT_9POINT1POINT6, AudioChannelLayout::LAYOUT_9POINT1POINT6}, - {xsd::AudioChannelLayout::LAYOUT_13POINT_360RA, AudioChannelLayout::LAYOUT_13POINT_360RA}, - {xsd::AudioChannelLayout::LAYOUT_22POINT2, AudioChannelLayout::LAYOUT_22POINT2}, - {xsd::AudioChannelLayout::LAYOUT_MONO_HAPTIC_A, AudioChannelLayout::LAYOUT_MONO_HAPTIC_A}, - {xsd::AudioChannelLayout::LAYOUT_STEREO_HAPTIC_A, - AudioChannelLayout::LAYOUT_STEREO_HAPTIC_A}, - {xsd::AudioChannelLayout::LAYOUT_HAPTIC_AB, AudioChannelLayout::LAYOUT_HAPTIC_AB}, - {xsd::AudioChannelLayout::LAYOUT_MONO_HAPTIC_AB, AudioChannelLayout::LAYOUT_MONO_HAPTIC_AB}, - {xsd::AudioChannelLayout::LAYOUT_STEREO_HAPTIC_AB, - AudioChannelLayout::LAYOUT_STEREO_HAPTIC_AB}, - {xsd::AudioChannelLayout::LAYOUT_FRONT_BACK, AudioChannelLayout::LAYOUT_FRONT_BACK}, -}; - -template -struct overloaded : Ts... { - using Ts::operator()...; -}; -template -overloaded(Ts...)->overloaded; - -static inline bool maybeVendorExtension(const std::string& s) { - // Only checks whether the string starts with the "vendor prefix". - static const std::string vendorPrefix = "VX_"; - return s.size() > vendorPrefix.size() && s.substr(0, vendorPrefix.size()) == vendorPrefix; -} - -static auto findPortByTagName(const std::vector& collection, std::string tagName) { - return std::find_if(collection.begin(), collection.end(), - [&](const auto& e) { return (e.name == tagName); }); -} - -static int32_t findPortIdByTagName(const std::vector& ports, std::string tagName) { - auto portItr = findPortByTagName(ports, tagName); - if (portItr == ports.end()) { - return -EINVAL; - } - return (*portItr).id; -} - -static std::vector getAudioHalConfigurationPaths() { - static const std::vector paths = []() { - return std::vector({"/vendor/etc/audio"}); - }(); - return paths; -} - -static std::string getReadAbleConfigurationFile(const char* fileName) { - for (const auto& path : getAudioHalConfigurationPaths()) { - std::string tryPath = path + "/" + fileName; - if (::access(tryPath.c_str(), R_OK) == 0) { - return tryPath; - } - } - return {}; -} - -static void fillProfile(AudioProfile* profile, const std::string& name, - const std::vector& channelLayouts, - const std::vector& sampleRates, - AudioEncapsulationType encapsulationType) { - profile->name = name; - for (auto layout : channelLayouts) { - profile->channelMasks.push_back( - AudioChannelLayout::make(layout)); - } - profile->sampleRates.insert(profile->sampleRates.end(), sampleRates.begin(), sampleRates.end()); - profile->encapsulationType = encapsulationType; -} - -static AudioProfile createProfile( - const std::string& name, PcmType pcmType, const std::vector& channelLayouts, - const std::vector& sampleRates, - AudioEncapsulationType encapsulationType = AudioEncapsulationType::NONE) { - AudioProfile profile; - profile.format.type = AudioFormatType::PCM; - profile.format.pcm = pcmType; - fillProfile(&profile, name, channelLayouts, sampleRates, encapsulationType); - return profile; -} - -static AudioProfile createProfile( - const std::string& name, const std::string& encodingType, - const std::vector& channelLayouts, const std::vector& sampleRates, - AudioEncapsulationType encapsulationType = AudioEncapsulationType::NONE) { - AudioProfile profile; - profile.format.encoding = encodingType; - profile.format.type = ::aidl::android::media::audio::common::AudioFormatType::NON_PCM; - fillProfile(&profile, name, channelLayouts, sampleRates, encapsulationType); - return profile; -} - -static AudioGain createGain(int32_t mode, int32_t channelMask, - std::pair minMaxGain, - std::pair minMaxRamp, - std::pair stepAndDefault, bool useForVolume) { - AudioGain gain; - gain.mode = mode; - gain.channelMask = AudioChannelLayout::make(channelMask); - gain.minValue = std::get<0>(minMaxGain); - gain.maxValue = std::get<1>(minMaxGain); - gain.minRampMs = std::get<0>(minMaxRamp); - gain.maxRampMs = std::get<1>(minMaxRamp); - gain.stepValue = std::get<0>(stepAndDefault); - gain.defaultValue = std::get<1>(stepAndDefault); - gain.useForVolume = useForVolume; - return gain; -} - -static AudioPortExt createDeviceExt(AudioDeviceType devType, int32_t flags, - std::vector formats, - AudioDeviceAddress address = "", std::string connection = "") { - AudioPortDeviceExt deviceExt; - deviceExt.device.type.type = devType; - deviceExt.device.type.connection = connection; - deviceExt.flags = flags; - deviceExt.device.address = address; - deviceExt.encodedFormats = formats; - return AudioPortExt::make(deviceExt); -} - -static AudioPortExt createPortMixExt(int32_t maxOpenStreamCount, int32_t maxActiveStreamCount, - int32_t recommendedMuteDurationMs = 0) { - AudioPortMixExt mixExt; - mixExt.maxOpenStreamCount = maxOpenStreamCount; - mixExt.maxActiveStreamCount = maxActiveStreamCount; - mixExt.recommendedMuteDurationMs = recommendedMuteDurationMs; - return AudioPortExt::make(mixExt); -} - -static AudioPort createPort(int32_t id, const std::string& name, int32_t flags, bool isInput, - const AudioPortExt& ext) { - AudioPort port; - port.id = id; - port.name = name; - port.flags = isInput ? AudioIoFlags::make(flags) - : AudioIoFlags::make(flags); - port.ext = ext; - return port; -} - -static AudioPortConfig createPortConfig(int32_t id, int32_t portId, PcmType pcmType, int32_t layout, - int32_t sampleRate, int32_t flags, bool isInput, - const AudioPortExt& ext) { - AudioPortConfig config; - config.id = id; - config.portId = portId; - config.sampleRate = Int{.value = sampleRate}; - config.channelMask = AudioChannelLayout::make(layout); - config.format = AudioFormatDescription{.type = AudioFormatType::PCM, .pcm = pcmType}; - config.gain = AudioGainConfig(); - config.flags = isInput ? AudioIoFlags::make(flags) - : AudioIoFlags::make(flags); - config.ext = ext; - return config; -} - -static AudioRoute createRoute(const std::vector& sources, const AudioPort& sink) { - AudioRoute route; - route.sinkPortId = sink.id; - std::transform(sources.begin(), sources.end(), std::back_inserter(route.sourcePortIds), - [](const auto& port) { return port.id; }); - return route; -} - -static void sortAudioProfiles(std::vector& profiles) { - std::sort(profiles.begin(), profiles.end()); -} - -static void dumpProfiles(const AudioProfile& profile, int32_t portId) { - LOG(INFO) << " --------- PROFILE for Port ID = " << portId << " ----------"; - LOG(INFO) << " Name: " << profile.name; - if (profile.format.type == AudioFormatType::PCM) { - LOG(INFO) << " Format: PCM, type: 0x" << std::hex - << static_cast(profile.format.pcm); - } else { - LOG(INFO) << " Format: NON_PCM, encoding: " << profile.format.encoding; - } - std::string sampleRates; - std::for_each(profile.sampleRates.begin(), profile.sampleRates.end(), - [&](int32_t rate) { sampleRates += std::to_string(rate) + ", "; }); - if (!sampleRates.empty()) { - sampleRates = sampleRates.substr(0, sampleRates.size() - 2); - } - LOG(INFO) << " Sample rates: " << sampleRates; - - std::ostringstream os; - std::for_each(profile.channelMasks.begin(), profile.channelMasks.end(), - [&](const auto ele) { os << ele.toString(); }); - LOG(INFO) << " Channel Masks: " << os.str(); - - // TODO: Print channel layouts -} - -static void dumpRoute(const AudioRoute& route) { - LOG(DEBUG) << "\n---------ROUTE DUMP----------"; - std::string sourcePorts; - std::for_each(route.sourcePortIds.begin(), route.sourcePortIds.end(), - [&](int32_t rate) { sourcePorts += std::to_string(rate) + ", "; }); - if (!sourcePorts.empty()) { - sourcePorts = sourcePorts.substr(0, sourcePorts.size() - 2); - } - LOG(DEBUG) << "Source Port IDs: " << sourcePorts; -} - -static void dumpMixExt(const AudioPortExt& ext) { - auto& mixExt = ext.get(); - LOG(DEBUG) << "MixExt: maxOpenStreamCount: " << mixExt.maxOpenStreamCount - << " maxActiveStreamCount: " << mixExt.maxActiveStreamCount; - if (mixExt.recommendedMuteDurationMs) { - LOG(DEBUG) << "MixExt: recommendedMuteDurationMs: " << mixExt.recommendedMuteDurationMs; - } -} - -static void dumpDeviceExt(const AudioPortExt& ext) { - auto& deviceExt = ext.get(); - LOG(DEBUG) << "DeviceExt: type: 0x" << std::hex - << static_cast(deviceExt.device.type.type) - << ", connection: " << deviceExt.device.type.connection; - LOG(DEBUG) << "DeviceExt: flags: 0x" << std::hex << deviceExt.flags - << " address: " << deviceExt.device.address.get(); - std::for_each(deviceExt.encodedFormats.begin(), deviceExt.encodedFormats.end(), - [&](const auto& format) { - LOG(DEBUG) << "DeviceExt: encoding format: " << format.encoding; - }); -} - -static void dumpPort(const AudioPort& port, bool isInput, bool isMix) { - LOG(DEBUG) << "\n---------PORT DUMP----------"; - LOG(DEBUG) << "Port ID: " << port.id; - LOG(DEBUG) << "Port Name: " << port.name; - if (isInput) { - LOG(DEBUG) << "Input flags: 0x" << std::hex << port.flags.get(); - } else { - LOG(DEBUG) << "Output flags: 0x" << std::hex << port.flags.get(); - } - auto dumpExtension = isMix ? dumpMixExt : dumpDeviceExt; - dumpExtension(port.ext); - std::for_each(port.profiles.begin(), port.profiles.end(), - [&](const auto& profile) { dumpProfiles(profile, port.id); }); -} - -static std::vector populateProfiles( - const std::variant& - audioPort) { - std::vector audioProfiles; - - auto isFormatInvalid = [](const xsd::Profile& profile) { - if (!profile.hasPcmType() && !profile.hasEncoding()) { - return true; - } - return false; - }; - auto getName = [](const xsd::Profile& profile) { - if (!profile.hasName()) { - return ""; - } - return profile.getName().c_str(); - }; - auto getFormat = [](const xsd::Profile& profile) -> std::variant { - if (profile.hasEncoding()) { - return profile.getEncoding(); - } - if (XsdToPcmType.find(profile.getPcmType()) == XsdToPcmType.end()) { - return PcmType::DEFAULT; - } - return XsdToPcmType.at(profile.getPcmType()); - }; - auto getEncapsulationType = [](const xsd::Profile& profile) { - if (!profile.hasEncapsulationType()) { - return AudioEncapsulationType::NONE; - } - return static_cast(profile.getEncapsulationType()); - }; - auto getChannels = [](const xsd::Profile& profile) { - std::vector channels; - if (!profile.hasChannelLayouts()) { - return channels; - } - std::for_each(profile.getChannelLayouts().begin(), profile.getChannelLayouts().end(), - [&](const auto& chLayout) { - channels.push_back(XsdToAudioChannelLayout.at(chLayout)); - }); - return channels; - }; - - std::visit( - [&](const auto& port) { - for (const auto& profile : port.getProfile()) { - // Todo check if profiles must channel layouts - if (isFormatInvalid(profile) || !profile.hasSamplingRates() || - !profile.hasChannelLayouts()) { - if (profile.hasName()) { - LOG(WARNING) << __func__ << ": Ignore invalid profile " - << profile.getName(); - } - continue; - } - auto format = getFormat(profile); - std::visit( - overloaded{[&](const std::string& formatStr) { - audioProfiles.push_back(createProfile( - getName(profile), formatStr, - getChannels(profile), profile.getSamplingRates(), - getEncapsulationType(profile))); - }, - [&](const PcmType& formatPcm) { - audioProfiles.push_back(createProfile( - getName(profile), formatPcm, - getChannels(profile), profile.getSamplingRates(), - getEncapsulationType(profile))); - }}, - format); - } - }, - audioPort); - - return audioProfiles; -} - -static std::vector populateGains( - const std::variant& - audioPort) { - std::vector audioGains; - auto getMode = [](const xsd::Gains::Gain& gain) { - if (!gain.hasMode()) { - return 0; - } - return static_cast(gain.getMode()[0]); - }; - auto getChannelLayout = [](const xsd::Gains::Gain& gain) { - if (!gain.hasChannel_layout()) { - return xsd::AudioChannelLayout::LAYOUT_MONO; - } - return gain.getChannel_layout(); - }; - auto getMinMaxGain = [](const xsd::Gains::Gain& gain) { - int32_t min = gain.hasMinValueMB() ? gain.getMinValueMB() : 0; - int32_t max = gain.hasMaxValueMB() ? gain.getMaxValueMB() : 0; - return std::make_pair(min, max); - }; - auto getMinMaxRamp = [](const xsd::Gains::Gain& gain) { - int32_t min = gain.hasMinRampMs() ? gain.getMinRampMs() : 0; - int32_t max = gain.hasMaxRampMs() ? gain.getMaxRampMs() : 0; - return std::make_pair(min, max); - }; - auto getStepAndDefault = [](const xsd::Gains::Gain& gain) { - int32_t step = gain.hasStepValueMB() ? gain.getStepValueMB() : 0; - int32_t defaultVal = gain.hasDefaultValueMB() ? gain.getDefaultValueMB() : 0; - return std::make_pair(step, defaultVal); - }; - auto getUseForVolume = [](const xsd::Gains::Gain& gain) { - if (!gain.hasUseForVolume()) { - return false; - } - return gain.getUseForVolume(); - }; - - std::visit( - [&](const auto& port) { - for (const auto& gain : port.getFirstGains()->getGain()) { - auto g = createGain(getMode(gain), static_cast(getChannelLayout(gain)), - getMinMaxGain(gain), getMinMaxRamp(gain), - getStepAndDefault(gain), getUseForVolume(gain)); - audioGains.push_back(g); - } - }, - audioPort); - - return audioGains; -} - -static void populateMixPorts(const xsd::Modules::Module& module, - std::unique_ptr& moduleConfig) { - auto getFlags = [](const xsd::MixPorts::MixPort& mixPort, bool isInput) { - if (!mixPort.hasFlags()) { - return 0; - } - int32_t flags = 0; - auto flagVec = mixPort.getFlags(); - std::for_each(flagVec.begin(), flagVec.end(), [&](const auto& flagStr) { - LOG(VERBOSE) << " flag " << flagStr; - flags |= 1 << (isInput ? static_cast(xsd::stringToAudioInputFlag(flagStr)) - : static_cast(xsd::stringToAudioOutputFlag(flagStr))); - }); - return flags; - }; - - if (!module.getFirstMixPorts()) { - LOG(ERROR) << __func__ << " No mix ports"; - return; - } - for (const auto& mixPort : module.getFirstMixPorts()->getMixPort()) { - std::string name = mixPort.hasName() ? mixPort.getName() : ""; - auto role = mixPort.hasRole() ? mixPort.getRole() : xsd::Role::UNKNOWN; - bool isInput = role == xsd::Role::source ? false : true; - - int32_t maxOpenCount = mixPort.hasMaxOpenCount() ? mixPort.getMaxOpenCount() : 1; - int32_t maxActiveCount = mixPort.hasMaxActiveCount() ? mixPort.getMaxActiveCount() : 1; - int32_t recommendedMuteDurationMs = - mixPort.hasRecommendedMuteDurationMs() ? mixPort.getRecommendedMuteDurationMs() : 0; - - auto port = createPort( - moduleConfig->nextPortId++, name, getFlags(mixPort, isInput), isInput, - createPortMixExt(maxOpenCount, maxActiveCount, recommendedMuteDurationMs)); - if (mixPort.hasProfile()) { - port.profiles = populateProfiles(mixPort); - } - if (mixPort.hasGains()) { - port.gains = populateGains(mixPort); - } - moduleConfig->ports.emplace_back(std::move(port)); - - // dumpPort(moduleConfig->ports.at(port.id), isInput, true); - } -} - -static void populateDevicePorts(const xsd::Modules::Module& module, - std::unique_ptr& moduleConfig) { - auto getFlags = [](const xsd::DevicePorts::DevicePort& devPort) { - if (devPort.hasDefaultDevice() && devPort.getDefaultDevice() && !devPort.hasConnection()) { - return 1 << AudioPortDeviceExt::FLAG_INDEX_DEFAULT_DEVICE; - } - return 0; - }; - auto getFormats = [](const xsd::DevicePorts::DevicePort& devPort) { - std::vector encodings; - if (!devPort.hasEncodings()) { - return encodings; - } - for (const auto& encodingType : devPort.getEncodings()) { - auto format = AudioFormatDescription{.type = AudioFormatType::NON_PCM, - .encoding = encodingType}; - encodings.push_back(format); - } - return encodings; - }; - - if (!module.getFirstDevicePorts()) { - LOG(ERROR) << __func__ << " No device ports"; - return; - } - for (const auto& devicePort : module.getFirstDevicePorts()->getDevicePort()) { - std::string name = devicePort.hasTagName() ? devicePort.getTagName() : ""; - auto role = devicePort.hasRole() ? devicePort.getRole() : xsd::Role::UNKNOWN; - bool isInput = role == xsd::Role::source ? true : false; - AudioDeviceType devType = devicePort.hasDeviceType() - ? XsdToAudioDeviceType.at(devicePort.getDeviceType()) - : AudioDeviceType::NONE; - - auto address = devicePort.hasAddress() - ? AudioDeviceAddress::make( - devicePort.getAddress()) - : AudioDeviceAddress{}; - - std::string connections = - devicePort.hasConnection() ? toString(devicePort.getConnection()) : ""; - auto deviceExt = createDeviceExt(devType, getFlags(devicePort), getFormats(devicePort), - address, connections); - auto port = createPort(moduleConfig->nextPortId++, name, 0, isInput, deviceExt); - if (devicePort.hasProfile()) { - port.profiles = populateProfiles(devicePort); - } - if (devicePort.hasGains()) { - port.gains = populateGains(devicePort); - } - // only external device ports - if (!devicePort.hasAttached() || (devicePort.hasAttached() && !devicePort.getAttached())) { - // not attached - moduleConfig->mExternalDevicePortProfiles[port.id] = port.profiles; - port.profiles.clear(); - } - moduleConfig->ports.emplace_back(std::move(port)); - // dumpPort(moduleConfig->ports.at(port.id), isInput, false); - } -} - -static void populateRoutes(const xsd::Modules::Module& module, - std::unique_ptr& moduleConfig) { - if (!module.getFirstRoutes()) { - LOG(ERROR) << __func__ << " No routes"; - return; - } - for (const auto& route : module.getFirstRoutes()->getRoute()) { - if (!route.hasSources() || !route.hasSink()) { - if (route.hasSink()) { - LOG(WARNING) << __func__ << ": Invalid route for sink " << route.getSink(); - } - continue; - } - - std::string source = route.getSources(); - std::vector srcTags; - std::string::size_type pos = 0; - while ((pos = source.find(kRouteDelimiter)) != std::string::npos) { - std::string tag(source, 0, pos); - LOG(VERBOSE) << __func__ << ": source tag " << tag; - srcTags.push_back(tag); - if (pos > source.size()) { - break; - } - source = source.substr(pos + 1); - } - if (!source.empty()) { - LOG(VERBOSE) << __func__ << ": source tag " << source; - srcTags.push_back(source); - } - - std::vector sources; - for (const auto& tag : srcTags) { - auto srcItr = findPortByTagName(moduleConfig->ports, tag); - if (srcItr != moduleConfig->ports.end()) { - sources.push_back(*srcItr); - } - } - - auto sink = findPortByTagName(moduleConfig->ports, route.getSink()); - LOG(VERBOSE) << __func__ << ": sink tag " << route.getSink(); - if (sink != moduleConfig->ports.end()) { - moduleConfig->routes.push_back(createRoute(sources, *sink)); - // dumpRoute(moduleConfig->routes.back()); - } - } -} - -static std::unique_ptr getModuleConfig(const xsd::Modules::Module& module) { - auto moduleConfig = std::make_unique(); - populateMixPorts(module, moduleConfig); - populateDevicePorts(module, moduleConfig); - populateRoutes(module, moduleConfig); - - return std::move(moduleConfig); -} - -// static -#ifdef SEC_AUDIO_COMMON -std::unique_ptr ModuleConfig::getPrimaryConfiguration(bool secAudioFeatureEnabled) { - const std::string& filePath = secAudioFeatureEnabled ? - kPrimaryModuleConfigFileName : kGsiPrimaryModuleConfigFileName; - auto xsdConfig = - xsd::read(getReadAbleConfigurationFile(filePath.c_str()).c_str()); -#else // QC -std::unique_ptr ModuleConfig::getPrimaryConfiguration() { - auto xsdConfig = - xsd::read(getReadAbleConfigurationFile(kPrimaryModuleConfigFileName.c_str()).c_str()); -#endif - if (!xsdConfig.has_value()) { - LOG(WARNING) << __func__ << ": primary config retrieval failed, setting defaults"; - return nullptr; - } - auto modules = xsdConfig.value(); - if (!modules.has_module()) { - LOG(WARNING) << __func__ << ": config has no modules at all, setting defaults"; - return nullptr; - } - auto module = - std::find_if(modules.get_module().cbegin(), modules.get_module().cend(), [](auto& ele) { - if (ele.hasName() && ele.getName() == "default") { - return true; - } - return false; - }); - if (module == modules.get_module().cend()) { - LOG(WARNING) << __func__ << ": config has no default module, setting defaults"; - return nullptr; - } - return std::move(getModuleConfig(*module)); -} - -std::string ModuleConfig::toString() const { - std::ostringstream os; - - os << std::endl << "--ModuleConfig start--" << std::endl; - - os << std::endl << "port Configs:" << std::endl; - std::for_each(portConfigs.cbegin(), portConfigs.cend(), - [&](const auto& ele) { os << ele.toString() << std::endl; }); - - os << std::endl << "initial PortConfigs:" << std::endl; - std::for_each(initialConfigs.cbegin(), initialConfigs.cend(), - [&](const auto& ele) { os << ele.toString() << std::endl; }); - - os << std::endl << "ports:" << std::endl; - std::for_each(ports.cbegin(), ports.cend(), - [&](const auto& ele) { os << ele.toString() << std::endl; }); - - os << std::endl << "mExternalDevicePortProfiles:" << std::endl; - for (const auto & [ portId, profilesList ] : mExternalDevicePortProfiles) { - os << "External device port id:" << portId << std::endl; - std::for_each(profilesList.cbegin(), profilesList.cend(), - [&](auto& ele) { os << ele.toString() << std::endl; }); - os << std::endl; - } - - os << std::endl << "routes:" << std::endl; - std::for_each(routes.cbegin(), routes.cend(), - [&](const auto& ele) { os << ele.toString() << std::endl; }); - - os << std::endl << "patches:" << std::endl; - std::for_each(patches.cbegin(), patches.cend(), - [&](const auto& ele) { os << ele.toString() << std::endl; }); - os << std::endl << "--ModuleConfig end--" << std::endl; - return os.str(); -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/include/qti-audio-core/ModuleConfig.h b/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/include/qti-audio-core/ModuleConfig.h deleted file mode 100755 index 472fe945..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/include/qti-audio-core/ModuleConfig.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * ​​​​​Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -// { SEC_AUDIO_COMMON -#include -// } SEC_AUDIO_COMMON - -namespace qti::audio::core { - -#ifdef SEC_AUDIO_COMMON -static const std::string kGsiPrimaryModuleConfigFileName{"audio_module_config_primary_sec_on_gsi.xml"}; -#endif -static const std::string kPrimaryModuleConfigFileName{"audio_module_config_primary.xml"}; - -class ModuleConfig { - public: - std::vector<::aidl::android::media::audio::common::MicrophoneInfo> microphones; - std::vector<::aidl::android::media::audio::common::AudioPort> ports; - // Exclusive for external device ports and their possible profiles - std::unordered_map> - mExternalDevicePortProfiles; - std::vector<::aidl::android::media::audio::common::AudioPortConfig> portConfigs; - std::vector<::aidl::android::media::audio::common::AudioPortConfig> initialConfigs; - // Port id -> List of profiles to use when the device port state is set to - // 'connected' in connection simulation mode. - std::map> - connectedProfiles; - std::vector<::aidl::android::hardware::audio::core::AudioRoute> routes; - std::vector<::aidl::android::hardware::audio::core::AudioPatch> patches; - std::string toString() const; - int32_t nextPortId = 1; - int32_t nextPatchId = 1; -#ifdef SEC_AUDIO_COMMON - static std::unique_ptr getPrimaryConfiguration(bool secAudioFeatureEnabled = false); -#else // QC - static std::unique_ptr getPrimaryConfiguration(); -#endif -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/Android.bp b/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/Android.bp deleted file mode 100755 index 1d0052cd..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/Android.bp +++ /dev/null @@ -1,18 +0,0 @@ -xsd_config { - name: "audio_module_config_qti", - srcs: ["audio_module_config_qti.xsd"], - package_name: "audio_module_config_qti", - nullability: true, -} - -// Uncomment below to check the validity of XML with respect to XSD -/* -prebuilt_etc_xml { - name: "audio_module_config_primary.xml", - src: "audio_module_config_primary.xml", - schema:"audio_module_config_qti.xsd", - vendor: true, - relative_install_path : "audio" -} -*/ - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/current.txt b/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/current.txt deleted file mode 100755 index 151809c1..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/current.txt +++ /dev/null @@ -1,374 +0,0 @@ -// Signature format: 2.0 -package audio_module_config_qti { - - public enum AudioChannelIndexMask { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_1; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_10; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_11; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_12; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_13; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_14; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_15; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_16; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_17; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_18; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_19; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_2; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_20; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_21; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_22; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_23; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_24; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_3; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_4; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_5; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_6; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_7; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_8; - enum_constant public static final audio_module_config_qti.AudioChannelIndexMask INDEX_MASK_9; - } - - public enum AudioChannelLayout { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_13POINT_360RA; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_22POINT2; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_2POINT0POINT2; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_2POINT1; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_2POINT1POINT2; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_3POINT0POINT2; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_3POINT1; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_3POINT1POINT2; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_5POINT1; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_5POINT1POINT2; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_5POINT1POINT4; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_5POINT1_SIDE; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_6POINT1; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_7POINT1; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_7POINT1POINT2; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_7POINT1POINT4; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_9POINT1POINT4; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_9POINT1POINT6; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_FRONT_BACK; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_HAPTIC_AB; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_MONO; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_MONO_HAPTIC_A; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_MONO_HAPTIC_AB; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_PENTA; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_QUAD; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_QUAD_SIDE; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_STEREO; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_STEREO_HAPTIC_A; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_STEREO_HAPTIC_AB; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_SURROUND; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_TRI; - enum_constant public static final audio_module_config_qti.AudioChannelLayout LAYOUT_TRI_BACK; - } - - public enum AudioDeviceType { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_ACCESSORY; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_AFE_PROXY; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_DEFAULT; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_DEVICE; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_DOCK; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_ECHO_REFERENCE; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_FM_TUNER; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_HEADSET; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_LOOPBACK; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_MICROPHONE; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_MICROPHONE_BACK; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_SUBMIX; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_TELEPHONY_RX; - enum_constant public static final audio_module_config_qti.AudioDeviceType IN_TV_TUNER; - enum_constant public static final audio_module_config_qti.AudioDeviceType NONE; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_ACCESSORY; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_AFE_PROXY; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_BROADCAST; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_CARKIT; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_DEFAULT; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_DEVICE; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_DOCK; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_ECHO_CANCELLER; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_FM; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_HEADPHONE; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_HEADSET; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_HEARING_AID; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_LINE_AUX; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_SPEAKER; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_SPEAKER_EARPIECE; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_SPEAKER_SAFE; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_SUBMIX; - enum_constant public static final audio_module_config_qti.AudioDeviceType OUT_TELEPHONY_TX; - } - - public enum AudioEncapsulationType { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioEncapsulationType IEC61937; - enum_constant public static final audio_module_config_qti.AudioEncapsulationType NONE; - } - - public enum AudioFormatType { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioFormatType DEFAULT; - enum_constant public static final audio_module_config_qti.AudioFormatType NON_PCM; - enum_constant public static final audio_module_config_qti.AudioFormatType PCM; - enum_constant public static final audio_module_config_qti.AudioFormatType SYS_RESERVED_INVALID; - } - - public enum AudioGainMode { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioGainMode CHANNELS; - enum_constant public static final audio_module_config_qti.AudioGainMode JOINT; - enum_constant public static final audio_module_config_qti.AudioGainMode RAMP; - } - - public enum AudioInputFlag { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioInputFlag DIRECT; - enum_constant public static final audio_module_config_qti.AudioInputFlag FAST; - enum_constant public static final audio_module_config_qti.AudioInputFlag HW_AV_SYNC; - enum_constant public static final audio_module_config_qti.AudioInputFlag HW_HOTWORD; - enum_constant public static final audio_module_config_qti.AudioInputFlag MMAP_NOIRQ; - enum_constant public static final audio_module_config_qti.AudioInputFlag RAW; - enum_constant public static final audio_module_config_qti.AudioInputFlag SYNC; - enum_constant public static final audio_module_config_qti.AudioInputFlag ULTRASOUND; - enum_constant public static final audio_module_config_qti.AudioInputFlag VOIP_TX; - } - - public enum AudioOutputFlag { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioOutputFlag COMPRESS_OFFLOAD; - enum_constant public static final audio_module_config_qti.AudioOutputFlag DEEP_BUFFER; - enum_constant public static final audio_module_config_qti.AudioOutputFlag DIRECT; - enum_constant public static final audio_module_config_qti.AudioOutputFlag DIRECT_PCM; - enum_constant public static final audio_module_config_qti.AudioOutputFlag FAST; - enum_constant public static final audio_module_config_qti.AudioOutputFlag GAPLESS_OFFLOAD; - enum_constant public static final audio_module_config_qti.AudioOutputFlag HW_AV_SYNC; - enum_constant public static final audio_module_config_qti.AudioOutputFlag IEC958_NONAUDIO; - enum_constant public static final audio_module_config_qti.AudioOutputFlag INCALL_MUSIC; - enum_constant public static final audio_module_config_qti.AudioOutputFlag MMAP_NOIRQ; - enum_constant public static final audio_module_config_qti.AudioOutputFlag NON_BLOCKING; - enum_constant public static final audio_module_config_qti.AudioOutputFlag PRIMARY; - enum_constant public static final audio_module_config_qti.AudioOutputFlag RAW; - enum_constant public static final audio_module_config_qti.AudioOutputFlag SPATIALIZER; - enum_constant public static final audio_module_config_qti.AudioOutputFlag SYNC; - enum_constant public static final audio_module_config_qti.AudioOutputFlag TTS; - enum_constant public static final audio_module_config_qti.AudioOutputFlag ULTRASOUND; - enum_constant public static final audio_module_config_qti.AudioOutputFlag VOIP_RX; - } - - public enum AudioPcmType { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioPcmType DEFAULT; - enum_constant public static final audio_module_config_qti.AudioPcmType FIXED_Q_8_24; - enum_constant public static final audio_module_config_qti.AudioPcmType FLOAT_32_BIT; - enum_constant public static final audio_module_config_qti.AudioPcmType INT_16_BIT; - enum_constant public static final audio_module_config_qti.AudioPcmType INT_24_BIT; - enum_constant public static final audio_module_config_qti.AudioPcmType INT_32_BIT; - enum_constant public static final audio_module_config_qti.AudioPcmType UINT_8_BIT; - } - - public enum AudioUsage { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_ALARM; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_ANNOUNCEMENT; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_ASSISTANCE_ACCESSIBILITY; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_ASSISTANCE_NAVIGATION_GUIDANCE; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_ASSISTANCE_SONIFICATION; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_ASSISTANT; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_CALL_ASSISTANT; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_EMERGENCY; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_GAME; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_INVALID; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_MEDIA; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_NOTIFICATION; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_NOTIFICATION_EVENT; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_NOTIFICATION_TELEPHONY_RINGTONE; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_SAFETY; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_SYS_RESERVED_NOTIFICATION_COMMUNICATION_DELAYED; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_SYS_RESERVED_NOTIFICATION_COMMUNICATION_INSTANT; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_SYS_RESERVED_NOTIFICATION_COMMUNICATION_REQUEST; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_UNKNOWN; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_VEHICLE_STATUS; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_VIRTUAL_SOURCE; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_VOICE_COMMUNICATION; - enum_constant public static final audio_module_config_qti.AudioUsage AUDIOUSAGE_VOICE_COMMUNICATION_SIGNALLING; - } - - public enum ConnectionType { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.ConnectionType analog; - enum_constant public static final audio_module_config_qti.ConnectionType bta2dp; - enum_constant public static final audio_module_config_qti.ConnectionType btle; - enum_constant public static final audio_module_config_qti.ConnectionType btsco; - enum_constant public static final audio_module_config_qti.ConnectionType bus; - enum_constant public static final audio_module_config_qti.ConnectionType hdmi; - enum_constant public static final audio_module_config_qti.ConnectionType hdmiarc; - enum_constant public static final audio_module_config_qti.ConnectionType hdmiearc; - enum_constant public static final audio_module_config_qti.ConnectionType ipv4; - enum_constant public static final audio_module_config_qti.ConnectionType spdif; - enum_constant public static final audio_module_config_qti.ConnectionType usb; - enum_constant public static final audio_module_config_qti.ConnectionType virtual; - enum_constant public static final audio_module_config_qti.ConnectionType wireless; - } - - public class DevicePorts { - ctor public DevicePorts(); - method @Nullable public java.util.List getDevicePort(); - } - - public static class DevicePorts.DevicePort { - ctor public DevicePorts.DevicePort(); - method @Nullable public String getAddress(); - method @Nullable public boolean getAttached(); - method @Nullable public audio_module_config_qti.ConnectionType getConnection(); - method @Nullable public boolean getDefaultDevice(); - method @Nullable public audio_module_config_qti.AudioDeviceType getDeviceType(); - method @Nullable public java.util.List getEncodings(); - method @Nullable public audio_module_config_qti.Gains getGains(); - method @Nullable public java.util.List getProfile(); - method @Nullable public audio_module_config_qti.Role getRole(); - method @Nullable public String getTagName(); - method @Nullable public boolean get_default(); - method public void setAddress(@Nullable String); - method public void setAttached(@Nullable boolean); - method public void setConnection(@Nullable audio_module_config_qti.ConnectionType); - method public void setDefaultDevice(@Nullable boolean); - method public void setDeviceType(@Nullable audio_module_config_qti.AudioDeviceType); - method public void setEncodings(@Nullable java.util.List); - method public void setGains(@Nullable audio_module_config_qti.Gains); - method public void setRole(@Nullable audio_module_config_qti.Role); - method public void setTagName(@Nullable String); - method public void set_default(@Nullable boolean); - } - - public class Gains { - ctor public Gains(); - method @Nullable public java.util.List getGain(); - } - - public static class Gains.Gain { - ctor public Gains.Gain(); - method @Nullable public audio_module_config_qti.AudioChannelLayout getChannel_layout(); - method @Nullable public int getDefaultValueMB(); - method @Nullable public int getMaxRampMs(); - method @Nullable public int getMaxValueMB(); - method @Nullable public int getMinRampMs(); - method @Nullable public int getMinValueMB(); - method @Nullable public java.util.List getMode(); - method @Nullable public String getName(); - method @Nullable public int getStepValueMB(); - method @Nullable public boolean getUseForVolume(); - method public void setChannel_layout(@Nullable audio_module_config_qti.AudioChannelLayout); - method public void setDefaultValueMB(@Nullable int); - method public void setMaxRampMs(@Nullable int); - method public void setMaxValueMB(@Nullable int); - method public void setMinRampMs(@Nullable int); - method public void setMinValueMB(@Nullable int); - method public void setMode(@Nullable java.util.List); - method public void setName(@Nullable String); - method public void setStepValueMB(@Nullable int); - method public void setUseForVolume(@Nullable boolean); - } - - public class MixPorts { - ctor public MixPorts(); - method @Nullable public java.util.List getMixPort(); - } - - public static class MixPorts.MixPort { - ctor public MixPorts.MixPort(); - method @Nullable public java.util.List getFlags(); - method @Nullable public audio_module_config_qti.Gains getGains(); - method @Nullable public long getMaxActiveCount(); - method @Nullable public long getMaxOpenCount(); - method @Nullable public String getName(); - method @Nullable public java.util.List getPreferredUsage(); - method @Nullable public java.util.List getProfile(); - method @Nullable public long getRecommendedMuteDurationMs(); - method @Nullable public audio_module_config_qti.Role getRole(); - method public void setFlags(@Nullable java.util.List); - method public void setGains(@Nullable audio_module_config_qti.Gains); - method public void setMaxActiveCount(@Nullable long); - method public void setMaxOpenCount(@Nullable long); - method public void setName(@Nullable String); - method public void setPreferredUsage(@Nullable java.util.List); - method public void setRecommendedMuteDurationMs(@Nullable long); - method public void setRole(@Nullable audio_module_config_qti.Role); - } - - public enum MixType { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.MixType mix; - enum_constant public static final audio_module_config_qti.MixType mux; - } - - public class Modules { - ctor public Modules(); - method @Nullable public audio_module_config_qti.Modules.Module getModule(); - method public void setModule(@Nullable audio_module_config_qti.Modules.Module); - } - - public static class Modules.Module { - ctor public Modules.Module(); - method @Nullable public audio_module_config_qti.DevicePorts getDevicePorts(); - method @Nullable public audio_module_config_qti.MixPorts getMixPorts(); - method @Nullable public String getName(); - method @Nullable public audio_module_config_qti.Routes getRoutes(); - method public void setDevicePorts(@Nullable audio_module_config_qti.DevicePorts); - method public void setMixPorts(@Nullable audio_module_config_qti.MixPorts); - method public void setName(@Nullable String); - method public void setRoutes(@Nullable audio_module_config_qti.Routes); - } - - public class Profile { - ctor public Profile(); - method @Nullable public java.util.List getChannelLayouts(); - method @Nullable public java.util.List getChannelMasks(); - method @Nullable public audio_module_config_qti.AudioEncapsulationType getEncapsulationType(); - method @Nullable public String getEncoding(); - method @Nullable public audio_module_config_qti.AudioFormatType getFormatType(); - method @Nullable public String getName(); - method @Nullable public audio_module_config_qti.AudioPcmType getPcmType(); - method @Nullable public java.util.List getSamplingRates(); - method public void setChannelLayouts(@Nullable java.util.List); - method public void setChannelMasks(@Nullable java.util.List); - method public void setEncapsulationType(@Nullable audio_module_config_qti.AudioEncapsulationType); - method public void setEncoding(@Nullable String); - method public void setFormatType(@Nullable audio_module_config_qti.AudioFormatType); - method public void setName(@Nullable String); - method public void setPcmType(@Nullable audio_module_config_qti.AudioPcmType); - method public void setSamplingRates(@Nullable java.util.List); - } - - public enum Role { - method @NonNull public String getRawName(); - enum_constant public static final audio_module_config_qti.Role sink; - enum_constant public static final audio_module_config_qti.Role source; - } - - public class Routes { - ctor public Routes(); - method @Nullable public java.util.List getRoute(); - } - - public static class Routes.Route { - ctor public Routes.Route(); - method @Nullable public String getSink(); - method @Nullable public String getSources(); - method @Nullable public audio_module_config_qti.MixType getType(); - method public void setSink(@Nullable String); - method public void setSources(@Nullable String); - method public void setType(@Nullable audio_module_config_qti.MixType); - } - - public class XmlParser { - ctor public XmlParser(); - method @Nullable public static audio_module_config_qti.Modules read(@NonNull java.io.InputStream) throws javax.xml.datatype.DatatypeConfigurationException, java.io.IOException, org.xmlpull.v1.XmlPullParserException; - method @Nullable public static String readText(@NonNull org.xmlpull.v1.XmlPullParser) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException; - method public static void skip(@NonNull org.xmlpull.v1.XmlPullParser) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException; - } - -} - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/last_current.txt b/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/last_current.txt deleted file mode 100755 index e69de29b..00000000 diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/last_removed.txt b/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/last_removed.txt deleted file mode 100755 index e69de29b..00000000 diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/removed.txt b/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/removed.txt deleted file mode 100755 index d802177e..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/api/removed.txt +++ /dev/null @@ -1 +0,0 @@ -// Signature format: 2.0 diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/audio_module_config_qti.xsd b/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/audio_module_config_qti.xsd deleted file mode 100755 index 0d08e6ec..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/module_config/schema/audio_module_config_qti.xsd +++ /dev/null @@ -1,425 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/Android.mk deleted file mode 100755 index 0fbd8228..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/Android.mk +++ /dev/null @@ -1,43 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) -LOCAL_MODULE := libaudioplatform.qti -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_C_INCLUDES += \ - $(LOCAL_PATH)/include \ - $(LOCAL_PATH)/../extensions/include \ - $(TOP)/system/media/audio/include \ - $(TOP)/hardware/libhardware/include - -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include - -LOCAL_SRC_FILES := \ - Platform.cpp \ - AudioUsecase.cpp \ - PlatformUtils.cpp - -LOCAL_WHOLE_STATIC_LIBRARIES := libaudio_microphoneinfo_parser - -LOCAL_STATIC_LIBRARIES := \ - libaudiohalutils.qti - -LOCAL_SHARED_LIBRARIES := \ - libbinder_ndk \ - libbase \ - libstagefright_foundation \ - android.hardware.audio.core-V2-ndk \ - android.media.audio.common.types-V3-ndk \ - libaudioaidlcommon \ - qti-audio-types-aidl-V1-ndk \ - libaudioplatformconverter.qti \ - libar-pal - -# { SEC_AUDIO_COMMON -SEC_AUDIO_VARS := vendor/samsung/variant/audio/sec_audioreach_vars.mk -include $(SEC_AUDIO_VARS) -# } SEC_AUDIO_COMMON - -include $(BUILD_STATIC_LIBRARY) diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/AudioUsecase.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/AudioUsecase.cpp deleted file mode 100755 index e1255db1..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/AudioUsecase.cpp +++ /dev/null @@ -1,1264 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -#define LOG_TAG "AHAL_Usecase_QTI" - - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using ::aidl::android::media::audio::common::AudioIoFlags; -using ::aidl::android::media::audio::common::AudioInputFlags; -using ::aidl::android::media::audio::common::AudioOutputFlags; -using ::aidl::android::media::audio::common::AudioSource; -using ::aidl::android::media::audio::common::AudioStreamType; -using ::aidl::android::hardware::audio::common::isBitPositionFlagSet; -using ::aidl::android::hardware::audio::common::getChannelCount; -using ::aidl::android::hardware::audio::common::getFrameSizeInBytes; -using ::aidl::android::hardware::audio::common::getPcmSampleSizeInBytes; -using ::aidl::android::media::audio::common::AudioPortConfig; -using ::aidl::android::media::audio::common::AudioPortExt; -using ::aidl::android::media::audio::common::AudioPortMixExtUseCase; -using ::aidl::android::hardware::audio::core::VendorParameter; -using ::aidl::android::media::audio::common::AudioChannelLayout; -using ::aidl::android::hardware::audio::common::AudioOffloadMetadata; - -namespace qti::audio::core { - -#ifdef SEC_AUDIO_COMMON -std::optional getMixPortAudioSource( - const AudioPortConfig& mixPortconfig) noexcept { - if (mixPortconfig.ext.getTag() != AudioPortExt::Tag::mix) { - LOG(ERROR) << __func__ << ": not a mix port, " << mixPortconfig.toString(); - return std::nullopt; - } - if (mixPortconfig.ext.get().usecase.getTag() != - AudioPortMixExtUseCase::Tag::source) { - LOG(ERROR) << __func__ << ": no source provided, " << mixPortconfig.toString(); - return std::nullopt; - } - return mixPortconfig.ext.get() - .usecase.get(); -} -#endif - -Usecase getUsecaseTag(const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) { - Usecase tag = Usecase::INVALID; - if (!mixPortConfig.flags || mixPortConfig.ext.getTag() != AudioPortExt::Tag::mix) { - LOG(ERROR) << __func__ << " cannot determine usecase, no flags set for mix port " - "config or it isn't mix port, " - << mixPortConfig.toString(); - return tag; - } - - if (!(mixPortConfig.sampleRate) || (mixPortConfig.sampleRate.value().value == 0)) { - LOG(ERROR) << __func__ << ": mix port config missing sample rate!!!"; - return tag; - } - - const auto& streamSampleRate = mixPortConfig.sampleRate.value().value; - const auto& mixUsecase = mixPortConfig.ext.get().usecase; - const auto mixUsecaseTag = mixUsecase.getTag(); - - const auto& flagsTag = mixPortConfig.flags.value().getTag(); - constexpr auto flagCastToint = [](auto flag) { return static_cast(flag); }; - - const auto& channelLayout = mixPortConfig.channelMask.value(); - - constexpr int32_t noneFlags = 0; - constexpr auto primaryPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::PRIMARY)); - constexpr auto deepBufferPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::DEEP_BUFFER)); - constexpr auto compressOffloadPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::DIRECT) | - 1 << flagCastToint(AudioOutputFlags::COMPRESS_OFFLOAD) | - 1 << flagCastToint(AudioOutputFlags::NON_BLOCKING) | - 1 << flagCastToint(AudioOutputFlags::GAPLESS_OFFLOAD)); - constexpr auto fastRecordFlags = - static_cast(1 << flagCastToint(AudioInputFlags::FAST)); - constexpr auto ullRecordFlags = static_cast( - 1 << flagCastToint(AudioInputFlags::FAST)| 1 << flagCastToint(AudioInputFlags::RAW)); - constexpr auto compressCaptureFlags = - static_cast(1 << flagCastToint(AudioInputFlags::DIRECT)); -#ifdef SEC_AUDIO_COMMON - constexpr auto lowLatencyPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::FAST) -#ifdef SEC_AUDIO_SUPPORT_LOWLATENCY_MEDIA - | 1 << flagCastToint(AudioOutputFlags::MEDIA) -#endif - ); -#else - constexpr auto lowLatencyPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::PRIMARY) | - 1 << flagCastToint(AudioOutputFlags::FAST)); -#endif - constexpr auto pcmOffloadPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::DIRECT)); - constexpr auto voipPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::VOIP_RX)); - constexpr auto spatialPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::SPATIALIZER)); - constexpr auto recordVoipFlags = - static_cast(1 << flagCastToint(AudioInputFlags::VOIP_TX)); - constexpr auto ullPlaybackFlags = static_cast( - 1 << flagCastToint(AudioOutputFlags::FAST) | 1 << flagCastToint(AudioOutputFlags::RAW)); - constexpr auto mmapPlaybackFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::DIRECT) | - 1 << flagCastToint(AudioOutputFlags::MMAP_NOIRQ)); - constexpr auto mmapRecordFlags = - static_cast(1 << flagCastToint(AudioInputFlags::MMAP_NOIRQ)); - constexpr auto inCallMusicFlags = - static_cast(1 << flagCastToint(AudioOutputFlags::INCALL_MUSIC)); - constexpr auto hotWordRecordFlags = - static_cast(1 << flagCastToint(AudioInputFlags::HW_HOTWORD)); - - if (flagsTag == AudioIoFlags::Tag::output) { - auto& outFlags = mixPortConfig.flags.value().get(); - if (channelLayout.getTag() == AudioChannelLayout::Tag::layoutMask && - channelLayout.get() == - AudioChannelLayout::LAYOUT_STEREO_HAPTIC_A) { - tag = Usecase::HAPTICS_PLAYBACK; - } else if (outFlags == primaryPlaybackFlags) { - tag = Usecase::PRIMARY_PLAYBACK; - } else if (outFlags == deepBufferPlaybackFlags || (outFlags == noneFlags)) { - tag = Usecase::DEEP_BUFFER_PLAYBACK; - } else if (outFlags == lowLatencyPlaybackFlags) { - tag = Usecase::LOW_LATENCY_PLAYBACK; - } else if (outFlags == compressOffloadPlaybackFlags) { - tag = Usecase::COMPRESS_OFFLOAD_PLAYBACK; - } else if (outFlags == pcmOffloadPlaybackFlags) { - tag = Usecase::PCM_OFFLOAD_PLAYBACK; - } else if (outFlags == voipPlaybackFlags) { - tag = Usecase::VOIP_PLAYBACK; - } else if (outFlags == spatialPlaybackFlags) { - tag = Usecase::SPATIAL_PLAYBACK; - } else if (outFlags == ullPlaybackFlags) { - tag = Usecase::ULL_PLAYBACK; - } else if (outFlags == mmapPlaybackFlags) { - tag = Usecase::MMAP_PLAYBACK; - } else if (outFlags == inCallMusicFlags) { - tag = Usecase::IN_CALL_MUSIC; - } - } else if (flagsTag == AudioIoFlags::Tag::input) { - auto& inFlags = mixPortConfig.flags.value().get(); - tag = Usecase::PCM_RECORD; - if (inFlags == noneFlags) { - tag = Usecase::PCM_RECORD; - if (mixUsecaseTag == AudioPortMixExtUseCase::source) { - auto& source = mixUsecase.get(); - if (source == AudioSource::VOICE_UPLINK || source == AudioSource::VOICE_DOWNLINK || - source == AudioSource::VOICE_CALL) { - tag = Usecase::VOICE_CALL_RECORD; - } - } - } else if (inFlags == fastRecordFlags) { - tag = Usecase::FAST_RECORD; - } else if (inFlags == ullRecordFlags) { - tag = Usecase::ULTRA_FAST_RECORD; - } else if (inFlags == compressCaptureFlags) { - tag = Usecase::COMPRESS_CAPTURE; -#if SEC_AUDIO_CALL_VOIP - } else if (inFlags == recordVoipFlags && mixUsecaseTag == AudioPortMixExtUseCase::source && - ((mixUsecase.get() == - AudioSource::VOICE_COMMUNICATION) || - (mixUsecase.get() == - AudioSource::MIC))) { - -#else - } else if (inFlags == recordVoipFlags && mixUsecaseTag == AudioPortMixExtUseCase::source && - mixUsecase.get() == - AudioSource::VOICE_COMMUNICATION) { -#endif - tag = Usecase::VOIP_RECORD; - } else if (inFlags == mmapRecordFlags) { - tag = Usecase::MMAP_RECORD; - } else if (inFlags == hotWordRecordFlags) { - tag = Usecase::HOTWORD_RECORD; - } -#ifdef SEC_AUDIO_SOUND_TRIGGER_TYPE - auto& platform = Platform::getInstance(); - const auto& source = getAudioSource(mixPortConfig); - if (inFlags != hotWordRecordFlags && platform.isSeamlessEnabled() && source && source.value() == AudioSource::VOICE_RECOGNITION) { - tag = Usecase::HOTWORD_RECORD; - } -#endif - } - LOG(VERBOSE) << __func__ << " choosen " << getName(tag) << " for mix port config " - << mixPortConfig.toString(); - return tag; -} - -std::string getName(const Usecase tag) { - switch (tag) { - case Usecase::INVALID: - return "INVALID"; - case Usecase::PRIMARY_PLAYBACK: - return "PRIMARY_PLAYBACK"; - case Usecase::DEEP_BUFFER_PLAYBACK: - return "DEEP_BUFFER_PLAYBACK"; - case Usecase::LOW_LATENCY_PLAYBACK: - return "LOW_LATENCY_PLAYBACK"; - case Usecase::PCM_RECORD: - return "PCM_RECORD"; - case Usecase::COMPRESS_OFFLOAD_PLAYBACK: - return "COMPRESS_OFFLOAD_PLAYBACK"; - case Usecase::COMPRESS_CAPTURE: - return "COMPRESS_CAPTURE"; - case Usecase::PCM_OFFLOAD_PLAYBACK: - return "PCM_OFFLOAD_PLAYBACK"; - case Usecase::VOIP_PLAYBACK: - return "VOIP_PLAYBACK"; - case Usecase::SPATIAL_PLAYBACK: - return "SPATIAL_PLAYBACK"; - case Usecase::VOIP_RECORD: - return "VOIP_RECORD"; - case Usecase::ULL_PLAYBACK: - return "ULL_PLAYBACK"; - case Usecase::MMAP_PLAYBACK: - return "MMAP_PLAYBACK"; - case Usecase::MMAP_RECORD: - return "MMAP_RECORD"; - case Usecase::VOICE_CALL_RECORD: - return "VOICE_CALL_RECORD"; - case Usecase::IN_CALL_MUSIC: - return "IN_CALL_MUSIC"; - case Usecase::FAST_RECORD: - return "FAST_RECORD"; - case Usecase::ULTRA_FAST_RECORD: - return "ULTRA_FAST_RECORD"; - case Usecase::HOTWORD_RECORD: - return "HOTWORD_RECORD"; - case Usecase::HAPTICS_PLAYBACK: - return "HAPTICS_PLAYBACK"; - default: - return std::to_string(static_cast(tag)); - } -} - -auto getIntValueFromVString = []( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& parameters, - const std::string& searchKey) -> std::optional { - std::optional<::aidl::qti::audio::core::VString> parcel; - for (const auto& p : parameters) { - if (p.id == searchKey && p.ext.getParcelable(&parcel) == ::android::OK && - parcel.has_value()) { - int32_t value = strtol(parcel.value().value.c_str(), nullptr, 10); - return value; - } - } - return std::nullopt; -}; - -// [LowLatencyPlayback Start] -std::unordered_set LowLatencyPlayback::kSupportedFrameSizes = {160, 192, 240, 320, 480}; - -size_t LowLatencyPlayback::getFrameCount(const AudioPortConfig& mixPortConfig) { - const std::string kPeriodSizeProp = "vendor.audio_hal.period_size"; - size_t periodSize = kPeriodDurationMs * getSampleRate(mixPortConfig).value() / 1000; - auto frameSize = ::android::base::GetUintProperty(kPeriodSizeProp, periodSize); - if (kSupportedFrameSizes.count(frameSize)) { - return frameSize; - } - return periodSize; -} - -// [LowLatencyPlayback End] - -// [Deep Buffer Start] - -size_t DeepBufferPlayback::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kPeriodDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [Deep Buffer End] -size_t PrimaryPlayback::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kPeriodDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [ULLPlayback Start] -size_t UllPlayback::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kPeriodDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [ULLPlayback End] - -// [MmapUsecaseBase Start] - -void MmapUsecaseBase::setPalHandle(pal_stream_handle_t* handle) { - mPalHandle = handle; -} - -int32_t MmapUsecaseBase::createMMapBuffer(int64_t frameSize, int32_t* fd, int64_t* burstSizeFrames, - int32_t* flags, int32_t* bufferSizeFrames) { - if (!mPalHandle) { - LOG(ERROR) << __func__ << ": pal stream handle is null"; - return -EINVAL; - } - struct pal_mmap_buffer palMMapBuf; - if (int32_t ret = pal_stream_create_mmap_buffer(mPalHandle, frameSize, &palMMapBuf); ret) { - LOG(ERROR) << __func__ << ": pal stream create mmap buffer failed " - << "returned " << ret; - return ret; - } - *fd = palMMapBuf.fd; - *burstSizeFrames = palMMapBuf.burst_size_frames; - *flags = palMMapBuf.flags; - *bufferSizeFrames = palMMapBuf.buffer_size_frames; - LOG(DEBUG) << __func__ << " burstSizeFrames " << *burstSizeFrames << " flags " << *flags - << " bufferSizeFrames " << *bufferSizeFrames << " fd " << *fd; - return 0; -} - -int32_t MmapUsecaseBase::getMMapPosition(int64_t* frames, int64_t* timeNs) { - if (!mPalHandle) { - LOG(ERROR) << __func__ << ": pal stream handle is null"; - return -EINVAL; - } - struct pal_mmap_position pal_mmap_pos; - if (int32_t ret = pal_stream_get_mmap_position(mPalHandle, &pal_mmap_pos); ret) { - LOG(ERROR) << __func__ << ": failed to get mmap positon " - << "returned " << ret; - return ret; - } - *timeNs = pal_mmap_pos.time_nanoseconds; - *frames = pal_mmap_pos.position_frames; - LOG(VERBOSE) << __func__ << ": frames:" << *frames << ", timeNs:" << *timeNs; - return 0; -} - -int32_t MmapUsecaseBase::start() { - if (!mPalHandle) { - LOG(ERROR) << __func__ << ": pal stream handle is null"; - return -EINVAL; - } - - if (mIsStarted) { - LOG(VERBOSE) << __func__ << ": MMAP already started"; - return 0; - } - - if (int32_t ret = ::pal_stream_start(mPalHandle); ret) { - LOG(ERROR) << __func__ << " pal stream start failed, ret:" << ret; - return ret; - } - - mIsStarted = true; - LOG(VERBOSE) << __func__ << ": MMAP start success"; - - return 0; -} - -int32_t MmapUsecaseBase::stop() { - if (!mPalHandle) { - LOG(ERROR) << __func__ << ": pal stream handle is null"; - return -EINVAL; - } - - if (!mIsStarted) { - LOG(VERBOSE) << __func__ << ": MMAP already stopped"; - return 0; - } - - if (int32_t ret = ::pal_stream_stop(mPalHandle); ret) { - LOG(ERROR) << __func__ << " pal stream stop failed, ret:" << ret; - return -EINVAL; - } - - mIsStarted = false; - LOG(VERBOSE) << __func__ << ": MMAP stop success"; - - return 0; -} - -// [MmapUsecaseBase End] -// [MMapPlayback Start] -size_t MMapPlayback::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kPeriodDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [MMapPlayback End] - -// [CompressPlayback Start] -size_t CompressPlayback::getFrameCount(const AudioPortConfig& mixPortConfig) { - auto format = mixPortConfig.format.value(); - size_t periodSize = kPeriodSize; - if (format.encoding == ::android::MEDIA_MIMETYPE_AUDIO_FLAC) { - periodSize = Flac::kPeriodSize; - } - - const std::string kCompressPeriodSizeProp{"vendor.audio.offload.buffer.size.kb"}; - auto propPeriodSize = - ::android::base::GetUintProperty(kCompressPeriodSizeProp, 0) * 1024; - - if (propPeriodSize > periodSize) { - periodSize = propPeriodSize; - } - return periodSize; -} - -CompressPlayback::CompressPlayback( - const ::aidl::android::media::audio::common::AudioOffloadInfo& offloadInfo, - PlatformStreamCallback* const callback, - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) - : mOffloadInfo(offloadInfo), mPlatformStreamCallback(callback), mMixPortConfig(mixPortConfig) { - configureDefault(); -} - -void CompressPlayback::configureDefault() { - mSampleRate = mOffloadInfo.base.sampleRate; - mCompressFormat = mOffloadInfo.base.format; - mChannelLayout = mOffloadInfo.base.channelMask; - mBitWidth = mOffloadInfo.bitWidth; - - if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_MP4 || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADIF || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS || -#ifdef SEC_AUDIO_OFFLOAD - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC || -#endif - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_HE_V1 || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_HE_V2 || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_LC) { - mPalSndDec.aac_dec.audio_obj_type = 29; - mPalSndDec.aac_dec.pce_bits_size = 0; - } - - LOG(INFO) << __func__ << ": " << mOffloadInfo.toString(); - return; -} - -void CompressPlayback::setAndConfigureCodecInfo(pal_stream_handle_t* handle) { - mCompressPlaybackHandle = handle; - if (mCompressPlaybackHandle == nullptr) { - return; - } - configureCodecInfo(); -} - -void CompressPlayback::configureGapless(pal_stream_handle_t* handle) { - mCompressPlaybackHandle = handle; - if (mCompressPlaybackHandle == nullptr) { - return; - } - configureGapLessMetadata(); -} - -ndk::ScopedAStatus CompressPlayback::getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return) { - return ndk::ScopedAStatus::ok(); -} - -// static -int32_t CompressPlayback::palCallback(pal_stream_handle_t* palHandle, uint32_t eventId, - uint32_t* eventData, uint32_t eventSize, uint64_t cookie) { - auto compressPlayback = reinterpret_cast(cookie); - - switch (eventId) { - case PAL_STREAM_CBK_EVENT_WRITE_READY: { - compressPlayback->mPlatformStreamCallback->onTransferReady(); - } break; - case PAL_STREAM_CBK_EVENT_DRAIN_READY: { - compressPlayback->mPlatformStreamCallback->onDrainReady(); - } break; - case PAL_STREAM_CBK_EVENT_PARTIAL_DRAIN_READY: { - compressPlayback->mPlatformStreamCallback->onDrainReady(); - // gapless resets in PAL, when partial drain is received, - compressPlayback->mIsGaplessConfigured = false; - } break; - case PAL_STREAM_CBK_EVENT_ERROR: { - compressPlayback->mPlatformStreamCallback->onError(); - } break; - default: - LOG(ERROR) << __func__ << " invalid!!! event id:" << eventId; - return -EINVAL; - } - return 0; -} - -ndk::ScopedAStatus CompressPlayback::setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& in_parameters, - bool in_async) { - LOG(VERBOSE) << __func__ << ": parameter count:" << in_parameters.size() << " parsing for " - << mCompressFormat.encoding; - bool isCompressMetadataAvail = false; - if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_FLAC) { - if (auto value = getIntValueFromVString(in_parameters, Flac::kMinBlockSize); value) { - mPalSndDec.flac_dec.min_blk_size = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Flac::kMaxBlockSize); value) { - mPalSndDec.flac_dec.max_blk_size = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Flac::kMinFrameSize); value) { - mPalSndDec.flac_dec.min_frame_size = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Flac::kMaxFrameSize); value) { - mPalSndDec.flac_dec.max_frame_size = value.value(); - isCompressMetadataAvail = true; - } - // exception - mPalSndDec.flac_dec.sample_size = (mBitWidth == 32) ? 24 : mBitWidth; - } else if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_ALAC) { - if (auto value = getIntValueFromVString(in_parameters, Alac::kFrameLength); value) { - mPalSndDec.alac_dec.frame_length = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kCompatVer); value) { - mPalSndDec.alac_dec.compatible_version = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kBitDepth); value) { - mPalSndDec.alac_dec.bit_depth = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kPb); value) { - mPalSndDec.alac_dec.pb = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kMb); value) { - mPalSndDec.alac_dec.mb = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kKb); value) { - mPalSndDec.alac_dec.kb = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kNumChannels); value) { - mPalSndDec.alac_dec.num_channels = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kMaxRun); value) { - mPalSndDec.alac_dec.max_run = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kMaxFrameBytes); value) { - mPalSndDec.alac_dec.max_frame_bytes = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kBitRate); value) { - mPalSndDec.alac_dec.avg_bit_rate = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kSamplingRate); value) { - mPalSndDec.alac_dec.sample_rate = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Alac::kChannelLayoutTag); value) { - mPalSndDec.alac_dec.channel_layout_tag = value.value(); - isCompressMetadataAvail = true; - } - } else if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_MP4 || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADIF || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC) { - mPalSndDec.aac_dec.audio_obj_type = 29; - mPalSndDec.aac_dec.pce_bits_size = 0; - } else if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_VORBIS) { - if (auto value = getIntValueFromVString(in_parameters, Vorbis::kBitStreamFormat); value) { - mPalSndDec.vorbis_dec.bit_stream_fmt = value.value(); - isCompressMetadataAvail = true; - } - } else if (mCompressFormat.encoding == "audio/x-ape") { - if (auto value = getIntValueFromVString(in_parameters, Ape::kCompatibleVersion); value) { - mPalSndDec.ape_dec.compatible_version = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Ape::kCompressionLevel); value) { - mPalSndDec.ape_dec.compression_level = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Ape::kFormatFlags); value) { - mPalSndDec.ape_dec.format_flags = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Ape::kBlocksPerFrame); value) { - mPalSndDec.ape_dec.blocks_per_frame = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Ape::kFinalFrameBlocks); value) { - mPalSndDec.ape_dec.final_frame_blocks = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Ape::kTotalFrames); value) { - mPalSndDec.ape_dec.total_frames = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Ape::kBitsPerSample); value) { - mPalSndDec.ape_dec.bits_per_sample = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Ape::kNumChannels); value) { - mPalSndDec.ape_dec.num_channels = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Ape::kSampleRate); value) { - mPalSndDec.ape_dec.sample_rate = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Ape::kSeekTablePresent); value) { - mPalSndDec.ape_dec.seek_table_present = value.value(); - isCompressMetadataAvail = true; - } - } else if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_WMA || - mCompressFormat.encoding == "audio/x-ms-wma.pro") { - if (auto value = getIntValueFromVString(in_parameters, Wma::kFormatTag); value) { - mPalSndDec.wma_dec.fmt_tag = value.value(); - isCompressMetadataAvail = true; - } - mPalSndDec.wma_dec.avg_bit_rate = mOffloadMetadata.averageBitRatePerSecond; - - LOG(VERBOSE) << __func__ << ": averageBitRatePerSecond " - << mOffloadMetadata.averageBitRatePerSecond; - if (auto value = getIntValueFromVString(in_parameters, Wma::kBlockAlign); value) { - mPalSndDec.wma_dec.super_block_align = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Wma::kBitPerSample); value) { - mPalSndDec.wma_dec.bits_per_sample = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Wma::kChannelMask); value) { - mPalSndDec.wma_dec.channelmask = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Wma::kEncodeOption); value) { - mPalSndDec.wma_dec.encodeopt = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Wma::kEncodeOption1); value) { - mPalSndDec.wma_dec.encodeopt1 = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Wma::kEncodeOption2); value) { - mPalSndDec.wma_dec.encodeopt2 = value.value(); - isCompressMetadataAvail = true; - } - } else if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_OPUS) { - if (auto value = getIntValueFromVString(in_parameters, Opus::kBitStreamFormat); value) { - mPalSndDec.opus_dec.bitstream_format = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kPayloadType); value) { - mPalSndDec.opus_dec.payload_type = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kVersion); value) { - mPalSndDec.opus_dec.version = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kNumChannels); value) { - mPalSndDec.opus_dec.num_channels = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kPreSkip); value) { - mPalSndDec.opus_dec.pre_skip = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kOutputGain); value) { - mPalSndDec.opus_dec.output_gain = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kMappingFamily); value) { - mPalSndDec.opus_dec.mapping_family = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kStreamCount); value) { - mPalSndDec.opus_dec.stream_count = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kCoupledCount); value) { - mPalSndDec.opus_dec.coupled_count = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kChannelMap0); value) { - mPalSndDec.opus_dec.channel_map[0] = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kChannelMap1); value) { - mPalSndDec.opus_dec.channel_map[1] = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kChannelMap2); value) { - mPalSndDec.opus_dec.channel_map[2] = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kChannelMap3); value) { - mPalSndDec.opus_dec.channel_map[3] = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kChannelMap4); value) { - mPalSndDec.opus_dec.channel_map[4] = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kChannelMap5); value) { - mPalSndDec.opus_dec.channel_map[5] = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kChannelMap6); value) { - mPalSndDec.opus_dec.channel_map[6] = value.value(); - isCompressMetadataAvail = true; - } - if (auto value = getIntValueFromVString(in_parameters, Opus::kChannelMap7); value) { - mPalSndDec.opus_dec.channel_map[7] = value.value(); - isCompressMetadataAvail = true; - } - mPalSndDec.opus_dec.sample_rate = mSampleRate; - } - if(mCompressPlaybackHandle == nullptr){ - return ndk::ScopedAStatus::ok(); - } - LOG(VERBOSE) << __func__ << ": trying for on-the-fly codec configuration"; - if (isCompressMetadataAvail) - configureCodecInfo(); - return ndk::ScopedAStatus::ok(); -} - -bool CompressPlayback::configureGapLessMetadata() { - const auto payloadSize = sizeof(pal_param_payload); - const auto kGapLessSize = sizeof(pal_compr_gapless_mdata); - auto dataPtr = std::make_unique(payloadSize + kGapLessSize); - auto payloadPtr = reinterpret_cast(dataPtr.get()); - payloadPtr->payload_size = kGapLessSize; - auto gapLessPtr = reinterpret_cast(dataPtr.get() + payloadSize); - gapLessPtr->encoderDelay = mOffloadMetadata.delayFrames; - gapLessPtr->encoderPadding = mOffloadMetadata.paddingFrames; - - if (mCompressPlaybackHandle) { - if (int32_t ret = ::pal_stream_set_param(mCompressPlaybackHandle, PAL_PARAM_ID_GAPLESS_MDATA, - payloadPtr); - ret) { - LOG(ERROR) << __func__ << ": failed PAL_PARAM_ID_GAPLESS_MDATA!! ret:" << ret; - return false; - } - mIsGaplessConfigured = true; - LOG(VERBOSE) << __func__ << ": encoderDelay:" << gapLessPtr->encoderDelay - << ", encoderPadding:" << gapLessPtr->encoderPadding; - return true; - } -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - LOG(INFO) << __func__ << " PAL stream handle is NULL!"; -#else - LOG(ERROR) << __func__ << " PAL stream handle is NULL!"; -#endif - return false; -} - -void CompressPlayback::updateOffloadMetadata( - const ::aidl::android::hardware::audio::common::AudioOffloadMetadata& offloadMetaData) { - mOffloadMetadata = offloadMetaData; - mSampleRate = mOffloadMetadata.sampleRate; - mChannelLayout = mOffloadMetadata.channelMask; - configureGapLessMetadata(); - return; -} - -void CompressPlayback::updateSourceMetadata( - const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetaData) { - mSourceMetadata = &sourceMetaData; - // TODO check for any pal update - LOG(INFO) << __func__ << ": " << mSourceMetadata->toString(); - return; -} - -bool CompressPlayback::configureCodecInfo() const { - auto dataPtr = std::make_unique(sizeof(pal_param_payload) + sizeof(pal_snd_dec_t)); - auto palParamPayload = reinterpret_cast(dataPtr.get()); - palParamPayload->payload_size = sizeof(pal_snd_dec_t); - auto palSndDecPtr = reinterpret_cast(dataPtr.get() + sizeof(pal_param_payload)); - *palSndDecPtr = mPalSndDec; - if (mCompressPlaybackHandle) { - if (int32_t ret = - ::pal_stream_set_param(mCompressPlaybackHandle, PAL_PARAM_ID_CODEC_CONFIGURATION, - reinterpret_cast(dataPtr.get())); - ret) { - LOG(ERROR) << __func__ << " PAL_PARAM_ID_CODEC_CONFIGURATION failed, ret:" << ret; - return false; - } - LOG(VERBOSE) << __func__ << " PAL_PARAM_ID_CODEC_CONFIGURATION successful"; - return true; - } - LOG(ERROR) << __func__ << " PAL stream handle is NULL!"; - return false; -} - -int64_t CompressPlayback::getPositionInFrames(pal_stream_handle_t* palHandle) { - if (palHandle == nullptr) { - return mTotalDSPFrames + mPrevFrames; - } - - pal_session_time tstamp; - if (int32_t ret = ::pal_get_timestamp(palHandle, &tstamp); ret) { - LOG(ERROR) << __func__ << " pal_get_timestamp failure, returning previous" << ret; - return mTotalDSPFrames + mPrevFrames; - } - - uint64_t sessionTimeUs = - ((static_cast(tstamp.session_time.value_msw)) << 32 | - tstamp.session_time.value_lsw); - const auto& sampleRate = getSampleRate(mMixPortConfig).value(); - // sessionTimeUs to frames - // try to convert the session to frames without loss of precision. - mPrevFrames = static_cast((sessionTimeUs / 1000) * sampleRate / 1000); - LOG(VERBOSE) << __func__ << " dsp frames consumed: (" << mTotalDSPFrames << "+" << mPrevFrames - << ") = " << mTotalDSPFrames + mPrevFrames; - return mTotalDSPFrames + mPrevFrames; -} - -void CompressPlayback::onFlush() { - // on flush SPR module is reset to 0. Hence, we cache the DSP frames - mTotalDSPFrames = mTotalDSPFrames + mPrevFrames; - mPrevFrames = 0; -} - -// [CompressPlayback End] - -// [PcmOffloadPlayback Start] - -size_t PcmOffloadPlayback::getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) { - const auto frameSize = - getFrameSizeInBytes(mixPortConfig.format.value(), mixPortConfig.channelMask.value()); - if (frameSize == 0) { - LOG(ERROR) << __func__ << ": could not calculate frame size for port config " - << mixPortConfig.toString(); - return 0; - } - - size_t periodSize = - (mixPortConfig.sampleRate.value().value * kPeriodDurationMs * frameSize) / 1000; - - if (periodSize < kMinPeriodSize) { - periodSize = kMinPeriodSize; - } else if (periodSize > kMaxPeriodSize) { - periodSize = kMaxPeriodSize; - } - - periodSize = ALIGN(periodSize, (frameSize * 32)); - - if (auto res = Platform::requiresBufferReformat(mixPortConfig)) { - audio_format_t inFormat = res->first; - audio_format_t outFormat = res->second; - periodSize = - (periodSize * audio_bytes_per_sample(inFormat)) / audio_bytes_per_sample(outFormat); - } - - return periodSize / frameSize; -} - -int64_t PcmOffloadPlayback::getPositionInFrames(pal_stream_handle_t* palHandle) { - if (palHandle == nullptr) { - return mTotalDSPFrames + mPrevFrames; - } - - // if sound card not up, then cache position - auto& platform = Platform::getInstance(); - if (!platform.isSoundCardUp()) { - mTotalDSPFrames = mTotalDSPFrames + mPrevFrames; - return mTotalDSPFrames; - } - - pal_session_time tstamp; - if (int32_t ret = ::pal_get_timestamp(palHandle, &tstamp); ret) { - LOG(ERROR) << __func__ << " pal_get_timestamp failure, returning previous" << ret; - return mTotalDSPFrames + mPrevFrames; - } - - uint64_t sessionTimeUs = - ((static_cast(tstamp.session_time.value_msw)) << 32 | - tstamp.session_time.value_lsw); - const auto& sampleRate = getSampleRate(mMixPortConfig).value(); - // sessionTimeUs to frames - // try to convert the session to frames without loss of precision. - mPrevFrames = static_cast((sessionTimeUs / 1000) * sampleRate / 1000); - LOG(VERBOSE) << __func__ << " dsp frames consumed: (" << mTotalDSPFrames << "+" << mPrevFrames - << ") = " << mTotalDSPFrames + mPrevFrames; - return mTotalDSPFrames + mPrevFrames; -} - -void PcmOffloadPlayback::onFlush() { - // on flush SPR module is reset to 0. Hence, we cache the DSP frames - mTotalDSPFrames = mTotalDSPFrames + mPrevFrames; - mPrevFrames = 0; -} - -// [PcmOffloadPlayback End] - -// [SpatialPlayback Start] -size_t SpatialPlayback::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kPeriodDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [SpatialPlayback End] - -// [InCallMusic Start] -size_t InCallMusic::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kPeriodDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [InCallMusic End] - -// [VoipPlayback Start] -size_t VoipPlayback::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kPeriodDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [VoipPlayback End] - -// [HapticPlayback Start] -size_t HapticsPlayback::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kPeriodDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [HapticsPlayback End] -// [PcmRecord Start] -size_t PcmRecord::getFrameCount(const AudioPortConfig& mixPortConfig) { - size_t frameCount = kCaptureDurationMs * getSampleRate(mixPortConfig).value() / 1000; - frameCount = getNearestMultiple( - frameCount, std::lcm(32, getPcmSampleSizeInBytes(mixPortConfig.format.value().pcm))); - // Adjusting to frameCount as atleast kFMQMinFrameSize (160). - // Todo check the sanity of this requirement in the VTS test. - frameCount = std::max(frameCount, kFMQMinFrameSize); - return frameCount; -} - -// [PcmRecord End] - -// [FastRecord Start] -size_t FastRecord::getFrameCount(const AudioPortConfig& mixPortConfig) { - /** - * Some clients which directly uses AHAL service for Fast Record like - * proxy capture - **/ - auto& platform = Platform::getInstance(); - if (const auto& propFrameSize = platform.getProxyRecordFMQSize(); propFrameSize > 0) { - LOG(VERBOSE) << __func__ << ": client applied FMQSize in Frames:" << propFrameSize; - return propFrameSize; - } - - size_t periodSize = (kCaptureDurationMs * getSampleRate(mixPortConfig).value()) / 1000; - size_t frameSize = - getFrameSizeInBytes(mixPortConfig.format.value(), mixPortConfig.channelMask.value()); - if (frameSize == 0) { - LOG(ERROR) << __func__ << ": could not calculate frame size for port config " - << mixPortConfig.toString(); - return 0; - } - size_t size = periodSize * frameSize; - size = getNearestMultiple(size, std::lcm(32, frameSize)); - return size / frameSize; -} -// [FastRecord End] - -// [UltraFastRecord Start] -size_t UltraFastRecord::getFrameCount(const AudioPortConfig& mixPortConfig) { - /** - * Some clients which directly uses AHAL service for ULL Record like - * proxy capture - **/ - auto& platform = Platform::getInstance(); - if (const auto& propFrameSize = platform.getProxyRecordFMQSize(); propFrameSize > 0) { - LOG(VERBOSE) << __func__ << ": client applied FMQSize in Frames:" << propFrameSize; - return propFrameSize; - } - - // return default period size for ULL - return kCaptureDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [UltraFastRecord End] - -// [MMapRecord Start] - -size_t MMapRecord::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kCaptureDurationMs * getSampleRate(mixPortConfig).value() / 1000; -} - -// [MMapRecord End] - -// [HotwordRecord Start] -size_t HotwordRecord::getFrameCount(const AudioPortConfig& mixPortConfig) { - return PcmRecord::getFrameCount(mixPortConfig); -} - -pal_stream_handle_t* HotwordRecord::getPalHandle( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) { - size_t payloadSize = 0; - pal_param_st_capture_info_t stCaptureInfo{0, nullptr}; - - auto& ioHandle = mixPortConfig.ext.get().handle; -#ifdef SEC_AUDIO_SOUND_TRIGGER_TYPE - if (mIsSeamless) - stCaptureInfo.capture_handle = AUDIO_IO_HANDLE_NONE; - else -#endif - stCaptureInfo.capture_handle = ioHandle; - - int32_t ret = pal_get_param(PAL_PARAM_ID_ST_CAPTURE_INFO, (void**)&stCaptureInfo, &payloadSize, - nullptr); - if (ret || !stCaptureInfo.pal_handle) { - LOG(ERROR) << __func__ << ": sound trigger handle not found, status " << ret; - return nullptr; - } - - if (!mIsStRecord) { - mIsStRecord = true; - LOG(DEBUG) << __func__ << ": sound trigger pal handle " << stCaptureInfo.pal_handle - << " for IOHandle " << ioHandle; - } - - return stCaptureInfo.pal_handle; -} -// [HotwordRecord End] - -// [VoipRecord Start] -size_t VoipRecord::getFrameCount(const AudioPortConfig& mixPortConfig) { - return (kCaptureDurationMs * mixPortConfig.sampleRate.value().value) / 1000; -} - -// [VoipRecord End] - -// [VoiceCallRecord Start] -size_t VoiceCallRecord::getFrameCount(const AudioPortConfig& mixPortConfig) { - return kCaptureDurationMs * (mixPortConfig.sampleRate.value().value / 1000); -} - -pal_incall_record_direction VoiceCallRecord::getRecordDirection( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) { - auto& source = mixPortConfig.ext.get() - .usecase.get(); - if (source == AudioSource::VOICE_UPLINK) { - return INCALL_RECORD_VOICE_UPLINK; - } else if (source == AudioSource::VOICE_DOWNLINK) { - return INCALL_RECORD_VOICE_DOWNLINK; - } else if (source == AudioSource::VOICE_CALL) { - return INCALL_RECORD_VOICE_UPLINK_DOWNLINK; - } - LOG(ERROR) << __func__ << ": Invalid source for VoiceCallRecord" << static_cast(source); - return static_cast(0); -} - -// [VoiceCallRecord End] - -// [CompressCapture Start] -size_t CompressCapture::getFrameCount(const AudioPortConfig& mixPortConfig) { - auto format = mixPortConfig.format.value(); - if (format.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_LC || - format.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC || - format.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V1 || - format.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V2) { - return Aac::KAacMaxOutputSize; - } - return 0; -} - -CompressCapture::CompressCapture( - const ::aidl::android::media::audio::common::AudioFormatDescription& format, - const int32_t sampleRate, - const ::aidl::android::media::audio::common::AudioChannelLayout& channelLayout) - : mCompressFormat(format), mSampleRate(sampleRate), mChannelLayout(channelLayout) { - if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_LC || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC) { - mPalSndEnc.aac_enc.enc_cfg.aac_enc_mode = Aac::EncodingMode::LC; - mPalSndEnc.aac_enc.enc_cfg.aac_fmt_flag = Aac::EncodingFormat::ADTS; - mPalSndEnc.aac_enc.aac_bit_rate = Aac::kAacDefaultBitrate; - } else if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V1) { - mPalSndEnc.aac_enc.enc_cfg.aac_enc_mode = Aac::EncodingMode::SBR; - mPalSndEnc.aac_enc.enc_cfg.aac_fmt_flag = Aac::EncodingFormat::ADTS; - mPalSndEnc.aac_enc.aac_bit_rate = Aac::kAacDefaultBitrate; - } else if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V2) { - mPalSndEnc.aac_enc.enc_cfg.aac_enc_mode = Aac::EncodingMode::PS; - mPalSndEnc.aac_enc.enc_cfg.aac_fmt_flag = Aac::EncodingFormat::ADTS; - mPalSndEnc.aac_enc.aac_bit_rate = Aac::kAacDefaultBitrate; - } - mPCMSamplesPerFrame = (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_LC || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC) - ? Aac::kAacLcPCMSamplesPerFrame - : Aac::kHeAacPCMSamplesPerFrame; -} - -void CompressCapture::setPalHandle(pal_stream_handle_t* handle) { - mCompressHandle = handle; -} - -size_t CompressCapture::getLatencyMs() { - constexpr size_t kMilliSeconds = 1000; - return mPCMSamplesPerFrame * kMilliSeconds / mSampleRate; -} -void CompressCapture::advanceReadCount() { - mNumReadCalls++; -} - -int64_t CompressCapture::getPositionInFrames() { - return (mNumReadCalls * mPCMSamplesPerFrame); -} - -bool CompressCapture::configureCodecInfo(){ - /* check for global cut-off frequency*/ - if (mPalSndEnc.aac_enc.global_cutoff_freq <= 0 /* not configured*/) { - const std::string kAACCutOffFrequencyProp{"vendor.audio.compress_capture.aac.cut_off_freq"}; - mPalSndEnc.aac_enc.global_cutoff_freq = - ::android::base::GetIntProperty(kAACCutOffFrequencyProp, 0); - } - - auto dataPtr = std::make_unique(sizeof(pal_param_payload) + sizeof(pal_snd_enc_t)); - auto palParamPayload = reinterpret_cast(dataPtr.get()); - palParamPayload->payload_size = sizeof(pal_snd_enc_t); - auto payloadPtr = reinterpret_cast(dataPtr.get() + sizeof(pal_param_payload)); - *payloadPtr = mPalSndEnc; - if (mCompressHandle) { - if (int32_t ret = ::pal_stream_set_param(mCompressHandle, PAL_PARAM_ID_CODEC_CONFIGURATION, - palParamPayload); ret) { - LOG(ERROR) << __func__ << " PAL_PARAM_ID_CODEC_CONFIGURATION failed!!! ret:" << ret; - return false; - } - - LOG(VERBOSE) << __func__ << " PAL_PARAM_ID_CODEC_CONFIGURATION configured"; - return true; - } - LOG(ERROR) << __func__ << " PAL stream handle is NULL!"; - return false; -} - -ndk::ScopedAStatus CompressCapture::setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& in_parameters, - bool in_async) { - LOG(VERBOSE) << __func__ << " parsing for " << mCompressFormat.encoding; - if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_LC || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V1 || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V2 || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC) { - if (auto value = getIntValueFromVString(in_parameters, Aac::kDSPAacBitRate); value) { - auto requested = value.value(); - const auto min = getAACMinBitrateValue(); - const auto max = getAACMaxBitrateValue(); - mPalSndEnc.aac_enc.aac_bit_rate = - requested < min ? min : (requested > max ? max : requested); - mCompressHandle != nullptr ? (void)setAACDSPBitRate() : (void)0; - } - if (auto value = getIntValueFromVString(in_parameters, Aac::kDSPAacGlobalCutoffFrequency); - value) { - if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_LC) { - mPalSndEnc.aac_enc.global_cutoff_freq = value.value(); - } - } - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus CompressCapture::getVendorParameters( - const std::vector& in_ids, std::vector* _aidl_return) { - std::vector result; - for (const auto& id : in_ids) { - if (id == Aac::kDSPAacBitRate) { - result.emplace_back( - makeVendorParameter(id, std::to_string(mPalSndEnc.aac_enc.aac_bit_rate))); - } else if (id == Aac::kDSPAacGlobalCutoffFrequency) { - result.emplace_back(makeVendorParameter( - id, std::to_string(mPalSndEnc.aac_enc.global_cutoff_freq))); - } - } - *_aidl_return = result; - return ndk::ScopedAStatus::ok(); -} - -void CompressCapture::setAACDSPBitRate() { - const auto palSndEncSize = sizeof(pal_snd_enc_t); - auto payload = std::make_unique(sizeof(pal_param_payload) + palSndEncSize); - auto paramPayload = (pal_param_payload*)payload.get(); - paramPayload->payload_size = palSndEncSize; - memcpy(paramPayload->payload, &mPalSndEnc, paramPayload->payload_size); - if (mCompressHandle) { - if (int32_t ret = ::pal_stream_set_param(mCompressHandle, PAL_PARAM_ID_RECONFIG_ENCODER, - paramPayload); - ret) { - LOG(ERROR) << __func__ << "pal set param PAL_PARAM_ID_RECONFIG_ENCODER failed:" << ret; - } - } else { - LOG(ERROR) << __func__ << "PAL stream handle is NULL!"; - } - -} - -int32_t CompressCapture::getAACMinBitrateValue() { - const auto channelCount = - ::aidl::android::hardware::audio::common::getChannelCount(mChannelLayout); - if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_LC || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC) { - if (channelCount == 1) { - return Aac::kAacLcMonoMinSupportedBitRate; - } else { - return Aac::kAacLcStereoMinSupportedBitRate; - } - } else if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V1) { - if (channelCount == 1) { - return (mSampleRate == 24000 || mSampleRate == 32000) - ? Aac::kHeAacMonoMinSupportedBitRate1 - : Aac::kHeAacMonoMinSupportedBitRate2; - } else { - return (mSampleRate == 24000 || mSampleRate == 32000) - ? Aac::kHeAacStereoMinSupportedBitRate1 - : Aac::kHeAacStereoMinSupportedBitRate2; - } - } else { - // AUDIO_FORMAT_AAC_ADTS_HE_V2 - return (mSampleRate == 24000 || mSampleRate == 32000) - ? Aac::kHeAacPsStereoMinSupportedBitRate1 - : Aac::kHeAacPsStereoMinSupportedBitRate2; - } -} - -int32_t CompressCapture::getAACMaxBitrateValue() { - const auto channelCount = - ::aidl::android::hardware::audio::common::getChannelCount(mChannelLayout); - if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_LC || - mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC) { - if (channelCount == 1) { - return std::min(Aac::kAacLcMonoMaxSupportedBitRate, 6 * mSampleRate); - } else { - return std::min(Aac::kAacLcStereoMaxSupportedBitRate, 12 * mSampleRate); - } - } else if (mCompressFormat.encoding == ::android::MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V1) { - if (channelCount == 1) { - return std::min(Aac::kHeAacMonoMaxSupportedBitRate, 6 * mSampleRate); - } else { - return std::min(Aac::kHeAacStereoMaxSupportedBitRate, 12 * mSampleRate); - } - } else { - // AUDIO_FORMAT_AAC_ADTS_HE_V2 - return std::min(Aac::kHeAacPstereoMaxSupportedBitRate, 6 * mSampleRate); - } -} - -uint32_t CompressCapture::getAACMaxBufferSize() { - int32_t maxBitRate = getAACMaxBitrateValue(); - /** - * AAC Encoder 1024 PCM samples => 1 compress AAC frame; - * 1 compress AAC frame => max possible length => max-bitrate bits; - * let's take example of 48K HZ; - * 1 second ==> 384000 bits ; 1 second ==> 48000 PCM samples; - * 1 AAC frame ==> 1024 PCM samples; - * Max buffer size possible; - * 48000/1024 = (8/375) seconds ==> ( 8/375 ) * 384000 bits - * ==> ( (8/375) * 384000 / 8 ) bytes; - **/ - return (uint32_t)( - (((((double)mPCMSamplesPerFrame) / mSampleRate) * ((uint32_t)(maxBitRate))) / 8) + - /* Just in case; not to miss precision */ 1); -} - -} // namespace qti::audio::core - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/Platform.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/Platform.cpp deleted file mode 100755 index ff384501..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/Platform.cpp +++ /dev/null @@ -1,2724 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_NDEBUG 0 -#define LOG_TAG "AHAL_Platform_QTI" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(SEC_AUDIO_OFFLOAD_COMPRESSED_OPUS) && defined(SEC_AUDIO_OFFLOAD_SOUNDSPEED) -#include -#endif - -#define LC3_SWB_CODEC_CONFIG_INDEX 4 -#define LC3_BROADCAST_TRANSIT_MODE 1 -#define LC3_HFP_TRANSIT_MODE 3 - -using ::aidl::android::media::audio::common::AudioChannelLayout; -using ::aidl::android::media::audio::common::AudioDevice; -using ::aidl::android::media::audio::common::AudioDeviceAddress; -using ::aidl::android::media::audio::common::AudioDeviceDescription; -using ::aidl::android::media::audio::common::AudioDeviceType; -using ::aidl::android::media::audio::common::AudioFormatDescription; -using ::aidl::android::media::audio::common::AudioFormatType; -using ::aidl::android::media::audio::common::AudioIoFlags; -using ::aidl::android::media::audio::common::AudioOutputFlags; -using ::aidl::android::media::audio::common::AudioPort; -using ::aidl::android::media::audio::common::AudioPortConfig; -using ::aidl::android::media::audio::common::AudioPortDeviceExt; -using ::aidl::android::media::audio::common::AudioPortExt; -using ::aidl::android::media::audio::common::AudioProfile; -using ::aidl::android::media::audio::common::PcmType; -#ifdef SEC_AUDIO_COMMON -using ::aidl::android::media::audio::common::AudioSource; -using ::aidl::android::hardware::audio::common::getPcmSampleSizeInBytes; -#endif - -using ::aidl::android::hardware::audio::common::getChannelCount; -using ::aidl::android::hardware::audio::common::getFrameSizeInBytes; -using ::aidl::android::hardware::audio::common::isBitPositionFlagSet; -using ::aidl::android::hardware::audio::core::IModule; -using aidl::android::media::audio::common::MicrophoneDynamicInfo; -using aidl::android::media::audio::common::MicrophoneInfo; - -#ifdef ENABLE_TAS_SPK_PROT -const char *AUDIO_PARAM_TI_HDR[] = { - AUDIO_PARAM_TI_SMARTPA_CH, - AUDIO_PARAM_TI_SMARTPA_IDX, - AUDIO_PARAM_TI_SMARTPA_LEN, - AUDIO_PARAM_TI_SMARTPA_GET -}; -const char *AUDIO_PARAM_TI_VIDX[] = { - "ti_v0", - "ti_v1", - "ti_v2", - "ti_v3", - "ti_v4", - "ti_v5", - "ti_v6", - "ti_v7", - "ti_v8", - "ti_v9", - "ti_v10" -}; -#endif - -namespace qti::audio::core { - -btsco_lc3_cfg_t Platform::btsco_lc3_cfg = {}; -#ifdef ENABLE_TAS_SPK_PROT -pal_tispk_prot_param_t Platform::tiSpkProtParam = {}; -#endif - -size_t Platform::getFrameCount(const AudioPortConfig& mixPortConfig, Usecase const& inTag) { - const auto& tag = (inTag == Usecase::INVALID ? getUsecaseTag(mixPortConfig) : inTag); - size_t numFrames = 0; - - if (mUsecaseOpMap.find(tag) != mUsecaseOpMap.end()) { - numFrames = mUsecaseOpMap[tag].getFrameCount(mixPortConfig); - } else { - LOG(ERROR) << __func__ << "usecase not found " << getName(tag); - } - - LOG(VERBOSE) << __func__ << " frames: " << numFrames << " for " << getName(tag); - return numFrames; -} - -struct BufferConfig Platform::getBufferConfig(const AudioPortConfig& mixPortConfig, - Usecase const& inTag) { - const auto& tag = (inTag == Usecase::INVALID ? getUsecaseTag(mixPortConfig) : inTag); - struct BufferConfig config {}; - if (mUsecaseOpMap.find(tag) != mUsecaseOpMap.end()) { - config = mUsecaseOpMap[tag].getBufferConfig(mixPortConfig); - } else { - LOG(ERROR) << __func__ << "usecase not found " << getName(tag); - } - - return config; -} -#ifdef SEC_AUDIO_SUPPORT_UHQ -struct BufferConfig Platform::getBufferConfig(const AudioPortConfig& mixPortConfig, - std::optional>& uhqConfig, - Usecase const& inTag) { - const auto& tag = (inTag == Usecase::INVALID ? getUsecaseTag(mixPortConfig) : inTag); - struct BufferConfig config; - if (mUsecaseOpMap.find(tag) != mUsecaseOpMap.end()) { - config = mUsecaseOpMap[tag].getBufferConfig(mixPortConfig); - - if (tag == Usecase::DEEP_BUFFER_PLAYBACK && uhqConfig.has_value()) { - size_t formatRatio = getPcmSampleSizeInBytes(uhqConfig.value().first) / - getPcmSampleSizeInBytes(mixPortConfig.format.value().pcm); - size_t sampleRatio = (uint32_t)uhqConfig.value().second / mixPortConfig.sampleRate.value().value; - config.bufferSize = config.bufferSize * formatRatio * sampleRatio; - LOG(INFO) << __func__ << "newBufferSize for uhq " << config.bufferSize ; - } - } else { - LOG(ERROR) << __func__ << "usecase not found " << getName(tag); - } - - return config; -} -#endif - -int32_t Platform::getLatencyMs(const AudioPortConfig& mixPortConfig, Usecase const& inTag) { - if (mixPortConfig.ext.getTag() != AudioPortExt::Tag::mix) { - LOG(ERROR) << __func__ - << ": cannot deduce latency for port config which is not a mix port, " - << mixPortConfig.toString(); - return 0; - } - - int32_t latencyMs = 0; - - const auto& tag = (inTag == Usecase::INVALID ? getUsecaseTag(mixPortConfig) : inTag); - - if (mUsecaseOpMap.find(tag) != mUsecaseOpMap.end()) { - latencyMs = mUsecaseOpMap[tag].getLatency(); - } else { - LOG(ERROR) << __func__ << "usecase not found " << getName(tag); - } - - LOG(VERBOSE) << __func__ << ": latency" << latencyMs << " for " << getName(tag); - - return latencyMs; -} - -size_t Platform::getMinimumStreamSizeFrames(const std::vector& sources, - const std::vector& sinks) { - if (sources.size() > 1) { - LOG(WARNING) << __func__ << " unable to decide the minimum stream size for sources " - "more than one; actual size:" - << sources.size(); - return 0; - } - // choose the mix port - auto isMixPortConfig = [](const auto& audioPortConfig) { - return audioPortConfig.ext.getTag() == AudioPortExt::Tag::mix; - }; - - const auto& mixPortConfig = isMixPortConfig(*sources.at(0)) ? *(sources.at(0)) : *(sinks.at(0)); -#ifdef SEC_AUDIO_SAMSUNGRECORD - if(getUnconfiguredFlagsReceived() == (AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW)) { - return getFrameCount(mixPortConfig, Usecase::ULTRA_FAST_RECORD); - } -#endif - return getFrameCount(mixPortConfig); -} - -std::unique_ptr Platform::getPalStreamAttributes( - const AudioPortConfig& portConfig, const bool isInput -#ifdef SEC_AUDIO_SUPPORT_UHQ - , std::optional> uhqConfig -#endif - ) const { - const auto& audioFormat = portConfig.format.value(); - const auto palFormat = PlatformConverter::getPalFormatId(audioFormat); - if (palFormat == PAL_AUDIO_FMT_COMPRESSED_RANGE_END) { - return nullptr; - } - - const auto& audioChannelLayout = portConfig.channelMask.value(); - auto palChannelInfo = PlatformConverter::getPalChannelInfoForChannelCount( - getChannelCount(audioChannelLayout)); - if (palChannelInfo == nullptr) { - LOG(ERROR) << __func__ << " failed to find corresponding pal channel info for " - << audioChannelLayout.toString(); - return nullptr; - } - const auto sampleRate = portConfig.sampleRate.value().value; - if (!sampleRate) { - LOG(ERROR) << __func__ << " invalid sample rate " << std::to_string(sampleRate); - return nullptr; - } - - auto attributes = std::make_unique(); - auto bitWidth = PlatformConverter::getBitWidthForAidlPCM(audioFormat); - bitWidth == 0 ? (void)(bitWidth = kDefaultPCMBidWidth) : (void)0; - - if (!isInput) { - attributes->direction = PAL_AUDIO_OUTPUT; - attributes->out_media_config.sample_rate = sampleRate; - attributes->out_media_config.aud_fmt_id = palFormat; - attributes->out_media_config.ch_info = *(palChannelInfo); - attributes->out_media_config.bit_width = bitWidth; -#ifdef SEC_AUDIO_SUPPORT_UHQ - const auto& tag = getUsecaseTag(portConfig); - if (tag == Usecase::DEEP_BUFFER_PLAYBACK && uhqConfig.has_value()) { - AudioFormatDescription uhqFormat = - AudioFormatDescription{.type = AudioFormatType::PCM, .pcm = uhqConfig.value().first}; - attributes->out_media_config.sample_rate = (uint32_t)uhqConfig.value().second; - attributes->out_media_config.aud_fmt_id = PlatformConverter::getPalFormatId(uhqFormat); - attributes->out_media_config.bit_width = PlatformConverter::getBitWidthForAidlPCM(uhqFormat); - } -#endif - } else { - attributes->direction = PAL_AUDIO_INPUT; - attributes->in_media_config.sample_rate = sampleRate; - attributes->in_media_config.aud_fmt_id = palFormat; - attributes->in_media_config.ch_info = *(palChannelInfo); - attributes->in_media_config.bit_width = bitWidth; - } - - return std::move(attributes); -} - -std::unique_ptr Platform::getDefaultTelephonyAttributes() const { - auto attributes = std::make_unique(); - auto inChannelInfo = PlatformConverter::getPalChannelInfoForChannelCount(1); - auto outChannelInfo = PlatformConverter::getPalChannelInfoForChannelCount(2); - attributes->type = PAL_STREAM_VOICE_CALL; - attributes->direction = PAL_AUDIO_INPUT_OUTPUT; - attributes->in_media_config.sample_rate = kDefaultOutputSampleRate; - attributes->in_media_config.ch_info = *inChannelInfo; - attributes->in_media_config.bit_width = kDefaultPCMBidWidth; - attributes->in_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - attributes->out_media_config.sample_rate = kDefaultOutputSampleRate; - attributes->out_media_config.ch_info = *outChannelInfo; - attributes->out_media_config.bit_width = kDefaultPCMBidWidth; - attributes->out_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - return std::move(attributes); -} - -std::unique_ptr Platform::getDefaultCRSTelephonyAttributes() const { - auto attributes = std::make_unique(); - auto outChannelInfo = PlatformConverter::getPalChannelInfoForChannelCount(2); - attributes->type = PAL_STREAM_LOOPBACK; - attributes->info.opt_stream_info.loopback_type = PAL_STREAM_LOOPBACK_PLAYBACK_ONLY; - attributes->direction = PAL_AUDIO_OUTPUT; - attributes->out_media_config.sample_rate = kDefaultOutputSampleRate; - attributes->out_media_config.ch_info = *outChannelInfo; - attributes->out_media_config.bit_width = kDefaultPCMBidWidth; - attributes->out_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - return std::move(attributes); -} - -void Platform::configurePalDevicesCustomKey(std::vector& palDevices, - const std::string& customKey) const { - for (auto& palDevice : palDevices) { - setPalDeviceCustomKey(palDevice, customKey); - } -} - -bool Platform::getMicMuteStatus() { - return mMicMuted; -} - -void Platform::setMicMuteStatus(bool mute) { - mMicMuted = mute; -} - -bool Platform::setStreamMicMute(pal_stream_handle_t* streamHandlePtr, const bool muted) { - if (int32_t ret = ::pal_stream_set_mute(streamHandlePtr, muted); ret) { - return false; - } - return true; -} - -#ifdef SEC_AUDIO_SPK_AMP_MUTE -bool Platform::getSpeakerMuteStatus() const noexcept { - return mSpeakerMuted; -} - -void Platform::setSpeakerMute(const bool mute) noexcept { - LOG(INFO) << __func__ << " : mute " << mute << ", mSpeakerMuted " << mSpeakerMuted; - - if (mute != mSpeakerMuted) { - pal_param_speaker_status_t speakerStatus; - speakerStatus.mute_status = mute ? PAL_DEVICE_SPEAKER_MUTE : PAL_DEVICE_SPEAKER_UNMUTE; - if (int32_t ret = ::pal_set_param(PAL_PARAM_ID_SPEAKER_STATUS, &speakerStatus, - sizeof(pal_param_speaker_status_t)); - ret) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_SPEAKER_STATUS failed"; - return; - } - mSpeakerMuted = mute; - } -} -#endif - -bool Platform::updateScreenState(const bool isTurnedOn) noexcept { - mIsScreenTurnedOn = isTurnedOn; - pal_param_screen_state_t screenState{.screen_state = mIsScreenTurnedOn}; - if (int32_t ret = ::pal_set_param(PAL_PARAM_ID_SCREEN_STATE, &screenState, - sizeof(pal_param_screen_state_t)); - ret) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_SCREEN_STATE failed"; - return false; - } - return true; -} - -bool Platform::isScreenTurnedOn() const noexcept { - return mIsScreenTurnedOn; -} - -void Platform::configurePalDevicesForHIFIPCMFilter( - std::vector& palDevices) const noexcept { - if (palDevices.size() == 0) { - return; - } - - bool isEnabled = false; - - auto getStatus = [&]() -> bool { - bool status = false; - bool* payLoad = &status; - size_t payLoadSize = 0; - if (int32_t ret = - ::pal_get_param(PAL_PARAM_ID_HIFI_PCM_FILTER, - reinterpret_cast(&payLoad), &payLoadSize, nullptr); - ret) { - LOG(ERROR) << ": failed to get PAL_PARAM_ID_HIFI_PCM_FILTER status"; - return false; - } - return status; - }; - - for (auto& palDevice : palDevices) { - if ((palDevice.id == PAL_DEVICE_OUT_WIRED_HEADSET || - palDevice.id == PAL_DEVICE_OUT_WIRED_HEADPHONE)) { - if (!isEnabled) { - isEnabled = getStatus(); - } - if (isEnabled) { - setPalDeviceCustomKey(palDevice, "hifi-filter_custom_key"); - } - } - } -} - -void Platform::customizePalDevices(const AudioPortConfig& mixPortConfig, const Usecase& tag, - std::vector& palDevices) const noexcept { - const auto& sampleRate = getSampleRate(mixPortConfig); - if (sampleRate && sampleRate.value() != 384000 && sampleRate.value() != 352800) { - configurePalDevicesForHIFIPCMFilter(palDevices); - } - - if (mIsHACEnabled && hasOutputVoipRxFlag(mixPortConfig.flags.value())) { - auto itr = std::find_if(palDevices.begin(), palDevices.end(), [](const auto& palDevice) { - return palDevice.id == PAL_DEVICE_OUT_HANDSET; - }); - setPalDeviceCustomKey(*itr, "HAC"); - } -} - -std::vector Platform::convertToPalDevices( - const std::vector& devices) const noexcept { - if (devices.size() == 0) { - LOG(ERROR) << __func__ << " the set devices is empty"; - return {}; - } - std::vector palDevices{devices.size()}; - - size_t i = 0; - for (auto& device : devices) { - const auto palDeviceId = PlatformConverter::getPalDeviceId(device.type); - if (palDeviceId == PAL_DEVICE_OUT_MIN) { - return {}; - } - palDevices[i].id = palDeviceId; - - /* Todo map each AIDL device type to alteast one PAL device */ - if (palDevices[i].id == PAL_DEVICE_OUT_SPEAKER && - device.type.type == AudioDeviceType::OUT_SPEAKER_SAFE) { - setPalDeviceCustomKey(palDevices[i], "speaker-safe"); - } else if (palDevices[i].id == PAL_DEVICE_OUT_SPEAKER && - device.type.type == AudioDeviceType::OUT_SPEAKER) { - const auto isMSPPEnabled = - ::android::base::GetBoolProperty("vendor.audio.mspp.enable", false); - if (isMSPPEnabled) { - setPalDeviceCustomKey(palDevices[i], "mspp"); - } - } - - palDevices[i].config.sample_rate = kDefaultOutputSampleRate; - palDevices[i].config.bit_width = kDefaultPCMBidWidth; - palDevices[i].config.aud_fmt_id = kDefaultPalPCMFormat; - - if (isUsbDevice(device)) { - const auto& deviceAddress = device.address; - if (deviceAddress.getTag() != AudioDeviceAddress::Tag::alsa) { - LOG(ERROR) << __func__ << " failed to find alsa address for given usb device " - << device.toString(); - return {}; - } - const auto& deviceAddressAlsa = deviceAddress.get(); - if (!isValidAlsaAddr(deviceAddressAlsa)) - return {}; - palDevices[i].address.card_id = deviceAddressAlsa[0]; - palDevices[i].address.device_num = deviceAddressAlsa[1]; - } else if (isHdmiDevice(device)) { - if (auto result = getHdmiParameters(device)) { - palDevices[i].id = result->deviceId; - } else { - return {}; - } - } - i++; - } - if (devices.size() == 2 && isHdmiDevice(devices[0]) && isHdmiDevice(devices[1])) { - LOG(INFO) << __func__ << " Send latest DP device in the Pal list " << palDevices[1].id; - return {palDevices[1]}; - } - return palDevices; -} - -std::vector Platform::getDummyPalDevices(const AudioPortConfig& mixPortConfig) const { - struct pal_device dummyDevice = {}; - - dummyDevice.config.sample_rate = Platform::kDefaultOutputSampleRate; - dummyDevice.config.bit_width = Platform::kDefaultPCMBidWidth; - dummyDevice.config.aud_fmt_id = Platform::kDefaultPalPCMFormat; - dummyDevice.config.ch_info.channels = 2; - - if (isInputMixPortConfig(mixPortConfig)) { - dummyDevice.id = PAL_DEVICE_IN_DUMMY; - } else { - dummyDevice.id = PAL_DEVICE_OUT_DUMMY; - } - - return {dummyDevice}; -} - -/** - * API is common for both Output and input streams - */ -std::vector Platform::configureAndFetchPalDevices( - const AudioPortConfig& mixPortConfig, const Usecase& tag, - const std::vector& devices, const bool dummyDevice) const { - if (devices.empty()) { - if (dummyDevice) { - return getDummyPalDevices(mixPortConfig); - } else { - LOG(ERROR) << __func__ << " the set devices is empty"; - return {}; - } - } - auto palDevices = convertToPalDevices(devices); - - customizePalDevices(mixPortConfig, tag, palDevices); - - return palDevices; -} - -#ifdef SEC_AUDIO_COMMON -std::vector Platform::configureSecPalDevicesForTelephony( - const std::vector& devices) noexcept { - if (devices.size() == 0) { - LOG(ERROR) << __func__ << " the set devices is empty"; - return {}; - } - auto palDevices = convertToPalDevices(devices); - - int ck_id = CUSTOM_KEY_INVALID; - int key_dir = PAL_RX; - size_t i = 0; - for (auto& device : devices) { - const auto palDeviceId = PlatformConverter::getPalDeviceId(device.type); - if (palDeviceId == PAL_DEVICE_OUT_MIN) { - return {}; - } - palDevices[i].id = palDeviceId; - - // reset - setPalDeviceCustomKey(palDevices[i], ""); - - /* Case 1: call tx - * - rcv : FLIP - * - bt : BT_HEADSET_NREC - * - spk : (volte vt) : VIDEO_CALL / VIDEO_CALL_FLEX / VIDEO_CALL_FLIP - * (comm) : DEX / FLIP - */ - if (palDevices[i].id > PAL_DEVICE_IN_MIN) { - key_dir = PAL_TX; -#if 0//def SEC_AUDIO_CALL_TTY//TEMP_FOR_SETUP_V - for (int idx = 0; idx < MAX_VOICE_SESSIONS; idx++) { - int cur_tty = avoice->voice_.session[idx].tty_mode; - if ((cur_tty != PAL_TTY_OFF) - && avoice->voice_.session[idx].vsid == avoice->sec_voice_->cur_vsid) { - if (palDevices[i].id == PAL_DEVICE_IN_WIRED_HEADSET - || palDevices[i].id == PAL_DEVICE_IN_USB_HEADSET) { - if (cur_tty == PAL_TTY_FULL) { - ck_id = CUSTOM_KEY_TTY_FULL_MIC; - } else { - ck_id = CUSTOM_KEY_TTY; - } - } else if (cur_tty == PAL_TTY_VCO) { - if (palDevices[i].id == PAL_DEVICE_IN_HANDSET_MIC - || palDevices[i].id == PAL_DEVICE_IN_SPEAKER_MIC) { - ck_id = CUSTOM_KEY_TTY_VCO_MIC; - } - } - } - } -#endif - if (palDevices[i].id == PAL_DEVICE_IN_HANDSET_MIC) { - if (palDevices[1-i].id == PAL_DEVICE_OUT_HEARING_AID) { - ck_id = CUSTOM_KEY_HEARING_AID; - } else if (palDevices[1-i].id == PAL_DEVICE_OUT_WIRED_HEADPHONE) { - ck_id = CUSTOM_KEY_HEADPHONE_MIC; - } else if (palDevices[1-i].id == PAL_DEVICE_OUT_USB_HEADSET - && !mUSBCapEnable) { - ck_id = CUSTOM_KEY_USB_HEADPHONE_MIC; - } -#ifdef SEC_AUDIO_SUPPORT_RCV_FLIP_CALL - else if (!mHacIncall && mFolderclosed) { - ck_id = CUSTOM_KEY_FLIP; - } -#endif - } else if (palDevices[i].id == PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET) { - if (!bt_nrec) { - ck_id = CUSTOM_KEY_BT_HEADSET_NREC; - } - } else if (palDevices[i].id == PAL_DEVICE_IN_SPEAKER_MIC) { -#ifdef SEC_AUDIO_SUPPORT_PERSONAL_VIDEOCALL - if (mIsVolteVT) { - ck_id = CUSTOM_KEY_VIDEO_CALL; - if (mFlexmode) { - ck_id = CUSTOM_KEY_VIDEO_CALL_FLEX; - } else if (mFolderclosed) { - ck_id = CUSTOM_KEY_VIDEO_CALL_FLIP; - } - } else -#endif - { - if (mDexConnected) { - ck_id = CUSTOM_KEY_DEX; - } - else if (mFolderclosed) { - ck_id = CUSTOM_KEY_FLIP; - } - } - } - } - /* Case 2: call rx - * - headphone : HEADPHONE_MIC / USB_HEADPHONE_MIC - * - spk : (volte vt) : VIDEO_CALL / VIDEO_CALL_FLEX / VIDEO_CALL_FLIP - * (comm) : DEX / FLIP - * - rev : HAC / FLIP - */ - else { - key_dir = PAL_RX; -#if 0//def SEC_AUDIO_CALL_TTY//TEMP_FOR_SETUP_V - for (int idx = 0; idx < MAX_VOICE_SESSIONS; idx++) { - int cur_tty = avoice->voice_.session[idx].tty_mode; - if ((cur_tty != PAL_TTY_OFF) - && avoice->voice_.session[idx].vsid == avoice->sec_voice_->cur_vsid) { - if (palDevices[i].id == PAL_DEVICE_OUT_WIRED_HEADPHONE - || palDevices[i].id == PAL_DEVICE_OUT_WIRED_HEADSET - || palDevices[i].id == PAL_DEVICE_OUT_USB_HEADSET) { - ck_id = CUSTOM_KEY_TTY; - } else if (cur_tty == PAL_TTY_HCO) { - if (palDevices[i].id == PAL_DEVICE_OUT_HANDSET - || palDevices[i].id == PAL_DEVICE_OUT_SPEAKER) { - ck_id = CUSTOM_KEY_TTY; - } - } - } - } -#endif - if (palDevices[i].id == PAL_DEVICE_OUT_SPEAKER) { -#ifdef SEC_AUDIO_SUPPORT_PERSONAL_VIDEOCALL - if (mIsVolteVT) { - ck_id = CUSTOM_KEY_VIDEO_CALL; - if (mFlexmode) { - ck_id = CUSTOM_KEY_VIDEO_CALL_FLEX; - } else if (mFolderclosed) { - ck_id = CUSTOM_KEY_VIDEO_CALL_FLIP; - } - } else -#endif - { - if (mDexConnected) { - ck_id = CUSTOM_KEY_DEX; - } else if (mFolderclosed) { - ck_id = CUSTOM_KEY_FLIP; - } - } - } else if (palDevices[i].id == PAL_DEVICE_OUT_HANDSET) { -#ifdef SEC_AUDIO_CALL_HAC - if (mHacIncall) { - ck_id = GetHacCustomKeyId(); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_RCV_FLIP_CALL - else if (mFolderclosed) { - ck_id = CUSTOM_KEY_FLIP; - } -#endif - } - } - - if (ck_id != CUSTOM_KEY_INVALID) { - setPalDeviceCustomKey(palDevices[i], ck_table[ck_id]); - ck_id = CUSTOM_KEY_INVALID; - LOG(INFO) << __func__ << ": Setting custom key voice_" << (i == PAL_TX ? "tx " : "rx ") - << palDevices[i].custom_config.custom_key; - } - - i++; - } - return palDevices; -} - -std::vector Platform::configureSecPalDevicesForPlayback(const AudioPortConfig& mixPortConfig, const Usecase& tag, - const std::vector& devices) noexcept { - if (devices.size() == 0) { - LOG(ERROR) << __func__ << " the set devices is empty"; - return {}; - } - auto palDevices = convertToPalDevices(devices); - - int ck_id = CUSTOM_KEY_INVALID; - size_t i = 0; - for (auto& device : devices) { - const auto palDeviceId = PlatformConverter::getPalDeviceId(device.type); - if (palDeviceId == PAL_DEVICE_OUT_MIN) { - return {}; - } - palDevices[i].id = palDeviceId; - - // reset - setPalDeviceCustomKey(palDevices[i], ""); - - /* Case 1: usb+spk dual path */ - if (palDevices[i].id == PAL_DEVICE_OUT_USB_HEADSET && - ((devices.size() == 2) -#ifdef SEC_AUDIO_USB_GAIN_CONTROL - || (tag == Usecase::DEEP_BUFFER_PLAYBACK && getUSBGainForCombo()) -#endif - )) { - ck_id = CUSTOM_KEY_SPEAKER_AND_USB_HEADPHONES; - } - /* Case 2: wifi call - * - default : VOWIFI - * - rcv : VOWIFI_HAC / VOWIFI_FLIP - * - spk : VOWIFI_DEX / VOWIFI_FLIP - */ - else if (mIsVoWiFi) { - ck_id = CUSTOM_KEY_VOWIFI; - if (palDevices[i].id == PAL_DEVICE_OUT_HANDSET) { -#ifdef SEC_AUDIO_CALL_HAC - if (mHacIncall) { - ck_id = GetVoWifiHacCustomKeyId(); - } -#endif -#ifdef SEC_AUDIO_SUPPORT_RCV_FLIP_CALL - else if (mFolderclosed) { - ck_id = CUSTOM_KEY_VOWIFI_FLIP; - } -#endif - } - - else if (palDevices[i].id == PAL_DEVICE_OUT_SPEAKER) { - if (mDexConnected) { - ck_id = CUSTOM_KEY_VOWIFI_DEX; - } - else if (mFolderclosed) { - ck_id = CUSTOM_KEY_VOWIFI_FLIP; - } - } - } - /* Case 3: video call (SUPPORT_PERSONAL_VIDEOCALL model only) - * - default : VIDEO_CALL - * - spk : VIDEO_CALL_FLIP/ VIDEO_CALL_FLEX - */ -#ifdef SEC_AUDIO_SUPPORT_PERSONAL_VIDEOCALL - else if (mIsVolteVT) { - ck_id = CUSTOM_KEY_VIDEO_CALL; - if (palDevices[i].id == PAL_DEVICE_OUT_SPEAKER) { - if (mFolderclosed) { - ck_id = CUSTOM_KEY_VIDEO_CALL_FLIP; - } else if (mFlexmode) { - ck_id = CUSTOM_KEY_VIDEO_CALL_FLEX; - } - } - } -#endif - /* Case 4: voip comm call - * - default : VOIP_COMM - * - rcv : HAC / FLIP - * - spk : DEX / VOIP_TV / VOIP_GAMING_FLIP / VOIP_GAMING / FLIP / FLEX - */ - else if (mCallMode == AUDIO_MODE_IN_COMMUNICATION) { - if (tag == Usecase::VOIP_PLAYBACK) { - ck_id = CUSTOM_KEY_VOIP_COMM; - if (palDevices[i].id == PAL_DEVICE_OUT_HANDSET) { -#ifdef SEC_AUDIO_CALL_HAC - if (mHacIncall) { - ck_id = GetHacCustomKeyId(); - } -#endif - else if (mFolderclosed) { - ck_id = CUSTOM_KEY_FLIP; - } - } else if (palDevices[i].id == PAL_DEVICE_OUT_SPEAKER) { - if (mDexConnected) { - ck_id = CUSTOM_KEY_DEX; - } -#ifdef SEC_AUDIO_SCREEN_MIRRORING // { SUPPORT_VOIP_VIA_SMART_VIEW - /*else*/ if (mVoipViaSmartView) { - ck_id = CUSTOM_KEY_VOIP_TV; - } -#endif // } SUPPORT_VOIP_VIA_SMART_VIEW -#ifdef SEC_AUDIO_SUPPORT_GAMECHAT_SPK_AEC - else if (mGamechatMode) { - if (mFolderclosed) - ck_id = CUSTOM_KEY_VOIP_GAMING_FLIP; - else - ck_id = CUSTOM_KEY_VOIP_GAMING; - } -#endif - else if (mFolderclosed) { - ck_id = CUSTOM_KEY_FLIP; - } -#ifdef SEC_AUDIO_SUPPORT_PERSONAL_VIDEOCALL - else if (mFlexmode) { - ck_id = CUSTOM_KEY_FLEX; - } -#endif - } - } - } - /* Case 5: karaoke */ -#ifdef SEC_AUDIO_KARAOKE - else if (is_karaoke_on && palDevices[i].id == PAL_DEVICE_OUT_SPEAKER) { - if (isKaraokeUsecases(tag)) { - ck_id = CUSTOM_KEY_KARAOKE; - } - } -#endif - /* Case 6: dual spk ampL off */ -#if defined(SEC_AUDIO_DUAL_SPEAKER) && defined(SEC_AUDIO_ENHANCED_DUAL_SPEAKER) && \ - !defined(SEC_AUDIO_FACTORY_TEST_MODE) - else if (isSpeakerLeftAmpOff() - && (devices.size() == 1) - && (palDevices[i].id == PAL_DEVICE_OUT_SPEAKER)) { - LOG(INFO) << __func__ << ": set custom key for SPEAKER_LEFT_AMP_OFF"; - ck_id = CUSTOM_KEY_SPEAKER_LEFT_AMP_OFF; - } -#endif - - if (ck_id != CUSTOM_KEY_INVALID) { - setPalDeviceCustomKey(palDevices[i], ck_table[ck_id]); - LOG(INFO) << __func__ << ": Setting custom key as " << palDevices[i].custom_config.custom_key; - } - - i++; - } - -#ifdef SEC_AUDIO_CALL_VOIP - if (tag == Usecase::VOIP_PLAYBACK) { - mPalDevicesOnVoipRx = palDevices; - } -#endif - - return palDevices; -} - -std::vector Platform::configureSecPalDevicesForCapture(const AudioPortConfig& mixPortConfig, const Usecase& tag, - const std::vector& devices) const noexcept { - if (devices.size() == 0) { - LOG(ERROR) << __func__ << " the set devices is empty"; - return {}; - } - auto palDevices = convertToPalDevices(devices); - - int ck_id = CUSTOM_KEY_INVALID; - size_t i = 0; - auto attr = getPalStreamAttributes(mixPortConfig, true); - const auto& source = getMixPortAudioSource(mixPortConfig); - - auto isDeviceAvailable = [&](AudioDevice d) { - return (std::find(devices.begin(), devices.end(), d) != devices.end()); - }; - -#ifdef SEC_AUDIO_CALL_VOIP - auto isDeviceAvailableOnVoipOut = [&](pal_device_id_t device) { - return (std::find_if(mPalDevicesOnVoipRx.begin(), mPalDevicesOnVoipRx.end(), - [&](const auto& d) { return d.id == device; }) != mPalDevicesOnVoipRx.end()); - }; -#endif - - if (!attr) { - LOG(ERROR) << __func__ << " no pal attributes"; - return {}; - } - for (auto& device : devices) { - const auto palDeviceId = PlatformConverter::getPalDeviceId(device.type); - if (palDeviceId == PAL_DEVICE_OUT_MIN) { - return {}; - } - palDevices[i].id = palDeviceId; - - // reset - setPalDeviceCustomKey(palDevices[i], ""); - -#ifdef SEC_AUDIO_COMPRESS_CAPTURE - if (tag == Usecase::COMPRESS_CAPTURE) { - LOG(DEBUG) << __func__ << " Compress capture doesn't need custom key"; - return {}; - } -#endif - - /* Case 1: camcorder */ - if (source && source.value() == AudioSource::CAMCORDER) { -#if SEC_AUDIO_MULTI_MIC >= 3 || defined (SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO) - if (GetRecMultiMic(mixPortConfig, devices, tag)) { -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - if (IsBtForMultiDevice(devices) && multidevice_rec) - ck_id = CUSTOM_KEY_CAMCORDER_MULTI_AND_BT_MIC; - else -#endif - ck_id = CUSTOM_KEY_CAMCORDER_MULTI_MIC; - } else -#endif - if (isDeviceAvailable(AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_MULTI})) { - if (attr->type == PAL_STREAM_ULTRA_LOW_LATENCY) - ck_id = CUSTOM_KEY_REC_STEREO_MIC; - else - ck_id = CUSTOM_KEY_CAMCORDER_MULTI_MIC; - } else { - ck_id = CUSTOM_KEY_CAMCORDER; - } - } - /* Case 2: beamforming */ - else if (source && source.value() == AudioSource::SEC_VOICENOTE_BEAMFORMING) { - ck_id = CUSTOM_KEY_REC_INTERVIEW; - } - /* Case 3: voip tx - * (1): wifi call - * - default : VOWIFI - * - headphone : VOWIFI_HEADPHONE_MIC / VOWIFI_USB_HEADPHONE_MIC - * - bt : VOWIFI_BT_HEADSET_NREC - * - rcv : VOWIFI_FLIP - * - spk : VOWIFI_DEX / VOWIFI_FLIP - * (2) video call (SUPPORT_PERSONAL_VIDEOCALL model only) - * - default : VIDEO_CALL - * - spk : VIDEO_CALL_FLIP/ VIDEO_CALL_FLEX - * (3) voip comm call - * - headphone : HEADPHONE_MIC / USB_HEADPHONE_MIC - * - bt : BT_HEADSET_NREC - * - rcv : FLIP - * - spk : DEX / VOIP_TV / VOIP_GAMING_FLIP / VOIP_GAMING / FLIP / FLEX - */ - else if (tag == Usecase::VOIP_RECORD) { - if (mIsVoWiFi) { - ck_id = CUSTOM_KEY_VOWIFI; - if (isDeviceAvailableOnVoipOut(PAL_DEVICE_OUT_WIRED_HEADPHONE) - && device.type.type == AudioDeviceType::IN_MICROPHONE) { - ck_id = CUSTOM_KEY_VOWIFI_HEADPHONE_MIC; - } else if (isDeviceAvailableOnVoipOut(PAL_DEVICE_OUT_USB_HEADSET) - && device.type.type == AudioDeviceType::IN_MICROPHONE) { - ck_id = CUSTOM_KEY_VOWIFI_USB_HEADPHONE_MIC; - } else if (palDevices[i].id == PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET) { - if (!bt_nrec) { - ck_id = CUSTOM_KEY_VOWIFI_BT_HEADSET_NREC; - } - } else if (palDevices[i].id == PAL_DEVICE_IN_HANDSET_MIC) { -#ifdef SEC_AUDIO_SUPPORT_RCV_FLIP_CALL - if (!mHacIncall && mFolderclosed) { - ck_id = CUSTOM_KEY_VOWIFI_FLIP; - } -#endif - } else if (palDevices[i].id == PAL_DEVICE_IN_SPEAKER_MIC) { - if (mDexConnected) { - ck_id = CUSTOM_KEY_VOWIFI_DEX; - } else if (mFolderclosed) { - ck_id = CUSTOM_KEY_VOWIFI_FLIP; - } - } - } -#ifdef SEC_AUDIO_SUPPORT_PERSONAL_VIDEOCALL - else if (avoice->sec_voice_->volte_vt) { - ck_id = CUSTOM_KEY_VIDEO_CALL; - else if (palDevices[i].id == PAL_DEVICE_IN_SPEAKER_MIC) { - if (mFolderclosed) { - ck_id = CUSTOM_KEY_VIDEO_CALL_FLIP; - } else if (mFlexmode) { - ck_id = CUSTOM_KEY_VIDEO_CALL_FLEX; - } - } - } -#endif - else { - if (isDeviceAvailableOnVoipOut(PAL_DEVICE_OUT_WIRED_HEADPHONE) - && device.type.type == AudioDeviceType::IN_MICROPHONE) { - ck_id = CUSTOM_KEY_HEADPHONE_MIC; - } else if (isDeviceAvailableOnVoipOut(PAL_DEVICE_OUT_USB_HEADSET) - && device.type.type == AudioDeviceType::IN_MICROPHONE) { - ck_id = CUSTOM_KEY_USB_HEADPHONE_MIC; - } else if (palDevices[i].id == PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET) { - if (!bt_nrec) { - ck_id = CUSTOM_KEY_BT_HEADSET_NREC; - } - } else if (palDevices[i].id == PAL_DEVICE_IN_HANDSET_MIC) { -#ifdef SEC_AUDIO_SUPPORT_RCV_FLIP_CALL - if (mFolderclosed) { - ck_id = CUSTOM_KEY_FLIP; - } -#endif - } -#ifdef SEC_AUDIO_HDMI // { SUPPORT_VOIP_VIA_SMART_MONITOR - else if (isDeviceAvailableOnVoipOut(PAL_DEVICE_OUT_AUX_DIGITAL) && - (palDevices[i].id == PAL_DEVICE_IN_SPEAKER_MIC)) { - ck_id = CUSTOM_KEY_VOIP_SMONITOR; - } -#endif // } SUPPORT_VOIP_VIA_SMART_MONITOR - else if (palDevices[i].id == PAL_DEVICE_IN_SPEAKER_MIC) { - if (mDexConnected) { - ck_id = CUSTOM_KEY_DEX; - } -#ifdef SEC_AUDIO_SCREEN_MIRRORING // { SUPPORT_VOIP_VIA_SMART_VIEW - else if (mVoipViaSmartView) { - ck_id = CUSTOM_KEY_VOIP_TV; - } -#endif // } SUPPORT_VOIP_VIA_SMART_VIEW -#ifdef SEC_AUDIO_SUPPORT_GAMECHAT_SPK_AEC - else if (mGamechatMode) { - if (mFolderclosed) - ck_id = CUSTOM_KEY_VOIP_GAMING_FLIP; - else - ck_id = CUSTOM_KEY_VOIP_GAMING; - } -#endif - else if (mFolderclosed) { - ck_id = CUSTOM_KEY_FLIP; - } -#ifdef SEC_AUDIO_SUPPORT_PERSONAL_VIDEOCALL - else if (mFlexmode) { - ck_id = CUSTOM_KEY_FLEX; - } -#endif - } - } - } - /* Case 4: voice recognition */ - else if (source && source.value() == AudioSource::VOICE_RECOGNITION) { - if (tag == Usecase::ULTRA_FAST_RECORD - && getChannelCount(mixPortConfig.channelMask.value()) == 2) { - ck_id = CUSTOM_KEY_VR_DUAL; - } else - ck_id = CUSTOM_KEY_VR; -#ifdef SEC_AUDIO_SOUND_TRIGGER_TYPE - if (register_voice_keyword) { - ck_id = CUSTOM_KEY_BIXBY_ENROLL; - } else if (tag == Usecase::HOTWORD_RECORD && - palDevices[i].id == PAL_DEVICE_IN_HANDSET_MIC) { - ck_id = CUSTOM_KEY_VR_LOWPOWER; - } else -#endif -#ifdef SEC_AUDIO_KARAOKE - if (is_karaoke_on && - palDevices[i].id == PAL_DEVICE_IN_SPEAKER_MIC) { - ck_id = CUSTOM_KEY_KARAOKE; - } -#endif - } - /* Case 5: sec voice recognition */ - else if (source && source.value() == AudioSource::SEC_VOICE_RECOGNITION) { - ck_id = CUSTOM_KEY_BARGEIN_TTS; - if ((mCallMode != AUDIO_MODE_IN_CALL && mCallMode != AUDIO_MODE_IN_COMMUNICATION) && - (palDevices[i].id == PAL_DEVICE_IN_HANDSET_MIC)) - palDevices[i].id = PAL_DEVICE_IN_SPEAKER_MIC; - } - /* Case 6: 2mic svoice driving */ - else if (source && source.value() == AudioSource::SEC_2MIC_SVOICE_DRIVING) { - ck_id = CUSTOM_KEY_VR_FARFIELD; - } - /* Case 7: 2mic svoice */ - else if (source && source.value() == AudioSource::SEC_2MIC_SVOICE_NORMAL) { - if (palDevices[i].id == PAL_DEVICE_IN_SPEAKER_MIC) { - ck_id = CUSTOM_KEY_VR_DUAL; - } else { - ck_id = CUSTOM_KEY_VR; - } - } - /* Case 8: bargeing driving */ - else if (source && source.value() == AudioSource::SEC_BARGEIN_DRIVING) { -#ifdef SEC_AUDIO_INTERPRETER_MODE - if (interpreter_mode == INTERPRETER_CONVERSATION) { - if (device.type.type == AudioDeviceType::IN_HEADSET && - device.type.connection == AudioDeviceDescription::CONNECTION_USB) { - ck_id = CUSTOM_KEY_INTERPRETER_CONVERSATION_USB; - } else { - ck_id = CUSTOM_KEY_INTERPRETER_CONVERSATION_SPK; - palDevices[i].id = PAL_DEVICE_IN_SPEAKER_MIC; - } - } else if (interpreter_mode == INTERPRETER_LISTENING) { - palDevices[i].id = PAL_DEVICE_IN_SPEAKER_MIC; - ck_id = CUSTOM_KEY_INTERPRETER_LISTENING_SPK; - if (hasBluetoothDevice(mOutDeepDevices)) { - ck_id = CUSTOM_KEY_INTERPRETER_LISTENING_BT; - } else if (hasUsbHeadsetDevice(mOutDeepDevices)) { - ck_id = CUSTOM_KEY_INTERPRETER_LISTENING_USB; - } - } - else -#endif - { - ck_id = CUSTOM_KEY_BARGEIN_AEC; - auto palTelephonyDevices = convertToPalDevices(getTelephonyDevices()); - if (palDevices[i].id == PAL_DEVICE_IN_HANDSET_MIC && - !((mCallMode == AUDIO_MODE_IN_CALL && - palTelephonyDevices.size() > 0 && palTelephonyDevices[0].id == PAL_DEVICE_OUT_HANDSET) || - (mCallMode == AUDIO_MODE_IN_COMMUNICATION && - isDeviceAvailableOnVoipOut(PAL_DEVICE_OUT_HANDSET)))) { - palDevices[i].id = PAL_DEVICE_IN_SPEAKER_MIC; - } - } - } - /* Case 9: 2mic rec */ - else if (isDeviceAvailable(AudioDevice{.type.type = AudioDeviceType::IN_MICROPHONE_MULTI})) { - ck_id = CUSTOM_KEY_REC_STEREO_MIC; - } - /* Case 10: karaoke */ -#ifdef SEC_AUDIO_KARAOKE - else if (is_karaoke_on && - palDevices[i].id == PAL_DEVICE_IN_SPEAKER_MIC) { - ck_id = CUSTOM_KEY_KARAOKE; - } -#endif - else if (source && - (source.value() == AudioSource::UNPROCESSED || source.value() == AudioSource::VOICE_PERFORMANCE)) { - if (getChannelCount(mixPortConfig.channelMask.value()) == 2) - ck_id = CUSTOM_KEY_VR_DUAL; - else - ck_id = CUSTOM_KEY_VR; - } - - if (ck_id != CUSTOM_KEY_INVALID) { - setPalDeviceCustomKey(palDevices[i], ck_table[ck_id]); - LOG(INFO) << __func__ << ": Setting custom key as " << palDevices[i].custom_config.custom_key; - } - - // SEC_AUDIO_FACTORY - - i++; - } - return palDevices; -} -#endif -#ifdef SEC_AUDIO_CALL_HAC -int Platform::GetHacCustomKeyId() { - int ck_id = CUSTOM_KEY_HAC; - - switch (mHacMode) { - case HAC_MODE_MIC: - ck_id = CUSTOM_KEY_HAC; - break; - case HAC_MODE_TCOIL: - ck_id = CUSTOM_KEY_TCOIL_HAC; - break; - } - - return ck_id; -} - -int Platform::GetVoWifiHacCustomKeyId() { - int ck_id = CUSTOM_KEY_VOWIFI_HAC; - - switch (mHacMode) { - case HAC_MODE_MIC: - ck_id = CUSTOM_KEY_VOWIFI_HAC; - break; - case HAC_MODE_TCOIL: - ck_id = CUSTOM_KEY_VOWIFI_TCOIL_HAC; - break; - } - - return ck_id; -} -#endif - -#ifdef SEC_AUDIO_CALL_FORWARDING -bool Platform::isCallForwarding() -{ - if (mCallForwarding || mCallMemo == CALLMEMO_ON) { - return true; - } - return false; -} -#endif - -#ifdef SEC_AUDIO_CALL -int Platform::GetDeviceType(pal_device_id_t rx_device_id) { - int device_type = VOICE_DEVICE_ETC; - - if (rx_device_id == PAL_DEVICE_OUT_SPEAKER) - device_type = VOICE_DEVICE_SPEAKER; - else if (rx_device_id == PAL_DEVICE_OUT_WIRED_HEADSET || - rx_device_id == PAL_DEVICE_OUT_WIRED_HEADPHONE) - device_type = VOICE_DEVICE_EARPHONE; - else if (rx_device_id == PAL_DEVICE_OUT_BLUETOOTH_SCO) - device_type = VOICE_DEVICE_BLUETOOTH; - else if (rx_device_id == PAL_DEVICE_OUT_HANDSET) - device_type = VOICE_DEVICE_RECEIVER; - - LOG(INFO) << __func__ << " device id " << rx_device_id<< " device_type " << device_type; - return device_type; -} -#endif - -void Platform::getPositionInFrames(pal_stream_handle_t* palHandle, int32_t const& sampleRate, - int64_t* const dspFrames) const { - pal_session_time tstamp; - if (int32_t ret = ::pal_get_timestamp(palHandle, &tstamp); ret) { - LOG(ERROR) << __func__ << " pal_get_timestamp failure, ret:" << ret; - return; - } - - uint64_t sessionTimeUs = - ((static_cast(tstamp.session_time.value_msw)) << 32 | - tstamp.session_time.value_lsw); - // sessionTimeUs to frames - *dspFrames = static_cast((sessionTimeUs / 1000) * (sampleRate / 1000)); - LOG(VERBOSE) << __func__ << " dsp frames consumed:" << *dspFrames; - return; -} - -int Platform::setVolume(pal_stream_handle_t* handle, const std::vector& volumes) const { - auto data = makePalVolumes(volumes); - if (data.empty()) { - LOG(ERROR) << __func__ << ": failed to configure volume"; - return -1; - } - auto palVolumeData = reinterpret_cast(data.data()); - - return ::pal_stream_set_volume(handle, palVolumeData); -} - -#ifdef SEC_AUDIO_COMMON -std::vector Platform::getPalVolume(const std::vector& volumes) { - return makePalVolumes(volumes); -} -#endif - -std::unique_ptr Platform::getPalBufferConfig(const size_t bufferSize, - const size_t bufferCount) const { - auto palBufferConfig = std::make_unique(); - palBufferConfig->buf_size = bufferSize; - palBufferConfig->buf_count = bufferCount; - return std::move(palBufferConfig); -} - -std::vector<::aidl::android::media::audio::common::AudioProfile> Platform::getUsbProfiles( - const AudioPort& port) const { - const auto& devicePortExt = port.ext.get(); - auto& audioDeviceDesc = devicePortExt.device.type; - const auto palDeviceId = PlatformConverter::getPalDeviceId(audioDeviceDesc); - if (palDeviceId == PAL_DEVICE_OUT_MIN) { - return {}; - } - - const auto& addressTag = devicePortExt.device.address.getTag(); - if (addressTag != AudioDeviceAddress::Tag::alsa) { - LOG(ERROR) << __func__ << ": no alsa address provided for the AudioPort" << port.toString(); - return {}; - } - const auto& deviceAddressAlsa = - devicePortExt.device.address.get(); - if (!isValidAlsaAddr(deviceAddressAlsa)) - return {}; - const auto cardId = deviceAddressAlsa[0]; - const auto deviceId = deviceAddressAlsa[1]; - - // get capability from device of USB - auto deviceCapability = std::make_unique(); - if (!deviceCapability) { - LOG(ERROR) << __func__ << ": allocation failed "; - return {}; - } - - auto dynamicMediaConfig = std::make_unique(); - if (!dynamicMediaConfig) { - LOG(ERROR) << __func__ << ": allocation failed "; - return {}; - } - - size_t payloadSize = 0; - deviceCapability->addr.card_id = cardId; - deviceCapability->addr.device_num = deviceId; - deviceCapability->config = dynamicMediaConfig.get(); - if (isOutputDevice(devicePortExt.device)) { - deviceCapability->id = palDeviceId; - deviceCapability->is_playback = true; - } else { - deviceCapability->id = PAL_DEVICE_IN_USB_HEADSET; - deviceCapability->is_playback = false; - } - - void* deviceCapabilityPtr = deviceCapability.get(); - if (int32_t ret = pal_get_param(PAL_PARAM_ID_DEVICE_CAPABILITY, &deviceCapabilityPtr, - &payloadSize, nullptr); - ret != 0) { - LOG(ERROR) << __func__ << " PAL get param failed for PAL_PARAM_ID_DEVICE_CAPABILITY" << ret; - return {}; - } - if (!dynamicMediaConfig->jack_status) { - LOG(ERROR) << __func__ << " false usb jack status "; - return {}; - } - if (!deviceCapability->is_playback) { - if ((dynamicMediaConfig.get()->sample_rate[0] == 0 && dynamicMediaConfig.get()->format[0] == 0 && - dynamicMediaConfig.get()->mask[0] == 0) || (dynamicMediaConfig->jack_status == false)) { - mUSBCapEnable = false; - } else { - mUSBCapEnable = true; - } - } - - return getSupportedAudioProfiles(deviceCapability.get(), "usb"); -} - -std::vector Platform::getDynamicProfiles( - const AudioPort& dynamicDeviceAudioPort) const { - const auto& deviceExtTag = dynamicDeviceAudioPort.ext.getTag(); - if (deviceExtTag != AudioPortExt::Tag::device) { - LOG(ERROR) << __func__ << ": provided AudioPort is not device port" - << dynamicDeviceAudioPort.toString(); - return {}; - } - - LOG(VERBOSE) << __func__ << ": fetching dynamic profiles for " - << dynamicDeviceAudioPort.toString(); - - const auto& devicePortExt = dynamicDeviceAudioPort.ext.get(); - - if (isUsbDevice(devicePortExt.device)) { - return getUsbProfiles(dynamicDeviceAudioPort); - } - - LOG(VERBOSE) << __func__ << " unsupported " << dynamicDeviceAudioPort.toString(); - return {}; -} - -std::optional Platform::getHdmiParameters( - const ::aidl::android::media::audio::common::AudioDevice& device) const { -#ifdef SEC_AUDIO_HDMI - int controller = 0; - int stream = 0; -#else - const auto& addressTag = device.address.getTag(); - if (addressTag != AudioDeviceAddress::Tag::id || - device.address.get().empty()) { - LOG(ERROR) << __func__ << ": no hdmi address controller/stream provided for the device" - << device.toString(); - return std::nullopt; - } - const auto hdmiAddress = device.address.get(); - int controller = -1; - int stream = -1; - - int status = std::sscanf(hdmiAddress.c_str(), "controller=%d;stream=%d", &controller, &stream); - if (status != 2) { - LOG(ERROR) << __func__ << ": failed to extract HDMI parameter from device" - << device.toString(); - return std::nullopt; - } -#endif - pal_device_id_t deviceId = PAL_DEVICE_OUT_AUX_DIGITAL; - LOG(DEBUG) << __func__ << " controller " << controller << " stream " << stream; - if (stream) { - deviceId = PAL_DEVICE_OUT_AUX_DIGITAL_1; - LOG(DEBUG) << __func__ << " override palDevice with PAL_DEVICE_OUT_AUX_DIGITAL_1"; - } - struct HdmiParameters hdmiParam = { - .controller = controller, .stream = stream, .deviceId = deviceId}; - return hdmiParam; -} - -int Platform::handleDeviceConnectionChange(const AudioPort& deviceAudioPort, - const bool isConnect) const { - const auto& devicePortExt = deviceAudioPort.ext.get(); - - auto& audioDeviceDesc = devicePortExt.device.type; - const auto palDeviceId = PlatformConverter::getPalDeviceId(audioDeviceDesc); - if (palDeviceId == PAL_DEVICE_OUT_MIN) { - return -EINVAL; - } - - void* v = nullptr; - const auto deviceConnection = std::make_unique(); - if (!deviceConnection) { - LOG(ERROR) << __func__ << ": allocation failed "; - return -EINVAL; - } - - deviceConnection->connection_state = isConnect; - deviceConnection->id = palDeviceId; - - if (isUsbDevice(devicePortExt.device)) { - const auto& addressTag = devicePortExt.device.address.getTag(); - if (addressTag != AudioDeviceAddress::Tag::alsa) { - LOG(ERROR) << __func__ << ": no alsa address provided for the AudioPort" - << deviceAudioPort.toString(); - return -EINVAL; - } - const auto& deviceAddressAlsa = - devicePortExt.device.address.get(); - if (!isValidAlsaAddr(deviceAddressAlsa)) { - return -EINVAL; - } - const auto cardId = deviceAddressAlsa[0]; - const auto deviceId = deviceAddressAlsa[1]; - deviceConnection->device_config.usb_addr.card_id = cardId; - deviceConnection->device_config.usb_addr.device_num = deviceId; -#ifdef SEC_AUDIO_SUPPORT_USB_OFFLOAD - AudioExtensionBase::setUSBCardConfig(deviceConnection->device_config.usb_addr); - if (!isConnect && isInputDevice(devicePortExt.device)) { - mUSBCapEnable = false; - } -#endif - } else if (isHdmiDevice(devicePortExt.device)) { - if (auto result = getHdmiParameters(devicePortExt.device)) { - deviceConnection->device_config.dp_config.controller = result->controller; - deviceConnection->device_config.dp_config.stream = result->stream; - deviceConnection->id = result->deviceId; - } else { - return -EINVAL; - } - } else if (isIPDevice(devicePortExt.device)) { - if (!isIPAsProxyDeviceConnected()) { - return -EINVAL; - } - } - -#ifdef SEC_AUDIO_BT_OFFLOAD - if (isBluetoothA2dpDevice(devicePortExt.device)) { -#ifdef SEC_AUDIO_BT_MULTIPLE_PROFILE - if (!audio_is_bt_offload_format(bt_a2dp_format)) { - LOG(WARNING) << __func__ << " offload state change when only offload format"; - return 0; - } -#endif - bool isBtOffload = isConnect ? - audio_is_bt_offload_format(bt_a2dp_format) : false; - deviceConnection->is_bt_offload_enabled = isBtOffload; - LOG(INFO) << __func__ << "bt_offload state is" - << (isBtOffload ? " enabled" : " disabled"); - } -#endif - - v = deviceConnection.get(); - if (int32_t ret = ::pal_set_param(PAL_PARAM_ID_DEVICE_CONNECTION, v, - sizeof(pal_param_device_connection_t)); - ret != 0) { - LOG(ERROR) << __func__ << ": pal_set_param failed for PAL_PARAM_ID_DEVICE_CONNECTION for " - << audioDeviceDesc.toString(); - return ret; - } - LOG(INFO) << __func__ << devicePortExt.device.toString() - << (isConnect ? ": connected" : "disconnected"); - - return 0; -} - -void Platform::setWFDProxyChannels(const uint32_t numProxyChannels) noexcept { - mWFDProxyChannels = numProxyChannels; - pal_param_proxy_channel_config_t paramProxyChannelConfig{.num_proxy_channels = - mWFDProxyChannels}; - if (int32_t ret = ::pal_set_param(PAL_PARAM_ID_PROXY_CHANNEL_CONFIG, ¶mProxyChannelConfig, - sizeof(pal_param_proxy_channel_config_t)); - ret) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_PROXY_CHANNEL_CONFIG failed: " << ret; - return; - } -} - -void Platform::setProxyRecordFMQSize(const size_t& FMQSize) noexcept { - mProxyRecordFMQSize = FMQSize; -} - -size_t Platform::getProxyRecordFMQSize() const noexcept { - return mProxyRecordFMQSize; -} - -uint32_t Platform::getWFDProxyChannels() const noexcept { - return mWFDProxyChannels; -} - -std::string Platform::IsProxyRecordActive() const noexcept{ - int ret = 0; - size_t size = 0; - char proxy_record_state[6] = "false"; - ret = pal_get_param(PAL_PARAM_ID_PROXY_RECORD_SESSION, (void **)&proxy_record_state, &size, - nullptr); - if (!ret && size > 0) { - LOG(INFO) << __func__ << " proxyRecordActive = " << proxy_record_state; - } else { - LOG(ERROR) << __func__ << " : PAL_PARAM_ID_PROXY_RECORD_SESSION failed: " << ret; - } - return std::string(proxy_record_state); -} - -void Platform::updateUHQA(const bool enable) noexcept { - mIsUHQAEnabled = enable; -#ifndef SEC_AUDIO_SUPPORT_UHQ - pal_param_uhqa_t paramUHQAFlags{.uhqa_state = mIsUHQAEnabled}; - if (int32_t ret = - ::pal_set_param(PAL_PARAM_ID_UHQA_FLAG, ¶mUHQAFlags, sizeof(pal_param_uhqa_t)); - ret) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_UHQA_FLAG failed: " << ret; - return; - } -#endif - return; -} - -#ifdef SEC_AUDIO_SUPPORT_UHQ -void Platform::updateUHQA(const pal_uhqa_state sample) noexcept { - pal_param_uhqa_t paramInfo{.state = sample }; - mIsUHQAEnabled = (sample > PAL_UHQ_STATE_NORMAL) ? true : false; - - if (int32_t ret = - ::pal_set_param(PAL_PARAM_ID_UHQA_FLAG, ¶mInfo, sizeof(pal_param_uhqa_t)); - ret) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_UHQA_FLAG failed: " << ret; - return; - } -} -#endif - -bool Platform::isUHQAEnabled() const noexcept { - return mIsUHQAEnabled; -} - -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION -void Platform::triggerSpeakerCalibration() const noexcept { - pal_param_cal_trigger_t param_cal_trigger{.enable = true}; - if (int32_t ret = ::pal_set_param(PAL_PARAM_ID_SEPAKER_AMP_RUN_CAL, ¶m_cal_trigger, - sizeof(pal_param_cal_trigger_t)); - ret) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_SEPAKER_AMP_RUN_CAL failed: " << ret; - return; - } -} -#endif - -void Platform::setFTMSpeakerProtectionMode(uint32_t const heatUpTime, uint32_t const runTime, - bool const isFactoryTest, bool const isValidationMode, - bool const isDynamicCalibration) const noexcept { - pal_spkr_prot_payload spPayload{ - .spkrHeatupTime = heatUpTime, .operationModeRunTime = runTime, - }; - - if (isFactoryTest) - spPayload.operationMode = PAL_SP_MODE_FACTORY_TEST; - else if (isValidationMode) - spPayload.operationMode = PAL_SP_MODE_V_VALIDATION; - else if (isDynamicCalibration) - spPayload.operationMode = PAL_SP_MODE_DYNAMIC_CAL; - else - return; - - if (int32_t ret = - ::pal_set_param(PAL_PARAM_ID_SP_MODE, &spPayload, sizeof(pal_spkr_prot_payload)); - ret) { - LOG(ERROR) << ": PAL_PARAM_ID_SP_MODE failed, ret:" << ret; - return; - } -} - -std::optional Platform::getFTMResult() const noexcept { - char ftmValue[255]; - size_t dataSize = 0; - if (int32_t ret = ::pal_get_param(PAL_PARAM_ID_SP_MODE, reinterpret_cast(&ftmValue), - &dataSize, nullptr); - (ret || dataSize <= 0)) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_SP_MODE failed, ret:" << ret - << ", data size:" << dataSize; - return std::nullopt; - } - return std::string(ftmValue, dataSize); -} - -std::optional Platform::getSpeakerCalibrationResult() const noexcept { - char calValue[255]; - size_t dataSize = 0; - if (int32_t ret = ::pal_get_param(PAL_PARAM_ID_SP_GET_CAL, reinterpret_cast(&calValue), - &dataSize, nullptr); - (ret || dataSize <= 0)) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_SP_GET_CAL failed, ret:" << ret - << ", data size:" << dataSize; - return std::nullopt; - } - return std::string(calValue, dataSize); -} - -#ifdef ENABLE_TAS_SPK_PROT -std::optional Platform::getSpeakerProtectionResult() const noexcept { - std::string kvpairs = ";"; - if (!tiSpkProtParam.hdr[AUDIO_PARAM_TI_SMARTPA_GET_IDX]) { - LOG(ERROR) << __func__ << " TI-SmartPA: get_without_set"; - return std::nullopt; - } else { - LOG(INFO) << __func__ << " TI-SmartPA: get ch=" << tiSpkProtParam.hdr[0] - << ", idx=0x" << std::hex << tiSpkProtParam.hdr[1] - << ", len=" << tiSpkProtParam.hdr[2]; - pal_tispk_prot_param_t *pTiSpkProtParam = &tiSpkProtParam; - size_t size = 0; - int32_t ret = pal_get_param(PAL_TISA_PARAM_GEN_GETPARAM, - (void**)&pTiSpkProtParam, &size, nullptr); - if (!ret) { - std::string tiSpkProtParamStr; - for (int i = 0; i < AUDIO_PARAM_HDR_LEN - 1; i++) { - tiSpkProtParamStr = AUDIO_PARAM_TI_HDR[i]; - kvpairs += tiSpkProtParamStr + "=" - + std::to_string(tiSpkProtParam.hdr[i]) + ";"; - } - for (int i = 0; i < tiSpkProtParam.hdr[AUDIO_PARAM_TI_SMARTPA_LEN_IDX]; i++) { - tiSpkProtParamStr = AUDIO_PARAM_TI_VIDX[i]; - kvpairs += tiSpkProtParamStr + "=" - + std::to_string(tiSpkProtParam.data[i]) + ";"; - } - } - } - memset(&tiSpkProtParam, 0, sizeof(tiSpkProtParam)); - return kvpairs; -} -#endif - -void Platform::updateScreenRotation(const IModule::ScreenRotation in_rotation) noexcept { - pal_param_device_rotation_t paramDeviceRotation{}; - - auto notifyDeviceRotation = [&]() -> void { - if (int32_t ret = ::pal_set_param(PAL_PARAM_ID_DEVICE_ROTATION, ¶mDeviceRotation, - sizeof(pal_param_device_rotation_t)); - ret) { - LOG(ERROR) << ": PAL_PARAM_ID_DEVICE_ROTATION failed"; - } - LOG(INFO) << ": updated screen rotation from " - << ::aidl::android::hardware::audio::core::toString(mCurrentScreenRotation) - << " to " - << ::aidl::android::hardware::audio::core::toString( - in_rotation); // validation log - }; - - if (in_rotation == IModule::ScreenRotation::DEG_270 && - mCurrentScreenRotation != IModule::ScreenRotation::DEG_270) { - /* Device rotated from normal position to inverted landscape. */ - paramDeviceRotation.rotation_type = PAL_SPEAKER_ROTATION_RL; - notifyDeviceRotation(); - } else if (in_rotation != IModule::ScreenRotation::DEG_270 && - mCurrentScreenRotation == IModule::ScreenRotation::DEG_270) { - /* Phone was in inverted landspace and now is changed to portrait or inverted portrait. */ - paramDeviceRotation.rotation_type = PAL_SPEAKER_ROTATION_LR; - notifyDeviceRotation(); - } - - // set for hdr params - if (in_rotation == IModule::ScreenRotation::DEG_90 || - in_rotation == IModule::ScreenRotation::DEG_270) { - setOrientation("landscape"); - } else { - setOrientation("portrait"); - } - - if (in_rotation == IModule::ScreenRotation::DEG_270 || - in_rotation == IModule::ScreenRotation::DEG_180) { - setInverted(true); - } else { - setInverted(false); - } - - mCurrentScreenRotation = in_rotation; -} - -IModule::ScreenRotation Platform::getCurrentScreenRotation() const noexcept { - return mCurrentScreenRotation; -} - -void Platform::setHapticsVolume(const float hapticsVolume) const noexcept { - auto data = makePalVolumes({hapticsVolume}); - if (data.empty()) { - LOG(ERROR) << __func__ << ": failed to configure haptics volume"; - return; - } - auto payloadPtr = reinterpret_cast(data.data()); - if (int32_t ret = ::pal_set_param(PAL_PARAM_ID_HAPTICS_VOLUME, payloadPtr, data.size()); ret) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_HAPTICS_VOLUME failed: " << ret; - return; - } -} - -void Platform::setHapticsIntensity(const int hapticsIntensity) const noexcept { - pal_param_haptics_intensity_t paramHapticsIntensity{.intensity = hapticsIntensity}; - if (int32_t ret = ::pal_set_param(PAL_PARAM_ID_HAPTICS_INTENSITY, ¶mHapticsIntensity, - sizeof(pal_param_haptics_intensity_t)); - ret) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_HAPTICS_INTENSITY failed: " << ret; - return; - } -} - -#ifdef SEC_AUDIO_SUPPORT_HAPTIC_PLAYBACK -void Platform::setHapticsSource(const int hapticsSource) const noexcept { - pal_param_haptic_source_t paramHapticsSource{.haptic_source = (haptic_source_t)hapticsSource}; - if (int32_t ret = ::pal_set_param(PAL_PARAM_ID_HAPTIC_SOURCE, (void*)¶mHapticsSource, - sizeof(pal_param_haptic_source_t)); - ret) { - LOG(ERROR) << __func__ << ": PAL_PARAM_ID_HAPTIC_SOURCE failed: " << ret; - return; - } -} -#endif - -bool Platform::setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& in_parameters, - bool in_async) { - std::string kvpairs = getkvPairsForVendorParameter(in_parameters); - if (!kvpairs.empty()) { - setBluetoothParameters(kvpairs.c_str()); -#ifdef ENABLE_TAS_SPK_PROT - setSpeakerProtectionParameters(kvpairs.c_str()); -#endif - } - return true; -} - -#ifdef ENABLE_TAS_SPK_PROT -bool Platform::setSpeakerProtectionParameters(const char* kvpairs) { - struct str_parms* parms = NULL; - int ret = 0, val = 0; - char value[256]; - LOG(VERBOSE) << __func__ << "kvpairs " << kvpairs; - parms = str_parms_create_str(kvpairs); - ret = str_parms_get_str(parms, AUDIO_PARAM_TI_SMARTPA, value, sizeof(value)); - if (ret >= 0) { - int i; - int get = 0; - int param_len; - - memset(&tiSpkProtParam, 0, sizeof(tiSpkProtParam)); - - for (i = 0; i < AUDIO_PARAM_HDR_LEN; i++) { - ret = str_parms_get_int(parms, AUDIO_PARAM_TI_HDR[i], - &tiSpkProtParam.hdr[i]); - if (ret) - break; - } - - if (i < (AUDIO_PARAM_HDR_LEN - 1)) { - ret = -EINVAL; - } else if (i == (AUDIO_PARAM_HDR_LEN - 1)) { - tiSpkProtParam.hdr[AUDIO_PARAM_TI_SMARTPA_GET_IDX] = 0; - ret = 0; - } - - if (!ret) { - get = tiSpkProtParam.hdr[AUDIO_PARAM_TI_SMARTPA_GET_IDX]; - param_len = tiSpkProtParam.hdr[AUDIO_PARAM_TI_SMARTPA_LEN_IDX]; - - LOG(INFO) << __func__ - << " TI-SmartPA: setparam ch=" << tiSpkProtParam.hdr[0] - << ", idx=" << tiSpkProtParam.hdr[1] - << ", len=" << param_len - << ", get=" << (get ? 1 : 0); - - if (!get) { - if (param_len > AUDIO_PARAM_MAX_LEN) { - ret = -EINVAL; - } else { - for (i = 0; i < param_len; i++) { - ret = str_parms_get_int(parms, AUDIO_PARAM_TI_VIDX[i], - &tiSpkProtParam.data[i]); - if (ret) - break; - } - if (i == param_len) { - /* success */ - ret = pal_set_param(PAL_TISA_PARAM_GEN_SETPARAM, - (void*)&tiSpkProtParam, sizeof(tiSpkProtParam)); - } else { - LOG(ERROR) << __func__ - << " TI-SmartPA: Unable to extract all params"; - } - } - } - } else { - LOG(INFO) << __func__ - << " TI-SmartPA: invalid params, kvparis=" << kvpairs; - } - } - if (parms) - str_parms_destroy(parms); - return true; -} -#endif - -bool Platform::setBluetoothParameters(const char* kvpairs) { - struct str_parms* parms = NULL; - int ret = 0, val = 0; - char value[256]; - LOG(VERBOSE) << __func__ << "kvpairs " << kvpairs; - parms = str_parms_create_str(kvpairs); - ret = str_parms_get_str(parms, AUDIO_PARAMETER_RECONFIG_A2DP, value, sizeof(value)); - if (ret >= 0) { - pal_param_bta2dp_t param_bt_a2dp; - param_bt_a2dp.reconfig = true; - - LOG(VERBOSE) << __func__ << " BT A2DP Reconfig command received"; - pal_set_param(PAL_PARAM_ID_BT_A2DP_RECONFIG, (void*)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } - ret = str_parms_get_str(parms, "A2dpSuspended", value, sizeof(value)); - if (ret >= 0) { - pal_param_bta2dp_t param_bt_a2dp; - param_bt_a2dp.is_suspend_setparam = true; - - if (strncmp(value, "true", 4) == 0) - param_bt_a2dp.a2dp_suspended = true; - else - param_bt_a2dp.a2dp_suspended = false; - - param_bt_a2dp.dev_id = PAL_DEVICE_OUT_BLUETOOTH_A2DP; - - param_bt_a2dp.is_in_call = (mCallMode != AUDIO_MODE_NORMAL); - -#ifdef SEC_AUDIO_BT_OFFLOAD - param_bt_a2dp.is_bt_offload_enabled = audio_is_bt_offload_format(bt_a2dp_format); -#endif - - LOG(VERBOSE) << __func__ << " BT A2DP Suspended = " << value; - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - pal_set_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED, (void*)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } - ret = str_parms_get_str(parms, "TwsChannelConfig", value, sizeof(value)); - if (ret >= 0) { - pal_param_bta2dp_t param_bt_a2dp; - - LOG(VERBOSE) << __func__ << " Setting tws channel mode to = " << value; - if (!(strncmp(value, "mono", strlen(value)))) - param_bt_a2dp.is_tws_mono_mode_on = true; - else if (!(strncmp(value, "dual-mono", strlen(value)))) - param_bt_a2dp.is_tws_mono_mode_on = false; - pal_set_param(PAL_PARAM_ID_BT_A2DP_TWS_CONFIG, (void*)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } - ret = str_parms_get_str(parms, "LEAMono", value, sizeof(value)); - if (ret >= 0) { - pal_param_bta2dp_t param_bt_a2dp; - - LOG(VERBOSE) << __func__ << " Setting LC3 channel mode to = " << value; - if (!(strncmp(value, "true", strlen(value)))) - param_bt_a2dp.is_lc3_mono_mode_on = true; - else - param_bt_a2dp.is_lc3_mono_mode_on = false; - pal_set_param(PAL_PARAM_ID_BT_A2DP_LC3_CONFIG, (void*)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } - -#ifdef SEC_PRODUCT_FEATURE_BLUETOOTH_SUPPORT_A2DP_OFFLOAD - ret = str_parms_get_str(parms, "g_a2dp_delay_report", value, sizeof(value)); - if (ret >= 0) { - pal_param_bta2dp_delay_report_t param_bt_a2dp_delay_report; - param_bt_a2dp_delay_report.delay_report = atoi(value); - LOG(VERBOSE) << __func__ << " BT A2DP delay report = " << param_bt_a2dp_delay_report.delay_report << ", command received"; - pal_set_param(PAL_PARAM_ID_BT_A2DP_DELAY_REPORT, (void *)¶m_bt_a2dp_delay_report, - sizeof(pal_param_bta2dp_delay_report_t)); - } -#endif - - /* SCO parameters */ - ret = str_parms_get_str(parms, "BT_SCO", value, sizeof(value)); - if (ret >= 0) { - pal_param_btsco_t param_bt_sco; - memset(¶m_bt_sco, 0, sizeof(pal_param_btsco_t)); - if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0) { - param_bt_sco.bt_sco_on = true; - } else { - param_bt_sco.bt_sco_on = false; - } - - LOG(VERBOSE) << __func__ << " BTSCO on = " << param_bt_sco.bt_sco_on; - pal_set_param(PAL_PARAM_ID_BT_SCO, (void*)¶m_bt_sco, sizeof(pal_param_btsco_t)); -#ifdef SEC_AUDIO_BLUETOOTH - setBtScoState(param_bt_sco.bt_sco_on); -#endif - -#if 0 - if (param_bt_sco.bt_sco_on == true) { - if (crs_device.size() == 0) { - crs_device.insert(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET); - voice_->RouteStream(crs_device); - } else { - pos = std::find(crs_device.begin(), crs_device.end(), AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET); - if (pos != crs_device.end()) { - AHAL_INFO("same device has added"); - } else { - crs_device.insert(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET); - voice_->RouteStream({AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET}); - } - } - } else if (param_bt_sco.bt_sco_on == false) { - pos = std::find(crs_device.begin(), crs_device.end(), AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET); - if (pos != crs_device.end()) { - crs_device.erase(pos); - if (crs_device.size() >= 1) { - voice_->RouteStream(crs_device); - AHAL_INFO("route to device 0x%x", AudioExtn::get_device_types(crs_device)); - } else { - crs_device.clear(); - voice_->RouteStream({AUDIO_DEVICE_OUT_SPEAKER}); - } - } - } -#endif - } - - ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_SCO_WB, value, sizeof(value)); - if (ret >= 0) { - pal_param_btsco_t param_bt_sco = {}; - if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0) - param_bt_sco.bt_wb_speech_enabled = true; - else - param_bt_sco.bt_wb_speech_enabled = false; - - LOG(VERBOSE) << __func__ << " BTSCO WB mode = " << param_bt_sco.bt_wb_speech_enabled; - pal_set_param(PAL_PARAM_ID_BT_SCO_WB, (void*)¶m_bt_sco, - sizeof(pal_param_btsco_t)); - } - ret = str_parms_get_str(parms, "bt_swb", value, sizeof(value)); - if (ret >= 0) { - pal_param_btsco_t param_bt_sco = {}; - - val = atoi(value); - param_bt_sco.bt_swb_speech_mode = val; - LOG(VERBOSE) << __func__ << " BTSCO SWB mode = " << val; - pal_set_param(PAL_PARAM_ID_BT_SCO_SWB, (void*)¶m_bt_sco, - sizeof(pal_param_btsco_t)); - } - - ret = str_parms_get_str(parms, "bt_ble", value, sizeof(value)); - if (ret >= 0) { - pal_param_btsco_t param_bt_sco = {}; - if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0) { - bt_lc3_speech_enabled = true; - - // turn off wideband, super-wideband - param_bt_sco.bt_wb_speech_enabled = false; - pal_set_param(PAL_PARAM_ID_BT_SCO_WB, (void*)¶m_bt_sco, - sizeof(pal_param_btsco_t)); - - param_bt_sco.bt_swb_speech_mode = 0xFFFF; - pal_set_param(PAL_PARAM_ID_BT_SCO_SWB, (void*)¶m_bt_sco, - sizeof(pal_param_btsco_t)); - } else { - bt_lc3_speech_enabled = false; - param_bt_sco.bt_lc3_speech_enabled = false; - pal_set_param(PAL_PARAM_ID_BT_SCO_LC3, (void*)¶m_bt_sco, - sizeof(pal_param_btsco_t)); - - // clear btsco_lc3_cfg to avoid stale and partial cfg being used in next round - memset(&btsco_lc3_cfg, 0, sizeof(btsco_lc3_cfg_t)); - } - LOG(VERBOSE) << __func__ << " BTSCO LC3 mode = " << bt_lc3_speech_enabled; - } - - ret = str_parms_get_str(parms, "bt_lc3_swb", value, sizeof(value)); - if (ret >= 0) { - pal_param_btsco_t param_bt_sco_swb = {}; - if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0) { - // turn off wideband, super-wideband - param_bt_sco_swb.bt_wb_speech_enabled = false; - pal_set_param(PAL_PARAM_ID_BT_SCO_WB, (void*)¶m_bt_sco_swb, - sizeof(pal_param_btsco_t)); - - param_bt_sco_swb.bt_swb_speech_mode = 0xFFFF; - pal_set_param(PAL_PARAM_ID_BT_SCO_SWB, (void*)¶m_bt_sco_swb, - sizeof(pal_param_btsco_t)); - - char streamMap[PAL_LC3_MAX_STRING_LEN] = "(0, 0, M, 0, 1, M)"; - char vendor[PAL_LC3_MAX_STRING_LEN] = "00,00,00,00,00,00,00,00,00,02,00,00,00,0A,00,00"; - param_bt_sco_swb.bt_lc3_speech_enabled = true; - param_bt_sco_swb.lc3_cfg.num_blocks = 1; - param_bt_sco_swb.lc3_cfg.rxconfig_index = LC3_SWB_CODEC_CONFIG_INDEX; - param_bt_sco_swb.lc3_cfg.txconfig_index = LC3_SWB_CODEC_CONFIG_INDEX; - param_bt_sco_swb.lc3_cfg.api_version = 21; - param_bt_sco_swb.lc3_cfg.mode = LC3_HFP_TRANSIT_MODE; - strlcpy(param_bt_sco_swb.lc3_cfg.streamMap, streamMap, PAL_LC3_MAX_STRING_LEN); - strlcpy(param_bt_sco_swb.lc3_cfg.vendor, vendor, PAL_LC3_MAX_STRING_LEN); - - LOG(VERBOSE) << __func__ << " BTSCO LC3 SWB mode = on, sending.."; - pal_set_param(PAL_PARAM_ID_BT_SCO_LC3, (void*)¶m_bt_sco_swb, - sizeof(pal_param_btsco_t)); - } else { - param_bt_sco_swb.bt_lc3_speech_enabled = false; - - LOG(VERBOSE) << __func__ << " BTSCO LC3 SWB mode = off, sending.."; - pal_set_param(PAL_PARAM_ID_BT_SCO_LC3, (void*)¶m_bt_sco_swb, - sizeof(pal_param_btsco_t)); - } - } - - ret = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_BT_NREC, value, sizeof(value)); - if (ret >= 0) { - pal_param_btsco_t param_bt_sco = {}; - if (strcmp(value, AUDIO_PARAMETER_VALUE_ON) == 0) { - LOG(VERBOSE) << __func__ << " BTSCO NREC mode = ON"; - param_bt_sco.bt_sco_nrec = true; - } else { - LOG(VERBOSE) << __func__ << " BTSCO NREC mode = OFF"; - param_bt_sco.bt_sco_nrec = false; - } - pal_set_param(PAL_PARAM_ID_BT_SCO_NREC, (void*)¶m_bt_sco, - sizeof(pal_param_btsco_t)); -#ifdef SEC_AUDIO_BLUETOOTH - setBtNrecState(param_bt_sco.bt_sco_nrec); -#endif - } - - for (auto& key : lc3_reserved_params) { - ret = str_parms_get_str(parms, key, value, sizeof(value)); - if (ret < 0) continue; - - if (!strcmp(key, "Codec") && (!strcmp(value, "LC3"))) { - btsco_lc3_cfg.fields_map |= LC3_CODEC_BIT; - } else if (!strcmp(key, "StreamMap")) { - strlcpy(btsco_lc3_cfg.streamMap, value, PAL_LC3_MAX_STRING_LEN); - btsco_lc3_cfg.fields_map |= LC3_STREAM_MAP_BIT; - } else if (!strcmp(key, "FrameDuration")) { - btsco_lc3_cfg.frame_duration = atoi(value); - btsco_lc3_cfg.fields_map |= LC3_FRAME_DURATION_BIT; - } else if (!strcmp(key, "Blocks_forSDU")) { - btsco_lc3_cfg.num_blocks = atoi(value); - btsco_lc3_cfg.fields_map |= LC3_BLOCKS_FORSDU_BIT; - } else if (!strcmp(key, "rxconfig_index")) { - btsco_lc3_cfg.rxconfig_index = atoi(value); - btsco_lc3_cfg.fields_map |= LC3_RXCFG_IDX_BIT; - } else if (!strcmp(key, "txconfig_index")) { - btsco_lc3_cfg.txconfig_index = atoi(value); - btsco_lc3_cfg.fields_map |= LC3_TXCFG_IDX_BIT; - } else if (!strcmp(key, "version")) { - btsco_lc3_cfg.api_version = atoi(value); - btsco_lc3_cfg.fields_map |= LC3_VERSION_BIT; - } else if (!strcmp(key, "vendor")) { - strlcpy(btsco_lc3_cfg.vendor, value, PAL_LC3_MAX_STRING_LEN); - btsco_lc3_cfg.fields_map |= LC3_VENDOR_BIT; - } - } - - if (((btsco_lc3_cfg.fields_map & LC3_BIT_MASK) == LC3_BIT_VALID) && - (bt_lc3_speech_enabled == true)) { - pal_param_btsco_t param_bt_sco = {}; - param_bt_sco.bt_lc3_speech_enabled = bt_lc3_speech_enabled; - param_bt_sco.lc3_cfg.frame_duration = btsco_lc3_cfg.frame_duration; - param_bt_sco.lc3_cfg.num_blocks = btsco_lc3_cfg.num_blocks; - param_bt_sco.lc3_cfg.rxconfig_index = btsco_lc3_cfg.rxconfig_index; - param_bt_sco.lc3_cfg.txconfig_index = btsco_lc3_cfg.txconfig_index; - param_bt_sco.lc3_cfg.api_version = btsco_lc3_cfg.api_version; - param_bt_sco.lc3_cfg.mode = LC3_BROADCAST_TRANSIT_MODE; - strlcpy(param_bt_sco.lc3_cfg.streamMap, btsco_lc3_cfg.streamMap, PAL_LC3_MAX_STRING_LEN); - strlcpy(param_bt_sco.lc3_cfg.vendor, btsco_lc3_cfg.vendor, PAL_LC3_MAX_STRING_LEN); - - LOG(VERBOSE) << __func__ << " BTSCO LC3 mode = on, sending.."; - pal_set_param(PAL_PARAM_ID_BT_SCO_LC3, (void*)¶m_bt_sco, - sizeof(pal_param_btsco_t)); - - memset(&btsco_lc3_cfg, 0, sizeof(btsco_lc3_cfg_t)); - } - ret = str_parms_get_str(parms, "A2dpCaptureSuspend", value, sizeof(value)); - if (ret >= 0) { - pal_param_bta2dp_t param_bt_a2dp; - param_bt_a2dp.is_suspend_setparam = true; - - if (strncmp(value, "true", 4) == 0) - param_bt_a2dp.a2dp_capture_suspended = true; - else - param_bt_a2dp.a2dp_capture_suspended = false; - - param_bt_a2dp.dev_id = PAL_DEVICE_IN_BLUETOOTH_A2DP; - - param_bt_a2dp.is_in_call = (mCallMode != AUDIO_MODE_NORMAL); - - LOG(VERBOSE) << __func__ << " BT A2DP Capture Suspended " << value << "command received"; - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - pal_set_param(PAL_PARAM_ID_BT_A2DP_CAPTURE_SUSPENDED, (void*)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } - ret = str_parms_get_str(parms, "LeAudioSuspended", value, sizeof(value)); - if (ret >= 0) { - pal_param_bta2dp_t param_bt_a2dp; - param_bt_a2dp.is_suspend_setparam = true; - - if (strcmp(value, "true") == 0) { - param_bt_a2dp.a2dp_suspended = true; - param_bt_a2dp.a2dp_capture_suspended = true; - } else { - param_bt_a2dp.a2dp_suspended = false; - param_bt_a2dp.a2dp_capture_suspended = false; - } - - param_bt_a2dp.is_in_call = (mCallMode != AUDIO_MODE_NORMAL); - - LOG(INFO) << __func__ << " BT LEA Suspended = ," << value << " command received"; - // Synchronize the suspend/resume calls from setparams and reconfig_cb - std::unique_lock guard(AudioExtension::reconfig_wait_mutex_); - param_bt_a2dp.dev_id = PAL_DEVICE_OUT_BLUETOOTH_BLE; - pal_set_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED, (void*)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - - param_bt_a2dp.dev_id = PAL_DEVICE_IN_BLUETOOTH_BLE; - pal_set_param(PAL_PARAM_ID_BT_A2DP_CAPTURE_SUSPENDED, (void*)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - param_bt_a2dp.dev_id = PAL_DEVICE_OUT_BLUETOOTH_BLE_BROADCAST; - pal_set_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED, (void*)¶m_bt_a2dp, - sizeof(pal_param_bta2dp_t)); - } -#ifdef SEC_AUDIO_COMMON - if (parms) - str_parms_destroy(parms); -#endif - return true; -} - -bool Platform::setParameter(const std::string& key, const std::string& value) { - // Todo check for validity of key - const auto & [ first, second ] = mParameters.insert_or_assign(key, value); - LOG(VERBOSE) << __func__ << " platform parameter with key:" << key << " " - << (second ? "inserted" : "re-assigned") << " with value:" << value; - return true; -} - -std::string Platform::getParameter(const std::string& key) const { - if (mParameters.find(key) != mParameters.cend()) { - return mParameters.at(key); - } - return ""; -} - -#ifdef SEC_AUDIO_BT_OFFLOAD -bool Platform::isBluetoothA2dpDevice(const AudioDevice& d) const noexcept { - if (d.type.connection == AudioDeviceDescription::CONNECTION_BT_A2DP) { - return true; - } - return false; -} -#endif - -bool Platform::isSoundCardUp() const noexcept { - if (mSndCardStatus == CARD_STATUS_ONLINE) { - return true; - } - return false; -} - -bool Platform::isSoundCardDown() const noexcept { - if (mSndCardStatus == CARD_STATUS_OFFLINE || mSndCardStatus == CARD_STATUS_STANDBY) { - return true; - } - return false; -} - - -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO -bool Platform::IsBtForMultiDevice(const std::vector& devices) const noexcept { -#ifdef SEC_AUDIO_BLUETOOTH - if(bt_sco_on) { - return true; - } -#endif -#ifdef SEC_AUDIO_BLUETOOTH - for (auto& device : devices) { - const auto palDeviceId = PlatformConverter::getPalDeviceId(device.type); - if (palDeviceId == PAL_DEVICE_IN_BLUETOOTH_BLE) { - return true; - } - } -#endif - return false; -} -#endif - -uint32_t Platform::getBluetoothLatencyMs(const std::vector& bluetoothDevices) { - pal_param_bta2dp_t btConfig{}; - pal_param_bta2dp_t *param_bt_a2dp_ptr = &btConfig; - - for (const auto& device : bluetoothDevices) { - size_t payloadSize = 0; - param_bt_a2dp_ptr->dev_id = PlatformConverter::getPalDeviceId(device.type); - // first bluetooth device - if (param_bt_a2dp_ptr->dev_id == PAL_DEVICE_OUT_BLUETOOTH_A2DP || - param_bt_a2dp_ptr->dev_id == PAL_DEVICE_OUT_BLUETOOTH_BLE || - param_bt_a2dp_ptr->dev_id == PAL_DEVICE_OUT_BLUETOOTH_BLE_BROADCAST) { - if (int32_t ret = ::pal_get_param(PAL_PARAM_ID_BT_A2DP_ENCODER_LATENCY, - reinterpret_cast(¶m_bt_a2dp_ptr), &payloadSize, nullptr); - ret) { - LOG(ERROR) << __func__ << " failure in PARAM_ID_BT_A2DP_ENCODER_LATENCY: " << ret; - continue; - } - if (payloadSize == 0) { - LOG(ERROR) << __func__ << " empty payload size!!!"; - continue; - } - } - } -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - LOG(VERBOSE) << __func__ << " bt latency: " << param_bt_a2dp_ptr->latency; -#else - LOG(DEBUG) << __func__ << " bt latency: " << param_bt_a2dp_ptr->latency; -#endif - return param_bt_a2dp_ptr->latency; -} - -bool Platform::isA2dpSuspended() { - int ret = 0; - size_t bt_param_size = 0; - pal_param_bta2dp_t *param_bt_a2dp_ptr, param_bt_a2dp; - param_bt_a2dp_ptr = ¶m_bt_a2dp; - param_bt_a2dp_ptr->dev_id = PAL_DEVICE_OUT_BLUETOOTH_A2DP; - ret = pal_get_param(PAL_PARAM_ID_BT_A2DP_SUSPENDED, (void**)¶m_bt_a2dp_ptr, &bt_param_size, - nullptr); - if (!ret && bt_param_size && param_bt_a2dp_ptr && !param_bt_a2dp_ptr->a2dp_suspended) { - LOG(DEBUG) << __func__ << " A2dp suspended " << param_bt_a2dp_ptr->a2dp_suspended; - return param_bt_a2dp_ptr->a2dp_suspended; - } - return true; -} - -PlaybackRateStatus Platform::setPlaybackRate( - pal_stream_handle_t* handle, const Usecase& tag, - const ::aidl::android::media::audio::common::AudioPlaybackRate& playbackRate) { - if (!isValidPlaybackRate(playbackRate)) { - return PlaybackRateStatus::ILLEGAL_ARGUMENT; - } - - if (!usecaseSupportsOffloadSpeed(tag)) { - return PlaybackRateStatus::UNSUPPORTED; - } - - if (!handle) { - LOG(DEBUG) << __func__ << " stream inactive "; - return PlaybackRateStatus::SUCCESS; - } - - auto allocSize = sizeof(pal_param_payload) + sizeof(pal_param_playback_rate_t); - auto payload = - VALUE_OR_EXIT(allocate(allocSize), PlaybackRateStatus::UNSUPPORTED); - pal_param_payload* payloadPtr = payload.get(); - payloadPtr->payload_size = sizeof(pal_param_playback_rate_t); - - auto palPlaybackRatePtr = reinterpret_cast(payloadPtr->payload); - palPlaybackRatePtr->speed = playbackRate.speed; - palPlaybackRatePtr->pitch = playbackRate.pitch; - - if (auto ret = pal_stream_set_param(handle, PAL_PARAM_ID_TIMESTRETCH_PARAMS, payloadPtr); ret) { - LOG(ERROR) << __func__ << " failed to set " << playbackRate.toString(); - return PlaybackRateStatus::UNSUPPORTED; - } - return PlaybackRateStatus::SUCCESS; -} - -int Platform::getRecommendedLatencyModes( - std::vector<::aidl::android::media::audio::common::AudioLatencyMode>* _aidl_return) { - - size_t size; - int ret = 0; - auto palLatencyModeInfo = std::make_unique(); - if (!palLatencyModeInfo) { - LOG(ERROR) << __func__ << ": allocation failed "; - return -ENOMEM; - } - - palLatencyModeInfo->dev_id = PAL_DEVICE_OUT_BLUETOOTH_A2DP; - palLatencyModeInfo->num_modes = PAL_MAX_LATENCY_MODES; - void *palLatencyModeInfoPtr = palLatencyModeInfo.get(); - - ret = pal_get_param(PAL_PARAM_ID_LATENCY_MODE, - (void **)&palLatencyModeInfoPtr, &size, nullptr); - if (ret) { - LOG(ERROR) << __func__ << " get param latency mode failed"; - return ret; - } - - LOG(VERBOSE) << __func__ << " actual modes returned: " << palLatencyModeInfo->num_modes; - - for (int count = 0; count < palLatencyModeInfo->num_modes; count++) - { - _aidl_return->push_back( - (::aidl::android::media::audio::common::AudioLatencyMode)palLatencyModeInfo->modes[count]); - } - - return ret; -} - -bool Platform::isHDRARMenabled() { - const auto& platform = Platform::getInstance(); - const std::string kHdrArmProperty{"vendor.audio.hdr.record.enable"}; - const bool isArmEnabled = ::android::base::GetBoolProperty(kHdrArmProperty, false); - const bool isHdrSetOnPlatform = platform.isHDREnabled(); - if (isArmEnabled && isHdrSetOnPlatform) { - return true; - } - return false; - -} -bool Platform::isHDRSPFEnabled() { - const std::string kHdrSpfProperty{"vendor.audio.hdr.spf.record.enable"}; - const bool isSPFEnabled = ::android::base::GetBoolProperty(kHdrSpfProperty, false); - if (isSPFEnabled) { - return true; - } - return false; -} - -void Platform::setHdrOnPalDevice(pal_device* palDeviceIn) { - const auto& platform = Platform::getInstance(); - const bool isOrientationLandscape = platform.getOrientation() == "landscape"; - const bool isInverted = platform.isInverted(); - - LOG(ERROR) << __func__ << " platform.getOrientation():" << std::string(platform.getOrientation()); - - if (isOrientationLandscape && !isInverted) { - setPalDeviceCustomKey(*palDeviceIn, "unprocessed-hdr-mic-landscape"); - } else if (!isOrientationLandscape && !isInverted) { - setPalDeviceCustomKey(*palDeviceIn, "unprocessed-hdr-mic-portrait"); - } else if (isOrientationLandscape && isInverted) { - setPalDeviceCustomKey(*palDeviceIn, "unprocessed-hdr-mic-inverted-landscape"); - } else if (!isOrientationLandscape && isInverted) { - setPalDeviceCustomKey(*palDeviceIn, "unprocessed-hdr-mic-inverted-portrait"); - } - LOG(DEBUG) << __func__ - << " setting custom config:" << std::string(palDeviceIn->custom_config.custom_key); - -} - -void Platform::configurePalDevices( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - std::vector& palDevices) { - const auto& mixUsecase = - mixPortConfig.ext.get<::aidl::android::media::audio::common::AudioPortExt::Tag::mix>() - .usecase; - if (mixUsecase.getTag() != - ::aidl::android::media::audio::common::AudioPortMixExtUseCase::Tag::source) { - LOG(ERROR) << __func__ << " expected mix usecase as source instead found, " - << mixUsecase.toString(); - return; - } - const auto& sampleRate = mixPortConfig.sampleRate.value().value; - const auto& channelLayout = mixPortConfig.channelMask.value(); - const ::aidl::android::media::audio::common::AudioSource& audioSourceType = mixUsecase.get< - ::aidl::android::media::audio::common::AudioPortMixExtUseCase::Tag::source>(); - const bool isSourceUnprocessed = - audioSourceType == ::aidl::android::media::audio::common::AudioSource::UNPROCESSED; - const bool isSourceCamCorder = - audioSourceType == ::aidl::android::media::audio::common::AudioSource::CAMCORDER; - const bool isMic = audioSourceType == ::aidl::android::media::audio::common::AudioSource::MIC; - const bool isHdrArmEnable = isHDRARMenabled(); - const bool isHdrSpfEnable = isHDRSPFEnabled(); - if ((isSourceUnprocessed && sampleRate == 48000 && getChannelCount(channelLayout) == 4 && - isHdrArmEnable) || - (isHdrArmEnable) || (isHdrSpfEnable && (isSourceCamCorder || isMic))) { - std::for_each(palDevices.begin(), palDevices.end(), - [&](auto& palDevice) { this->setHdrOnPalDevice(&palDevice); }); - } -} - -int Platform::setLatencyMode(uint32_t mode) { - - int ret = 0; - auto palLatencyModeInfo = std::make_unique(); - if (!palLatencyModeInfo) { - LOG(ERROR) << __func__ << ": allocation failed "; - return -ENOMEM; - } - - palLatencyModeInfo->dev_id = PAL_DEVICE_OUT_BLUETOOTH_A2DP; - palLatencyModeInfo->num_modes = 1; - palLatencyModeInfo->modes[0] = (uint32_t)mode; - - ret = pal_set_param(PAL_PARAM_ID_LATENCY_MODE, - (void *)palLatencyModeInfo.get(), sizeof(pal_param_latency_mode_t)); - - return ret; -} - -std::optional> Platform::requiresBufferReformat( - const AudioPortConfig& portConfig) { - const auto& audioFormat = portConfig.format.value(); - - if (audioFormat.pcm == PcmType::FLOAT_32_BIT) { - return std::make_pair(AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT); - } - return std::nullopt; -} - -std::string Platform::toString() const { - std::ostringstream os; - os << " === platform start ===" << std::endl; - os << "sound card status: " << mSndCardStatus << std::endl; - for (const auto & [ key, value ] : mParameters) { - os << key << "=>" << value << std::endl; - } - os << PlatformConverter::toString() << std::endl; -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - os << toStringSec(); -#endif - os << " === platform end ===" << std::endl; - return os.str(); -} - -#ifdef SEC_AUDIO_ADD_FOR_DEBUG -std::string Platform::toStringSec() const { - std::ostringstream os; -#ifdef SEC_AUDIO_BLUETOOTH - os << " bt_sco_on : " << (bt_sco_on? "on" : "off") << std::endl; -#endif -#ifdef SEC_AUDIO_CALL - os << " mIsVoWiFi : " << (mIsVoWiFi? "on" : "off"); -#ifdef SEC_AUDIO_WB_AMR - os << ", mCallBand : " << mCallBand << std::endl; -#endif - os << " mRingbacktone : " << (mRingbacktone? "on" : "off") << std::endl; - os << " mNbQuality : " << (mNbQuality? "on" : "off") << std::endl; - if (mCallMode == AUDIO_MODE_IN_CALL) { - os << " Mute Voice : RX " << (mVoiceMuteState[PAL_RX]? "mute":"unmute") << - ", TX " << (mVoiceMuteState[PAL_TX]? "mute":"unmute ") << std::endl; - } - os << " mMicMuted : " << (mMicMuted? "on" : "off") << std::endl; -#endif -#ifdef SEC_AUDIO_ALL_SOUND_MUTE - os << " mAllSoundMute : " << (mAllSoundMute? "on" : "off") << std::endl; -#endif -#ifdef SEC_AUDIO_CALL_FORWARDING - os << " mCallMemo : " << mCallMemo << std::endl; - os << " mCallForwarding : " << (mCallForwarding? "on" : "off") << std::endl; -#endif -#ifdef SEC_AUDIO_VOICE_TX_FOR_INCALL_MUSIC - os << " mScreenCall : " << (mScreenCall? "on" : "off") << std::endl; -#endif -#ifdef SEC_AUDIO_CALL_TRANSLATION - os << " mCallTranslation : " << (mCallTranslation? "on" : "off") << std::endl; - os << " mVoiceRxControl : " << mVoiceRxControl << std::endl; -#endif -#ifdef SEC_AUDIO_ENFORCED_AUDIBLE - os << " mEnforcePlaybackState : " << mEnforcePlaybackState << std::endl; -#endif -#ifdef SEC_AUDIO_CALL_HAC - os << " mHacIncall : " << (mHacIncall? "on" : "off"); - os << ", mHacMode : " << mHacMode << std::endl; -#endif -#ifdef SEC_AUDIO_SCREEN_MIRRORING // { SUPPORT_VOIP_VIA_SMART_VIEW - os << " mVoipViaSmartView : " << (mVoipViaSmartView? "on" : "off") << std::endl; -#endif // } SUPPORT_VOIP_VIA_SMART_VIEW -#ifdef SEC_AUDIO_FMRADIO - os << " mFM : " << (mFM.on? "on" : "off") << (mFM.mute? " (mute)" : "") << std::endl; -#endif -#ifdef SEC_AUDIO_SUPPORT_NSRI - os << " is_NSRI_secure : " << (is_NSRI_secure? "on" : "off") << std::endl; -#endif -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC - os << " mAasEnabled : " << (mAasEnabled? "on" : "off") << std::endl; -#endif - os << std::endl; - return os.str(); -} - -void Platform::dump(int fd) const { - pal_dump(fd); -} -#endif - -// static -int Platform::palGlobalCallback(uint32_t event_id, uint32_t* event_data, uint64_t cookie) { - auto platform = reinterpret_cast(cookie); - switch (event_id) { - case PAL_SND_CARD_STATE: - platform->mSndCardStatus = static_cast(*event_data); - LOG(INFO) << __func__ << " card status changed to " << platform->mSndCardStatus; - break; - default: - LOG(ERROR) << __func__ << " invalid event id" << event_id; - return -EINVAL; - } - return 0; -} - -void Platform::initUsecaseOpMap() { - mUsecaseOpMap[Usecase::PRIMARY_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::LOW_LATENCY_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::DEEP_BUFFER_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::ULL_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::MMAP_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::COMPRESS_OFFLOAD_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::PCM_OFFLOAD_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::VOIP_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::HAPTICS_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::SPATIAL_PLAYBACK] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::IN_CALL_MUSIC] = makeUsecaseOps(); - - // Record usecases - mUsecaseOpMap[Usecase::PCM_RECORD] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::FAST_RECORD] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::ULTRA_FAST_RECORD] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::MMAP_RECORD] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::COMPRESS_CAPTURE] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::VOIP_RECORD] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::VOICE_CALL_RECORD] = makeUsecaseOps(); - mUsecaseOpMap[Usecase::HOTWORD_RECORD] = makeUsecaseOps(); -} - -std::vector Platform::getMicrophoneDynamicInfo( - const std::vector& devices) { - auto palDevices = convertToPalDevices(devices); - std::vector result; - for (const auto& palDevice : palDevices) { - auto id = palDevice.id; - if (mMicrophoneDynamicInfoMap.count(id) != 0) { - auto dynamicInfo = mMicrophoneDynamicInfoMap[id]; - result.insert(result.end(), dynamicInfo.begin(), dynamicInfo.end()); - } - } - return result; -} - -#ifdef SEC_AUDIO_SAMSUNGRECORD -int Platform::match_device_enums(const AudioDevice& device) const noexcept { - int ret = 0; - if (device.type.type == AudioDeviceType::IN_MICROPHONE) { // AUDIO_DEVICE_IN_BUILTIN_MIC - ret = AUDIO_DEVICE_IN_BUILTIN_MIC; - } else if (device.type.type == AudioDeviceType::IN_HEADSET && - device.type.connection == AudioDeviceDescription::CONNECTION_BT_SCO) { // AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET - ret = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET; - } else if (device.type.type == AudioDeviceType::IN_MICROPHONE_MULTI) { // AUDIO_DEVICE_IN_2MIC - ret = AUDIO_DEVICE_IN_2MIC; - } else if (device.type.type == AudioDeviceType::IN_HEADSET && - device.type.connection == AudioDeviceDescription::CONNECTION_ANALOG) { // AUDIO_DEVICE_IN_WIRED_HEADSET - ret = AUDIO_DEVICE_IN_WIRED_HEADSET; - }else if (device.type.type == AudioDeviceType::IN_ACCESSORY && - device.type.connection == AudioDeviceDescription::CONNECTION_USB) { // AUDIO_DEVICE_IN_USB_ACCESSORY - ret = AUDIO_DEVICE_IN_USB_ACCESSORY; - } else if (device.type.type == AudioDeviceType::IN_DEVICE && - device.type.connection == AudioDeviceDescription::CONNECTION_USB) { // AUDIO_DEVICE_IN_USB_DEVICE - ret = AUDIO_DEVICE_IN_USB_DEVICE; - } else if (device.type.type == AudioDeviceType::IN_HEADSET && - device.type.connection == AudioDeviceDescription::CONNECTION_USB) { // AUDIO_DEVICE_IN_USB_HEADSET - ret = AUDIO_DEVICE_IN_USB_HEADSET; - } else if (device.type.type == AudioDeviceType::IN_HEADSET && - device.type.connection == AudioDeviceDescription::CONNECTION_BT_LE) { // AUDIO_DEVICE_IN_BLE_HEADSET - ret = AUDIO_DEVICE_IN_BLE_HEADSET; - } else { - ret = 0; - } - return ret; -} - -int Platform::get_device_types(const std::vector& devices) const noexcept { - int device = 0; - for(auto itr = devices.cbegin(); itr < devices.cend(); itr++) { - device |= match_device_enums(*itr); - } - return device; -} - -bool Platform::GetRecMultiMic(const AudioPortConfig& mixPortConfig, const std::vector& connectedDevices, Usecase tag) const noexcept { - bool state = false; - audio_devices_t devices = static_cast(get_device_types(connectedDevices)); - // 4CH Supported Devices : - // 2mic(or buildin) - // BTMIX (2mic+bt) - // switching BTMIX : usb->btmix, ble->btmix - if (!audio_is_subset_device(devices, AUDIO_DEVICE_IN_2MIC) -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - && !(multidevice_rec - && (audio_is_subset_device(devices, AUDIO_DEVICE_IN_BLE_HEADSET) -#if (SEC_AUDIO_MULTI_MIC == 0) - || audio_is_usb_in_device(devices) -#endif - )) -#endif - ) { - return state; - } - -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - // not support releasing BTMIX : btmix(2mic+ble) -> no btmix - if (!multidevice_rec - && audio_is_subset_device(devices, AUDIO_DEVICE_IN_BLE_HEADSET) - && audio_is_subset_device(devices, AUDIO_DEVICE_IN_2MIC)) { - return state; - } -#endif - - const auto& source = getAudioSource(mixPortConfig); - - // Supported Scenario - if (IsSupportPreprocess(mixPortConfig, tag) - && tag == Usecase::PCM_RECORD - && !is_karaoke_on - && mIsLoopBackOff -#if (SEC_AUDIO_MULTI_MIC == 0) && defined(SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO) - && multidevice_rec -#endif - && source && (source.value() == AudioSource::CAMCORDER)) { - state = true; - } - return state; -} - -bool Platform::IsSupportPreprocess(const AudioPortConfig& mixPortConfig, Usecase tag) const noexcept { - bool ret = false; - - if (!SelectPreProcessSolutions(mixPortConfig)) { - return ret; - } - const auto& sampleRate = getSampleRate(mixPortConfig); - if (!(sampleRate && sampleRate.value() == 48000 - && (mixPortConfig.flags && hasInputFastFlag(mixPortConfig.flags.value())) != 0) - && !mIsRmsTestMode - && tag != Usecase::VOIP_RECORD) { - ret = true; - } - return ret; -} - -uint32_t Platform::SelectPreProcessSolutions(const AudioPortConfig& mixPortConfig) const noexcept { - uint32_t solutions = S_NONE; - const auto& source = getAudioSource(mixPortConfig); - auto& flags = mixPortConfig.flags.value(); - - if ((mCallMode == AUDIO_MODE_IN_CALL) - || (mCallMode== AUDIO_MODE_IN_COMMUNICATION) - || (mCallMode == AUDIO_MODE_CALL_SCREEN)) { - return solutions; - } - -#ifdef SEC_AUDIO_COMPRESS_CAPTURE - if (hasInputDirectFlag(flags)) { - return solutions; - } -#endif - - if (source) { - int src = static_cast(source.value()); - if ((src == static_cast(AudioSource::MIC)) - || (src == static_cast(AudioSource::CAMCORDER)) - || (src == static_cast(AudioSource::VOICE_PERFORMANCE) + 7)) { // SEC_CAMCORDER - solutions |= preprocess_eq_enables; - } else if (src == static_cast(AudioSource::VOICE_PERFORMANCE) + 8) { // SEC_BEAMFORMING - solutions |= S_REC_BF; - } - } -#ifdef SEC_AUDIO_RECORDALIVE_ON_REMOTE_MIC - //remote mic solution should be attached on recordalive supported source - if (hasInputRemoteMicFlag(flags) && solutions) { - solutions |= S_REC_REMOTE_MIC; - } -#endif - - return solutions; -} - -uint32_t Platform::GetBufferSize(const AudioPortConfig& mixPortConfig) { - const auto& sampleRate = mixPortConfig.sampleRate.value().value; - const auto& frameSize = getFrameSizeInBytes(mixPortConfig.format.value(), mixPortConfig.channelMask.value()); - uint32_t ret = (mixPortConfig.sampleRate.value().value / 1000) * AUDIO_CAPTURE_PERIOD_DURATION_MSEC * - frameSize; - LOG(DEBUG) << __func__ << " update buffer size : " << ret; - return ret; -} - -int Platform::GetRecFormat(const AudioPortConfig& mixPortConfig, const std::vector& connectedDevices, Usecase tag) { - const auto& source = getAudioSource(mixPortConfig); - int formats = 0; - audio_devices_t devices = static_cast(get_device_types(connectedDevices)); - // 24bit Supported Devices : - // 2mic(or buildin), usb, 3.5pi - // BTMIX (2mic+bt) - // switching BTMIX : ble->btmix - if (!audio_is_usb_in_device(devices) - && !audio_is_subset_device(devices, AUDIO_DEVICE_IN_WIRED_HEADSET) - && !audio_is_subset_device(devices, AUDIO_DEVICE_IN_2MIC) -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - && !(multidevice_rec - && audio_is_subset_device(devices, AUDIO_DEVICE_IN_BLE_HEADSET)) -#endif - ) { - return formats; - } - -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - // not support releasing BTMIX : btmix(2mic+ble) -> no btmix - if (!multidevice_rec - && audio_is_subset_device(devices, AUDIO_DEVICE_IN_BLE_HEADSET) - && audio_is_subset_device(devices, AUDIO_DEVICE_IN_2MIC)) { - return formats; - } -#endif - - // Supported Scenario - if(isLoopBackOff()) { - if (mixPortConfig.format.value().pcm == PcmType::INT_16_BIT - && IsSupportPreprocess(mixPortConfig, tag) - && tag == Usecase::PCM_RECORD - && source && (source.value() == AudioSource::MIC || source.value() == AudioSource::CAMCORDER)) { - formats = AUDIO_SUPPORTED_FORMAT_24; - } - } - return formats; -} -#endif - -#ifdef SEC_AUDIO_KARAOKE -bool Platform::isKaraokeUsecases(const Usecase& tag) { - switch (tag) { - case Usecase::LOW_LATENCY_PLAYBACK: - case Usecase::DEEP_BUFFER_PLAYBACK: - case Usecase::ULL_PLAYBACK: - return true; - default: - return false; - } -} -#endif - -#if defined(SEC_AUDIO_OFFLOAD_COMPRESSED_OPUS) && defined(SEC_AUDIO_OFFLOAD_SOUNDSPEED) -PlaybackRateStatus Platform::setSecPlaybackRate(pal_stream_handle_t* handle, const Usecase& tag, - const ::aidl::android::media::audio::common::AudioPlaybackRate& playbackRate, - const std::optional< ::aidl::android::media::audio::common::AudioOffloadInfo>& offloadInfo - ,std::function sendSpeed) { - if (!isValidPlaybackRate(playbackRate)) { - return PlaybackRateStatus::ILLEGAL_ARGUMENT; - } - - if (!usecaseSupportsOffloadSpeed(tag)) { - return PlaybackRateStatus::UNSUPPORTED; - } - - if (!isSecSupportsOffloadSpeed(offloadInfo)) { - return PlaybackRateStatus::UNSUPPORTED; - } - - if (!handle) { - LOG(DEBUG) << __func__ << " stream inactive "; - return PlaybackRateStatus::SUCCESS; - } - - sendSpeed(playbackRate.speed); - - return PlaybackRateStatus::SUCCESS; - -} - -bool Platform::isSecSupportsOffloadSpeed(const std::optional< ::aidl::android::media::audio::common::AudioOffloadInfo>& offloadInfo) { - if (!offloadInfo.has_value()) { - return false; - } - - if (offloadInfo.has_value() && offloadInfo.value().base.format.encoding != ::android::MEDIA_MIMETYPE_AUDIO_OPUS) { - return false; - } - - return true; -} -#endif - -Platform::Platform() { - initUsecaseOpMap(); - if (int32_t ret = pal_init(); ret) { - LOG(ERROR) << __func__ << "pal_init failed, ret:" << ret; - return; - } - LOG(VERBOSE) << __func__ << " pal_init successful"; - if (int32_t ret = - pal_register_global_callback(&palGlobalCallback, reinterpret_cast(this)); - ret) { - LOG(ERROR) << __func__ << "pal register global callback failed, ret:" << ret; - return; - } - mSndCardStatus = CARD_STATUS_ONLINE; - LOG(VERBOSE) << __func__ << " pal register global callback successful"; - mOffloadSpeedSupported = property_get_bool("vendor.audio.offload.playspeed", true); - MicrophoneInfoParser micInfoParser; - mMicrophoneInfo = micInfoParser.getMicrophoneInfo(); - mMicrophoneDynamicInfoMap = micInfoParser.getMicrophoneDynamicInfoMap(); -} - -// static -Platform& Platform::getInstance() { - static const auto kPlatform = []() { - std::unique_ptr platform{new Platform()}; - return std::move(platform); - }(); - return *(kPlatform.get()); -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/PlatformUtils.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/PlatformUtils.cpp deleted file mode 100755 index 7ba5b5a9..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/PlatformUtils.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_NDEBUG 0 -#define LOG_TAG "AHAL_PlatformUtils_QTI" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -using ::aidl::android::hardware::audio::common::getChannelCount; -using ::aidl::android::media::audio::common::AudioChannelLayout; -using ::aidl::android::media::audio::common::AudioFormatDescription; -using ::aidl::android::media::audio::common::AudioFormatType; -using ::aidl::android::media::audio::common::AudioProfile; -using ::aidl::android::media::audio::common::PcmType; -using ::aidl::android::media::audio::common::AudioPlaybackRate; -using ::aidl::android::hardware::audio::core::VendorParameter; -using ::aidl::qti::audio::core::VString; - -namespace qti::audio::core { - -using AudioChannelCountToMaskMap = std::map; -AudioChannelLayout getInvalidChannelLayout() { - static const AudioChannelLayout invalidChannelLayout = - AudioChannelLayout::make(0); - return invalidChannelLayout; -} - -static AudioChannelCountToMaskMap createChannelMaskMap( - const std::set& channelMasks) { - AudioChannelCountToMaskMap channelMaskToCountMap; - for (const auto& channelMask : channelMasks) { - channelMaskToCountMap.emplace(getChannelCount(channelMask), channelMask); - } - return channelMaskToCountMap; -} -#define MAKE_LAYOUT_MASK(n) \ - AudioChannelLayout::make(AudioChannelLayout::LAYOUT_##n) - -const AudioChannelCountToMaskMap& getSupportedChannelOutLayoutMap() { - static const std::set supportedOutChannelLayouts = { - MAKE_LAYOUT_MASK(MONO), MAKE_LAYOUT_MASK(STEREO), MAKE_LAYOUT_MASK(2POINT1), - MAKE_LAYOUT_MASK(QUAD), MAKE_LAYOUT_MASK(PENTA), MAKE_LAYOUT_MASK(5POINT1), - MAKE_LAYOUT_MASK(6POINT1), MAKE_LAYOUT_MASK(7POINT1), MAKE_LAYOUT_MASK(7POINT1POINT4), - MAKE_LAYOUT_MASK(22POINT2), - }; - static const AudioChannelCountToMaskMap outLayouts = - createChannelMaskMap(supportedOutChannelLayouts); - return outLayouts; -} - -const AudioChannelCountToMaskMap& getSupportedChannelInLayoutMap() { - static const std::set supportedInChannelLayouts = { - MAKE_LAYOUT_MASK(MONO), MAKE_LAYOUT_MASK(STEREO), - }; - static const AudioChannelCountToMaskMap inLayouts = - createChannelMaskMap(supportedInChannelLayouts); - return inLayouts; -} -#undef MAKE_LAYOUT_MASK -#define MAKE_INDEX_MASK(n) \ - AudioChannelLayout::make(AudioChannelLayout::INDEX_MASK_##n) - -const AudioChannelCountToMaskMap& getSupportedChannelIndexLayoutMap() { - static const std::set supportedIndexChannelLayouts = { - MAKE_INDEX_MASK(1), MAKE_INDEX_MASK(2), MAKE_INDEX_MASK(3), MAKE_INDEX_MASK(4), - MAKE_INDEX_MASK(5), MAKE_INDEX_MASK(6), MAKE_INDEX_MASK(7), MAKE_INDEX_MASK(8), - MAKE_INDEX_MASK(9), MAKE_INDEX_MASK(10), MAKE_INDEX_MASK(11), MAKE_INDEX_MASK(12), - MAKE_INDEX_MASK(13), MAKE_INDEX_MASK(14), MAKE_INDEX_MASK(15), MAKE_INDEX_MASK(16), - MAKE_INDEX_MASK(17), MAKE_INDEX_MASK(18), MAKE_INDEX_MASK(19), MAKE_INDEX_MASK(20), - MAKE_INDEX_MASK(21), MAKE_INDEX_MASK(22), MAKE_INDEX_MASK(23), MAKE_INDEX_MASK(24), - }; - static const AudioChannelCountToMaskMap indexLayouts = - createChannelMaskMap(supportedIndexChannelLayouts); - return indexLayouts; -} - -#undef MAKE_INDEX_MASK - -// Assuming that M is a map whose keys' type is K and values' type is V, -// return the corresponding value of the given key from the map or default -// value if the key is not found. -template -static auto findValueOrDefault(const M& m, const K& key, V defaultValue) { - auto it = m.find(key); - return it == m.end() ? defaultValue : it->second; -} - -AudioChannelLayout getChannelLayoutMaskFromChannelCount(unsigned int channelCount, int isInput) { - return findValueOrDefault( - isInput ? getSupportedChannelInLayoutMap() : getSupportedChannelOutLayoutMap(), - channelCount, getInvalidChannelLayout()); -} - -AudioChannelLayout getChannelIndexMaskFromChannelCount(unsigned int channelCount) { - return findValueOrDefault(getSupportedChannelIndexLayoutMap(), channelCount, - getInvalidChannelLayout()); -} -std::vector getChannelMasksFromProfile( - pal_param_device_capability_t* capability) { - const bool isInput = !capability->is_playback; - std::vector channels; - for (size_t i = 0; i < AUDIO_PORT_MAX_CHANNEL_MASKS && capability->config->mask[i] != 0; ++i) { - auto channelCount = - isInput ? audio_channel_count_from_in_mask(capability->config->mask[i]) - : audio_channel_count_from_out_mask(capability->config->mask[i]); - auto layoutMask = getChannelLayoutMaskFromChannelCount(channelCount, isInput); - if (layoutMask.getTag() == AudioChannelLayout::Tag::layoutMask) { - channels.push_back(layoutMask); - } - auto indexMask = getChannelIndexMaskFromChannelCount(channelCount); - if (indexMask.getTag() == AudioChannelLayout::Tag::indexMask) { - channels.push_back(indexMask); - } - } - return channels; -} -std::vector getSampleRatesFromProfile(pal_param_device_capability_t* capability) { - std::vector sampleRates; - for (int i = 0; capability->config->sample_rate[i] != 0; i++) { - sampleRates.push_back(capability->config->sample_rate[i]); - } - return sampleRates; -} - -static AudioFormatDescription make_AudioFormatDescription(AudioFormatType type) { - AudioFormatDescription result; - result.type = type; - return result; -} -static AudioFormatDescription make_AudioFormatDescription(PcmType pcm) { - auto result = make_AudioFormatDescription(AudioFormatType::PCM); - result.pcm = pcm; - return result; -} - -static AudioFormatDescription getLegacyToAidlFormat(int palFormat) { - switch (palFormat) { - case PCM_16_BIT: - return make_AudioFormatDescription(PcmType::INT_16_BIT); - case PCM_32_BIT: - return make_AudioFormatDescription(PcmType::INT_32_BIT); - case PCM_24_BIT_PACKED: - return make_AudioFormatDescription(PcmType::INT_24_BIT); - default: - return AudioFormatDescription(); - } -} - -std::vector getSupportedAudioProfiles(pal_param_device_capability_t* capability, - std::string devName) { - std::vector supportedProfiles; - std::vector channels = getChannelMasksFromProfile(capability); - std::vector sampleRates = getSampleRatesFromProfile(capability); - - std::string name = devName + "_" + (capability->is_playback ? "out" : "in"); - for (size_t i = 0; i < MAX_SUPPORTED_FORMATS && capability->config->format[i] != 0; ++i) { - auto audioFormatDescription = getLegacyToAidlFormat(capability->config->format[i]); - if (audioFormatDescription.type == AudioFormatType::DEFAULT) { - LOG(WARNING) << __func__ << ": unknown pcm type= " << capability->config->format[i]; - continue; - } - - AudioProfile audioProfile = {.name = name, - .format = audioFormatDescription, - .channelMasks = channels, - .sampleRates = sampleRates}; - - LOG(VERBOSE) << __func__ << " found profile " << audioProfile.toString(); - supportedProfiles.push_back(std::move(audioProfile)); - } - return supportedProfiles; -} - -bool isValidPlaybackRate( - const ::aidl::android::media::audio::common::AudioPlaybackRate& playbackRate) { - // For fallback mode MUTE, out of range values should not be rejected. - if (playbackRate.fallbackMode != AudioPlaybackRate::TimestretchFallbackMode::MUTE) { - if (playbackRate.speed < 0.1f || playbackRate.speed > 2.0f) { - LOG(ERROR) << __func__ << ": unsupported speed " << playbackRate.toString(); - return false; - } - - if (playbackRate.pitch != 1.0f) { - LOG(ERROR) << __func__ << ": unsupported pitch " << playbackRate.toString(); - return false; - } - } - - auto isValidStretchMode = [=](const auto& stretchMode) { - return (stretchMode == AudioPlaybackRate::TimestretchMode::DEFAULT || - stretchMode == AudioPlaybackRate::TimestretchMode::VOICE); - }; - - if (!isValidStretchMode(playbackRate.timestretchMode)) { - LOG(ERROR) << __func__ << ": unsupported timstrecth mode " << playbackRate.toString(); - return false; - } - - auto isValidFallbackMode = [=](const auto& fallMode) { - return (fallMode == AudioPlaybackRate::TimestretchFallbackMode::MUTE || - fallMode == AudioPlaybackRate::TimestretchFallbackMode::FAIL); - }; - - if (!isValidFallbackMode(playbackRate.fallbackMode)) { - LOG(ERROR) << __func__ << ": unsupported fallback mode " << playbackRate.toString(); - return false; - } - - return true; -} - -void setPalDeviceCustomKey(pal_device& palDevice, const std::string& customKey) noexcept { - strlcpy(palDevice.custom_config.custom_key, customKey.c_str(), PAL_MAX_CUSTOM_KEY_SIZE); -} - -std::vector makePalVolumes(std::vector const& volumes) noexcept { - if (volumes.empty()) { - return {}; - } - - auto channels = volumes.size(); - auto palChannelInfo = PlatformConverter::getPalChannelInfoForChannelCount(channels); - - const auto dataLength = sizeof(pal_volume_data) + sizeof(pal_channel_vol_kv) * channels; - auto data = std::vector(dataLength); - auto palVolumeData = reinterpret_cast(data.data()); - palVolumeData->no_of_volpair = channels; - - for (unsigned long channel = 0; channel < channels; channel++) { - palVolumeData->volume_pair[channel].channel_mask = palChannelInfo->ch_map[channel]; - palVolumeData->volume_pair[channel].vol = volumes[channel]; - } - return data; -} - -} // namespace qti::audio::core \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/AudioUsecase.h b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/AudioUsecase.h deleted file mode 100755 index 6db8de49..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/AudioUsecase.h +++ /dev/null @@ -1,624 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#define DIV_ROUND_UP(x, y) (((x) + (y) - 1) / (y)) -#define ALIGN(x, y) ((y) * DIV_ROUND_UP((x), (y))) -#define DEFAULT_SAMPLE_RATE 48000 -namespace qti::audio::core { - -// forward declaration -struct PlatformStreamCallback; - -enum class Usecase : uint16_t { - INVALID = 0, - PRIMARY_PLAYBACK, - LOW_LATENCY_PLAYBACK, - DEEP_BUFFER_PLAYBACK, - ULL_PLAYBACK, - MMAP_PLAYBACK, - COMPRESS_OFFLOAD_PLAYBACK, - PCM_OFFLOAD_PLAYBACK, - VOIP_PLAYBACK, - HAPTICS_PLAYBACK, - SPATIAL_PLAYBACK, - IN_CALL_MUSIC, - PCM_RECORD, // Start of record usecases - FAST_RECORD, - ULTRA_FAST_RECORD, - MMAP_RECORD, - COMPRESS_CAPTURE, - VOIP_RECORD, - VOICE_CALL_RECORD, - HOTWORD_RECORD, -}; - -#ifdef SEC_AUDIO_COMMON -std::optional getMixPortAudioSource( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) noexcept; -#endif - -Usecase getUsecaseTag(const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - -std::string getName(const Usecase tag); - -/* - * Equivalent to getPeriodSize/getPeriodCount. - * where bufferSize = frameCount * frameSize; - * Single API getBufferConfig can be queried by Stream's to fetch Info about periodsize/count. - */ -struct BufferConfig { - size_t bufferSize; - size_t bufferCount; -}; - -/* -* Each usecase class should provide getLatency, getFrameCount, getBufferConfig which are -* used by Platform.cpp to map to respective usecase. -* getBufferConfig internally needs getBufferSize API. - -* Earlier in Hidl, getBufferSize was used by framework and to configure pal streams. -* In AIDL when a patch is created framecount is queried, so instead of buffer size -* frameCount is expected to be returned, so for FWK calls getFrameCount is used, -* and for internal pal setups getBufferConfig is used. -* -* Ideally for pcm formats totalBytes (bufferSizeInBytes) = framecount * framesize. -* while framesize = (channelCount * sizeof(audio_format)). - -* To summerize : getBufferSize = getFrameCount(portConfig) * getFrameSizeInBytes() -* -* However, for compress usecase, frameSize is 1, so bufferSize = getFrameSize. -* -* UsecaseConfig template is helpful to declare getBufferConfig and getBufferSize for -* each usecase, each new usecase can extend UsecaseConfig. -* As stated before, framesizes are different for pcm and compress types. -* UsecaseConfig by default uses pcm config, to use a pcm usecase extend like this -* class PcmUsecase : public UsecaseConfig -* To define a compress usecase 1 can use as below: -* class CompressUsecase : public UsecaseConfig -*/ - -template -class UsecaseConfig { - public: - /* - * brief create getBufferConfig definition for the usecases. - * BufferConfig publishes the bufferCount and bufferSize needed to configure the pal streams. - * To utilize this API, properly configure kPeriodCount and getBufferSize in the usecase. - */ - static BufferConfig getBufferConfig( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) { - BufferConfig config; - config.bufferCount = Usecase::kPeriodCount; - config.bufferSize = Usecase::getBufferSize(mixPortConfig); - return config; - } - - /* - * brief create getBufferSize definition based on if usecase is pcm or non pcm. - * For pcm case frameSize is calculated based on channel count and format. - * for compress usecases frameSize is used as 1. - */ - static size_t getBufferSize( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) { - size_t frameCount = Usecase::getFrameCount(mixPortConfig); - size_t frameSizeInBytes = 1; - if (IsPcm) { - frameSizeInBytes = ::aidl::android::hardware::audio::common::getFrameSizeInBytes( - mixPortConfig.format.value(), mixPortConfig.channelMask.value()); - } - return frameCount * frameSizeInBytes; - } -}; - -/** - * This port is opened by default and receives routing, audio mode and volume - * controls related to voice calls - **/ - -class PrimaryPlayback : public UsecaseConfig { - public: -#ifdef SEC_AUDIO_COMMON - constexpr static size_t kPeriodCount = 4; - constexpr static size_t kPeriodDurationMs = 20; -#else - constexpr static size_t kPeriodCount = 2; - constexpr static size_t kPeriodDurationMs = 40; -#endif - constexpr static size_t kPlatformDelayMs = 29; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPeriodDurationMs * kPeriodCount + kPlatformDelayMs; } -}; - -class DeepBufferPlayback : public UsecaseConfig { - public: -#ifdef SEC_AUDIO_COMMON - constexpr static size_t kPeriodCount = 4; - constexpr static size_t kPeriodDurationMs = 20; -#else - constexpr static size_t kPeriodCount = 2; - constexpr static size_t kPeriodDurationMs = 40; -#endif - constexpr static size_t kPlatformDelayMs = 49; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPeriodDurationMs * kPeriodCount + kPlatformDelayMs; } -}; - -class LowLatencyPlayback : public UsecaseConfig { - public: - constexpr static size_t kPeriodCount = 2; - constexpr static size_t kPlatformDelayMs = 13; - constexpr static size_t kPeriodDurationMs = 4; - static std::unordered_set kSupportedFrameSizes; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPeriodDurationMs * kPeriodCount + kPlatformDelayMs; } -}; - -class UllPlayback : public UsecaseConfig { - public: - constexpr static size_t kPlatformDelayMs = 4; - constexpr static uint32_t kPeriodCount = 512; - constexpr static size_t kPeriodDurationMs = 3; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPeriodDurationMs + kPlatformDelayMs; } -}; - -class MmapUsecaseBase { - public: - virtual ~MmapUsecaseBase() {} - virtual void setPalHandle(pal_stream_handle_t* handle); - virtual int32_t createMMapBuffer(int64_t frameSize, int32_t* fd, int64_t* burstSizeFrames, - int32_t* flags, int32_t* bufferSizeFrames); - virtual int32_t getMMapPosition(int64_t* frames, int64_t* timeNs); - virtual int32_t start(); - virtual int32_t stop(); - protected: - pal_stream_handle_t* mPalHandle{nullptr}; - bool mIsStarted = false; -}; - -class MMapPlayback : public MmapUsecaseBase, public UsecaseConfig { - public: - constexpr static size_t kPeriodDurationMs = 1; - constexpr static size_t kPlatformDelayMs = 3; - constexpr static uint32_t kPeriodCount = 512; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPeriodDurationMs + kPlatformDelayMs; } -}; - -class CompressPlayback : public UsecaseConfig { - public: - static constexpr size_t kPeriodSize = 32 * 1024; - static constexpr size_t kPeriodCount = 4; - static constexpr int32_t kLatencyMs = 50; - static constexpr size_t kPlatformDelayMs = 30; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kLatencyMs; } - - class Flac final { - public: - static constexpr size_t kPeriodSize = 256 * 1024; - inline const static std::string kMinBlockSize{"music_offload_flac_min_blk_size"}; - inline const static std::string kMaxBlockSize{"music_offload_flac_max_blk_size"}; - inline const static std::string kMinFrameSize{"music_offload_flac_min_frame_size"}; - inline const static std::string kMaxFrameSize{"music_offload_flac_max_frame_size"}; - }; - class Alac final { - public: - inline const static std::string kFrameLength{"music_offload_alac_frame_length"}; - inline const static std::string kCompatVer{"music_offload_alac_compatible_version"}; - inline const static std::string kBitDepth{"music_offload_alac_bit_depth"}; - inline const static std::string kPb{"music_offload_alac_pb"}; - inline const static std::string kMb{"music_offload_alac_mb"}; - inline const static std::string kKb{"music_offload_alac_kb"}; - inline const static std::string kNumChannels{"music_offload_alac_num_channels"}; - inline const static std::string kMaxRun{"music_offload_alac_max_run"}; - inline const static std::string kMaxFrameBytes{"music_offload_alac_max_frame_bytes"}; - inline const static std::string kBitRate{"music_offload_alac_avg_bit_rate"}; - inline const static std::string kSamplingRate{"music_offload_alac_sampling_rate"}; - inline const static std::string kChannelLayoutTag{"music_offload_alac_channel_layout_tag"}; - }; - class Vorbis final { - public: - inline const static std::string kBitStreamFormat{"music_offload_vorbis_bitstream_fmt"}; - }; - class Ape final { - public: - inline const static std::string kCompatibleVersion{"music_offload_ape_compatible_version"}; - inline const static std::string kCompressionLevel{"music_offload_ape_compression_level"}; - inline const static std::string kFormatFlags{"music_offload_ape_format_flags"}; - inline const static std::string kBlocksPerFrame{"music_offload_ape_blocks_per_frame"}; - inline const static std::string kFinalFrameBlocks{"music_offload_ape_final_frame_blocks"}; - inline const static std::string kTotalFrames{"music_offload_ape_total_frames"}; - inline const static std::string kBitsPerSample{"music_offload_ape_bits_per_sample"}; - inline const static std::string kNumChannels{"music_offload_ape_num_channels"}; - inline const static std::string kSampleRate{"music_offload_ape_sample_rate"}; - inline const static std::string kSeekTablePresent{"music_offload_seek_table_present"}; - }; - class Wma final { - public: - inline const static std::string kFormatTag{"music_offload_wma_format_tag"}; - inline const static std::string kBlockAlign{"music_offload_wma_block_align"}; - inline const static std::string kBitPerSample{"music_offload_wma_bit_per_sample"}; - inline const static std::string kChannelMask{"music_offload_wma_channel_mask"}; - inline const static std::string kEncodeOption{"music_offload_wma_encode_option"}; - inline const static std::string kEncodeOption1{"music_offload_wma_encode_option1"}; - inline const static std::string kEncodeOption2{"music_offload_wma_encode_option2"}; - }; - class Opus final { - public: - inline const static std::string kBitStreamFormat{"music_offload_opus_bitstream_format"}; - inline const static std::string kPayloadType{"music_offload_opus_payload_type"}; - inline const static std::string kVersion{"music_offload_opus_version"}; - inline const static std::string kNumChannels{"music_offload_opus_num_channels"}; - inline const static std::string kPreSkip{"music_offload_opus_pre_skip"}; - inline const static std::string kOutputGain{"music_offload_opus_output_gain"}; - inline const static std::string kMappingFamily{"music_offload_opus_mapping_family"}; - inline const static std::string kStreamCount{"music_offload_opus_stream_count"}; - inline const static std::string kCoupledCount{"music_offload_opus_coupled_count"}; - inline const static std::string kChannelMap0{"music_offload_opus_channel_map0"}; - inline const static std::string kChannelMap1{"music_offload_opus_channel_map1"}; - inline const static std::string kChannelMap2{"music_offload_opus_channel_map2"}; - inline const static std::string kChannelMap3{"music_offload_opus_channel_map3"}; - inline const static std::string kChannelMap4{"music_offload_opus_channel_map4"}; - inline const static std::string kChannelMap5{"music_offload_opus_channel_map5"}; - inline const static std::string kChannelMap6{"music_offload_opus_channel_map6"}; - inline const static std::string kChannelMap7{"music_offload_opus_channel_map7"}; - }; - - static int32_t palCallback(pal_stream_handle_t* palHandle, uint32_t eventId, - uint32_t* eventData, uint32_t eventSize, uint64_t cookie); - - explicit CompressPlayback( - const ::aidl::android::media::audio::common::AudioOffloadInfo& offloadInfo, - PlatformStreamCallback* const platformStreamCallback, - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - /* To reconfigure the codec, gapless info */ - void setAndConfigureCodecInfo(pal_stream_handle_t* handle); - void configureGapless(pal_stream_handle_t* handle); - ndk::ScopedAStatus getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return); - ndk::ScopedAStatus setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async); - void updateOffloadMetadata( - const ::aidl::android::hardware::audio::common::AudioOffloadMetadata& offloadMetaData); - void updateSourceMetadata( - const ::aidl::android::hardware::audio::common::SourceMetadata& sourceMetaData); - int64_t getPositionInFrames(pal_stream_handle_t* palHandle); - void onFlush(); - bool isGaplessConfigured() const noexcept { return mIsGaplessConfigured; } - - protected: - void configureDefault(); - // configure the codec info which is cached already - bool configureCodecInfo() const; - // configure the gapless info which is cached already - bool configureGapLessMetadata(); - - protected: - // dynamic compress info - ::aidl::android::hardware::audio::common::AudioOffloadMetadata mOffloadMetadata{}; - const ::aidl::android::hardware::audio::common::SourceMetadata* mSourceMetadata{nullptr}; - // this is static info at the stream creation, for dynamic info check AudioOffloadMetadata - const ::aidl::android::media::audio::common::AudioOffloadInfo& mOffloadInfo; - uint16_t mCompressBitWidth{0}; - pal_stream_handle_t* mCompressPlaybackHandle{nullptr}; - pal_snd_dec_t mPalSndDec{}; - int32_t mSampleRate; - ::aidl::android::media::audio::common::AudioFormatDescription mCompressFormat; - ::aidl::android::media::audio::common::AudioChannelLayout mChannelLayout; - int32_t mBitWidth; - int64_t mTotalDSPFrames{0}; - int64_t mPrevFrames{0}; - const ::aidl::android::media::audio::common::AudioPortConfig& mMixPortConfig; - PlatformStreamCallback * const mPlatformStreamCallback; - std::atomic mIsGaplessConfigured = false; -}; - -class PcmOffloadPlayback : public UsecaseConfig { - public: - explicit PcmOffloadPlayback( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) - : mMixPortConfig(mixPortConfig) {} - constexpr static size_t kPeriodDurationMs = 80; - constexpr static size_t kPeriodCount = 2; - constexpr static size_t kPlatformDelayMs = 30; - constexpr static size_t kMinPeriodSize = 512; - constexpr static size_t kMaxPeriodSize = 240 * 1024; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPeriodDurationMs * kPeriodCount + kPlatformDelayMs; } - - int64_t getPositionInFrames(pal_stream_handle_t* palHandle); - void onFlush(); - - private: - int64_t mTotalDSPFrames{0}; - int64_t mPrevFrames{0}; - const ::aidl::android::media::audio::common::AudioPortConfig& mMixPortConfig; -}; - -class VoipPlayback : public UsecaseConfig { - public: - constexpr static size_t kPeriodDurationMs = 20; - constexpr static size_t kPeriodCount = 2; - constexpr static size_t kPlatformDelayMs = 30; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPeriodDurationMs * kPeriodCount + kPlatformDelayMs; } -}; - -class SpatialPlayback : public UsecaseConfig { - public: - constexpr static size_t kPeriodDurationMs = 10; - constexpr static size_t kPeriodCount = 2; - constexpr static size_t kPlatformDelayMs = 13; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPeriodDurationMs * kPeriodCount + kPlatformDelayMs; } -}; - -class InCallMusic : public UsecaseConfig { - public: - constexpr static size_t kPeriodCount = 4; - constexpr static size_t kPlatformDelayMs = 0; - constexpr static size_t kPeriodDurationMs = 20; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return PrimaryPlayback::getLatency(); } -}; - -class HapticsPlayback : public UsecaseConfig { - public: -#ifdef SEC_AUDIO_SUPPORT_HAPTIC_PLAYBACK // Set the same as Generic - constexpr static size_t kPeriodCount = 4; - constexpr static size_t kPlatformDelayMs = 30; - constexpr static size_t kPeriodDurationMs = 20; -#else - constexpr static size_t kPeriodCount = 2; - constexpr static size_t kPlatformDelayMs = 30; - constexpr static size_t kPeriodDurationMs = 4; -#endif - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPeriodDurationMs * kPeriodCount + kPlatformDelayMs; } -}; - -class PcmRecord : public UsecaseConfig { - public: - constexpr static uint32_t kCaptureDurationMs = 20; - constexpr static uint32_t kPeriodCount = 4; - constexpr static size_t kFMQMinFrameSize = 160; - constexpr static size_t kPlatformDelayMs = 20; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kCaptureDurationMs * kPeriodCount + kPlatformDelayMs; } -}; - -class FastRecord : public UsecaseConfig { - public: - constexpr static uint32_t kCaptureDurationMs = 5; - constexpr static size_t kPeriodCount = 4; - constexpr static size_t kPlatformDelayMs = 5; - bool mIsWFDCapture{false}; - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPlatformDelayMs; } -}; - -class UltraFastRecord : public UsecaseConfig { - public: -#ifdef SEC_AUDIO_SAMSUNGRECORD - constexpr static int32_t kSampleRate = 48000; -#endif - constexpr static uint32_t kCaptureDurationMs = 2; - // The below values at the moment are not generic, TODO make generic - constexpr static size_t kPeriodCount = 512; - constexpr static size_t kPlatformDelayMs = 2; - bool mIsWFDCapture{false}; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPlatformDelayMs; } -}; - -class MMapRecord : public MmapUsecaseBase, public UsecaseConfig { - public: - constexpr static uint32_t kCaptureDurationMs = 2; - constexpr static size_t kPeriodCount = 512; - constexpr static size_t kPlatformDelayMs = 4; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPlatformDelayMs; } -}; - -class HotwordRecord : public UsecaseConfig { - public: - constexpr static uint32_t kPeriodCount = 4; - constexpr static size_t kPlatformDelayMs = 0; - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - // use same as pcm record - static int32_t getLatency() { return PcmRecord::getLatency(); } - pal_stream_handle_t* getPalHandle( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - bool isStRecord() { return mIsStRecord; } -#ifdef SEC_AUDIO_SOUND_TRIGGER_TYPE - void enableSeamless(bool enable) { mIsSeamless = enable; } -#endif - - private: - bool mIsStRecord{false}; -#ifdef SEC_AUDIO_SOUND_TRIGGER_TYPE - bool mIsSeamless{false}; -#endif -}; - -class VoipRecord : public UsecaseConfig { - public: - constexpr static uint32_t kCaptureDurationMs = 20; - constexpr static uint32_t kPeriodCount = 4; - constexpr static size_t kPlatformDelayMs = 0; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return PcmRecord::getLatency(); } -}; - -class VoiceCallRecord : public UsecaseConfig { - public: - constexpr static size_t kCaptureDurationMs = 20; - constexpr static size_t kPeriodCount = 2; - constexpr static size_t kPlatformDelayMs = 0; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - pal_incall_record_direction getRecordDirection( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - static int32_t getLatency() { return PcmRecord::getLatency(); } -}; - -class CompressCapture : public UsecaseConfig { - public: - constexpr static size_t kPlatformDelayMs = 20; - - static size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - - static int32_t getLatency() { return kPlatformDelayMs; } - class Aac final { - public: - inline static const std::string kDSPAacBitRate{"dsp_aac_audio_bitrate"}; - inline static const std::string kDSPAacGlobalCutoffFrequency{ - "dsp_aac_audio_global_cutoff_frequency"}; - enum EncodingMode { - LC = 0x02, - SBR = 0x05, - PS = 0x1D, - }; - enum EncodingFormat { - ADTS = 0x00, - LOAS = 0x01, - RAW = 0x03, - LATM = 0x04, - }; - - constexpr static uint32_t kAacLcPCMSamplesPerFrame = 1024; - constexpr static uint32_t kHeAacPCMSamplesPerFrame = 2048; - constexpr static int32_t kAacLcMonoMinSupportedBitRate = 8000; - constexpr static int32_t kAacLcStereoMinSupportedBitRate = 16000; - constexpr static int32_t kHeAacMonoMinSupportedBitRate1 = 10000; - constexpr static int32_t kHeAacMonoMinSupportedBitRate2 = 12000; - constexpr static int32_t kHeAacStereoMinSupportedBitRate1 = 18000; - constexpr static int32_t kHeAacStereoMinSupportedBitRate2 = 24000; - constexpr static int32_t kHeAacPsStereoMinSupportedBitRate1 = 10000; - constexpr static int32_t kHeAacPsStereoMinSupportedBitRate2 = 12000; - - constexpr static int32_t kAacLcMonoMaxSupportedBitRate = 192000; - constexpr static int32_t kAacLcStereoMaxSupportedBitRate = 384000; - constexpr static int32_t kHeAacMonoMaxSupportedBitRate = 192000; - constexpr static int32_t kHeAacStereoMaxSupportedBitRate = 192000; - constexpr static int32_t kHeAacPstereoMaxSupportedBitRate = 192000; - static const uint32_t KAacMaxOutputSize = 2048; // bytes - static const int32_t kAacDefaultBitrate = 36000; // bps - }; - - constexpr static size_t kPeriodCount = 4; - explicit CompressCapture( - const ::aidl::android::media::audio::common::AudioFormatDescription& format, - int32_t sampleRate, - const ::aidl::android::media::audio::common::AudioChannelLayout& channelLayout); - void setPalHandle(pal_stream_handle_t* handle); - ndk::ScopedAStatus setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async); - size_t getLatencyMs(); - ndk::ScopedAStatus getVendorParameters( - const std::vector& in_ids, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* _aidl_return); - bool configureCodecInfo(); - int32_t getAACMinBitrateValue(); - - int32_t getAACMaxBitrateValue(); - - uint32_t getAACMaxBufferSize(); - void setAACDSPBitRate(); - void advanceReadCount(); - int64_t getPositionInFrames(); - - private: - const ::aidl::android::media::audio::common::AudioFormatDescription& mCompressFormat; - const ::aidl::android::media::audio::common::AudioChannelLayout& mChannelLayout; - int32_t mSampleRate{}; - size_t mPCMSamplesPerFrame{0}; - pal_stream_handle_t* mCompressHandle{nullptr}; - size_t mNumReadCalls{0}; - pal_snd_enc_t mPalSndEnc{}; -}; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/Platform.h b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/Platform.h deleted file mode 100755 index 8df64786..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/Platform.h +++ /dev/null @@ -1,762 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#ifdef SEC_AUDIO_COMMON -#include -#include "SecPalDefs.h" -#endif -#ifdef ENABLE_TAS_SPK_PROT -#include "TISpeakerProtDefs.h" -#endif -#ifdef SEC_AUDIO_SAMSUNGRECORD -#include "PreProcess.h" -#endif - -#ifdef SEC_AUDIO_SAMSUNGRECORD -#define AUDIO_CAPTURE_PERIOD_DURATION_MSEC 20 -#endif - -namespace qti::audio::core { - -struct HdmiParameters { - int controller; - int stream; - pal_device_id_t deviceId; -}; - -enum class PlaybackRateStatus { SUCCESS, UNSUPPORTED, ILLEGAL_ARGUMENT }; - -using GetLatency = int32_t (*)(); -using GetFrameCount = - size_t (*)(const ::aidl::android::media::audio::common::AudioPortConfig& portConfig); -using GetBufferConfig = struct BufferConfig (*)( - const ::aidl::android::media::audio::common::AudioPortConfig& portConfig); - -/* - * Helper to map getLatency, getFrameCount, getBufferConfig APIs - * from platform to audiousecase. While Introducing new usecase - * always provide the APIS. - */ -struct UsecaseOps { - GetLatency getLatency; - GetFrameCount getFrameCount; - GetBufferConfig getBufferConfig; -}; - -template -inline UsecaseOps makeUsecaseOps() { - UsecaseOps ops; - ops.getLatency = UsecaseClass::getLatency; - ops.getFrameCount = UsecaseClass::getFrameCount; - ops.getBufferConfig = UsecaseClass::getBufferConfig; - return ops; -} - -class Platform { - private: - explicit Platform(); - - Platform(const Platform&) = delete; - Platform& operator=(const Platform& x) = delete; - - Platform(Platform&& other) = delete; - Platform& operator=(Platform&& other) = delete; - static int palGlobalCallback(uint32_t event_id, uint32_t* event_data, uint64_t cookie); - - public: - // BT related params used across - bool bt_lc3_speech_enabled; - static btsco_lc3_cfg_t btsco_lc3_cfg; -#ifdef SEC_AUDIO_BLUETOOTH - bool bt_nrec{false}; - bool bt_sco_on{false}; -#endif -#ifdef SEC_AUDIO_SUPPORT_BT_RVC - bool bt_rvc_support{false}; -#endif -#ifdef SEC_AUDIO_BT_OFFLOAD - audio_format_t bt_a2dp_format{AUDIO_FORMAT_DEFAULT}; -#endif -#ifdef ENABLE_TAS_SPK_PROT - static pal_tispk_prot_param_t tiSpkProtParam; -#endif - mutable bool mUSBCapEnable; - int mCallState; - int mCallMode; -#ifdef SEC_AUDIO_CALL - float mVoiceVolume{-1.0f}; - bool mIsVoWiFi{false}; -#ifdef SEC_AUDIO_CALL_SATELLITE - bool mSatelliteCall{false}; -#endif - bool mRingbacktone{false}; - bool mVoiceMuteState[2]{false/*RX*/,false/*TX*/}; - bool mNbQuality{false}; -#ifdef SEC_AUDIO_WB_AMR - int mCallBand = WB; -#endif -#ifdef SEC_AUDIO_CALL_FORWARDING - int mCallMemo{CALLMEMO_OFF}; - bool mCallForwarding{false}; -#endif - int mDeviceInfo{VOICE_DEVICE_INVALID}; - bool mDexConnected{false}; - bool mDexPadConnected{false}; - std::vector<::aidl::android::media::audio::common::AudioDevice> mTelephonyDevices{}; -#endif -#ifdef SEC_AUDIO_ALL_SOUND_MUTE - bool mAllSoundMute{false}; -#endif -#ifdef SEC_AUDIO_CALL_HAC - bool mHacIncall{false}; - int mHacMode{HAC_MODE_MIC}; -#endif -#ifdef SEC_AUDIO_CALL_TRANSLATION - bool mCallTranslation{false}; - int mVoiceTxControl{TRANSLATION_UNMUTE}; - int mVoiceRxControl{TRANSLATION_UNMUTE}; -#endif -#ifdef SEC_AUDIO_CALL_VOIP - bool mCngEnable{false}; - uint32_t mVoipIsolationMode{EFFECTS_MICMODE_STANDARD}; - uint32_t mCallIsolationMode{EFFECTS_MICMODE_STANDARD}; - std::vector mPalDevicesOnVoipRx{}; -#endif -#ifdef SEC_AUDIO_INTERPRETER_MODE - std::vector<::aidl::android::media::audio::common::AudioDevice> mOutDeepDevices{}; -#endif -#ifdef SEC_AUDIO_SCREEN_MIRRORING // { SUPPORT_VOIP_VIA_SMART_VIEW - bool mVoipViaSmartView{false}; -#endif // } SUPPORT_VOIP_VIA_SMART_VIEW -#ifdef SEC_AUDIO_ENFORCED_AUDIBLE - int mEnforcePlaybackState{NOT_MUTE}; -#endif -#ifdef SEC_AUDIO_DUAL_SPEAKER - bool mSpeakerLeftAmpOff{false}; -#endif -#if defined(SEC_AUDIO_DUAL_SPEAKER) || defined(SEC_AUDIO_MULTI_SPEAKER) - int mRotationInfo{TOP_UP}; - int mFlatmotionInfo{FLATMOTION_FLAT}; -#endif -#ifdef SEC_AUDIO_VOICE_TX_FOR_INCALL_MUSIC - bool mScreenCall{false}; -#endif -#ifdef SEC_AUDIO_FMRADIO - fmradio_config_t mFM{false,AUDIO_DEVICE_NONE,0.0f,false}; -#endif -#if defined(SEC_AUDIO_SUPPORT_FLIP_CALL) || defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_FOLD_PARAM_ON_DSP) - bool mFolderclosed{false}; - bool mFlexmode{false}; -#endif -#ifdef SEC_AUDIO_SUPPORT_GAMECHAT_SPK_AEC - bool mGamechatMode{false}; -#endif -#ifdef SEC_AUDIO_SAMSUNGRECORD - uint32_t preprocess_eq_enables{S_REC}; - bool multidevice_rec{false}; - int32_t mUnconfiguredFlagsReceived{0}; -#endif -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC - bool mAasEnabled{false}; - float mAasVolume{1.0f}; -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - bool usb_input_dev_enabled{false}; - pal_device_id_t listenback_device{PAL_DEVICE_NONE}; - bool listenback_on{false}; - std::mutex karaoke_mutex; -#endif -#ifdef SEC_AUDIO_CAMCORDER - bool tx_data_inversion{false}; -#endif -#ifdef SEC_AUDIO_SUPPORT_NSRI - bool is_NSRI_secure{false}; -#endif -#ifdef SEC_AUDIO_SOUND_TRIGGER_TYPE - int register_voice_keyword{0}; - bool seamless_enabled{false}; -#endif -#ifdef SEC_AUDIO_INTERPRETER_MODE - int interpreter_mode{INTERPRETER_OFF}; -#endif -#ifdef SEC_AUDIO_USB_GAIN_CONTROL - bool mUSBGainForCombo{false}; -#endif -#ifdef SEC_AUDIO_KARAOKE - bool is_karaoke_on{false}; -#endif - static Platform& getInstance(); - - size_t getFrameCount( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - Usecase const& inTag = Usecase::INVALID); - - struct BufferConfig getBufferConfig( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - Usecase const& inTag = Usecase::INVALID); - -#ifdef SEC_AUDIO_SUPPORT_UHQ - struct BufferConfig getBufferConfig( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - std::optional>& uhqConfig, - Usecase const& inTag); -#endif - - int32_t getLatencyMs( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - Usecase const& inTag = Usecase::INVALID); - - std::vector<::aidl::android::media::audio::common::MicrophoneInfo> getMicrophoneInfo() { - return mMicrophoneInfo; - } - std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo> - getMicrophoneDynamicInfo( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices); - - bool setParameter(const std::string& key, const std::string& value); - bool setBluetoothParameters(const char* kvpairs); -#ifdef ENABLE_TAS_SPK_PROT - bool setSpeakerProtectionParameters(const char* kvpairs); -#endif - bool setVendorParameters( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - bool in_async); - - std::string getParameter(const std::string& key) const; - std::string toString() const; -#ifdef SEC_AUDIO_ADD_FOR_DEBUG - std::string toStringSec() const; - void dump(int fd) const; -#endif - - bool isSoundCardUp() const noexcept; - bool isSoundCardDown() const noexcept; - -#ifdef SEC_AUDIO_BT_OFFLOAD - bool isBluetoothA2dpDevice(const ::aidl::android::media::audio::common::AudioDevice& d) const - noexcept; -#endif -#ifdef SEC_AUDIO_RECORDALIVE_SUPPORT_MULTIDEVICE_PROVIDEO - bool IsBtForMultiDevice(const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) const noexcept; -#endif - - size_t getMinimumStreamSizeFrames( - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sources, - const std::vector<::aidl::android::media::audio::common::AudioPortConfig*>& sinks); - std::unique_ptr getPalStreamAttributes( - const ::aidl::android::media::audio::common::AudioPortConfig& portConfig, - const bool isInput -#ifdef SEC_AUDIO_SUPPORT_UHQ - , std::optional> uhqConfig = std::nullopt -#endif - ) const; - std::vector convertToPalDevices( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) - const noexcept; - - /* - * @breif provides pal devices for given mixport and audiodevices. - * - * @param mixPortConfig mixportconfig for which devices are requested - * @param tag usecase tag - * @param setDevices vector of devices for which pal devices are requested - * @param dummyDevice setDevices can be empty, in that case if client needs - * dummy device in form of PAL_DEVICE_[IN/OUT]_DUMMY - */ - - std::vector configureAndFetchPalDevices( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - const Usecase& tag, - const std::vector<::aidl::android::media::audio::common::AudioDevice>& setDevices, - const bool dummyDevice = false) const; - - std::vector getDummyPalDevices( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) const; - -#ifdef SEC_AUDIO_COMMON - std::vector configureSecPalDevicesForTelephony( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& setDevices) noexcept; - std::vector configureSecPalDevicesForPlayback( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - const Usecase& tag, - const std::vector<::aidl::android::media::audio::common::AudioDevice>& setDevices) noexcept; - std::vector configureSecPalDevicesForCapture( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - const Usecase& tag, - const std::vector<::aidl::android::media::audio::common::AudioDevice>& setDevices) const noexcept; -#endif - /* - * @breif In order to get stream position in the DSP pipeline - * - * @param, - * Input Parameters: - * palHandle, a valid stream pal handle - * sampleRate, a valid stream sample rate - * - * Output Parameters: - * dspFrames, num of frames delivered by DSP - */ - void getPositionInFrames(pal_stream_handle_t* palHandle, int32_t const& sampleRate, - int64_t* const dspFrames) const; - - /* - * @brief requiresBufferReformat is used to check if format converter is needed for - * a PCM format or not, it is not applicable for compressed formats. - * It is possible that framework can use a format which might not - * be supported at below layers, so HAL needs to convert the buffer in desired format - * before writing. - * - * @param portConfig : mixport config of the stream. - * return return a pair of input and output audio_format_t in case a format converter - * is needed, otherwise nullopt. - * For example, mix port using audio format FLOAT is not supported, closest to FLOAT, - * INT_32 can be used as target format. so, return a pair of - * - * Caller can utilize this to create a converter based of provided input, output formats. - */ - static std::optional> requiresBufferReformat( - const ::aidl::android::media::audio::common::AudioPortConfig& portConfig); - - /* - * @brief creates a pal payload for a pal volume and sets to PAL - * @param handle : valid pal stream handle - * @param volumes vector of volumes in floats - * return 0 in success, error code otherwise - */ - int setVolume(pal_stream_handle_t* handle, const std::vector& volumes) const; -#ifdef SEC_AUDIO_COMMON - std::vector getPalVolume(const std::vector& volumes); -#endif - - std::unique_ptr getPalBufferConfig(const size_t bufferSize, - const size_t bufferCount) const; - std::vector<::aidl::android::media::audio::common::AudioProfile> getDynamicProfiles( - const ::aidl::android::media::audio::common::AudioPort& dynamicDeviceAudioPort) const; - int handleDeviceConnectionChange( - const ::aidl::android::media::audio::common::AudioPort& deviceAudioPort, - const bool isConnect) const; - uint32_t getBluetoothLatencyMs( - const std::vector<::aidl::android::media::audio::common::AudioDevice>& - bluetoothDevices); - std::unique_ptr getDefaultTelephonyAttributes() const; - std::unique_ptr getDefaultCRSTelephonyAttributes() const; - void configurePalDevicesCustomKey(std::vector& palDevices, - const std::string& customKey) const; - - bool setStreamMicMute(pal_stream_handle_t* streamHandlePtr, const bool muted); - bool getMicMuteStatus(); - void setMicMuteStatus(bool mute); - bool updateScreenState(const bool isTurnedOn) noexcept; - bool isScreenTurnedOn() const noexcept; -#ifdef SEC_AUDIO_SPK_AMP_MUTE - bool getSpeakerMuteStatus() const noexcept; - void setSpeakerMute(const bool mute) noexcept; -#endif - - bool isHDREnabled() const { return mHDREnabled; } - void setHDREnabled(bool const& enable) { mHDREnabled = enable; } - - int32_t getHDRSampleRate() const { return mHDRSampleRate; } - - void setHDRSampleRate(int32_t const& sampleRate) { mHDRSampleRate = sampleRate; } - - int32_t getHDRChannelCount() const { return mHDRChannelCount; } - - void setHDRChannelCount(int32_t const& channelCount) { mHDRChannelCount = channelCount; } - - bool isWNREnabled() const { return mWNREnabled; } - void setWNREnabled(bool const& enable) { mWNREnabled = enable; } - - bool isANREnabled() const { return mANREnabled; } - void setANREnabled(bool const& enable) { mANREnabled = enable; } - - bool isInverted() const { return mInverted; } - void setInverted(bool const& enable) { mInverted = enable; } - - std::string getOrientation() const { return mOrientation; } - - void setOrientation(std::string const& value) { mOrientation = value; } - - std::string getFacing() const { return mFacing; } - - void setFacing(std::string const& value) { mFacing = value; } - - void setTelephony(const std::weak_ptr<::aidl::android::hardware::audio::core::ITelephony> telephony) noexcept { - mTelephony = telephony; - } - - std::weak_ptr<::aidl::android::hardware::audio::core::ITelephony> getTelephony() const noexcept { - return mTelephony; - } - - /* - * @brief creates a pal payload for a speed factor and sets to PAL - * @param handle : pal stream handle - * @param tag usecase tag - * @param playbackRate playback rate to be set - * return PlaybackRateStatus::SUCCESS on success, or if stream handle is not set. - * return PlaybackRateStatus::UNSUPPORTED operation, usecase does not support speed operations - * or speed parameters are not in the range - * return PlaybackRateStatus::ILLEGAL_ARGUMENT in case of any other failure - */ - PlaybackRateStatus setPlaybackRate( - pal_stream_handle_t* handle, const Usecase& tag, - const ::aidl::android::media::audio::common::AudioPlaybackRate& playbackRate); - - void setInCallMusicState(const bool state) noexcept { mInCallMusicEnabled = state; } - bool getInCallMusicState() noexcept { return mInCallMusicEnabled; } - - // Set and Get Value Functions for Translate Record. - void setTranslationRecordState(const bool state) noexcept { mIsTranslationRecordEnabled = state; } - bool getTranslationRecordState() noexcept { return mIsTranslationRecordEnabled; } - - // Set and Get Value Functions for Voice Call Volume mute during Translation Record Usecase. - void setTranslationRxMuteState(const bool state) noexcept { mIsTranslationRxMuteEnabled = state; } - bool getTranslationRxMuteState() noexcept { return mIsTranslationRxMuteEnabled; } - - void setHACEnabled(const bool& enable) noexcept { mIsHACEnabled = enable; } - - bool isHACEnabled() const noexcept { return mIsHACEnabled; } - - void updateCallState(int callState) { mCallState = callState; } - void updateCallMode(int callMode) { mCallMode = callMode; } - - int getCallState() { return mCallState; } - int getCallMode() { return mCallMode; } - -#ifdef SEC_AUDIO_CALL - void setTelephonyDevices(const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) { - mTelephonyDevices = devices; - } - std::vector<::aidl::android::media::audio::common::AudioDevice> getTelephonyDevices() - const { return mTelephonyDevices; } - void setVoiceVolume(const float volume) { mVoiceVolume = volume; } - float getVoiceVolume() { return mVoiceVolume; } - void updateVoWiFiState(bool isVoWiFi) { mIsVoWiFi = isVoWiFi; } - bool getVoWiFiState() { return mIsVoWiFi; } -#ifdef SEC_AUDIO_CALL_SATELLITE - void setSatelliteCall(bool enable) { mSatelliteCall = enable; } - bool getSatelliteCall() { return mSatelliteCall; } -#endif - void setNbQuality(bool enable) { mNbQuality = enable; } - bool getNbQuality() { return mNbQuality; } - void setRingbacktone(bool enable) { mRingbacktone = enable; } - bool getRingbacktone() { return mRingbacktone; } - void setVoiceMuteState(int dir, bool mute) { mVoiceMuteState[dir] = mute; } - bool getVoiceMuteState(int dir) { return mVoiceMuteState[dir]; } -#ifdef SEC_AUDIO_WB_AMR - void updateSecCallBand(int callBand) { mCallBand = callBand; } - int getSecCallBand() { return mCallBand; } -#endif -#ifdef SEC_AUDIO_CALL_FORWARDING - bool isCallForwarding(); - void setCallForwarding(bool enable) { mCallForwarding = enable; } - bool getCallForwarding() { return mCallForwarding; }; - void setCallMemo(int mode) { mCallMemo = mode; } - int getCallMemo() { return mCallMemo; }; -#endif - void setDexConnected(bool connected) { mDexConnected = connected; } - bool getDexConnected() { return mDexConnected; }; - void setDexPadConnected(bool connected) { mDexPadConnected = connected; } - bool getDexPadConnected() { return mDexPadConnected; }; - void setDeviceInfo(int deviceType) { mDeviceInfo = deviceType; } - int getDeviceInfo() { return mDeviceInfo;} - int GetDeviceType(pal_device_id_t rx_device_id); -#endif -#ifdef SEC_AUDIO_ALL_SOUND_MUTE - void setAllSoundMute(bool mute) { mAllSoundMute = mute; } - bool getAllSoundMute() { return mAllSoundMute; } -#endif -#ifdef SEC_AUDIO_CALL_HAC - void setHacIncall(bool mode) { mHacIncall = mode; } - bool getHacIncall() { return mHacIncall; } - void setHacMode(int mode) { mHacMode = mode; } - int getHacMode() { return mHacMode; } - - int GetHacCustomKeyId(); - int GetVoWifiHacCustomKeyId(); -#endif -#ifdef SEC_AUDIO_BLUETOOTH - void setBtNrecState(bool isOn) { bt_nrec = isOn; } - bool isBtNrecOn() { return bt_nrec; } - void setBtScoState(bool isOn) { bt_sco_on = isOn; } - bool isBtScoOn() { return bt_sco_on; } -#endif -#ifdef SEC_AUDIO_SUPPORT_BT_RVC - void setBtRvcSupportState(bool isOn) { bt_rvc_support = isOn; } - bool isBtRvcSupportState() { return bt_rvc_support; } -#endif -#ifdef SEC_AUDIO_BT_OFFLOAD - void setBtA2dpFormat(audio_format_t format) { bt_a2dp_format = format; } - audio_format_t getBtA2dpFormat() { return bt_a2dp_format; } -#endif -#ifdef SEC_AUDIO_SCREEN_MIRRORING // { SUPPORT_VOIP_VIA_SMART_VIEW - void setVoipViaSmartView(bool enable) { mVoipViaSmartView = enable; } - bool getVoipViaSmartView() { return mVoipViaSmartView; } -#endif // } SUPPORT_VOIP_VIA_SMART_VIEW -#ifdef SEC_AUDIO_ENFORCED_AUDIBLE - void updateEnforcePlaybackState(int mode) { mEnforcePlaybackState = mode; } - int getEnforcePlaybackState() { return mEnforcePlaybackState; } -#endif -#ifdef SEC_AUDIO_DUAL_SPEAKER - void setSpeakerLeftAmpOff(bool isOff) { mSpeakerLeftAmpOff = isOff; } - bool isSpeakerLeftAmpOff() { return mSpeakerLeftAmpOff; } -#endif -#ifdef SEC_AUDIO_CALL_TRANSLATION - void setCallTranslation(bool mode) { mCallTranslation = mode; } - bool getCallTranslation() { return mCallTranslation; } - void setVoiceTxControl(int mode) { mVoiceTxControl = mode; } - int getVoiceTxControl() { return mVoiceTxControl; } - void setVoiceRxControl(int mode) { mVoiceRxControl = mode; } - int getVoiceRxControl() { return mVoiceRxControl; } -#endif -#ifdef SEC_AUDIO_CALL_VOIP - void setCngEnable(bool enable) { mCngEnable = enable; } - bool getCngEnable() { return mCngEnable; } - void setVoipIsolationMode(int mode) { mVoipIsolationMode = mode; } - uint32_t getVoipIsolationMode() { return mVoipIsolationMode; } - void setCallIsolationMode(int mode) { mCallIsolationMode = mode; } - uint32_t getCallIsolationMode() { return mCallIsolationMode; } -#endif -#if defined(SEC_AUDIO_DUAL_SPEAKER) || defined(SEC_AUDIO_MULTI_SPEAKER) - void updateRotationInfo(int mode) { mRotationInfo = mode; } - int getRotationInfo() { return mRotationInfo; } - void updateFlatmotionInfo(int mode) { mFlatmotionInfo = mode; } - int getFlatmotionInfo() { return mFlatmotionInfo; } -#endif -#ifdef SEC_AUDIO_VOICE_TX_FOR_INCALL_MUSIC - void setScreenCall(bool mode) { mScreenCall = mode; } - bool getScreenCall() { return mScreenCall; } -#endif -#ifdef SEC_AUDIO_FMRADIO - void setFMRadioOn(bool on) { mFM.on = on; } - bool getFMRadioOn() { return mFM.on; } - void setFMRadioDevice(audio_devices_t device) { mFM.device = device; } - audio_devices_t getFMRadioDevice() { return mFM.device; } - void setFMRadioVolume(float volume) { mFM.volume = volume; } - float getFMRadioVolume() { return mFM.volume; } - void setFMRadioMute(bool mute) { mFM.mute = mute; } - bool getFMRadioMute() { return mFM.mute; } -#endif -#if defined(SEC_AUDIO_SUPPORT_FLIP_CALL) || defined(SEC_AUDIO_SUPPORT_SOUNDBOOSTER_FOLD_PARAM_ON_DSP) - void setFolderclosed(bool closed){ mFolderclosed = closed; }; - bool getFolderclosed(){ return mFolderclosed; }; - void setFlexmode(bool mode){ mFlexmode = mode; }; - bool getFlexmode(){ return mFlexmode; }; -#endif -#ifdef SEC_AUDIO_SUPPORT_GAMECHAT_SPK_AEC - void setGamechatMode(bool mode) { mGamechatMode = mode; } - bool getGamechatMode() { return mGamechatMode; }; -#endif -#ifdef SEC_AUDIO_SUPPORT_REMOTE_MIC - void setAasEnabled(const bool enable) { mAasEnabled = enable; } - bool isAasEnabled() { return mAasEnabled; } - void setAasVolume(const float volume) { mAasVolume = volume; } - float getAasVolume() { return mAasVolume; } -#endif -#ifdef SEC_AUDIO_SUPPORT_AFE_LISTENBACK - void setUsbInputEnabled(bool mode) { usb_input_dev_enabled = mode; } - bool isUsbInputEnabled() { return usb_input_dev_enabled; }; - void setListenbackDevice(pal_device_id_t device) { listenback_device = device; } - pal_device_id_t getListenbackDevice() { return listenback_device; }; - void setListenBackEnabled(bool mode) { listenback_on = mode; } - bool isListenBackEnabled() { return listenback_on; }; -#endif -#ifdef SEC_AUDIO_CAMCORDER - void setTxDataInversion(bool on) { tx_data_inversion = on; } - bool isTxDataInversionEnabled() { return tx_data_inversion; } -#endif -#ifdef SEC_AUDIO_SUPPORT_NSRI - void setNSRISecureEnabled(bool on) { is_NSRI_secure = on; } - bool isNSRISecureEnabled() { return is_NSRI_secure; } -#endif -#ifdef SEC_AUDIO_SOUND_TRIGGER_TYPE - void setRegisterVoiceKeyword(int value) { register_voice_keyword = value; } - void setSeamlessEnabled(bool on) { seamless_enabled = on; } - bool isSeamlessEnabled() { return seamless_enabled; } -#endif -#ifdef SEC_AUDIO_INTERPRETER_MODE - void setInterpreterMode(int mode) { interpreter_mode = mode; } - int getInterpreterMode() { return interpreter_mode; } -#endif -#ifdef SEC_AUDIO_USB_GAIN_CONTROL - void setUSBGainForCombo(bool on) { mUSBGainForCombo = on; } - bool getUSBGainForCombo() { return mUSBGainForCombo; } -#endif - bool isA2dpSuspended(); - - void setWFDProxyChannels(const uint32_t numProxyChannels) noexcept; - void setProxyRecordFMQSize(const size_t& FMQSize) noexcept; - size_t getProxyRecordFMQSize() const noexcept; - uint32_t getWFDProxyChannels() const noexcept; - /* Check if proxy record session is active in PAL_DEVICE_IN_RECORD_PROXY */ - std::string IsProxyRecordActive() const noexcept; - bool isIPAsProxyDeviceConnected() const noexcept { return mIsIPAsProxyConnected; }; - void setIPAsProxyDeviceConnected(bool isIPAsProxy) noexcept { mIsIPAsProxyConnected = isIPAsProxy; }; - - void setHapticsVolume(const float hapticsVolume) const noexcept; - void setHapticsIntensity(const int hapticsIntensity) const noexcept; -#ifdef SEC_AUDIO_SUPPORT_HAPTIC_PLAYBACK - void setHapticsSource(const int hapticsSource) const noexcept; -#endif - - void updateUHQA(const bool enable) noexcept; -#ifdef SEC_AUDIO_SUPPORT_UHQ - void updateUHQA(const pal_uhqa_state sample) noexcept; -#endif - bool isUHQAEnabled() const noexcept; -#ifdef SEC_AUDIO_SPEAKER_CALIBRATION - void triggerSpeakerCalibration() const noexcept; -#endif - void setFTMSpeakerProtectionMode(uint32_t const heatUpTime, uint32_t const runTime, - bool const isFactoryTest, bool const isValidationMode, - bool const isDynamicCalibration) const noexcept; - std::optional getFTMResult() const noexcept; - std::optional getSpeakerCalibrationResult() const noexcept; -#ifdef ENABLE_TAS_SPK_PROT - std::optional getSpeakerProtectionResult() const noexcept; -#endif - - void updateScreenRotation(const ::aidl::android::hardware::audio::core::IModule::ScreenRotation - in_rotation) noexcept; - ::aidl::android::hardware::audio::core::IModule::ScreenRotation getCurrentScreenRotation() const - noexcept; - - bool platformSupportsOffloadSpeed() { return mOffloadSpeedSupported; } - bool usecaseSupportsOffloadSpeed(const Usecase& tag) { - return platformSupportsOffloadSpeed() && isOffload(tag); - } - - bool isOffload(const Usecase& tag) { return tag == Usecase::COMPRESS_OFFLOAD_PLAYBACK; } - int setLatencyMode(uint32_t mode); - int getRecommendedLatencyModes( - std::vector<::aidl::android::media::audio::common::AudioLatencyMode>* _aidl_return); - - void configurePalDevices( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - std::vector& palDevices); - void setHdrOnPalDevice(pal_device* palDeviceIn); - bool isHDRARMenabled(); - bool isHDRSPFEnabled(); - bool getUSBCapEnable() { return mUSBCapEnable; } - -#ifdef SEC_AUDIO_SAMSUNGRECORD - bool GetRecMultiMic(const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, const std::vector<::aidl::android::media::audio::common::AudioDevice>& connectedDevices, Usecase tag) const noexcept; - int match_device_enums(const ::aidl::android::media::audio::common::AudioDevice& device) const noexcept; - int get_device_types(const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) const noexcept; - bool IsSupportPreprocess(const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, Usecase tag) const noexcept; - uint32_t GetBufferSize(const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig); - int GetRecFormat(const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, const std::vector<::aidl::android::media::audio::common::AudioDevice>& connectedDevices, Usecase tag); - uint32_t SelectPreProcessSolutions(const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig) const noexcept; - bool isLoopBackOff() { return mIsLoopBackOff; } - bool isRmsTestMode() { return mIsRmsTestMode; } - void setLoopBackOff(bool enable) { mIsLoopBackOff = enable; } - void setRmsTestMode(bool enable) { mIsRmsTestMode = enable; } - void setUnconfiguredFlagsReceived(int32_t flags) { mUnconfiguredFlagsReceived = flags; } - int32_t getUnconfiguredFlagsReceived() { return mUnconfiguredFlagsReceived; } -#endif -#ifdef SEC_AUDIO_KARAOKE - void setKaraokeEnabled(bool on) { is_karaoke_on = on; } - bool isKaraokeEnabled() { return is_karaoke_on; } - static bool isKaraokeUsecases(const Usecase& tag); -#endif -#ifdef SEC_AUDIO_COMMON - bool isSecAudioFeatureSupported() { return mIsSecAudioFeatureSupported; } - void setSecAudioFeatureSupported(bool supported) { mIsSecAudioFeatureSupported = supported; } -#endif -#if defined(SEC_AUDIO_OFFLOAD_COMPRESSED_OPUS) && defined(SEC_AUDIO_OFFLOAD_SOUNDSPEED) - PlaybackRateStatus setSecPlaybackRate(pal_stream_handle_t* handle, const Usecase& tag, - const ::aidl::android::media::audio::common::AudioPlaybackRate& playbackRate, - const std::optional< ::aidl::android::media::audio::common::AudioOffloadInfo>& offloadInfo, - std::function sendSpeed); - bool isSecSupportsOffloadSpeed(const std::optional< ::aidl::android::media::audio::common::AudioOffloadInfo>& offloadInfo); -#endif - private: - void customizePalDevices( - const ::aidl::android::media::audio::common::AudioPortConfig& mixPortConfig, - const Usecase& tag, std::vector& palDevices) const noexcept; - void configurePalDevicesForHIFIPCMFilter(std::vector&) const noexcept; - std::vector<::aidl::android::media::audio::common::AudioProfile> getUsbProfiles( - const ::aidl::android::media::audio::common::AudioPort& port) const; - - std::optional getHdmiParameters( - const ::aidl::android::media::audio::common::AudioDevice&) const; - - void initUsecaseOpMap(); - - public: - constexpr static uint32_t kDefaultOutputSampleRate = 48000; - constexpr static uint32_t kDefaultPCMBidWidth = 16; - constexpr static pal_audio_fmt_t kDefaultPalPCMFormat = PAL_AUDIO_FMT_PCM_S16_LE; - constexpr static int32_t kDefaultLatencyMs = 51; - - private: - std::vector<::aidl::android::media::audio::common::AudioDevice> mPrimaryPlaybackDevices{}; - - std::map mParameters; - card_status_t mSndCardStatus{CARD_STATUS_OFFLINE}; - bool mInCallMusicEnabled{false}; - bool mIsTranslationRecordEnabled{false}; - bool mIsTranslationRxMuteEnabled{false}; - bool mIsScreenTurnedOn{false}; - uint32_t mWFDProxyChannels{0}; - bool mIsUHQAEnabled{false}; - bool mIsIPAsProxyConnected{false}; - ::aidl::android::hardware::audio::core::IModule::ScreenRotation mCurrentScreenRotation{ - ::aidl::android::hardware::audio::core::IModule::ScreenRotation::DEG_0}; - bool mOffloadSpeedSupported = false; - bool mMicMuted = false; -#ifdef SEC_AUDIO_SPK_AMP_MUTE - bool mSpeakerMuted = false; -#endif -#ifdef SEC_AUDIO_COMMON - bool mIsSecAudioFeatureSupported{false}; -#endif - /* HDR */ - bool mHDREnabled{false}; - int32_t mHDRSampleRate{0}; - int32_t mHDRChannelCount{0}; - bool mWNREnabled{false}; - bool mANREnabled{false}; - bool mInverted{false}; - std::string mOrientation{""}; - std::string mFacing{""}; - - /* HAC enablement*/ - bool mIsHACEnabled{false}; - - std::unordered_map mUsecaseOpMap; - std::vector<::aidl::android::media::audio::common::MicrophoneInfo> mMicrophoneInfo; - using PalDevToMicDynamicInfoMap = std::unordered_map< - pal_device_id_t, - std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo>>; - PalDevToMicDynamicInfoMap mMicrophoneDynamicInfoMap; - // proxy related info - size_t mProxyRecordFMQSize{0}; - std::weak_ptr<::aidl::android::hardware::audio::core::ITelephony> mTelephony; -#ifdef SEC_AUDIO_SAMSUNGRECORD - bool mIsLoopBackOff{true}; - bool mIsRmsTestMode{false}; -#endif -}; -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/PlatformStreamCallback.h b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/PlatformStreamCallback.h deleted file mode 100755 index 5ddf8b39..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/PlatformStreamCallback.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -namespace qti::audio::core { - -struct PlatformStreamCallback { - virtual ~PlatformStreamCallback() = default; - virtual void onTransferReady() = 0; - virtual void onDrainReady() = 0; - virtual void onError() = 0; -}; - -} // namespace qti::audio::core \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/PlatformUtils.h b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/PlatformUtils.h deleted file mode 100755 index 1ad48a9b..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/PlatformUtils.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include - -namespace qti::audio::core { - -using ::aidl::android::media::audio::common::AudioProfile; -using ::aidl::android::media::audio::common::AudioChannelLayout; - -constexpr size_t getNearestMultiple(size_t num, size_t multiplier) { - size_t remainder = 0; - - if (!multiplier) return num; - - remainder = num % multiplier; - if (remainder) num += (multiplier - remainder); - - return num; -} - -// std::string getStringForVendorParameter( -auto getkvPairsForVendorParameter = - [](const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& param) - -> std::string { - std::string str = ""; - std::optional<::aidl::qti::audio::core::VString> parcel; - for (const auto& p : param) { - if (p.ext.getParcelable(&parcel) == STATUS_OK && parcel.has_value()) { - std::string keyvalue = p.id + "=" + parcel.value().value + ";"; - str.append(keyvalue); - } - } - return str; - }; - -auto getBoolValueFromVString = []( - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& parameters, - const std::string& searchKey) -> std::optional { - std::optional<::aidl::qti::audio::core::VString> parcel; - for (const auto& p : parameters) { - if (p.id == searchKey && p.ext.getParcelable(&parcel) == STATUS_OK && parcel.has_value()) { - return parcel.value().value == "true"; - } - } - return std::nullopt; -}; - -std::vector getSupportedAudioProfiles(pal_param_device_capability_t* capability, - std::string devName); -std::vector getChannelMasksFromProfile( - pal_param_device_capability_t* capability); -std::vector getSampleRatesFromProfile(pal_param_device_capability_t* capability); -AudioChannelLayout getChannelIndexMaskFromChannelCount(unsigned int channelCount); -AudioChannelLayout getChannelLayoutMaskFromChannelCount(unsigned int channelCount, int isInput); - -void setPalDeviceCustomKey(pal_device& palDevice, const std::string& customKey) noexcept; - -std::vector makePalVolumes(std::vector const& volumes) noexcept; - -/* -* validates if the playback rate parameters are valid -*/ -bool isValidPlaybackRate( - const ::aidl::android::media::audio::common::AudioPlaybackRate& playbackRate); - -/** - * @brief Expects a std::unique_ptr - * checks if unique_ptr is allocated or not - * If memory is allocated then return unique_ptr - * otherwise exit with retValue which caller needs to pass -*/ -#define VALUE_OR_EXIT(ptr, retValue) \ - ({ \ - auto temp = (ptr); \ - if (temp.get() == nullptr) { \ - LOG(ERROR) << __func__ << " could not allocate memory "; \ - return retValue; \ - } \ - std::move(temp); \ - }) - -/** -* @brief allocator with custom deleter -* Takes a type T and size -* return the unique_ptr for type allocated with calloc -* When goes out of scope will be deallocated with free -* client needs to check if returned ptr is null or not. -* Usage: -* with calloc and free: -* struct pal_param_payload *param_payload = (struct pal_param_payload*)calloc(1, -* sizeof(struct pal_param_payload)); -* if (param_payload == NULL) { -* ALOGE("%s: Cannot allocate memory for param_payload\n", __func__); -* return -ENOMEM; -* } -* .... -* free(param_payload); -* Now: -* auto param_payload = VALUE_OR_EXIT(allocate(sizeof(pal_param_payload))); -* allocate will allocate unique_ptr as per type pal_param_payload -* VALUE_OR_EXIT will return the unique_ptr if allocation is succesfull -* otherwise it will exit. -* custom deletor will take to deallocate memory using free when scope is cleared. -* @param size size to be allocated for type T -* @return unique_ptr of type T with size requested. -*/ - -using CustomDeletor = void (*)(void*); -template -std::unique_ptr allocate(int size) { - T* obj = reinterpret_cast(calloc(1, size)); - return std::unique_ptr{obj, free}; -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/SecPlatformDefs.h b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/SecPlatformDefs.h deleted file mode 100755 index 7148c3b9..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/include/qti-audio-core/SecPlatformDefs.h +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2023 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 - -// pal device direction for voice -enum { - PAL_RX = 0, - PAL_TX, - PAL_TX_RX, -}; - -typedef enum { - VOICE_DEVICE_INVALID = -1, - VOICE_DEVICE_ETC = 0, - VOICE_DEVICE_SPEAKER, - VOICE_DEVICE_EARPHONE, - VOICE_DEVICE_BLUETOOTH, - VOICE_DEVICE_RECEIVER, - VOICE_DEVICE_MAX -} voice_device_type; - -#ifdef SEC_AUDIO_CALL_HAC -enum { - HAC_MODE_MIC = 0, - HAC_MODE_TCOIL, - HAC_MODE_MAX -}; -#endif - -#ifdef SEC_AUDIO_CALL_TRANSLATION -enum { - TRANSLATION_MODE_OFF = 0, - TRANSLATION_MODE_HANDSET, - TRANSLATION_MODE_SPEAKER, - TRANSLATION_MODE_EARPHONE, - TRANSLATION_MODE_BLUETOOTH, -}; -#endif - -enum { - EFFECTS_MICMODE_STANDARD = 0, /* default */ - EFFECTS_MICMODE_VOICE_FOCUS = 1, - EFFECTS_MICMODE_ALL_SOUND = 2, - EFFECTS_TRANSLATION = 3, - EFFECTS_MICMODE_DEFAULT = 100, -}; - -enum { - CALLMEMO_ON = 0x00000001, /* need to enable music device */ - CALLMEMO_OFF = 0x00000002, - CALLMEMO_REC = 0x00000010, /* need to disable music mixer path, and keep music device */ - CALLMEMO_INIT = 0x10000000, -}; - -#ifdef SEC_AUDIO_CALL_VOIP -// refer to vendor/qcom/proprietary/mm-audio/ar-acdb/acdbdata/inc/kvh2xml.h -const std::map getVoipMicMode { - {EFFECTS_MICMODE_STANDARD, 1 /* STANDARD_MODE */}, - {EFFECTS_MICMODE_VOICE_FOCUS, 2 /* VOICE_FOCUS_MODE */}, - {EFFECTS_MICMODE_ALL_SOUND, 3 /* ALL_SOUND_MODE */}, - {EFFECTS_TRANSLATION, 4 /* TRANSLATION_MODE */}, -}; - -const std::map getVoipSampleRate { - {8000, 0 /* VOIP_SR_NB */}, - {16000, 1 /* VOIP_SR_WB */}, - {32000, 2 /* VOIP_SR_SWB */}, - {48000, 3 /* VOIP_SR_FB */}, -}; -#endif - - -#ifdef SEC_AUDIO_ENFORCED_AUDIBLE -enum { - NOT_MUTE = 0, - MUTE_CALL, - MUTE_CALL_AND_REC // For Camcording -}; -#endif - -#if defined(SEC_AUDIO_DUAL_SPEAKER) || defined(SEC_AUDIO_MULTI_SPEAKER) -// (TODO) check : need to move AudioEffect? -enum { - TOP_UP = 0, - RIGHT_UP, - BUTTOM_UP, - LEFT_UP -}; - -enum { - FLATMOTION_NOT_FLAT = 0, - FLATMOTION_FLAT -}; -#endif - -#ifdef SEC_AUDIO_ADAPT_SOUND -#define MAX_DHA_DATA_SIZE 40 -enum { - DHA_RESET = 0, /* for CP call stop case, reset mixer as dha off */ - DHA_SET, /* for CP call start case, set dha mixer */ - DHA_UPDATE /* update dha param, and only call/wfc/vt case set dha mixer */ -}; -#endif - -#ifdef SEC_AUDIO_FMRADIO -// defined in FM.cpp -const static std::string kHandleFM{"handle_fm"}; -const static std::string kFMVolume{"fm_volume"}; -const static std::string kFMMute{"fm_mute"}; -const static std::string kFMRouting{"fm_routing"}; - -struct fmradio_config_t { - bool on; - audio_devices_t device; - float volume; - bool mute; -}; -#endif - -#ifdef SEC_AUDIO_SUPPORT_FLIP_CALL -enum { - FOLDER_CLOSE = 0, - FOLDER_OPEN = 1, - FOLDER_FLEX_ON, // fold open/close - FOLDER_FLEX_OFF // fold open -}; -#endif diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/Android.bp b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/Android.bp deleted file mode 100755 index cd0c5ae2..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/Android.bp +++ /dev/null @@ -1,31 +0,0 @@ -cc_library_static { - name: "libaudio_microphoneinfo_parser", - vendor: true, - export_include_dirs: ["include"], - srcs: [ - "MicrophoneInfoParser.cpp", - ], - shared_libs: [ - "libbase", - "libcutils", - "liblog", - "libutils", - "libxml2", - "android.media.audio.common.types-V3-ndk", - ], - header_libs: [ - "libxsdc-utils", - "libaudio_system_headers", - "libarpal_headers", - ], - generated_headers: ["libaudio_microphone_info"], - generated_sources: ["libaudio_microphone_info"], - export_generated_headers: ["libaudio_microphone_info"], - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - "-Wthread-safety", - ], -} - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/MicrophoneInfoParser.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/MicrophoneInfoParser.cpp deleted file mode 100755 index 740e821a..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/MicrophoneInfoParser.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_NDEBUG 0 -#define LOG_TAG "AHAL_MicrophoneInfoParser_QTI" - -#include -#include -#include -#include -#include -#include -#include - -using ::aidl::android::media::audio::common::AudioDevice; -using ::aidl::android::media::audio::common::AudioDeviceAddress; -using ::aidl::android::media::audio::common::AudioDeviceDescription; -using ::aidl::android::media::audio::common::AudioDeviceType; -using aidl::android::media::audio::common::MicrophoneDynamicInfo; -using aidl::android::media::audio::common::MicrophoneInfo; - -namespace xsd = ::qti::audio::microphone_info; -using MicrophoneInfoType = xsd::MicrophoneInfoType; -using FrequencyResponseType = xsd::FrequencyResponseType; -using MicrophoneInfoAndDynamicInfo = qti::audio::microphone_info::MicrophoneInfoAndDynamicInfo; - -namespace qti::audio::core { -std::vector<::aidl::android::media::audio::common::MicrophoneInfo::FrequencyResponsePoint> - MicrophoneInfoParser::getFrequencyResponse(const FrequencyResponseType *freqResponse) { - std::vector freq; - std::vector response; - if (freqResponse->hasFrequencyHz()) { - freq = freqResponse->getFrequencyHz(); - } - if (freqResponse->hasLeveldB()) { - response = freqResponse->getLeveldB(); - } - - if (freq.size() != response.size()) { - LOG(ERROR) << __func__ << " frequency / respone size mismatch " << freq.size() << " " - << response.size(); - return {}; - } - - std::vector<::aidl::android::media::audio::common::MicrophoneInfo::FrequencyResponsePoint> frps; - for (unsigned long i = 0; i < freq.size(); i++) { - frps.push_back({.frequencyHz = freq[i], .leveldB = response[i]}); - } - return frps; -} - -static std::optional populateDevice(const MicrophoneInfoType &xmlInfo) { - if (!xmlInfo.hasDevice()) { - LOG(ERROR) << __func__ << " device attribute is missing for microphone"; - return std::nullopt; - } - auto xsdDevice = xmlInfo.getFirstDevice(); - if (!xsdDevice->hasName()) { - LOG(ERROR) << __func__ << " name attribute is missing for device"; - return std::nullopt; - } - - auto devName = xsdDevice->getName(); - if (XsdToAudioDeviceType.count(devName) == 0) { - LOG(ERROR) << __func__ << " unknown device " << toString(devName); - return std::nullopt; - } - - AudioDeviceType fwkDevice = XsdToAudioDeviceType.at(devName); - auto address = - xsdDevice->hasAddress() - ? AudioDeviceAddress::make(xsdDevice->getAddress()) - : AudioDeviceAddress{}; - - std::string connection = xsdDevice->hasConnection() ? xsdDevice->getConnection() : ""; - AudioDevice device = {.type = {.type = fwkDevice, .connection = connection}, - .address = address}; - return device; -} - -void MicrophoneInfoParser::populateMicrophoneInfo(const MicrophoneInfoAndDynamicInfo &mXsdcConfig) { - for (const auto &xmlInfo : mXsdcConfig.getFirstMicrophoneInfoList()->getMicrophoneInfo()) { - ::aidl::android::media::audio::common::MicrophoneInfo info; - if (!xmlInfo.hasId()) { - LOG(ERROR) << __func__ << " invalid id attribute"; - return; - } - - info.id = xmlInfo.getId(); - - auto dev = populateDevice(xmlInfo); - if (!dev.has_value()) { - LOG(ERROR) << __func__ << " invalid device attribute"; - return; - } - - info.device = dev.value(); - - if (xmlInfo.hasLocation()) info.location = XsdToLocationType.at(xmlInfo.getLocation()); - - if (xmlInfo.hasGroup()) info.group = xmlInfo.getGroup(); - - if (xmlInfo.hasIndexInTheGroup()) info.indexInTheGroup = xmlInfo.getIndexInTheGroup(); - - if (xmlInfo.hasSensitivity()) { - auto xsdSensitivity = xmlInfo.getFirstSensitivity(); - ::aidl::android::media::audio::common::MicrophoneInfo::Sensitivity ss; - ss.leveldBFS = xsdSensitivity->hasLeveldBFS() ? xsdSensitivity->getLeveldBFS() : 0.0f; - ss.maxSpldB = xsdSensitivity->hasMaxSpldB() ? xsdSensitivity->getMaxSpldB() : 0.0f; - ss.minSpldB = xsdSensitivity->hasMinSpldB() ? xsdSensitivity->getMinSpldB() : 0.0f; - info.sensitivity = ss; - } - - if (xmlInfo.hasDirectionality()) { - info.directionality = XsdToDirectionalityType.at(xmlInfo.getDirectionality()); - } - - if (xmlInfo.hasFrequencyResponse()) { - info.frequencyResponse = getFrequencyResponse(xmlInfo.getFirstFrequencyResponse()); - } else { - // should have some frequencies.. may be an error, drop - } - - auto getCordinates = [](auto &xsdCord) { - MicrophoneInfo::Coordinate coordinates; - if (xsdCord->hasX() && xsdCord->hasY() && xsdCord->hasZ()) { - coordinates.x = xsdCord->getX(); - coordinates.y = xsdCord->getY(); - coordinates.z = xsdCord->getZ(); - } - return coordinates; - }; - - if (xmlInfo.hasPosition(); auto coords = xmlInfo.getFirstPosition()) { - info.position = getCordinates(coords); - } - - if (xmlInfo.hasOrientation(); auto coords = xmlInfo.getFirstOrientation()) { - info.orientation = getCordinates(coords); - } - - mInfo.emplace_back(info); - } -} - -void MicrophoneInfoParser::populateMicrophoneDynamicInfo( - const MicrophoneInfoAndDynamicInfo &mXsdcConfig) { - auto infoList = mXsdcConfig.getFirstMicrophoneDynamicInfoList()->getMicrophoneDynamicInfo(); - - for (const auto &xmlInfo : infoList) { - if (!xmlInfo.hasDevice() || !xmlInfo.hasMicInfo()) { - LOG(ERROR) << " invalid device or micInfo attributes"; - return; - } - - if (XsdToPalDeviceType.count(xmlInfo.getDevice()) == 0) { - LOG(ERROR) << __func__ << " unknown device " << toString(xmlInfo.getDevice()); - return; - } - - pal_device_id_t palDevice = XsdToPalDeviceType.at(xmlInfo.getDevice()); - std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo> infos; - - for (const auto &micInfo : xmlInfo.getMicInfo()) { - ::aidl::android::media::audio::common::MicrophoneDynamicInfo info; - if (!micInfo.hasId()) { - LOG(ERROR) << " skip micinfo with invalid id"; - continue; - } - info.id = micInfo.getId(); - if (micInfo.hasChannelMapping()) { - for (const auto channel : micInfo.getChannelMapping()) { - info.channelMapping.push_back(XsdToChannelMap.at(channel)); - } - } - infos.push_back(info); - } - mDynamicInfoMap[palDevice] = infos; - } -} - -MicrophoneInfoParser::MicrophoneInfoParser(const std::string &fileName) { - auto configFile = android::audio_find_readable_configuration_file(fileName.c_str()); - if (configFile == "") { - LOG(WARNING) << __func__ << " file " << fileName << " not found"; - return; - } - auto xsdConfig = xsd::read(configFile.c_str()); - if (!xsdConfig.has_value()) { - LOG(WARNING) << __func__ << ": could not read the xml"; - return; - } - - auto mXsdcConfig = xsdConfig.value(); - if (!mXsdcConfig.hasMicrophoneInfoList() || !mXsdcConfig.hasMicrophoneDynamicInfoList()) { - LOG(ERROR) << " invalid micInfo or dynamic mic info "; - return; - } - - populateMicrophoneInfo(mXsdcConfig); - populateMicrophoneDynamicInfo(mXsdcConfig); -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/include/qti-audio-core/MicrophoneInfoParser.h b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/include/qti-audio-core/MicrophoneInfoParser.h deleted file mode 100755 index 5038d304..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/include/qti-audio-core/MicrophoneInfoParser.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include - -#include -#include - -// Forward declare microphone_info classes -namespace qti::audio::microphone_info { -class FrequencyResponseType; -class MicrophoneInfoAndDynamicInfo; -} - -using PalDevToMicDynamicInfoMap = std::unordered_map< - pal_device_id_t, std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo>>; - -namespace qti::audio::core { -static const std::string kDefaultConfigName{"microphone_characteristics.xml"}; - -class MicrophoneInfoParser { - public: - MicrophoneInfoParser(const std::string &fileName = kDefaultConfigName); - std::vector<::aidl::android::media::audio::common::MicrophoneInfo> getMicrophoneInfo() { - return mInfo; - } - PalDevToMicDynamicInfoMap getMicrophoneDynamicInfoMap() { return mDynamicInfoMap; } - - private: - std::vector<::aidl::android::media::audio::common::MicrophoneInfo> mInfo; - PalDevToMicDynamicInfoMap mDynamicInfoMap; - void populateMicrophoneInfo( - const qti::audio::microphone_info::MicrophoneInfoAndDynamicInfo &xsdcConfig); - void populateMicrophoneDynamicInfo( - const qti::audio::microphone_info::MicrophoneInfoAndDynamicInfo &xsdcConfig); - // qti::audio::microphone_info::MicrophoneInfoAndDynamicInfo mXsdcConfig; - - std::vector<::aidl::android::media::audio::common::MicrophoneInfo::FrequencyResponsePoint> - getFrequencyResponse( - const qti::audio::microphone_info::FrequencyResponseType *freqResponse); -}; - -} // namespace qti::audio::core \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/include/qti-audio-core/MicrophoneInfoTypes.h b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/include/qti-audio-core/MicrophoneInfoTypes.h deleted file mode 100755 index 7db3259c..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/include/qti-audio-core/MicrophoneInfoTypes.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#include - -#include - -using ::aidl::android::media::audio::common::AudioDeviceType; -using aidl::android::media::audio::common::MicrophoneDynamicInfo; -using aidl::android::media::audio::common::MicrophoneInfo; - -namespace xsd = ::qti::audio::microphone_info; -using FrequencyResponseType = xsd::FrequencyResponseType; -using MicrophoneInfoAndDynamicInfo = xsd::MicrophoneInfoAndDynamicInfo; - -namespace qti::audio::core { - -const static std::unordered_map XsdToAudioDeviceType = { - {xsd::AudioDeviceType::IN_AFE_PROXY, AudioDeviceType::IN_AFE_PROXY}, - {xsd::AudioDeviceType::IN_DEVICE, AudioDeviceType::IN_DEVICE}, - {xsd::AudioDeviceType::IN_ECHO_REFERENCE, AudioDeviceType::IN_ECHO_REFERENCE}, - {xsd::AudioDeviceType::IN_FM_TUNER, AudioDeviceType::IN_FM_TUNER}, - {xsd::AudioDeviceType::IN_HEADSET, AudioDeviceType::IN_HEADSET}, - {xsd::AudioDeviceType::IN_LOOPBACK, AudioDeviceType::IN_LOOPBACK}, - {xsd::AudioDeviceType::IN_MICROPHONE, AudioDeviceType::IN_MICROPHONE}, - {xsd::AudioDeviceType::IN_MICROPHONE_BACK, AudioDeviceType::IN_MICROPHONE_BACK}, - {xsd::AudioDeviceType::IN_SUBMIX, AudioDeviceType::IN_SUBMIX}, - {xsd::AudioDeviceType::IN_TELEPHONY_RX, AudioDeviceType::IN_TELEPHONY_RX}, - {xsd::AudioDeviceType::IN_TV_TUNER, AudioDeviceType::IN_TV_TUNER}, - {xsd::AudioDeviceType::IN_DOCK, AudioDeviceType::IN_DOCK}, -}; - -const static std::unordered_map - XsdToDirectionalityType = { - {xsd::DirectionalityType::OMNI, MicrophoneInfo::Directionality::OMNI}, - {xsd::DirectionalityType::BI_DIRECTIONAL, - MicrophoneInfo::Directionality::BI_DIRECTIONAL}, - {xsd::DirectionalityType::CARDIOID, MicrophoneInfo::Directionality::CARDIOID}, - {xsd::DirectionalityType::HYPER_CARDIOID, - MicrophoneInfo::Directionality::HYPER_CARDIOID}, - {xsd::DirectionalityType::SUPER_CARDIOID, - MicrophoneInfo::Directionality::SUPER_CARDIOID}, -}; - -const static std::unordered_map XsdToLocationType = { - {xsd::LocationType::UNKNOWN, MicrophoneInfo::Location::UNKNOWN}, - {xsd::LocationType::MAINBODY, MicrophoneInfo::Location::MAINBODY}, - {xsd::LocationType::MAINBODY_MOVABLE, MicrophoneInfo::Location::MAINBODY_MOVABLE}, - {xsd::LocationType::PERIPHERAL, MicrophoneInfo::Location::PERIPHERAL}, -}; - -const static std::unordered_map - XsdToChannelMap = { - {xsd::ChannelMappingType::UNUSED, MicrophoneDynamicInfo::ChannelMapping::UNUSED}, - {xsd::ChannelMappingType::DIRECT, MicrophoneDynamicInfo::ChannelMapping::DIRECT}, - {xsd::ChannelMappingType::PROCESSED, - MicrophoneDynamicInfo::ChannelMapping::PROCESSED}, -}; - -const static std::unordered_map XsdToPalDeviceType = { - {xsd::PalInDevicesType::PAL_DEVICE_IN_HANDSET_MIC, PAL_DEVICE_IN_HANDSET_MIC}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_SPEAKER_MIC, PAL_DEVICE_IN_SPEAKER_MIC}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET, - PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_WIRED_HEADSET, PAL_DEVICE_IN_WIRED_HEADSET}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_AUX_DIGITAL, PAL_DEVICE_IN_AUX_DIGITAL}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_HDMI, PAL_DEVICE_IN_HDMI}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_USB_ACCESSORY, PAL_DEVICE_IN_USB_ACCESSORY}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_USB_DEVICE, PAL_DEVICE_IN_USB_DEVICE}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_USB_HEADSET, PAL_DEVICE_IN_USB_HEADSET}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_FM_TUNER, PAL_DEVICE_IN_FM_TUNER}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_LINE, PAL_DEVICE_IN_LINE}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_SPDIF, PAL_DEVICE_IN_SPDIF}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_PROXY, PAL_DEVICE_IN_PROXY}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_HANDSET_VA_MIC, PAL_DEVICE_IN_HANDSET_VA_MIC}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_BLUETOOTH_A2DP, PAL_DEVICE_IN_BLUETOOTH_A2DP}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_HEADSET_VA_MIC, PAL_DEVICE_IN_HEADSET_VA_MIC}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_VI_FEEDBACK, PAL_DEVICE_IN_VI_FEEDBACK}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_TELEPHONY_RX, PAL_DEVICE_IN_TELEPHONY_RX}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_ULTRASOUND_MIC, PAL_DEVICE_IN_ULTRASOUND_MIC}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_EXT_EC_REF, PAL_DEVICE_IN_EXT_EC_REF}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_ECHO_REF, PAL_DEVICE_IN_ECHO_REF}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_HAPTICS_VI_FEEDBACK, - PAL_DEVICE_IN_HAPTICS_VI_FEEDBACK}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_BLUETOOTH_BLE, PAL_DEVICE_IN_BLUETOOTH_BLE}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_CPS_FEEDBACK, PAL_DEVICE_IN_CPS_FEEDBACK}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_DUMMY, PAL_DEVICE_IN_DUMMY}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_CPS2_FEEDBACK, PAL_DEVICE_IN_CPS2_FEEDBACK}, - {xsd::PalInDevicesType::PAL_DEVICE_IN_RECORD_PROXY, PAL_DEVICE_IN_RECORD_PROXY}, -}; - -} // namespace qti::audio::core \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/Android.bp b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/Android.bp deleted file mode 100755 index 2259f20f..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/Android.bp +++ /dev/null @@ -1,7 +0,0 @@ -xsd_config { - name: "libaudio_microphone_info", - srcs: ["microphone_info_schema.xsd"], - package_name: "qti.audio.microphone_info", - nullability: true, -} - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/current.txt b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/current.txt deleted file mode 100755 index a9cae53a..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/current.txt +++ /dev/null @@ -1,188 +0,0 @@ -// Signature format: 2.0 -package qti.audio.microphone_info { - - public enum AudioDeviceType { - method @NonNull public String getRawName(); - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_AFE_PROXY; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_DEVICE; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_DOCK; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_ECHO_REFERENCE; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_FM_TUNER; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_HEADSET; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_LOOPBACK; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_MICROPHONE; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_MICROPHONE_BACK; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_SUBMIX; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_TELEPHONY_RX; - enum_constant public static final qti.audio.microphone_info.AudioDeviceType IN_TV_TUNER; - } - - public enum ChannelMappingType { - method @NonNull public String getRawName(); - enum_constant public static final qti.audio.microphone_info.ChannelMappingType DIRECT; - enum_constant public static final qti.audio.microphone_info.ChannelMappingType PROCESSED; - enum_constant public static final qti.audio.microphone_info.ChannelMappingType UNUSED; - } - - public class CoordinatesType { - ctor public CoordinatesType(); - method @Nullable public float getX(); - method @Nullable public float getY(); - method @Nullable public float getZ(); - method public void setX(@Nullable float); - method public void setY(@Nullable float); - method public void setZ(@Nullable float); - } - - public enum DirectionalityType { - method @NonNull public String getRawName(); - enum_constant public static final qti.audio.microphone_info.DirectionalityType BI_DIRECTIONAL; - enum_constant public static final qti.audio.microphone_info.DirectionalityType CARDIOID; - enum_constant public static final qti.audio.microphone_info.DirectionalityType HYPER_CARDIOID; - enum_constant public static final qti.audio.microphone_info.DirectionalityType OMNI; - enum_constant public static final qti.audio.microphone_info.DirectionalityType SUPER_CARDIOID; - } - - public class FrequencyResponseType { - ctor public FrequencyResponseType(); - method @Nullable public java.util.List getFrequencyHz(); - method @Nullable public java.util.List getLeveldB(); - method public void setFrequencyHz(@Nullable java.util.List); - method public void setLeveldB(@Nullable java.util.List); - } - - public enum LocationType { - method @NonNull public String getRawName(); - enum_constant public static final qti.audio.microphone_info.LocationType MAINBODY; - enum_constant public static final qti.audio.microphone_info.LocationType MAINBODY_MOVABLE; - enum_constant public static final qti.audio.microphone_info.LocationType PERIPHERAL; - } - - public class MicInfoType { - ctor public MicInfoType(); - method @Nullable public java.util.List getChannelMapping(); - method @Nullable public String getId(); - method public void setChannelMapping(@Nullable java.util.List); - method public void setId(@Nullable String); - } - - public class MicrophoneDynamicInfoListType { - ctor public MicrophoneDynamicInfoListType(); - method @Nullable public java.util.List getMicrophoneDynamicInfo(); - } - - public class MicrophoneDynamicInfoType { - ctor public MicrophoneDynamicInfoType(); - method @Nullable public qti.audio.microphone_info.PalInDevicesType getDevice(); - method @Nullable public qti.audio.microphone_info.MicInfoType getMicInfo(); - method public void setDevice(@Nullable qti.audio.microphone_info.PalInDevicesType); - method public void setMicInfo(@Nullable qti.audio.microphone_info.MicInfoType); - } - - public class MicrophoneInfoAndDynamicInfo { - ctor public MicrophoneInfoAndDynamicInfo(); - method @Nullable public qti.audio.microphone_info.MicrophoneDynamicInfoListType getMicrophoneDynamicInfoList(); - method @Nullable public qti.audio.microphone_info.MicrophoneInfoListType getMicrophoneInfoList(); - method public void setMicrophoneDynamicInfoList(@Nullable qti.audio.microphone_info.MicrophoneDynamicInfoListType); - method public void setMicrophoneInfoList(@Nullable qti.audio.microphone_info.MicrophoneInfoListType); - } - - public class MicrophoneInfoListType { - ctor public MicrophoneInfoListType(); - method @Nullable public java.util.List getMicrophoneInfo(); - } - - public class MicrophoneInfoType { - ctor public MicrophoneInfoType(); - method @Nullable public qti.audio.microphone_info.MicrophoneInfoType.Device getDevice(); - method @Nullable public qti.audio.microphone_info.DirectionalityType getDirectionality(); - method @Nullable public qti.audio.microphone_info.FrequencyResponseType getFrequencyResponse(); - method @Nullable public int getGroup(); - method @Nullable public String getId(); - method @Nullable public int getIndexInTheGroup(); - method @Nullable public qti.audio.microphone_info.LocationType getLocation(); - method @Nullable public qti.audio.microphone_info.CoordinatesType getOrientation(); - method @Nullable public qti.audio.microphone_info.CoordinatesType getPosition(); - method @Nullable public qti.audio.microphone_info.MicrophoneInfoType.Sensitivity getSensitivity(); - method public void setDevice(@Nullable qti.audio.microphone_info.MicrophoneInfoType.Device); - method public void setDirectionality(@Nullable qti.audio.microphone_info.DirectionalityType); - method public void setFrequencyResponse(@Nullable qti.audio.microphone_info.FrequencyResponseType); - method public void setGroup(@Nullable int); - method public void setId(@Nullable String); - method public void setIndexInTheGroup(@Nullable int); - method public void setLocation(@Nullable qti.audio.microphone_info.LocationType); - method public void setOrientation(@Nullable qti.audio.microphone_info.CoordinatesType); - method public void setPosition(@Nullable qti.audio.microphone_info.CoordinatesType); - method public void setSensitivity(@Nullable qti.audio.microphone_info.MicrophoneInfoType.Sensitivity); - } - - public static class MicrophoneInfoType.Device { - ctor public MicrophoneInfoType.Device(); - method @Nullable public String getAddress(); - method @Nullable public String getConnection(); - method @Nullable public qti.audio.microphone_info.AudioDeviceType getName(); - method public void setAddress(@Nullable String); - method public void setConnection(@Nullable String); - method public void setName(@Nullable qti.audio.microphone_info.AudioDeviceType); - } - - public static class MicrophoneInfoType.Sensitivity { - ctor public MicrophoneInfoType.Sensitivity(); - method @Nullable public float getLeveldBFS(); - method @Nullable public float getMaxSpldB(); - method @Nullable public float getMinSpldB(); - method public void setLeveldBFS(@Nullable float); - method public void setMaxSpldB(@Nullable float); - method public void setMinSpldB(@Nullable float); - } - - public enum PalInDevicesType { - method @NonNull public String getRawName(); - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_AUX_DIGITAL; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_BLUETOOTH_A2DP; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_BLUETOOTH_BLE; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_CPS2_FEEDBACK; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_CPS_FEEDBACK; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_DUMMY; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_ECHO_REF; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_EXT_EC_REF; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_FM_TUNER; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_HANDSET_MIC; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_HANDSET_VA_MIC; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_HAPTICS_VI_FEEDBACK; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_HDMI; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_HEADSET_VA_MIC; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_LINE; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_PROXY; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_RECORD_PROXY; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_SPDIF; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_SPEAKER_MIC; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_TELEPHONY_RX; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_ULTRASOUND_MIC; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_USB_ACCESSORY; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_USB_DEVICE; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_USB_HEADSET; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_VI_FEEDBACK; - enum_constant public static final qti.audio.microphone_info.PalInDevicesType PAL_DEVICE_IN_WIRED_HEADSET; - } - - public class SensitivityType { - ctor public SensitivityType(); - method @Nullable public float getLeveldBFS(); - method @Nullable public float getMaxSpldB(); - method @Nullable public float getMinSpldB(); - method public void setLeveldBFS(@Nullable float); - method public void setMaxSpldB(@Nullable float); - method public void setMinSpldB(@Nullable float); - } - - public class XmlParser { - ctor public XmlParser(); - method @Nullable public static qti.audio.microphone_info.MicrophoneInfoAndDynamicInfo read(@NonNull java.io.InputStream) throws javax.xml.datatype.DatatypeConfigurationException, java.io.IOException, org.xmlpull.v1.XmlPullParserException; - method @Nullable public static String readText(@NonNull org.xmlpull.v1.XmlPullParser) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException; - method public static void skip(@NonNull org.xmlpull.v1.XmlPullParser) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException; - } - -} - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/last_current.txt b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/last_current.txt deleted file mode 100755 index e69de29b..00000000 diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/last_removed.txt b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/last_removed.txt deleted file mode 100755 index e69de29b..00000000 diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/removed.txt b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/removed.txt deleted file mode 100755 index d802177e..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/api/removed.txt +++ /dev/null @@ -1 +0,0 @@ -// Signature format: 2.0 diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/microphone_info_schema.xsd b/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/microphone_info_schema.xsd deleted file mode 100755 index 704d06e6..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/platform/microphoneInfoParser/schema/microphone_info_schema.xsd +++ /dev/null @@ -1,177 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/utils/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/core/utils/Android.mk deleted file mode 100755 index d284c733..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/utils/Android.mk +++ /dev/null @@ -1,40 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -# Recommend to have only utils for Audio types -# defined by AOSP - -LOCAL_MODULE := libaudiohalutils.qti -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_TAGS := optional -LOCAL_VENDOR_MODULE := true - -LOCAL_C_INCLUDES := \ - $(LOCAL_PATH)/include - -LOCAL_EXPORT_C_INCLUDE_DIRS := \ - $(LOCAL_PATH)/include - -LOCAL_SRC_FILES := \ - Utils.cpp - -LOCAL_HEADER_LIBRARIES := \ - libaudio_system_headers - -LOCAL_SHARED_LIBRARIES := \ - libbase \ - libutils \ - libaudioutils \ - android.media.audio.common.types-V3-ndk \ - android.hardware.audio.core-V2-ndk \ - qti-audio-types-aidl-V1-ndk - -LOCAL_CFLAGS := \ - -DBACKEND_NDK \ - -Wall \ - -Wextra \ - -Werror \ - -Wthread-safety - -include $(BUILD_STATIC_LIBRARY) diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/utils/Utils.cpp b/qcom/opensource/audio-hal/primary-hal/hal/core/utils/Utils.cpp deleted file mode 100755 index 006471d2..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/utils/Utils.cpp +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_Utils_QTI" - -#include -#include -#include -#include -#include - -using ::aidl::android::media::audio::common::AudioDevice; -using ::aidl::android::media::audio::common::AudioDeviceDescription; -using ::aidl::android::media::audio::common::AudioDeviceType; -using ::aidl::android::media::audio::common::AudioDeviceAddress; -using ::aidl::android::media::audio::common::AudioPortConfig; -using ::aidl::android::media::audio::common::AudioPortExt; -using ::aidl::android::media::audio::common::AudioIoFlags; -using ::aidl::android::media::audio::common::AudioInputFlags; -using ::aidl::android::media::audio::common::AudioOutputFlags; -using ::aidl::android::media::audio::common::AudioPortExt; -using ::aidl::android::media::audio::common::AudioSource; -using ::aidl::android::media::audio::common::AudioPortMixExtUseCase; - -using ::aidl::android::hardware::audio::core::VendorParameter; - -using ::aidl::qti::audio::core::VString; - -namespace qti::audio::core { - -BufferFormatConverter::BufferFormatConverter(audio_format_t inFormat, audio_format_t outFormat, - size_t bufSize) { - mInFormat = inFormat; - mOutFormat = outFormat; - mAllocSize = bufSize; - mInBytesPerSample = audio_bytes_per_sample(inFormat); - mOutBytesPerSample = audio_bytes_per_sample(outFormat); - int sizeoffloat = sizeof(float); - mBuffer = std::make_unique(mAllocSize); - if (!mBuffer) { - LOG(ERROR) << __func__ << " failed to init convert buffer"; - // alloc size to 0, so convert won't operate - mAllocSize = 0; - } - LOG(VERBOSE) << __func__ << "inFormat " << inFormat << " outFormat " << mOutFormat - << " inBytesPerSample " << mInBytesPerSample << " outBytesPerSample " - << mOutBytesPerSample << " size " << mAllocSize; -} - -std::optional> BufferFormatConverter::convert(const void* buffer, - size_t bytes) { - if (bytes > mAllocSize) { - LOG(ERROR) << " Error writing" << bytes << " to convertBuffer of capacity " << mAllocSize; - return std::nullopt; - } - size_t frames = bytes / mInBytesPerSample; - memcpy_by_audio_format(mBuffer.get(), mOutFormat, buffer, mInFormat, frames); - uint8_t* outBuffer = reinterpret_cast(mBuffer.get()); - return std::make_pair(outBuffer, frames * mOutBytesPerSample); -} - -bool isMixPortConfig(const AudioPortConfig& audioPortConfig) noexcept { - return audioPortConfig.ext.getTag() == AudioPortExt::Tag::mix; -}; - -bool isInputMixPortConfig(const AudioPortConfig& audioPortConfig) noexcept { - return isMixPortConfig(audioPortConfig) && audioPortConfig.flags && - audioPortConfig.flags.value().getTag() == AudioIoFlags::Tag::input; -} - -bool isDevicePortConfig(const AudioPortConfig& audioPortConfig) noexcept { - return audioPortConfig.ext.getTag() == AudioPortExt::Tag::device; -}; - -bool isOutputAudioDevice(const AudioDevice& device) noexcept { - if (device.type.type >= AudioDeviceType::OUT_DEFAULT) { - return true; - } - return false; -} - -bool isTelephonyRXDevice(const AudioDevice& device) noexcept { - return device.type.type == AudioDeviceType::IN_TELEPHONY_RX; -}; - -bool isTelephonyTXDevice(const AudioDevice& device) noexcept { - return device.type.type == AudioDeviceType::OUT_TELEPHONY_TX; -}; - -bool isBluetoothSCODevice(const AudioDevice& device) noexcept { - return (device.type.connection == AudioDeviceDescription::CONNECTION_BT_SCO); -} - -bool isBluetoothLEDevice(const AudioDevice& device) noexcept { - return (device.type.connection == AudioDeviceDescription::CONNECTION_BT_LE); -} - -bool isBluetoothLETXDevice(const AudioDevice& device) noexcept { - return (device.type.type == AudioDeviceType::IN_HEADSET && - device.type.connection == AudioDeviceDescription::CONNECTION_BT_LE); -} - -bool isBluetoothDevice(const AudioDevice& device) noexcept { - return (device.type.connection == AudioDeviceDescription::CONNECTION_BT_A2DP || - device.type.connection == AudioDeviceDescription::CONNECTION_BT_LE); -} - -bool hasBluetoothDevice(const std::vector& devices) noexcept { - auto itr = std::find_if(devices.cbegin(), devices.cend(), isBluetoothDevice); - return itr != devices.cend(); -} - -bool hasBluetoothSCODevice(const std::vector& devices) noexcept { - auto itr = std::find_if(devices.cbegin(), devices.cend(), isBluetoothSCODevice); - return itr != devices.cend(); -} - -bool isBluetoothA2dpDevice(const AudioDevice& device) noexcept { - return (device.type.connection == AudioDeviceDescription::CONNECTION_BT_A2DP); -} - -bool isBluetoothA2dpTXDevice(const AudioDevice& device) noexcept { - return (device.type.type == AudioDeviceType::IN_DEVICE && - device.type.connection == AudioDeviceDescription::CONNECTION_BT_A2DP); -} - -bool hasBluetoothLEDevice(const std::vector& devices) noexcept { - auto itr = std::find_if(devices.cbegin(), devices.cend(), isBluetoothLEDevice); - return itr != devices.cend(); -} - -bool hasBluetoothA2dpDevice(const std::vector& devices) noexcept { - auto itr = std::find_if(devices.cbegin(), devices.cend(), isBluetoothA2dpDevice); - return itr != devices.cend(); -} - -bool hasInputMMapFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::input) { - constexpr auto inputMMapFlag = static_cast( - 1 << static_cast(AudioInputFlags::MMAP_NOIRQ)); - return ((inputMMapFlag & ioFlags.get()) != 0); - } - return false; -} - -bool hasOutputMMapFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::output) { - constexpr auto outputMMapFlag = static_cast( - 1 << static_cast(AudioOutputFlags::MMAP_NOIRQ)); - return ((outputMMapFlag & ioFlags.get()) != - 0); - } - return false; -} - -bool hasMMapFlagsEnabled(const AudioIoFlags& ioFlags) noexcept { - return (hasInputMMapFlag(ioFlags) || hasOutputMMapFlag(ioFlags)); -} - -bool isInputAFEProxyDevice(const AudioDevice& device) noexcept { - return device.type.type == AudioDeviceType::IN_AFE_PROXY; -} - -bool isIPDevice(const AudioDevice& d) noexcept { - return isIPInDevice(d) || isIPOutDevice(d); -} - -bool isIPInDevice(const AudioDevice& d) noexcept { - if(d.type.type == AudioDeviceType::IN_DEVICE && - d.type.connection == AudioDeviceDescription::CONNECTION_IP_V4) { - return true; - } - return false; -} - -bool isIPOutDevice(const AudioDevice& d) noexcept { - if(d.type.type == AudioDeviceType::OUT_DEVICE && - d.type.connection == AudioDeviceDescription::CONNECTION_IP_V4) { - return true; - } - return false; -} - -bool isOutputSpeakerEarpiece(const AudioDevice& d) noexcept { - if (d.type.type == AudioDeviceType::OUT_SPEAKER_EARPIECE) { - return true; - } - return false; -} - -bool hasOutputSpeakerEarpiece(const std::vector& devices) noexcept { - auto itr = std::find_if(devices.cbegin(), devices.cend(), isOutputSpeakerEarpiece); - return itr != devices.cend(); -} - -bool isHdmiDevice(const AudioDevice& d) noexcept { - if (d.type.connection == AudioDeviceDescription::CONNECTION_HDMI) { - return true; - } - return false; -} - -bool isOutputDevice(const AudioDevice& d) noexcept { - if (d.type.type >= AudioDeviceType::OUT_DEFAULT) { - return true; - } - return false; -} - -bool isInputDevice(const AudioDevice& d) noexcept { - if (d.type.type < AudioDeviceType::OUT_DEFAULT) { - return true; - } - return false; -} - -bool isValidAlsaAddr(const std::vector& alsaAddress) noexcept { - if (alsaAddress.size() != 2 || alsaAddress[0] < 0 || alsaAddress[1] < 0) { - LOG(ERROR) << __func__ - << ": malformed alsa address: " - << ::android::internal::ToString(alsaAddress); - return false; - } - return true; -} - -bool isUsbDevice(const AudioDevice& d) noexcept { - if (d.type.connection == AudioDeviceDescription::CONNECTION_USB) { - return true; - } - return false; -} - -bool hasOutputDirectFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::output) { - constexpr auto directFlag = - static_cast(1 << static_cast(AudioOutputFlags::DIRECT)); - return ((directFlag & ioFlags.get()) != 0); - } - return false; -} - -bool hasInputRawFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::input) { - constexpr auto rawFlag = - static_cast(1 << static_cast(AudioInputFlags::RAW)); - return ((rawFlag & ioFlags.get()) != 0); - } - return false; -} - -bool hasOutputRawFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::output) { - constexpr auto rawFlag = - static_cast(1 << static_cast(AudioOutputFlags::RAW)); - return ((rawFlag & ioFlags.get()) != 0); - } - return false; -} - -bool hasOutputVoipRxFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::output) { - constexpr auto voipRxFlag = - static_cast(1 << static_cast(AudioOutputFlags::VOIP_RX)); - return ((voipRxFlag & ioFlags.get()) != 0); - } - return false; -} - -bool hasOutputDeepBufferFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::output) { - constexpr auto DeepBufferRxFlag = - static_cast(1 << static_cast(AudioOutputFlags::DEEP_BUFFER)); - return ((DeepBufferRxFlag & ioFlags.get()) != 0); - } - return false; -} - -bool hasOutputCompressOffloadFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::output) { - constexpr auto compressOffloadFlag = - static_cast(1 << static_cast(AudioOutputFlags::COMPRESS_OFFLOAD)); - return ((compressOffloadFlag & ioFlags.get()) != 0); - } - return false; -} - -#ifdef SEC_AUDIO_SAMSUNGRECORD -bool hasInputRemoteMicFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::input) { - constexpr auto remoteMicFlag = - static_cast(1 << static_cast(AudioInputFlags::REMOTE_MIC)); - return ((remoteMicFlag & ioFlags.get()) != 0); - } - return false; -} - -bool hasInputDirectFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::input) { - constexpr auto directFlag = - static_cast(1 << static_cast(AudioInputFlags::DIRECT)); - return ((directFlag & ioFlags.get()) != 0); - } - return false; -} - -bool hasInputFastFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::input) { - constexpr auto fastFlag = - static_cast(1 << static_cast(AudioInputFlags::FAST)); - return ((fastFlag & ioFlags.get()) != 0); - } - return false; -} -#endif - -#ifdef SEC_AUDIO_CALL -bool hasOutputPrimaryFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::output) { - constexpr auto primaryFlag = - static_cast(1 << static_cast(AudioOutputFlags::PRIMARY)); - return ((primaryFlag & ioFlags.get()) != 0); - } - return false; -} -#endif - -#ifdef SEC_AUDIO_SUPPORT_LOWLATENCY_MEDIA -bool hasOutputFastMediaFlag(const AudioIoFlags& ioFlags) noexcept { - if (ioFlags.getTag() == AudioIoFlags::Tag::output) { - constexpr auto fastmediaFlag = - static_cast(1 << static_cast(AudioOutputFlags::MEDIA)); - return ((fastmediaFlag & ioFlags.get()) != 0); - } - return false; -} -#endif - -#ifdef SEC_AUDIO_COMMON -bool isNoneDevice(const AudioDevice& device) noexcept { - return device.type.type == AudioDeviceType::NONE; -} - -bool hasNoneDevice(const std::vector& devices) noexcept { - auto itr = std::find_if(devices.cbegin(), devices.cend(), isNoneDevice); - return itr != devices.cend(); -} - -bool isSpeakerDevice(const AudioDevice& device) noexcept { - return !isBluetoothDevice(device) - && (device.type.type == AudioDeviceType::OUT_SPEAKER); -} - -bool hasSpeakerDevice(const std::vector& devices) noexcept { - auto itr = std::find_if(devices.cbegin(), devices.cend(), isSpeakerDevice); - return itr != devices.cend(); -} - -bool isUsbHeadsetDevice(const AudioDevice& device) noexcept { - return (device.type.type == AudioDeviceType::OUT_HEADSET && - device.type.connection == AudioDeviceDescription::CONNECTION_USB); -} - -bool hasUsbHeadsetDevice(const std::vector& devices) noexcept { - auto itr = std::find_if(devices.cbegin(), devices.cend(), isUsbHeadsetDevice); - return itr != devices.cend(); -} - -bool isHdmiOutputDevice(const AudioDevice& device) noexcept { - return (device.type.connection == AudioDeviceDescription::CONNECTION_HDMI && - device.type.type == AudioDeviceType::OUT_DEVICE); -} - -bool hasHdmiOutputDevice(const std::vector& devices) noexcept { - auto itr = std::find_if(devices.cbegin(), devices.cend(), isHdmiOutputDevice); - return itr != devices.cend(); -} -#endif - -std::optional getAudioSource(const AudioPortConfig& mixPortconfig) noexcept { - if (mixPortconfig.ext.getTag() != AudioPortExt::Tag::mix) { - LOG(ERROR) << __func__ << ": not a mix port, " << mixPortconfig.toString(); - return std::nullopt; - } - if (mixPortconfig.ext.get().usecase.getTag() != - AudioPortMixExtUseCase::Tag::source) { - LOG(ERROR) << __func__ << ": no source provided, " << mixPortconfig.toString(); - return std::nullopt; - } - return mixPortconfig.ext.get() - .usecase.get(); -} - -std::optional getSampleRate(const AudioPortConfig& portConfig) noexcept { - if (portConfig.sampleRate) { - return portConfig.sampleRate.value().value; - } - LOG(ERROR) << __func__ << ": no sample rate in port config " << portConfig.toString(); - return std::nullopt; -} - -std::vector getActiveInputMixPortConfigIds( - const std::vector& activePortConfigs) { - std::vector result; - for (const auto& activePortConfig : activePortConfigs) { - if (isInputMixPortConfig(activePortConfig)) { - result.emplace_back(activePortConfig.id); - } - } - return result; -} - -int64_t getInt64FromString(const std::string& s) noexcept { - // Todo handle actual value 0 - return static_cast(strtol(s.c_str(), nullptr, 10)); -} - -float getFloatFromString(const std::string& s) noexcept { - // Todo handle actual value 0 - return strtof(s.c_str(), nullptr); -} - -bool getBoolFromString(const std::string& s) noexcept { -#ifdef SEC_AUDIO_COMMON - return (s == "true" || s == "on"); -#else - return (s == "true"); -#endif -} - -bool setParameter(const VString& parcel, VendorParameter& parameter) noexcept { - if (parameter.ext.setParcelable(parcel) != android::OK) { - LOG(ERROR) << __func__ << ": failed to set parcel for " << parameter.id; - return false; - } - return true; -} - -VendorParameter makeVendorParameter(const std::string& id, const std::string& value) { - VString parcel; - parcel.value = value; - VendorParameter param; - param.id = id; - if (param.ext.setParcelable(parcel) != android::OK) { - LOG(ERROR) << __func__ << ": failed to set parcel for " << param.id; - } - return param; -} - -std::string makeParamValue(bool const& isTrue) noexcept { - return isTrue ? "true" : "false"; -} - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/core/utils/include/qti-audio-core/Utils.h b/qcom/opensource/audio-hal/primary-hal/hal/core/utils/include/qti-audio-core/Utils.h deleted file mode 100755 index d78b65c2..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/core/utils/include/qti-audio-core/Utils.h +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace qti::audio::core { - -/* -* Helper class used by streams when the target audio format differs -* from input audio format. This can happen if underlying layers don't support certain formats. -* In that case, convert the unsupported format to supported format -* using a aux buffer. -*/ -class BufferFormatConverter { - public: - BufferFormatConverter(audio_format_t inFormat, audio_format_t outFormat, size_t bufSize); - ~BufferFormatConverter() = default; - - /* - * @brief converts the input buffer from input format to output format. - * @param buffer, buffer to be converted. - * @param bytes total number of bytes in the buffer. - * @returns pointer to converted buffer and size of converted buffer in case of success. - * nullopt in case when bytes exceed the allocated size during setup. - */ - std::optional> convert(const void* buffer, size_t bytes); - size_t getInputBytesPerSample() { return mInBytesPerSample; } - size_t getOutputBytesPerSample() { return mOutBytesPerSample; } - - private: - audio_format_t mInFormat = AUDIO_FORMAT_PCM_16_BIT; - audio_format_t mOutFormat = AUDIO_FORMAT_PCM_16_BIT; - std::unique_ptr mBuffer{nullptr}; - size_t mAllocSize; - size_t mOutBytesPerSample; - size_t mInBytesPerSample; - - // Disallow copy and move assignments / constructors. - BufferFormatConverter(const BufferFormatConverter&) = delete; - BufferFormatConverter& operator=(const BufferFormatConverter&) = delete; - BufferFormatConverter& operator=(BufferFormatConverter&& other) = delete; - BufferFormatConverter(BufferFormatConverter&& other) = delete; -}; - -bool isMixPortConfig(const ::aidl::android::media::audio::common::AudioPortConfig&) noexcept; - -bool isInputMixPortConfig(const ::aidl::android::media::audio::common::AudioPortConfig&) noexcept; - -bool isDevicePortConfig(const ::aidl::android::media::audio::common::AudioPortConfig&) noexcept; - -bool isOutputAudioDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool isTelephonyRXDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool isTelephonyTXDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool isBluetoothSCODevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool isBluetoothLEDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool isBluetoothLETXDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool isBluetoothDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool hasBluetoothDevice(const std::vector<::aidl::android::media::audio::common::AudioDevice>&) noexcept; - -bool hasBluetoothSCODevice(const std::vector<::aidl::android::media::audio::common::AudioDevice>&) noexcept; - -bool isBluetoothA2dpDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool isBluetoothA2dpTXDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool hasBluetoothLEDevice(const std::vector<::aidl::android::media::audio::common::AudioDevice>&) noexcept; - -bool hasBluetoothA2dpDevice(const std::vector<::aidl::android::media::audio::common::AudioDevice>&) noexcept; - -bool hasInputMMapFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; - -bool hasOutputMMapFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; - -bool hasMMapFlagsEnabled(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; - -bool isInputAFEProxyDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool isIPDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool isIPInDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool isIPOutDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool isOutputSpeakerEarpiece(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool hasOutputSpeakerEarpiece( - const std::vector<::aidl::android::media::audio::common::AudioDevice>&) noexcept; - -bool isHdmiDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool isUsbDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool isValidAlsaAddr(const std::vector& alsaAddress) noexcept; -bool isInputDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool isOutputDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; - -bool hasOutputDirectFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; - -bool hasOutputRawFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; -bool hasInputRawFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; - -bool hasOutputVoipRxFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; -bool hasOutputDeepBufferFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; - -bool hasOutputCompressOffloadFlag( - const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; - -#ifdef SEC_AUDIO_SAMSUNGRECORD -bool hasInputRemoteMicFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; -bool hasInputDirectFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; -bool hasInputFastFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; -#endif -#ifdef SEC_AUDIO_CALL -bool hasOutputPrimaryFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; -#endif -#ifdef SEC_AUDIO_SUPPORT_LOWLATENCY_MEDIA -bool hasOutputFastMediaFlag(const ::aidl::android::media::audio::common::AudioIoFlags&) noexcept; -#endif -#ifdef SEC_AUDIO_COMMON -bool isNoneDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool hasNoneDevice(const std::vector<::aidl::android::media::audio::common::AudioDevice>&) noexcept; -bool isSpeakerDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool hasSpeakerDevice(const std::vector<::aidl::android::media::audio::common::AudioDevice>&) noexcept; -bool isUsbHeadsetDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool hasUsbHeadsetDevice(const std::vector<::aidl::android::media::audio::common::AudioDevice>&) noexcept; -bool isHdmiOutputDevice(const ::aidl::android::media::audio::common::AudioDevice&) noexcept; -bool hasHdmiOutputDevice(const std::vector<::aidl::android::media::audio::common::AudioDevice>&) noexcept; -#endif - -std::optional getAudioSource( - const ::aidl::android::media::audio::common::AudioPortConfig&) noexcept; - -std::optional getSampleRate( - const ::aidl::android::media::audio::common::AudioPortConfig&) noexcept; - -std::vector getActiveInputMixPortConfigIds( - const std::vector<::aidl::android::media::audio::common::AudioPortConfig>& - activePortConfigs); - -template -std::ostream& operator<<(std::ostream& os, const std::vector& list) noexcept { - os << std::accumulate(list.cbegin(), list.cend(), std::string(""), - [](auto&& prev, const auto& l) { - return std::move(prev.append(",").append(l.toString())); - }); - return os; -} - -template -bool operator==(const std::vector& left, const std::vector& right) noexcept { - if (left.size() != right.size()) { - return false; - } - return std::equal(left.cbegin(), left.cend(), right.cbegin()); -} - -int64_t getInt64FromString(const std::string& s) noexcept; - -float getFloatFromString(const std::string& s) noexcept; - -bool getBoolFromString(const std::string& s) noexcept; - -bool setParameter(const ::aidl::qti::audio::core::VString& parcel, - ::aidl::android::hardware::audio::core::VendorParameter& parameter) noexcept; - -template -bool extractParameter(const ::aidl::android::hardware::audio::core::VendorParameter& p, - decltype(W::value)* v) { - std::optional value; - int32_t result = p.ext.getParcelable(&value); - if (result == 0 && value.has_value()) { - *v = value.value().value; - return true; - } - return false; -} - -// Return whether all the elements in the vector are unique. -template -bool all_unique(const std::vector& v) { - return std::set(v.begin(), v.end()).size() == v.size(); -} - -// Erase all the specified elements from a map. -template -auto erase_all(C& c, const V& keys) { - auto oldSize = c.size(); - for (auto& k : keys) { - c.erase(k); - } - return oldSize - c.size(); -} - -// Erase all the elements in the container that satisfy the provided predicate. -template -auto erase_if(C& c, P pred) { - auto oldSize = c.size(); - for (auto it = c.begin(); it != c.end();) { - if (pred(*it)) { - it = c.erase(it); - } else { - ++it; - } - } - return oldSize - c.size(); -} - -// Erase all the elements in the map that have specified values. -template -auto erase_all_values(C& c, const V& values) { - return erase_if(c, [values](const auto& pair) { return values.count(pair.second) != 0; }); -} - -// Return non-zero count of elements for any of the provided keys. -template -size_t count_any(const M& m, const V& keys) { - for (auto& k : keys) { - if (size_t c = m.count(k); c != 0) return c; - } - return 0; -} - -// Assuming that M is a map whose values have an 'id' field, -// find an element with the specified id. -template -auto findById(M& m, int32_t id) { - return std::find_if(m.begin(), m.end(), [&](const auto& p) { return p.second.id == id; }); -} - -// Assuming that the vector contains elements with an 'id' field, -// find an element with the specified id. -template -auto findById(std::vector& v, int32_t id) { - return std::find_if(v.begin(), v.end(), [&](const auto& e) { return e.id == id; }); -} - -// Return elements from the vector that have specified ids, also -// optionally return which ids were not found. -template -std::vector selectByIds(std::vector& v, const std::vector& ids, - std::vector* missingIds = nullptr) { - std::vector result; - std::set idsSet(ids.begin(), ids.end()); - for (size_t i = 0; i < v.size(); ++i) { - T& e = v[i]; - if (idsSet.count(e.id) != 0) { - result.push_back(&v[i]); - idsSet.erase(e.id); - } - } - if (missingIds) { - *missingIds = std::vector(idsSet.begin(), idsSet.end()); - } - return result; -} - -// Assuming that M is a map whose keys' type is K and values' type is V, -// return the corresponding value of the given key from the map or default -// value if the key is not found. -template -auto findValueOrDefault(const M& m, const K& key, V defaultValue) { - auto it = m.find(key); - return it == m.end() ? defaultValue : it->second; -} - -// Assuming that M is a map whose keys' type is K, return the given key if it -// is found from the map or default value. -template -auto findKeyOrDefault(const M& m, const K& key, K defaultValue) { - auto it = m.find(key); - return it == m.end() ? defaultValue : key; -} - -/* -* create a VendorParameter from a id and value, primarly used with getVendorParameters. -*/ -::aidl::android::hardware::audio::core::VendorParameter makeVendorParameter(const std::string& id, - const std::string& value); - -/* -* convert bool value to the corresponding string value -* true -> "true" -* false -> "false" -*/ -std::string makeParamValue(bool const&) noexcept; - -} // namespace qti::audio::core diff --git a/qcom/opensource/audio-hal/primary-hal/hal/default/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/default/Android.mk deleted file mode 100755 index 3c14a631..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/default/Android.mk +++ /dev/null @@ -1,47 +0,0 @@ -LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) - -LOCAL_MODULE := libaudiocorehal.default -LOCAL_VENDOR_MODULE := true -LOCAL_MODULE_RELATIVE_PATH := hw - -LOCAL_CFLAGS := \ - -DBACKEND_NDK \ - -Wall \ - -Wextra \ - -Werror \ - -Wthread-safety - -LOCAL_VINTF_FRAGMENTS += manifest_audiocorehal_default.xml - -LOCAL_SRC_FILES := \ - DefaultServices.cpp - -LOCAL_HEADER_LIBRARIES := \ - libxsdc-utils \ - liberror_headers - -LOCAL_SHARED_LIBRARIES := \ - libaudioaidlcommon \ - libaudioserviceexampleimpl \ - android.hardware.audio.core-V2-ndk \ - libbase \ - libbinder_ndk \ - libcutils \ - liblog \ - libdl \ - libxml2 \ - libaudioutils \ - libutils \ - android.hardware.common-V2-ndk \ - android.media.audio.common.types-V3-ndk \ - libmedia_helper \ - libstagefright_foundation \ - libhidlbase \ - libhardware \ - libfmq \ - android.hardware.common-V2-ndk \ - android.media.audio.common.types-V3-ndk - -include $(BUILD_SHARED_LIBRARY) - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/default/DefaultServices.cpp b/qcom/opensource/audio-hal/primary-hal/hal/default/DefaultServices.cpp deleted file mode 100755 index 5c0acbba..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/default/DefaultServices.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_DefaultService_QTI" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -using aidl::android::hardware::audio::core::ChildInterface; - -using aidl::android::hardware::audio::core::internal::AudioPolicyConfigXmlConverter; -AudioPolicyConfigXmlConverter gAudioPolicyConverter{ - ::android::audio_get_audio_policy_config_file()}; - -using AospModule = ::aidl::android::hardware::audio::core::Module; -using AospModuleConfig = ::aidl::android::hardware::audio::core::Module::Configuration; -using AospModuleConfigurationPair = std::pair>; -using AospModuleConfigs = std::vector; -std::unique_ptr gModuleConfigs; -std::vector> gModuleInstances; -std::shared_ptr<::aidl::android::hardware::audio::core::Config> gConfigDefaultAosp; - -namespace { - -ChildInterface createModule(const std::string &name, - std::unique_ptr &&config) { - ChildInterface result; - { - auto moduleType = AospModule::typeFromString(name); - if (!moduleType.has_value()) { - LOG(ERROR) << __func__ << ": module type \"" << name << "\" is not supported"; - return result; - } - auto module = AospModule::createInstance(*moduleType, std::move(config)); - if (module == nullptr) return result; - result = std::move(module); - } - const std::string moduleName = - std::string().append(AospModule::descriptor).append("/").append(name); - AIBinder_setMinSchedulerPolicy(result.getBinder(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO); - binder_status_t status = AServiceManager_addService(result.getBinder(), moduleName.c_str()); - if (status != STATUS_OK) { - LOG(ERROR) << __func__ << ": failed to register service for \"" << moduleName << "\""; - return ChildInterface(); - } else { - LOG(INFO) << __func__ << ": registered service for \"" << moduleName << "\""; - } - return result; -}; - -} // namespace - -extern "C" __attribute__((visibility("default"))) int32_t registerServices() { - gConfigDefaultAosp = ndk::SharedRefBase::make<::aidl::android::hardware::audio::core::Config>( - gAudioPolicyConverter); - const std::string configIntfName = - std::string().append(gConfigDefaultAosp->descriptor).append("/default"); - binder_status_t status = AServiceManager_addService(gConfigDefaultAosp->asBinder().get(), - configIntfName.c_str()); - if (status != STATUS_OK) { - LOG(ERROR) << "failed to register service for \"" << configIntfName << "\""; - } - gModuleConfigs = gAudioPolicyConverter.releaseModuleConfigs(); - - // check if IModule/default is registered or not - const std::string serviceName = std::string(AospModule::descriptor).append("/").append("default"); - AIBinder* binder = AServiceManager_checkService(serviceName.c_str()); - bool registerStubAsDefault = false; - if (binder == nullptr) { - LOG(INFO) <<"IModule/default is not registered yet"; - registerStubAsDefault = true; - } - for (AospModuleConfigurationPair &configPair : *gModuleConfigs) { - std::string name = configPair.first; - if (name == "default") { - registerStubAsDefault = false; - } else if (name == "stub") { - if (registerStubAsDefault) { - name = "default"; - LOG(INFO) <<"register stub hal as default hal"; - } else { - continue; - } - } - if (auto instance = createModule(name, std::move(configPair.second)); instance) { - gModuleInstances.push_back(std::move(instance)); - } - } - return STATUS_OK; -} diff --git a/qcom/opensource/audio-hal/primary-hal/hal/default/manifest_audiocorehal_default.xml b/qcom/opensource/audio-hal/primary-hal/hal/default/manifest_audiocorehal_default.xml deleted file mode 100755 index 28abe4cc..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/default/manifest_audiocorehal_default.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - android.hardware.audio.core - 2 - IConfig/default - - - - android.hardware.audio.core - 2 - IModule/default - - - - android.hardware.audio.core - 2 - IModule/r_submix - - - - android.hardware.audio.core - 2 - IModule/usb - - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/Android.bp b/qcom/opensource/audio-hal/primary-hal/hal/effects/Android.bp deleted file mode 100755 index d4b87a12..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/Android.bp +++ /dev/null @@ -1,68 +0,0 @@ -/* -// commenting compilation through Android.bp, as all vendor effects are -// generated using Android.mk, in that case it would require us to have -// version updated at different places. Moving base headers/shared lib -// compilation to make file so all effects libraries can utitlize -// common defaults intrdouced in target.mk to acheive behavior similar -// to cc_default of Android.bp -cc_defaults { - name: "aidlaudioeffectserviceqti_defaults", - - vendor: true, - shared_libs: [ - "libaudioaidlcommon", - "libbase", - "libbinder_ndk", - "libcutils", - "libfmq", - "liblog", - "libutils", - "android.hardware.common-V2-ndk", - "android.hardware.common.fmq-V1-ndk", - "android.hardware.audio.effect-V2-ndk", - ], - header_libs: [ - "libaudioeffectsaidlqti_headers", - "libaudio_system_headers", - "libsystem_headers", - ], - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - "-Wthread-safety", - ], -} - -cc_library_static { - name: "libaudioeffecthal_base_impl_static", - srcs: [ - "EffectThread.cpp", - "EffectImpl.cpp", - "EffectContext.cpp", - ], - defaults: ["aidlaudioeffectserviceqti_defaults"], -} - -cc_library_shared { - name: "libaudioeffecthal.qti", - relative_install_path: "hw", - vintf_fragments: ["audioeffectservice_qti.xml"], - defaults: ["aidlaudioeffectserviceqti_defaults"], - shared_libs: [ - "libtinyxml2", - ], - srcs: [ - "EffectConfig.cpp", - "EffectFactory.cpp", - "EffectMain.cpp", - ], -} - -cc_library_headers { - name: "libaudioeffectsaidlqti_headers", - export_include_dirs: ["include"], - vendor_available: true, - host_supported: true, -} -*/ \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/effects/Android.mk deleted file mode 100755 index 92a5a1cb..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/Android.mk +++ /dev/null @@ -1,59 +0,0 @@ -CURRENT_PATH := $(call my-dir) - -LOCAL_PATH:= $(call my-dir) - -# Build Header library to expose effect headers -include $(CLEAR_VARS) -LOCAL_MODULE := libaudioeffectsaidlqti_headers -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include -LOCAL_VENDOR_MODULE := true -include $(BUILD_HEADER_LIBRARY) - - -#Build static library used by all effects -include $(CLEAR_VARS) -LOCAL_MODULE:= libaudioeffecthal_base_impl_static -LOCAL_VENDOR_MODULE := true -LOCAL_MODULE_OWNER := qti - -LOCAL_C_FLAGS += -Werror -Wall -Wextra -Wthread-safety - -LOCAL_SRC_FILES:= \ - EffectThread.cpp \ - EffectImpl.cpp \ - EffectContext.cpp - -LOCAL_SHARED_LIBRARIES:= \ - $(EFFECTS_DEFAULTS_SHARED_LIBRARIES) - -LOCAL_HEADER_LIBRARIES:= $(EFFECTS_DEFAULTS_HEADERS_LIBRARIES) - -include $(BUILD_STATIC_LIBRARY) - -# build base effects library -include $(CLEAR_VARS) - -LOCAL_MODULE:= libaudioeffecthal.qti -LOCAL_VENDOR_MODULE := true -LOCAL_MODULE_OWNER := qti -LOCAL_MODULE_RELATIVE_PATH := hw - -LOCAL_C_FLAGS += -Werror -Wall -Wextra - -LOCAL_SRC_FILES:= \ - EffectConfig.cpp \ - EffectFactory.cpp \ - EffectMain.cpp - -LOCAL_STATIC_LIBRARIES := libaudioeffecthal_base_impl_static -LOCAL_VINTF_FRAGMENTS := audioeffectservice_qti.xml - -LOCAL_SHARED_LIBRARIES:= \ - $(EFFECTS_DEFAULTS_SHARED_LIBRARIES) \ - libtinyxml2 - -LOCAL_HEADER_LIBRARIES:= $(EFFECTS_DEFAULTS_HEADERS_LIBRARIES) - -include $(BUILD_SHARED_LIBRARY) - -include $(CURRENT_PATH)/qcom-effects/Android.mk \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectConfig.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectConfig.cpp deleted file mode 100755 index 5274b0ea..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectConfig.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_EffectConfigQti" -#include -#include -#include -#include -#include - -// { SEC_AUDIO_SUPPORT_AIDL_EFFECT -#include -// } SEC_AUDIO_SUPPORT_AIDL_EFFECT - -#include "effectFactory-impl/EffectConfig.h" - -using aidl::android::media::audio::common::AudioSource; -using aidl::android::media::audio::common::AudioStreamType; -using aidl::android::media::audio::common::AudioUuid; -using ::aidl::android::hardware::audio::effect::stringToUuid; -#ifdef SEC_AUDIO_SUPPORT_AIDL_EFFECT -using ::aidl::android::hardware::audio::effect::getEffectTypeUuidSoundAlive; -using ::aidl::android::hardware::audio::effect::getEffectTypeUuidMySpaceEffect; -using ::aidl::android::hardware::audio::effect::getEffectTypeUuidDolbyAudioEffect; -using ::aidl::android::hardware::audio::effect::getEffectTypeUuidVolumeMonitor; -#endif - -namespace aidl::qti::effects { - -EffectConfig::EffectConfig(const std::string& file) { - tinyxml2::XMLDocument doc; - doc.LoadFile(file.c_str()); - LOG(VERBOSE) << __func__ << " loading " << file; - // parse the xml file into maps - if (doc.Error()) { - LOG(ERROR) << __func__ << " tinyxml2 failed to load " << file - << " error: " << doc.ErrorStr(); - return; - } - - auto registerFailure = [&](bool result) { mSkippedElements += result ? 0 : 1; }; - - for (auto& xmlConfig : getChildren(doc, "audio_effects_conf")) { - // Parse library - for (auto& xmlLibraries : getChildren(xmlConfig, "libraries")) { - for (auto& xmlLibrary : getChildren(xmlLibraries, "library")) { - registerFailure(parseLibrary(xmlLibrary)); - } - } - - // Parse effects - for (auto& xmlEffects : getChildren(xmlConfig, "effects")) { - for (auto& xmlEffect : getChildren(xmlEffects)) { - registerFailure(parseEffect(xmlEffect)); - } - } - - // Parse pre processing chains - for (auto& xmlPreprocess : getChildren(xmlConfig, "preprocess")) { - for (auto& xmlStream : getChildren(xmlPreprocess, "stream")) { - // AudioSource - registerFailure(parseProcessing(Processing::Type::source, xmlStream)); - } - } - - // Parse post processing chains - for (auto& xmlPostprocess : getChildren(xmlConfig, "postprocess")) { - for (auto& xmlStream : getChildren(xmlPostprocess, "stream")) { - // AudioStreamType - registerFailure(parseProcessing(Processing::Type::streamType, xmlStream)); - } - } - } - LOG(DEBUG) << __func__ << " successfully parsed " << file << ", skipping " << mSkippedElements - << " element(s)"; -} - -std::vector> EffectConfig::getChildren( - const tinyxml2::XMLNode& node, const char* childTag) { - std::vector> children; - for (auto* child = node.FirstChildElement(childTag); child != nullptr; - child = child->NextSiblingElement(childTag)) { - children.emplace_back(*child); - } - return children; -} - -bool EffectConfig::resolveLibrary(const std::string& path, std::string* resolvedPath) { - for (auto* libraryDirectory : kEffectLibPath) { - std::string candidatePath = std::string(libraryDirectory) + '/' + path; - if (access(candidatePath.c_str(), R_OK) == 0) { - *resolvedPath = std::move(candidatePath); - return true; - } - } - return false; -} - -bool EffectConfig::parseLibrary(const tinyxml2::XMLElement& xml) { - const char* name = xml.Attribute("name"); - RETURN_VALUE_IF(!name, false, "noNameAttribute"); - const char* path = xml.Attribute("path"); - RETURN_VALUE_IF(!path, false, "noPathAttribute"); - - std::string resolvedPath; - if (!resolveLibrary(path, &resolvedPath)) { - LOG(ERROR) << __func__ << " can't find " << path; - return false; - } - mLibraryMap[name] = resolvedPath; - LOG(VERBOSE) << __func__ << " " << name << " : " << resolvedPath; - return true; -} - -bool EffectConfig::parseEffect(const tinyxml2::XMLElement& xml) { - struct EffectLibraries effectLibraries; - std::vector libraries; - std::string name = xml.Attribute("name"); - RETURN_VALUE_IF(name == "", false, "effectsNoName"); - - struct Library library; - if (std::strcmp(xml.Name(), "effectProxy") == 0) { - // proxy lib and uuid - RETURN_VALUE_IF(!parseLibrary(xml, library, true), false, "parseProxyLibFailed"); - effectLibraries.proxyLibrary = library; - // proxy effect libs and UUID - auto xmlProxyLib = xml.FirstChildElement(); - RETURN_VALUE_IF(!xmlProxyLib, false, "noLibForProxy"); - while (xmlProxyLib) { - struct Library tempLibrary; - RETURN_VALUE_IF(!parseLibrary(*xmlProxyLib, tempLibrary), false, - "parseEffectLibFailed"); - libraries.push_back(std::move(tempLibrary)); - xmlProxyLib = xmlProxyLib->NextSiblingElement(); - } - } else { - // expect only one library if not proxy - RETURN_VALUE_IF(!parseLibrary(xml, library), false, "parseEffectLibFailed"); - libraries.push_back(std::move(library)); - } - - effectLibraries.libraries = std::move(libraries); - mEffectsMap[name] = std::move(effectLibraries); - return true; -} - -bool EffectConfig::parseLibrary(const tinyxml2::XMLElement& xml, struct Library& library, - bool isProxy) { - // Retrieve library name only if not effectProxy element - if (!isProxy) { - const char* name = xml.Attribute("library"); - RETURN_VALUE_IF(!name, false, "noLibraryAttribute"); - library.name = name; - } - - const char* uuidStr = xml.Attribute("uuid"); - RETURN_VALUE_IF(!uuidStr, false, "noUuidAttribute"); - library.uuid = stringToUuid(uuidStr); - bool typeSameAsUuid = false; - if (const char* typeSameAsUuidStr = xml.Attribute("typeSameAsUuid")) { - typeSameAsUuid = (0 == strcmp(typeSameAsUuidStr, "true")); - } - - if (const char* typeUuidStr = xml.Attribute("type")) { - library.type = stringToUuid(typeUuidStr); - LOG(VERBOSE) << " type specified for " << library.name; - } else if (typeSameAsUuid) { - // for vendor effects, type and uuid are generally same, so instead of modifying - // the XML to add "type", add "typeSameAsUuid" tag, so type will be mapped to uuid - // However, if type and uuid needs to be different then set type explicitly in - // the XML file. - library.type = stringToUuid(uuidStr); - } - RETURN_VALUE_IF((library.uuid == getEffectUuidZero()), false, "invalidUuidAttribute"); - - LOG(VERBOSE) << __func__ << (isProxy ? " proxy " : library.name) << " : uuid " - << toString(library.uuid) - << " : type: " << (library.type.has_value() ? toString(library.type.value()) : ""); - return true; -} - -std::optional EffectConfig::stringToProcessingType(Processing::Type::Tag typeTag, - const std::string& type) { - // see list of audio stream types in audio_stream_type_t: - // system/media/audio/include/system/audio_effects/audio_effects_conf.h - // AUDIO_STREAM_DEFAULT_TAG is not listed here because according to SYS_RESERVED_DEFAULT in - // AudioStreamType.aidl: "Value reserved for system use only. HALs must never return this value - // to the system or accept it from the system". - static const std::map sAudioStreamTypeTable = { - {AUDIO_STREAM_VOICE_CALL_TAG, AudioStreamType::VOICE_CALL}, - {AUDIO_STREAM_SYSTEM_TAG, AudioStreamType::SYSTEM}, - {AUDIO_STREAM_RING_TAG, AudioStreamType::RING}, - {AUDIO_STREAM_MUSIC_TAG, AudioStreamType::MUSIC}, - {AUDIO_STREAM_ALARM_TAG, AudioStreamType::ALARM}, - {AUDIO_STREAM_NOTIFICATION_TAG, AudioStreamType::NOTIFICATION}, - {AUDIO_STREAM_BLUETOOTH_SCO_TAG, AudioStreamType::BLUETOOTH_SCO}, - {AUDIO_STREAM_ENFORCED_AUDIBLE_TAG, AudioStreamType::ENFORCED_AUDIBLE}, - {AUDIO_STREAM_DTMF_TAG, AudioStreamType::DTMF}, - {AUDIO_STREAM_TTS_TAG, AudioStreamType::TTS}, - {AUDIO_STREAM_ASSISTANT_TAG, AudioStreamType::ASSISTANT}}; - - // see list of audio sources in audio_source_t: - // system/media/audio/include/system/audio_effects/audio_effects_conf.h - static const std::map sAudioSourceTable = { - {MIC_SRC_TAG, AudioSource::MIC}, - {VOICE_UL_SRC_TAG, AudioSource::VOICE_UPLINK}, - {VOICE_DL_SRC_TAG, AudioSource::VOICE_DOWNLINK}, - {VOICE_CALL_SRC_TAG, AudioSource::VOICE_CALL}, - {CAMCORDER_SRC_TAG, AudioSource::CAMCORDER}, - {VOICE_REC_SRC_TAG, AudioSource::VOICE_RECOGNITION}, - {VOICE_COMM_SRC_TAG, AudioSource::VOICE_COMMUNICATION}, - {REMOTE_SUBMIX_SRC_TAG, AudioSource::REMOTE_SUBMIX}, - {UNPROCESSED_SRC_TAG, AudioSource::UNPROCESSED}, - {VOICE_PERFORMANCE_SRC_TAG, AudioSource::VOICE_PERFORMANCE}}; - - if (typeTag == Processing::Type::streamType) { - auto typeIter = sAudioStreamTypeTable.find(type); - if (typeIter != sAudioStreamTypeTable.end()) { - return typeIter->second; - } - } else if (typeTag == Processing::Type::source) { - auto typeIter = sAudioSourceTable.find(type); - if (typeIter != sAudioSourceTable.end()) { - return typeIter->second; - } - } - - return std::nullopt; -} - -bool EffectConfig::parseProcessing(Processing::Type::Tag typeTag, const tinyxml2::XMLElement& xml) { - const char* typeStr = xml.Attribute("type"); - auto aidlType = stringToProcessingType(typeTag, typeStr); - RETURN_VALUE_IF(!aidlType.has_value(), false, "illegalStreamType"); - RETURN_VALUE_IF(0 != mProcessingMap.count(aidlType.value()), false, "duplicateStreamType"); - - for (auto& apply : getChildren(xml, "apply")) { - const char* name = apply.get().Attribute("effect"); - if (mEffectsMap.find(name) == mEffectsMap.end()) { - LOG(ERROR) << __func__ << " effect " << name << " doesn't exist, skipping"; - continue; - } - RETURN_VALUE_IF(!name, false, "noEffectAttribute"); - mProcessingMap[aidlType.value()].emplace_back(mEffectsMap[name]); - LOG(VERBOSE) << __func__ << " " << typeStr << " : " << name - << " aidl: " << aidlType.value().toString(); - } - return true; -} - -const std::map>& - EffectConfig::getProcessingMap() const { - return mProcessingMap; -} - -bool EffectConfig::findUuid(const std::pair& effectElem, - AudioUuid* uuid) { -// Difference from EFFECT_TYPE_LIST_DEF, there could be multiple name mapping to same Effect Type -#define EFFECT_XML_TYPE_LIST_DEF(V) \ - V("acoustic_echo_canceler", AcousticEchoCanceler) \ - V("automatic_gain_control_v1", AutomaticGainControlV1) \ - V("automatic_gain_control_v2", AutomaticGainControlV2) \ - V("bassboost", BassBoost) \ - V("downmix", Downmix) \ - V("dynamics_processing", DynamicsProcessing) \ - V("equalizer", Equalizer) \ - V("haptic_generator", HapticGenerator) \ - V("loudness_enhancer", LoudnessEnhancer) \ - V("env_reverb", EnvReverb) \ - V("reverb_env_aux", EnvReverb) \ - V("reverb_env_ins", EnvReverb) \ - V("preset_reverb", PresetReverb) \ - V("reverb_pre_aux", PresetReverb) \ - V("reverb_pre_ins", PresetReverb) \ - V("noise_suppression", NoiseSuppression) \ - V("spatializer", Spatializer) \ - V("virtualizer", Virtualizer) \ - V("visualizer", Visualizer) \ - V("volume", Volume) - -#ifdef SEC_AUDIO_SUPPORT_AIDL_EFFECT -#define EFFECT_XML_TYPE_SEC_LIST_DEF(V) \ - V("soundalive", SoundAlive) \ - V("sa3d", MySpaceEffect) \ - V("dap", DolbyAudioEffect) \ - V("volumemonitor_hw", VolumeMonitor) \ - V("sa3d_sw", MySpaceEffect) \ - V("sa3d_hw", MySpaceEffect) -#endif - -#define GENERATE_MAP_ENTRY_V(s, symbol) {s, &getEffectTypeUuid##symbol}, - - const std::string xmlEffectName = effectElem.first; - typedef const AudioUuid& (*UuidGetter)(void); - static const std::map uuidMap{ - {EFFECT_XML_TYPE_LIST_DEF(GENERATE_MAP_ENTRY_V)}}; - if (auto it = uuidMap.find(xmlEffectName); it != uuidMap.end()) { - *uuid = (*it->second)(); - LOG(VERBOSE) << __func__ << " " << xmlEffectName << " found in standard effects"; - return true; - } - - const auto& libs = effectElem.second.libraries; - for (const auto& lib : libs) { - if (lib.type.has_value()) { - LOG(VERBOSE) << __func__ << " " << xmlEffectName << " found from XML type " - << toString(lib.type.value()); - *uuid = lib.type.value(); - return true; - } - } - -#ifdef SEC_AUDIO_SUPPORT_AIDL_EFFECT - static const std::map secUuidMap{ - {EFFECT_XML_TYPE_SEC_LIST_DEF(GENERATE_MAP_ENTRY_V)}}; - - if (auto it = secUuidMap.find(xmlEffectName); it != secUuidMap.end()) { - *uuid = (*it->second)(); - LOG(VERBOSE) << __func__ << " " << xmlEffectName << " found in sec effects"; - return true; - } -#endif - - // find in QTI specific effects - if (auto it = kUuidNameTypeMap.find(xmlEffectName); it != kUuidNameTypeMap.end()) { - *uuid = (it->second); - LOG(VERBOSE) << __func__ << " " << xmlEffectName << " found in QTI effects"; - return true; - } - return false; -} - -const char* EffectConfig::dump(const tinyxml2::XMLElement& element, - tinyxml2::XMLPrinter&& printer) const { - element.Accept(&printer); - return printer.CStr(); -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectContext.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectContext.cpp deleted file mode 100755 index bfbbf674..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectContext.cpp +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (C) 2024 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. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#define LOG_TAG "AHAL_EffectContextQti" -#include "effect-impl/EffectContext.h" -#include "include/effect-impl/EffectTypes.h" - -using aidl::android::hardware::audio::common::getChannelCount; -using aidl::android::hardware::audio::common::getFrameSizeInBytes; -using aidl::android::hardware::audio::effect::IEffect; -// using aidl::android::hardware::audio::effect::kReopenSupportedVersion; -using aidl::android::hardware::audio::effect::kEventFlagDataMqUpdate; -using aidl::android::media::audio::common::PcmType; -using ::android::hardware::EventFlag; - -namespace aidl::qti::effects { - -int kReopenSupportedVersion = 2; - -EffectContext::EffectContext(const Parameter::Common& common, bool processData) { - if (RetCode::SUCCESS != setCommon(common)) { - LOG(ERROR) << __func__ << " illegal common parameters"; - } - initMessageQueues(processData); -} - -void EffectContext::initMessageQueues(bool processData) { - if (processData) { - // in/outBuffer size in float (FMQ data format defined for DataMQ) - size_t inBufferSizeInFloat = mCommon.input.frameCount * mInputFrameSize / sizeof(float); - size_t outBufferSizeInFloat = mCommon.output.frameCount * mOutputFrameSize / sizeof(float); - - // only status FMQ use the EventFlag - mStatusMQ = std::make_shared(1 /*depth*/, true /*configureEventFlagWord*/); - mInputMQ = std::make_shared(inBufferSizeInFloat); - mOutputMQ = std::make_shared(outBufferSizeInFloat); - - if (!mStatusMQ->isValid() || !mInputMQ->isValid() || !mOutputMQ->isValid()) { - LOG(ERROR) << __func__ << " created invalid FMQ, statusMQ: " << mStatusMQ->isValid() - << " inputMQ: " << mInputMQ->isValid() - << " outputMQ: " << mOutputMQ->isValid(); - } - - ::android::status_t status = - EventFlag::createEventFlag(mStatusMQ->getEventFlagWord(), &mEfGroup); - if (status != ::android::OK || !mEfGroup) { - LOG(ERROR) << __func__ << " create EventFlagGroup failed "; - return; - } - mWorkBuffer.resize(std::max(inBufferSizeInFloat, outBufferSizeInFloat)); - } - - mProcessData = processData; -} - -EffectContext::~EffectContext() { - if (mEfGroup) { - ::android::hardware::EventFlag::deleteEventFlag(&mEfGroup); - } -} - -// reset buffer status by abandon input data in FMQ -void EffectContext::resetBuffer() { - if (mProcessData) { - auto buffer = static_cast(mWorkBuffer.data()); - if (mStatusMQ) { - std::vector status(mStatusMQ->availableToRead()); - } - if (mInputMQ) { - mInputMQ->read(buffer, mInputMQ->availableToRead()); - } - } -} - -void EffectContext::dupeFmqWithReopen(IEffect::OpenEffectReturn* effectRet) { - if (!mProcessData) return; - if (!mInputMQ) { - mInputMQ = std::make_shared(mCommon.input.frameCount * mInputFrameSize / - sizeof(float)); - } - if (!mOutputMQ) { - mOutputMQ = std::make_shared(mCommon.output.frameCount * mOutputFrameSize / - sizeof(float)); - } - dupeFmq(effectRet); -} - -void EffectContext::dupeFmq(IEffect::OpenEffectReturn* effectRet) { - if (!mProcessData) return; - if (effectRet && mStatusMQ && mInputMQ && mOutputMQ) { - effectRet->statusMQ = mStatusMQ->dupeDesc(); - effectRet->inputDataMQ = mInputMQ->dupeDesc(); - effectRet->outputDataMQ = mOutputMQ->dupeDesc(); - } -} - -float* EffectContext::getWorkBuffer() { - return static_cast(mWorkBuffer.data()); -} - -size_t EffectContext::getWorkBufferSize() const { - return mWorkBuffer.size(); -} - -std::shared_ptr EffectContext::getStatusFmq() const { - return mStatusMQ; -} - -std::shared_ptr EffectContext::getInputDataFmq() const { - return mInputMQ; -} - -std::shared_ptr EffectContext::getOutputDataFmq() const { - return mOutputMQ; -} - -size_t EffectContext::getInputFrameSize() const { - return mInputFrameSize; -} - -size_t EffectContext::getOutputFrameSize() const { - return mOutputFrameSize; -} - -int EffectContext::getSessionId() const { - return mCommon.session; -} - -int EffectContext::getIoHandle() const { - return mCommon.ioHandle; -} - -RetCode EffectContext::setOutputDevice( - const std::vector& device) { - mOutputDevice = device; - return RetCode::SUCCESS; -} - -std::vector - EffectContext::getOutputDevice() { - return mOutputDevice; -} - -RetCode EffectContext::setAudioMode(const aidl::android::media::audio::common::AudioMode& mode) { - mMode = mode; - return RetCode::SUCCESS; -} -aidl::android::media::audio::common::AudioMode EffectContext::getAudioMode() { - return mMode; -} - -RetCode EffectContext::setAudioSource( - const aidl::android::media::audio::common::AudioSource& source) { - mSource = source; - return RetCode::SUCCESS; -} - -aidl::android::media::audio::common::AudioSource EffectContext::getAudioSource() { - return mSource; -} - -RetCode EffectContext::setVolumeStereo(const Parameter::VolumeStereo& volumeStereo) { - mVolumeStereo = volumeStereo; - return RetCode::SUCCESS; -} - -Parameter::VolumeStereo EffectContext::getVolumeStereo() { - return mVolumeStereo; -} - -RetCode EffectContext::setCommon(const Parameter::Common& common) { - if (mCommon != common) { - LOG(VERBOSE) << __func__ << " Param Change from " << mCommon.toString(); - LOG(VERBOSE) << __func__ << " to " << common.toString(); - } - LOG(VERBOSE) << __func__ << common.toString(); - auto& input = common.input; - auto& output = common.output; - - if (input.base.format.pcm != aidl::android::media::audio::common::PcmType::FLOAT_32_BIT || - output.base.format.pcm != aidl::android::media::audio::common::PcmType::FLOAT_32_BIT) { - LOG(ERROR) << __func__ << " illegal IO, input " - << ::android::internal::ToString(input.base.format) << ", output " - << ::android::internal::ToString(output.base.format); - return RetCode::ERROR_ILLEGAL_PARAMETER; - } - - if (auto ret = updateIOFrameSize(common); ret != RetCode::SUCCESS) { - return ret; - } - - mInputChannelCount = getChannelCount(input.base.channelMask); - mOutputChannelCount = getChannelCount(output.base.channelMask); - if (mInputChannelCount == 0 || mOutputChannelCount == 0) { - LOG(ERROR) << __func__ << " illegal channel count input " << mInputChannelCount - << ", output " << mOutputChannelCount; - return RetCode::ERROR_ILLEGAL_PARAMETER; - } - - mCommon = common; - return RetCode::SUCCESS; -} - -Parameter::Common EffectContext::getCommon() { - LOG(VERBOSE) << __func__ << mCommon.toString(); - return mCommon; -} - -EventFlag* EffectContext::getStatusEventFlag() { - return mEfGroup; -} - -RetCode EffectContext::updateIOFrameSize(const Parameter::Common& common) { - const auto prevInputFrameSize = mInputFrameSize; - const auto prevOutputFrameSize = mOutputFrameSize; - mInputFrameSize = ::aidl::android::hardware::audio::common::getFrameSizeInBytes( - common.input.base.format, common.input.base.channelMask); - mOutputFrameSize = ::aidl::android::hardware::audio::common::getFrameSizeInBytes( - common.output.base.format, common.output.base.channelMask); - - if (!mProcessData) { - LOG(VERBOSE) << __func__ << " effect does not process data"; - return RetCode::SUCCESS; - } - // workBuffer and data MQ not allocated yet, no need to update - if (mWorkBuffer.size() == 0 || !mInputMQ || !mOutputMQ) { - return RetCode::SUCCESS; - } - // IEffect::reopen introduced in android.hardware.audio.effect-V2 - if (mVersion < kReopenSupportedVersion) { - LOG(WARNING) << __func__ << " skipped for HAL version " << mVersion; - return RetCode::SUCCESS; - } - bool needUpdateMq = false; - if (mInputFrameSize != prevInputFrameSize || - mCommon.input.frameCount != common.input.frameCount) { - mInputMQ.reset(); - needUpdateMq = true; - } - if (mOutputFrameSize != prevOutputFrameSize || - mCommon.output.frameCount != common.output.frameCount) { - mOutputMQ.reset(); - needUpdateMq = true; - } - - if (needUpdateMq) { - mWorkBuffer.resize(std::max(common.input.frameCount * mInputFrameSize / sizeof(float), - common.output.frameCount * mOutputFrameSize / sizeof(float))); - return notifyDataMqUpdate(); - } - return RetCode::SUCCESS; -} - -// this should only be called for software effects -RetCode EffectContext::notifyDataMqUpdate() { - if (!mEfGroup) { - LOG(ERROR) << __func__ << ": invalid EventFlag group"; - return RetCode::ERROR_EVENT_FLAG_ERROR; - } - - if (const auto ret = mEfGroup->wake(kEventFlagDataMqUpdate); ret != ::android::OK) { - LOG(ERROR) << __func__ << ": wake failure with ret " << ret; - return RetCode::ERROR_EVENT_FLAG_ERROR; - } - LOG(DEBUG) << __func__ << " : signal client for reopen"; - return RetCode::SUCCESS; -} - -RetCode EffectContext::setOffload(bool offload) { - mOffload = offload; - return RetCode::SUCCESS; -} - -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectFactory.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectFactory.cpp deleted file mode 100755 index 253bb54a..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectFactory.cpp +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#include -#include -#include -#include -#define LOG_TAG "AHAL_EffectFactoryQti" - -#include -#include -#include -#include - -#include "effect-impl/EffectTypes.h" -#include "effectFactory-impl/EffectFactory.h" - -using aidl::android::media::audio::common::AudioUuid; - -namespace aidl::qti::effects { - -Factory::Factory(const std::string& file) : mConfig(EffectConfig(file)) { - LOG(VERBOSE) << __func__ << " with config file: " << file; - loadEffectLibs(); -} - -Factory::~Factory() { - if (auto count = mEffectMap.size()) { - LOG(ERROR) << __func__ << " remaining " << count - << " effect instances not destroyed indicating resource leak!"; - for (const auto& it : mEffectMap) { - if (auto spEffect = it.first.lock()) { - LOG(ERROR) << __func__ << " erase remaining instance UUID " - << it.second.first.toString(); - destroyEffectImpl_l(spEffect); - } - } - } -} - -ndk::ScopedAStatus Factory::getDescriptorWithUuid_l(const AudioUuid& uuid, Descriptor* desc) { - RETURN_IF(!desc, EX_NULL_POINTER, "nullDescriptor"); - - if (mEffectLibMap.count(uuid)) { - auto& entry = mEffectLibMap[uuid]; - getDlSyms_l(entry); - auto& libInterface = std::get(entry); - RETURN_IF(!libInterface || !libInterface->queryEffectFunc, EX_NULL_POINTER, - "dlNullQueryEffectFunc"); - RETURN_IF_BINDER_EXCEPTION(libInterface->queryEffectFunc(&uuid, desc)); - return ndk::ScopedAStatus::ok(); - } - - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); -} - -ndk::ScopedAStatus Factory::queryEffects(const std::optional& in_type_uuid, - const std::optional& in_impl_uuid, - const std::optional& in_proxy_uuid, - std::vector* _aidl_return) { - std::lock_guard lg(mMutex); - // get the matching list - std::vector idList; - std::copy_if(mIdentitySet.begin(), mIdentitySet.end(), std::back_inserter(idList), - [&](auto& id) { - return (!in_type_uuid.has_value() || in_type_uuid.value() == id.type) && - (!in_impl_uuid.has_value() || in_impl_uuid.value() == id.uuid) && - (!in_proxy_uuid.has_value() || - (id.proxy.has_value() && in_proxy_uuid.value() == id.proxy.value())); - }); - // query through the matching list - for (const auto& id : idList) { - if (mEffectLibMap.count(id.uuid)) { - Descriptor desc; - RETURN_IF_ASTATUS_NOT_OK(getDescriptorWithUuid_l(id.uuid, &desc), - "getDescriptorFailed"); - // update proxy UUID with information from config xml - desc.common.id.proxy = id.proxy; - _aidl_return->emplace_back(std::move(desc)); - } - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Factory::queryProcessing(const std::optional& in_type, - std::vector* _aidl_return) { - std::lock_guard lg(mMutex); - const auto& processings = mConfig.getProcessingMap(); - // Processing stream type - for (const auto& procIter : processings) { - if (!in_type.has_value() || in_type.value() == procIter.first) { - Processing process = {.type = procIter.first /* Processing::Type */}; - for (const auto& libs : procIter.second /* std::vector */) { -// { SEC_AUDIO_EFFECT_COMMON - if (libs.proxyLibrary.has_value()) { - auto& proxyLibrary = libs.proxyLibrary.value(); - Descriptor desc; - desc.common.name = proxyLibrary.name; - desc.common.id.uuid = proxyLibrary.uuid; - desc.common.id.proxy = proxyLibrary.uuid; - process.ids.emplace_back(desc); - continue; - } -// } SEC_AUDIO_EFFECT_COMMON - for (const auto& lib : libs.libraries /* std::vector */) { - Descriptor desc; - if (libs.proxyLibrary.has_value()) { - desc.common.id.proxy = libs.proxyLibrary.value().uuid; - } - RETURN_IF_ASTATUS_NOT_OK(getDescriptorWithUuid_l(lib.uuid, &desc), - "getDescriptorFailed"); - process.ids.emplace_back(desc); - } - } - LOG(VERBOSE) << __func__ << " insert processing " << process.toString(); - _aidl_return->emplace_back(process); - } - } - LOG(VERBOSE) << __func__ << " return " << _aidl_return->size(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Factory::createEffect(const AudioUuid& in_impl_uuid, - std::shared_ptr* _aidl_return) { - LOG(VERBOSE) << __func__ << ": UUID " << toString(in_impl_uuid); - std::lock_guard lg(mMutex); - if (mEffectLibMap.count(in_impl_uuid)) { - auto& entry = mEffectLibMap[in_impl_uuid]; - getDlSyms_l(entry); - - auto& libInterface = std::get(entry); - RETURN_IF(!libInterface || !libInterface->createEffectFunc, EX_NULL_POINTER, - "dlNullcreateEffectFunc"); - std::shared_ptr effectSp; - RETURN_IF_BINDER_EXCEPTION(libInterface->createEffectFunc(&in_impl_uuid, &effectSp)); - if (!effectSp) { - LOG(ERROR) << __func__ << ": library created null instance without return error!"; - return ndk::ScopedAStatus::fromExceptionCode(EX_TRANSACTION_FAILED); - } - *_aidl_return = effectSp; - ndk::SpAIBinder effectBinder = effectSp->asBinder(); - AIBinder_setMinSchedulerPolicy(effectBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO); - AIBinder_setInheritRt(effectBinder.get(), true); - mEffectMap[std::weak_ptr(effectSp)] = - std::make_pair(in_impl_uuid, std::move(effectBinder)); - LOG(DEBUG) << __func__ << ": UUID " << toString(in_impl_uuid) << ": instance " - << effectSp.get() << " created successfully"; - return ndk::ScopedAStatus::ok(); - } else { - LOG(ERROR) << __func__ << ": library doesn't exist for uuid" << toString(in_impl_uuid); - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus Factory::destroyEffectImpl_l(const std::shared_ptr& in_handle) { - std::weak_ptr wpHandle(in_handle); - // find the effect entry with key (std::weak_ptr) - if (auto effectIt = mEffectMap.find(wpHandle); effectIt != mEffectMap.end()) { - auto& uuid = effectIt->second.first; - // find implementation library with UUID - if (auto libIt = mEffectLibMap.find(uuid); libIt != mEffectLibMap.end()) { - auto& interface = std::get(libIt->second); - RETURN_IF(!interface || !interface->destroyEffectFunc, EX_NULL_POINTER, - "dlNulldestroyEffectFunc"); - RETURN_IF_BINDER_EXCEPTION(interface->destroyEffectFunc(in_handle)); - } else { - LOG(ERROR) << __func__ << ": UUID " << uuid.toString() << " does not exist in libMap!"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } - mEffectMap.erase(effectIt); - return ndk::ScopedAStatus::ok(); - } else { - LOG(ERROR) << __func__ << ": instance " << in_handle << " does not exist!"; - return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT); - } -} - -// go over the map and cleanup all expired weak_ptrs. -void Factory::cleanupEffectMap_l() { - for (auto it = mEffectMap.begin(); it != mEffectMap.end();) { - if (nullptr == it->first.lock()) { - it = mEffectMap.erase(it); - } else { - ++it; - } - } -} - -ndk::ScopedAStatus Factory::destroyEffect(const std::shared_ptr& in_handle) { - LOG(DEBUG) << __func__ << ": instance " << in_handle.get(); - std::lock_guard lg(mMutex); - ndk::ScopedAStatus status = destroyEffectImpl_l(in_handle); - // always do the cleanup - cleanupEffectMap_l(); - return status; -} - -bool Factory::openEffectLibrary(const AudioUuid& impl, - const std::string& path) NO_THREAD_SAFETY_ANALYSIS { - std::function dlClose = [](void* handle) -> void { - if (handle && dlclose(handle)) { - LOG(ERROR) << " dlclose failed " << dlerror(); - } - }; - - auto libHandle = - std::unique_ptr{dlopen(path.c_str(), RTLD_LAZY), dlClose}; - if (!libHandle) { - LOG(ERROR) << __func__ << ": dlopen failed, err: " << dlerror(); - return false; - } - - LOG(VERBOSE) << __func__ << " dlopen lib: " << path.c_str() << " Impl " << toString(impl) - << " handle:" << libHandle; - auto interface = new effect_dl_interface_s{nullptr, nullptr, nullptr}; - mEffectLibMap.insert( - {impl, - std::make_tuple(std::move(libHandle), - std::unique_ptr(interface), path)}); - return true; -} - -void Factory::createIdentityWithConfig( - const EffectConfig::Library& configLib, const AudioUuid& typeUuid, - const std::optional proxyUuid) NO_THREAD_SAFETY_ANALYSIS { - static const auto& libMap = mConfig.getLibraryMap(); - const std::string& libName = configLib.name; - if (auto path = libMap.find(libName); path != libMap.end()) { - Descriptor::Identity id; - id.type = typeUuid; - id.uuid = configLib.uuid; - id.proxy = proxyUuid; - LOG(VERBOSE) << __func__ << " loading lib " << path->second << ": typeUuid " - << toString(id.type) << " implUuid " << toString(id.uuid) << " proxyUuid " - << (proxyUuid.has_value() ? toString(proxyUuid.value()) : "null"); - if (openEffectLibrary(id.uuid, path->second)) { - mIdentitySet.insert(std::move(id)); - } - } else { - LOG(ERROR) << __func__ << ": library " << libName << " does not exist!"; - } -} - -void Factory::loadEffectLibs() { - const auto& configEffectsMap = mConfig.getEffectsMap(); - for (const auto& configEffects : configEffectsMap) { - if (AudioUuid type; EffectConfig::findUuid(configEffects /* xml effect */, &type)) { - const auto& configLibs = configEffects.second; - std::optional proxyUuid; - if (configLibs.proxyLibrary.has_value()) { - const auto& proxyLib = configLibs.proxyLibrary.value(); - proxyUuid = proxyLib.uuid; - } - for (const auto& configLib : configLibs.libraries) { - createIdentityWithConfig(configLib, type, proxyUuid); - } - } else { - LOG(ERROR) << __func__ << ": can not find type UUID for effect " << configEffects.first - << " skipping!"; - } - } -} - -void Factory::getDlSyms_l(DlEntry& entry) { - auto& dlHandle = std::get(entry); - RETURN_VALUE_IF(!dlHandle, void(), "dlNullHandle"); - // Get the reference of the DL interfaces in library map tuple. - auto& dlInterface = std::get(entry); - // return if interface already exists - if (!dlInterface->createEffectFunc) { - dlInterface->createEffectFunc = (EffectCreateFunctor)dlsym(dlHandle.get(), "createEffect"); - } - if (!dlInterface->queryEffectFunc) { - dlInterface->queryEffectFunc = (EffectQueryFunctor)dlsym(dlHandle.get(), "queryEffect"); - } - if (!dlInterface->destroyEffectFunc) { - dlInterface->destroyEffectFunc = - (EffectDestroyFunctor)dlsym(dlHandle.get(), "destroyEffect"); - } - - if (!dlInterface->createEffectFunc || !dlInterface->destroyEffectFunc || - !dlInterface->queryEffectFunc) { - LOG(ERROR) << __func__ << ": create (" << dlInterface->createEffectFunc << "), query (" - << dlInterface->queryEffectFunc << "), or destroy (" - << dlInterface->destroyEffectFunc - << ") not exist in library: " << std::get(entry) - << " handle: " << dlHandle << " with dlerror: " << dlerror(); - } -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectImpl.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectImpl.cpp deleted file mode 100755 index 4f19a7f9..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectImpl.cpp +++ /dev/null @@ -1,395 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_EffectImplQti" - -#include "effect-impl/EffectImpl.h" -#include -#include "effect-impl/EffectTypes.h" -#include "include/effect-impl/EffectTypes.h" - -using aidl::android::hardware::audio::effect::IEffect; -using aidl::android::hardware::audio::effect::kEventFlagDataMqNotEmpty; -using aidl::android::hardware::audio::effect::kReopenSupportedVersion; -using aidl::android::hardware::audio::effect::State; -using aidl::android::media::audio::common::PcmType; -using ::android::hardware::EventFlag; -using ::aidl::android::hardware::audio::effect::kEventFlagNotEmpty; - -extern "C" binder_exception_t destroyEffect(const std::shared_ptr& instanceSp) { - State state; - ndk::ScopedAStatus status = instanceSp->getState(&state); - if (!status.isOk() || State::INIT != state) { - LOG(ERROR) << __func__ << " instance " << instanceSp.get() - << " in state: " << toString(state) << ", status: " << status.getDescription(); - return EX_ILLEGAL_STATE; - } - LOG(VERBOSE) << __func__ << " instance " << instanceSp.get() << " destroyed"; - return EX_NONE; -} - -namespace aidl::qti::effects { - -ndk::ScopedAStatus EffectImpl::open(const Parameter::Common& common, - const std::optional& specific, - OpenEffectReturn* ret) { - LOG(DEBUG) << getEffectName() << " " << __func__ << " sessionId " << common.session - << " ioHandle " << common.ioHandle; - // effect only support 32bits float - RETURN_IF(common.input.base.format.pcm != common.output.base.format.pcm || - common.input.base.format.pcm != PcmType::FLOAT_32_BIT, - EX_ILLEGAL_ARGUMENT, "dataMustBe32BitsFloat"); - std::lock_guard lg(mImplMutex); - RETURN_OK_IF(mState != State::INIT); - // check if the effects needs data processing or not, based on that init worker thread & FMQs - mProcessData = !isOffloadOrBypass(); - mImplContext = createContext(common, mProcessData); - RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext"); - - RETURN_IF(!getInterfaceVersion(&mVersion).isOk(), EX_UNSUPPORTED_OPERATION, - "FailedToGetInterfaceVersion"); - mImplContext->setVersion(mVersion); - mEventFlag = mImplContext->getStatusEventFlag(); - mDataMqNotEmptyEf = - mVersion >= kReopenSupportedVersion ? kEventFlagDataMqNotEmpty : kEventFlagNotEmpty; - - if (specific.has_value()) { - RETURN_IF_ASTATUS_NOT_OK(setParameterSpecific(specific.value()), "setSpecParamErr"); - } - - mState = State::IDLE; - - if (mProcessData) { - mEventFlag = mImplContext->getStatusEventFlag(); - mImplContext->dupeFmq(ret); - RETURN_IF(createThread(getEffectName()) != RetCode::SUCCESS, EX_UNSUPPORTED_OPERATION, - "FailedToCreateWorker"); - } else { - LOG(VERBOSE) << __func__ << " " << getEffectName() << " effect does not process data"; - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus EffectImpl::reopen(OpenEffectReturn* ret) { - std::lock_guard lg(mImplMutex); - RETURN_IF(mState == State::INIT, EX_ILLEGAL_STATE, "alreadyClosed"); - - LOG(DEBUG) << getEffectName() << " " << __func__; - // TODO: add reopen implementation - RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext"); - mImplContext->dupeFmqWithReopen(ret); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus EffectImpl::close() { - { - std::lock_guard lg(mImplMutex); - RETURN_OK_IF(mState == State::INIT); - RETURN_IF(mState == State::PROCESSING, EX_ILLEGAL_STATE, "closeAtProcessing"); - mState = State::INIT; - } - - RETURN_IF(notifyEventFlag(mDataMqNotEmptyEf) != RetCode::SUCCESS, EX_ILLEGAL_STATE, - "notifyEventFlagFailed"); - // stop the worker thread, ignore the return code - RETURN_IF(destroyThread() != RetCode::SUCCESS, EX_UNSUPPORTED_OPERATION, - "FailedToDestroyWorker"); - - { - std::lock_guard lg(mImplMutex); - releaseContext(); - mImplContext.reset(); - } - - LOG(DEBUG) << getEffectName() << " " << __func__; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus EffectImpl::setParameter(const Parameter& param) { - std::lock_guard lg(mImplMutex); - LOG(VERBOSE) << getEffectName() << __func__ << " with: " << param.toString(); - - const auto& tag = param.getTag(); - switch (tag) { - case Parameter::common: - case Parameter::deviceDescription: - case Parameter::mode: - case Parameter::source: - case Parameter::offload: - FALLTHROUGH_INTENDED; - case Parameter::volumeStereo: - return setParameterCommon(param); - case Parameter::specific: { - return setParameterSpecific(param.get()); - } - default: { - LOG(DEBUG) << getEffectName() << " " << __func__ << " unsupportedParameterTag " - << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "ParameterNotSupported"); - } - } -} - -ndk::ScopedAStatus EffectImpl::getParameter(const Parameter::Id& id, Parameter* param) { - std::lock_guard lg(mImplMutex); - LOG(VERBOSE) << getEffectName() << " " << __func__ << id.toString(); - auto tag = id.getTag(); - switch (tag) { - case Parameter::Id::commonTag: { - RETURN_IF_ASTATUS_NOT_OK(getParameterCommon(id.get(), param), - "CommonParamNotSupported"); - break; - } - case Parameter::Id::vendorEffectTag: - FALLTHROUGH_INTENDED; - default: { - Parameter::Specific specific; - RETURN_IF_ASTATUS_NOT_OK(getParameterSpecific(id, &specific), "SpecParamNotSupported"); - param->set(specific); - break; - } - } - LOG(VERBOSE) << getEffectName() << __func__ << id.toString() << param->toString(); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus EffectImpl::setParameterCommon(const Parameter& param) { - RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext"); - - const auto& tag = param.getTag(); - - LOG(VERBOSE) << getEffectName() << __func__ << param.toString(); - switch (tag) { - case Parameter::common: - RETURN_IF(mImplContext->setCommon(param.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setCommFailed"); - break; - case Parameter::deviceDescription: - RETURN_IF(mImplContext->setOutputDevice(param.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setDeviceFailed"); - break; - case Parameter::mode: - RETURN_IF(mImplContext->setAudioMode(param.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setModeFailed"); - break; - case Parameter::source: - RETURN_IF(mImplContext->setAudioSource(param.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setSourceFailed"); - break; - case Parameter::volumeStereo: - RETURN_IF(mImplContext->setVolumeStereo(param.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setVolumeStereoFailed"); - break; - case Parameter::offload: - RETURN_IF(mImplContext->setOffload(param.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setOffloadError"); - break; - default: { - LOG(DEBUG) << getEffectName() << " " << __func__ << " unsupportedParameterTag " - << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "commonParamNotSupported"); - } - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus EffectImpl::getParameterCommon(const Parameter::Tag& tag, Parameter* param) { - RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext"); - - switch (tag) { - case Parameter::common: { - param->set(mImplContext->getCommon()); - break; - } - case Parameter::deviceDescription: { - param->set(mImplContext->getOutputDevice()); - break; - } - case Parameter::mode: { - param->set(mImplContext->getAudioMode()); - break; - } - case Parameter::source: { - param->set(mImplContext->getAudioSource()); - break; - } - case Parameter::volumeStereo: { - param->set(mImplContext->getVolumeStereo()); - break; - } - default: { - LOG(DEBUG) << getEffectName() << " " << __func__ << " unsupported tag " - << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "tagNotSupported"); - } - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus EffectImpl::getState(State* state) { - *state = mState; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus EffectImpl::command(CommandId command) { - std::lock_guard lg(mImplMutex); - RETURN_IF(mState == State::INIT, EX_ILLEGAL_STATE, "instanceNotOpen"); - LOG(DEBUG) << getEffectName() << " " << __func__ << ": receive command: " << toString(command) - << " at state " << toString(mState); - - switch (command) { - case CommandId::START: - RETURN_OK_IF(mState == State::PROCESSING); - RETURN_IF_ASTATUS_NOT_OK(commandImpl(command), "commandImplFailed"); - mState = State::PROCESSING; - RETURN_IF(notifyEventFlag(mDataMqNotEmptyEf) != RetCode::SUCCESS, EX_ILLEGAL_STATE, - "notifyEventFlagFailed"); - startThread(); - break; - case CommandId::STOP: - case CommandId::RESET: - RETURN_OK_IF(mState == State::IDLE); - mState = State::IDLE; - RETURN_IF(notifyEventFlag(mDataMqNotEmptyEf) != RetCode::SUCCESS, EX_ILLEGAL_STATE, - "notifyEventFlagFailed"); - stopThread(); - RETURN_IF_ASTATUS_NOT_OK(commandImpl(command), "commandImplFailed"); - break; - default: - LOG(DEBUG) << getEffectName() << " " << __func__ << " instance still processing"; - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "CommandIdNotSupported"); - } - LOG(DEBUG) << getEffectName() << " " << __func__ << " transfer to state: " << toString(mState); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus EffectImpl::commandImpl(CommandId command) { - RETURN_IF(!mImplContext, EX_NULL_POINTER, "nullContext"); - if (command == CommandId::RESET) { - mImplContext->resetBuffer(); - } - return ndk::ScopedAStatus::ok(); -} - -std::shared_ptr EffectImpl::createContext(const Parameter::Common& common, - bool processData) { - return std::make_shared(common, processData); -} - -RetCode EffectImpl::releaseContext() { - if (mImplContext) { - mImplContext.reset(); - } - return RetCode::SUCCESS; -} - -void EffectImpl::cleanUp() { - command(CommandId::STOP); - close(); -} - -RetCode EffectImpl::notifyEventFlag(uint32_t flag) { - if (!mProcessData) { - return RetCode::SUCCESS; - } - - if (!mEventFlag) { - LOG(ERROR) << getEffectName() << __func__ << ": StatusEventFlag invalid"; - return RetCode::ERROR_EVENT_FLAG_ERROR; - } - if (const auto ret = mEventFlag->wake(flag); ret != ::android::OK) { - LOG(ERROR) << getEffectName() << __func__ << ": wake failure with ret " << ret; - return RetCode::ERROR_EVENT_FLAG_ERROR; - } - return RetCode::SUCCESS; -} - -IEffect::Status EffectImpl::status(binder_status_t status, size_t consumed, size_t produced) { - IEffect::Status ret; - ret.status = status; - ret.fmqConsumed = consumed; - ret.fmqProduced = produced; - return ret; -} - -void EffectImpl::process() { - // ATRACE_CALL(); - /** - * wait for the EventFlag without lock, it's ok because the mEfGroup pointer will not change - * in the life cycle of workerThread (threadLoop). - */ - uint32_t efState = 0; - if (!mEventFlag || - ::android::OK != mEventFlag->wait(mDataMqNotEmptyEf, &efState, 0 /* no timeout */, - true /* retry */) || - !(efState & mDataMqNotEmptyEf)) { - LOG(ERROR) << getEffectName() << __func__ << ": StatusEventFlag - " << mEventFlag - << " efState - " << std::hex << efState; - return; - } - - { - std::lock_guard lg(mImplMutex); - if (mState != State::PROCESSING) { - LOG(DEBUG) << getEffectName() << " skip process in state: " << toString(mState); - return; - } - RETURN_VALUE_IF(!mImplContext, void(), "nullContext"); - auto statusMQ = mImplContext->getStatusFmq(); - auto inputMQ = mImplContext->getInputDataFmq(); - auto outputMQ = mImplContext->getOutputDataFmq(); - auto buffer = mImplContext->getWorkBuffer(); - if (!inputMQ || !outputMQ) { - return; - } - - assert(mImplContext->getWorkBufferSize() >= - std::max(inputMQ->availableToRead(), outputMQ->availableToWrite())); - auto processSamples = std::min(inputMQ->availableToRead(), outputMQ->availableToWrite()); - if (processSamples) { - inputMQ->read(buffer, processSamples); - IEffect::Status status = effectProcessImpl(buffer, buffer, processSamples); - outputMQ->write(buffer, status.fmqProduced); - statusMQ->writeBlocking(&status, 1); - LOG(VERBOSE) << getEffectName() << __func__ << ": done processing, effect consumed " - << status.fmqConsumed << " produced " << status.fmqProduced; - } - } -} - -// A placeholder processing implementation to copy samples from input to output -IEffect::Status EffectImpl::effectProcessImpl(float* in, float* out, int samples) { - for (int i = 0; i < samples; i++) { - *out++ = *in++; - } - LOG(VERBOSE) << getEffectName() << __func__ << " done processing " << samples << " samples"; - return {STATUS_OK, samples, samples}; -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectMain.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectMain.cpp deleted file mode 100755 index f9b01038..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectMain.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_EffectMainQti" - -#include "effectFactory-impl/EffectFactory.h" - -#include -#include -#include -#include -#include - -// { SEC_AUDIO_SUPPORT_AIDL_EFFECT -#include -// } SEC_AUDIO_SUPPORT_AIDL_EFFECT - -#ifdef SEC_AUDIO_SUPPORT_AIDL_EFFECT -static const char* kDefaultConfigName = "audio_effects_config_sec.xml"; -#else -/** Default name of effect configuration file. */ -static const char* kDefaultConfigName = "audio_effects_config.xml"; -#endif -static const char* kStubConfigName = "audio_effects_config_stub.xml"; - -static inline std::string getEffectConfig() { - auto stubmode = ::android::base::GetIntProperty("vendor.audio.hal.stubmode", 0); - if (stubmode) { - LOG(INFO) << __func__ << " using effects in stub mode"; - return android::audio_find_readable_configuration_file(kStubConfigName); - } - - return android::audio_find_readable_configuration_file(kDefaultConfigName); -} - -extern "C" __attribute__((visibility("default"))) binder_status_t registerService() { - auto configFile = getEffectConfig(); - if (configFile == "") { - LOG(ERROR) << __func__ << ": config file " << kDefaultConfigName << " not found!"; - return EXIT_FAILURE; - } - LOG(INFO) << __func__ << ": start factory with configFile:" << configFile; - auto effectFactory = ndk::SharedRefBase::make(configFile); - int version = 0; - effectFactory->getInterfaceVersion(&version); - std::string serviceName = std::string() + effectFactory->descriptor + "/default"; - binder_status_t status = - AServiceManager_addService(effectFactory->asBinder().get(), serviceName.c_str()); - LOG(DEBUG) << __func__ << " " << serviceName << " version " << version << " status " << status; - return status; -} diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectThread.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectThread.cpp deleted file mode 100755 index c1dc9f8d..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/EffectThread.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#include - -#define LOG_TAG "AHAL_EffectThreadQti" -#include -#include -#include - -#include "effect-impl/EffectThread.h" -#include "effect-impl/EffectTypes.h" - -using ::android::hardware::EventFlag; -using ::aidl::android::hardware::audio::effect::kEventFlagNotEmpty; -namespace aidl::qti::effects { - -#define RET_SUCCESS_IF_THREAD_NOT_CREATED(threadCreated) \ - { \ - if (!threadCreated) { \ - LOG(VERBOSE) << __func__ << " no-op as thread wasn't created "; \ - return RetCode::SUCCESS; \ - } \ - } - -EffectThread::EffectThread() { - LOG(VERBOSE) << __func__ << this; -} - -EffectThread::~EffectThread() { - destroyThread(); - LOG(VERBOSE) << __func__ << " done" << this; -} -RetCode EffectThread::createThread(const std::string& name, int priority) { - if (mThread.joinable()) { - LOG(WARNING) << mName << __func__ << " thread already created, no-op"; - return RetCode::SUCCESS; - } - mName = name; - mPriority = priority; - { - std::lock_guard lg(mThreadMutex); - mStop = true; - mExit = false; - } - - mThread = std::thread(&EffectThread::threadLoop, this); - mThreadCreated = true; - LOG(VERBOSE) << mName << __func__ << " priority " << mPriority << " done"; - return RetCode::SUCCESS; -} - -RetCode EffectThread::destroyThread() { - RET_SUCCESS_IF_THREAD_NOT_CREATED(mThreadCreated); - - { - std::lock_guard lg(mThreadMutex); - mStop = mExit = true; - } - mCv.notify_one(); - - if (mThread.joinable()) { - mThread.join(); - } - - LOG(DEBUG) << mName << __func__; - return RetCode::SUCCESS; -} - -RetCode EffectThread::startThread() { - RET_SUCCESS_IF_THREAD_NOT_CREATED(mThreadCreated); - - { - std::lock_guard lg(mThreadMutex); - mStop = false; - mCv.notify_one(); - } - - LOG(DEBUG) << mName << __func__; - return RetCode::SUCCESS; -} - -RetCode EffectThread::stopThread() { - RET_SUCCESS_IF_THREAD_NOT_CREATED(mThreadCreated); - - { - std::lock_guard lg(mThreadMutex); - mStop = true; - mCv.notify_one(); - } - - LOG(DEBUG) << mName << __func__; - return RetCode::SUCCESS; -} - -void EffectThread::threadLoop() { - pthread_setname_np(pthread_self(), mName.substr(0, kMaxTaskNameLen - 1).c_str()); - setpriority(PRIO_PROCESS, 0, mPriority); - LOG(VERBOSE) << mName << __func__ << "Enter: "; - while (true) { - { - std::unique_lock l(mThreadMutex); - ::android::base::ScopedLockAssertion lock_assertion(mThreadMutex); - mCv.wait(l, [&]() REQUIRES(mThreadMutex) { return mExit || !mStop; }); - if (mExit) { - LOG(VERBOSE) << " " << mName << __func__ << " EXIT!"; - return; - } - } - process(); - } -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/audioeffectservice_qti.xml b/qcom/opensource/audio-hal/primary-hal/hal/effects/audioeffectservice_qti.xml deleted file mode 100755 index c3cfe7e6..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/audioeffectservice_qti.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - android.hardware.audio.effect - 2 - IFactory/default - - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectContext.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectContext.h deleted file mode 100755 index 1275fa68..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectContext.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once -#include -#include - -#include -#include -#include -#include - -#include -#include "EffectTypes.h" - -using aidl::android::hardware::audio::effect::IEffect; -using aidl::android::hardware::audio::effect::Parameter; - -namespace aidl::qti::effects { -class EffectContext { - public: - typedef ::android::AidlMessageQueue< - IEffect::Status, ::aidl::android::hardware::common::fmq::SynchronizedReadWrite> - StatusMQ; - typedef ::android::AidlMessageQueue< - float, ::aidl::android::hardware::common::fmq::SynchronizedReadWrite> - DataMQ; - - EffectContext(const Parameter::Common& common, bool processData); - - void initMessageQueues(bool processData); - virtual ~EffectContext(); - - void setVersion(int version) { mVersion = version; } - std::shared_ptr getStatusFmq() const; - std::shared_ptr getInputDataFmq() const; - std::shared_ptr getOutputDataFmq() const; - - float* getWorkBuffer(); - size_t getWorkBufferSize() const; - - // reset buffer status by abandon input data in FMQ - void resetBuffer(); - void dupeFmq(IEffect::OpenEffectReturn* effectRet); - size_t getInputFrameSize() const; - size_t getOutputFrameSize() const; - int getSessionId() const; - int getIoHandle() const; - - virtual void dupeFmqWithReopen(IEffect::OpenEffectReturn* effectRet); - - virtual RetCode setOutputDevice( - const std::vector& device); - - virtual std::vector - getOutputDevice(); - - virtual RetCode setAudioMode(const aidl::android::media::audio::common::AudioMode& mode); - virtual aidl::android::media::audio::common::AudioMode getAudioMode(); - - virtual RetCode setAudioSource(const aidl::android::media::audio::common::AudioSource& source); - virtual aidl::android::media::audio::common::AudioSource getAudioSource(); - - virtual RetCode setVolumeStereo(const Parameter::VolumeStereo& volumeStereo); - virtual Parameter::VolumeStereo getVolumeStereo(); - - virtual RetCode setCommon(const Parameter::Common& common); - virtual Parameter::Common getCommon(); - - virtual ::android::hardware::EventFlag* getStatusEventFlag(); - - virtual RetCode setOffload(bool offload); - - protected: - int mVersion = 0; - size_t mInputFrameSize = 0; - size_t mOutputFrameSize = 0; - size_t mInputChannelCount = 0; - size_t mOutputChannelCount = 0; - Parameter::Common mCommon = {}; - std::vector mOutputDevice = {}; - aidl::android::media::audio::common::AudioMode mMode = - aidl::android::media::audio::common::AudioMode::SYS_RESERVED_INVALID; - aidl::android::media::audio::common::AudioSource mSource = - aidl::android::media::audio::common::AudioSource::SYS_RESERVED_INVALID; - Parameter::VolumeStereo mVolumeStereo = {}; - RetCode updateIOFrameSize(const Parameter::Common& common); - RetCode notifyDataMqUpdate(); - - bool mOffload; - - private: - // fmq and buffers - bool mProcessData; - std::shared_ptr mStatusMQ = nullptr; - std::shared_ptr mInputMQ = nullptr; - std::shared_ptr mOutputMQ = nullptr; - // TODO handle effect process input and output - // work buffer set by effect instances, the access and update are in same thread - std::vector mWorkBuffer = {}; - - ::android::hardware::EventFlag* mEfGroup = nullptr; -}; -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectImpl.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectImpl.h deleted file mode 100755 index f9bd03fa..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectImpl.h +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once -#include -#include - -#include -#include - -#include "EffectContext.h" -#include "EffectThread.h" -#include "EffectTypes.h" -#include "effect-impl/EffectContext.h" -#include "effect-impl/EffectThread.h" -#include "effect-impl/EffectTypes.h" - -extern "C" binder_exception_t destroyEffect( - const std::shared_ptr& instanceSp); - -using aidl::android::hardware::audio::effect::IEffect; -using aidl::android::hardware::audio::effect::BnEffect; -using aidl::android::hardware::audio::effect::Parameter; -using aidl::android::hardware::audio::effect::CommandId; -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::android::hardware::audio::effect::State; -using aidl::android::hardware::audio::effect::Flags; - -namespace aidl::qti::effects { - -class EffectImpl : public BnEffect, public EffectThread { - public: - EffectImpl() = default; - virtual ~EffectImpl() = default; - - virtual ndk::ScopedAStatus open(const Parameter::Common& common, - const std::optional& specific, - OpenEffectReturn* ret) override; - virtual ndk::ScopedAStatus close() override; - virtual ndk::ScopedAStatus command(CommandId id) override; - virtual ndk::ScopedAStatus reopen(OpenEffectReturn* ret) override; - - virtual ndk::ScopedAStatus getState(State* state) override; - virtual ndk::ScopedAStatus setParameter(const Parameter& param) override; - virtual ndk::ScopedAStatus getParameter(const Parameter::Id& id, Parameter* param) override; - - virtual ndk::ScopedAStatus setParameterCommon(const Parameter& param); - virtual ndk::ScopedAStatus getParameterCommon(const Parameter::Tag& tag, Parameter* param); - - /* Methods MUST be implemented by each effect instances */ - virtual ndk::ScopedAStatus getDescriptor(Descriptor* desc) = 0; - virtual ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) = 0; - virtual ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, - Parameter::Specific* specific) = 0; - - virtual std::string getEffectName() = 0; - virtual std::shared_ptr createContext(const Parameter::Common& common, - bool processData); - - virtual RetCode releaseContext() = 0; - - /** - * @brief effectProcessImpl is running in worker thread which created in EffectThread. - * - * EffectThread will make sure effectProcessImpl only be called after startThread() successful - * and before stopThread() successful. - * - * effectProcessImpl implementation must not call any EffectThread interface, otherwise it will - * cause deadlock. - * - * @param in address of input float buffer. - * @param out address of output float buffer. - * @param samples number of samples to process. - * @return IEffect::Status - */ - virtual IEffect::Status effectProcessImpl(float* in, float* out, int samples); - - /** - * process() get data from data MQs, and call effectProcessImpl() for effect data processing. - * Its important for the implementation to use mImplMutex for context synchronization. - */ - void process() override; - - protected: - // current Hal version - int mVersion = 0; - // Use kEventFlagNotEmpty for V1 HAL, kEventFlagDataMqNotEmpty for V2 and above - int mDataMqNotEmptyEf = aidl::android::hardware::audio::effect::kEventFlagDataMqNotEmpty; - State mState = State::INIT; - const Descriptor* mDescriptor; - const std::string* mEffectName; - - IEffect::Status status(binder_status_t status, size_t consumed, size_t produced); - void cleanUp(); - - std::mutex mImplMutex; - std::shared_ptr mImplContext; - - /** - * Optional CommandId handling methods for effects to override. - * For CommandId::START, EffectImpl call commandImpl before starting the EffectThread - * processing. - * For CommandId::STOP and CommandId::RESET, EffectImpl call commandImpl after stop the - * EffectThread processing. - */ - virtual ndk::ScopedAStatus commandImpl(CommandId id); - - RetCode notifyEventFlag(uint32_t flag); - - // used with data processing. - ::android::hardware::EventFlag* mEventFlag; - - private: - bool mProcessData = false; - bool isOffloadOrBypass() { - return (mDescriptor->common.flags.hwAcceleratorMode == Flags::HardwareAccelerator::TUNNEL || - mDescriptor->common.flags.bypass); - } -}; -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectRange.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectRange.h deleted file mode 100755 index 5855b362..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectRange.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2023 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. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include - -namespace aidl::qti::effects { - -template -bool isInRange(const T& value, const T& low, const T& high) { - return (value >= low) && (value <= high); -} - -template -bool isTupleInRange(const T& test, const T& min, const T& max, std::index_sequence) { - return (isInRange(std::get(test), std::get(min), std::get(max)) && ...); -} - -template > -bool isTupleInRange(const T& test, const T& min, const T& max) { - return isTupleInRange(test, min, max, std::make_index_sequence{}); -} - -template -bool isTupleInRange(const std::vector& cfgs, const T& min, const T& max, const F& func) { - auto minT = func(min), maxT = func(max); - return std::all_of(cfgs.cbegin(), cfgs.cend(), - [&](const T& cfg) { return isTupleInRange(func(cfg), minT, maxT); }); -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectThread.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectThread.h deleted file mode 100755 index bbf4750a..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectThread.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once -#include -#include -#include -#include - -#include -#include -#include - -#include "effect-impl/EffectContext.h" -#include "effect-impl/EffectTypes.h" - -namespace aidl::qti::effects { - -class EffectThread { - public: - // default priority is same as HIDL: ANDROID_PRIORITY_URGENT_AUDIO - EffectThread(); - virtual ~EffectThread(); - - // called by effect implementation. - RetCode createThread(const std::string& name, int priority = ANDROID_PRIORITY_URGENT_AUDIO); - RetCode destroyThread(); - RetCode startThread(); - RetCode stopThread(); - - // Will call process() in a loop if the thread is running. - void threadLoop(); - - /** - * process() call effectProcessImpl() for effect data processing, it is necessary for the - * processing to be called under Effect thread mutex mThreadMutex, to avoid the effect state - * change before/during data processing, and keep the thread and effect state consistent. - */ - virtual void process() = 0; - - private: - static constexpr int kMaxTaskNameLen = 15; - - std::mutex mThreadMutex; - std::condition_variable mCv; - bool mStop GUARDED_BY(mThreadMutex) = true; - bool mExit GUARDED_BY(mThreadMutex) = false; - std::thread mThread; - int mPriority; - std::string mName; - bool mThreadCreated = false; -}; -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectTypes.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectTypes.h deleted file mode 100755 index 9f54d4f7..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectTypes.h +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once -#include - -#include -#include -#include -#include - -typedef binder_exception_t (*EffectCreateFunctor)( - const ::aidl::android::media::audio::common::AudioUuid*, - std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>*); -typedef binder_exception_t (*EffectDestroyFunctor)( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>&); -typedef binder_exception_t (*EffectQueryFunctor)( - const ::aidl::android::media::audio::common::AudioUuid*, - ::aidl::android::hardware::audio::effect::Descriptor*); - -struct effect_dl_interface_s { - EffectCreateFunctor createEffectFunc; - EffectDestroyFunctor destroyEffectFunc; - EffectQueryFunctor queryEffectFunc; -}; - -namespace aidl::qti::effects { - -enum class RetCode { - SUCCESS, - ERROR_ILLEGAL_PARAMETER, /* Illegal parameter */ - ERROR_THREAD, /* Effect thread error */ - ERROR_NULL_POINTER, /* NULL pointer */ - ERROR_ALIGNMENT_ERROR, /* Memory alignment error */ - ERROR_BLOCK_SIZE_EXCEED, /* Maximum block size exceeded */ - ERROR_EFFECT_LIB_ERROR, /* Effect implementation library error */ - ERROR_EVENT_FLAG_ERROR /* Error with effect event flags */ -}; - -static const int INVALID_AUDIO_SESSION_ID = -1; - -inline std::ostream& operator<<(std::ostream& out, const RetCode& code) { - switch (code) { - case RetCode::SUCCESS: - return out << "SUCCESS"; - case RetCode::ERROR_ILLEGAL_PARAMETER: - return out << "ERROR_ILLEGAL_PARAMETER"; - case RetCode::ERROR_THREAD: - return out << "ERROR_THREAD"; - case RetCode::ERROR_NULL_POINTER: - return out << "ERROR_NULL_POINTER"; - case RetCode::ERROR_ALIGNMENT_ERROR: - return out << "ERROR_ALIGNMENT_ERROR"; - case RetCode::ERROR_BLOCK_SIZE_EXCEED: - return out << "ERROR_BLOCK_SIZE_EXCEED"; - case RetCode::ERROR_EFFECT_LIB_ERROR: - return out << "ERROR_EFFECT_LIB_ERROR"; - case RetCode::ERROR_EVENT_FLAG_ERROR: - return out << "ERROR_EVENT_FLAG_ERROR"; - } - - return out << "EnumError: " << code; -} - -#define RETURN_IF_ASTATUS_NOT_OK(status, message) \ - do { \ - const ::ndk::ScopedAStatus curr_status = (status); \ - if (!curr_status.isOk()) { \ - LOG(ERROR) << __func__ << ":" << __LINE__ \ - << "return with status: " << curr_status.getDescription() << (message); \ - return ndk::ScopedAStatus::fromExceptionCodeWithMessage( \ - curr_status.getExceptionCode(), (message)); \ - } \ - } while (0) - -#define RETURN_IF(expr, exception, message) \ - do { \ - if (expr) { \ - LOG(VERBOSE) << __func__ << ":" << __LINE__ << " return with expr " << #expr; \ - return ndk::ScopedAStatus::fromExceptionCodeWithMessage((exception), (message)); \ - } \ - } while (0) - -#define RETURN_OK_IF(expr) \ - do { \ - if (expr) { \ - LOG(VERBOSE) << __func__ << ":" << __LINE__ << " return with expr " << #expr; \ - return ndk::ScopedAStatus::ok(); \ - } \ - } while (0) - -#define RETURN_VALUE_IF(expr, ret, log) \ - do { \ - if (expr) { \ - LOG(ERROR) << __func__ << ":" << __LINE__ << " return with expr \"" << #expr \ - << "\":" << (log); \ - return ret; \ - } \ - } while (0) - -#define RETURN_IF_BINDER_EXCEPTION(functor) \ - { \ - binder_exception_t exception = functor; \ - if (EX_NONE != exception) { \ - LOG(ERROR) << #functor << ": failed with error " << exception; \ - return ndk::ScopedAStatus::fromExceptionCode(exception); \ - } \ - } - -/** - * Make a Range::$EffectType$Range. - * T: The $EffectType$, Visualizer for example. - * Tag: The union tag name in $EffectType$ definition, latencyMs for example. - * l: The value of Range::$EffectType$Range.min. - * r: The value of Range::$EffectType$Range.max. - */ -#define MAKE_RANGE(T, Tag, l, r) \ - { .min = T::make(l), .max = T::make(r) } - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectUUID.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectUUID.h deleted file mode 100755 index fdeb04fe..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effect-impl/EffectUUID.h +++ /dev/null @@ -1,464 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once -#include - -#include -#include - -namespace aidl::qti::effects { - -using ::aidl::android::media::audio::common::AudioUuid; - -static inline std::string toString(const AudioUuid& uuid) { - return ::android::base::StringPrintf("%08x-%04x-%04x-%04x-%02x%02x%02x%02x%02x%02x", - uuid.timeLow, uuid.timeMid, uuid.timeHiAndVersion, - uuid.clockSeq, uuid.node[0], uuid.node[1], uuid.node[2], - uuid.node[3], uuid.node[4], uuid.node[5]); -} - -// ec7178ec-e5e1-4432-a3f4-4657e6795210 -static const AudioUuid kEffectNullUuid = {static_cast(0xec7178ec), - 0xe5e1, - 0x4432, - 0xa3f4, - {0x46, 0x57, 0xe6, 0x79, 0x52, 0x10}}; -// Zero UUID -static const AudioUuid kEffectZeroUuid = { - static_cast(0x0), 0x0, 0x0, 0x0, {0x0, 0x0, 0x0, 0x0, 0x0, 0x0}}; - -// 7b491460-8d4d-11e0-bd61-0002a5d5c51b. -static const AudioUuid kAcousticEchoCancelerTypeUUID = {static_cast(0x7b491460), - 0x8d4d, - 0x11e0, - 0xbd61, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// bb392ec0-8d4d-11e0-a896-0002a5d5c51b -static const AudioUuid kAcousticEchoCancelerSwImplUUID = {static_cast(0xbb392ec0), - 0x8d4d, - 0x11e0, - 0xa896, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// 0a8abfe0-654c-11e0-ba26-0002a5d5c51b -static const AudioUuid kAutomaticGainControlV1TypeUUID = {static_cast(0x0a8abfe0), - 0x654c, - 0x11e0, - 0xba26, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// aa8130e0-66fc-11e0-bad0-0002a5d5c51b -static const AudioUuid kAutomaticGainControlV1SwImplUUID = {static_cast(0xaa8130e0), - 0x66fc, - 0x11e0, - 0xbad0, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// ae3c653b-be18-4ab8-8938-418f0a7f06ac -static const AudioUuid kAutomaticGainControlV2TypeUUID = {static_cast(0xae3c653b), - 0xbe18, - 0x4ab8, - 0x8938, - {0x41, 0x8f, 0x0a, 0x7f, 0x06, 0xac}}; -// 89f38e65-d4d2-4d64-ad0e-2b3e799ea886 -static const AudioUuid kAutomaticGainControlV2SwImplUUID = {static_cast(0x89f38e65), - 0xd4d2, - 0x4d64, - 0xad0e, - {0x2b, 0x3e, 0x79, 0x9e, 0xa8, 0x86}}; -// 0634f220-ddd4-11db-a0fc-0002a5d5c51b -static const AudioUuid kBassBoostTypeUUID = {static_cast(0x0634f220), - 0xddd4, - 0x11db, - 0xa0fc, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// fa8181f2-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kBassBoostSwImplUUID = {static_cast(0xfa8181f2), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// 8631f300-72e2-11df-b57e-0002a5d5c51b -static const AudioUuid kBassBoostBundleImplUUID = {static_cast(0x8631f300), - 0x72e2, - 0x11df, - 0xb57e, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// 14804144-a5ee-4d24-aa88-0002a5d5c51b -static const AudioUuid kBassBoostProxyUUID = {static_cast(0x14804144), - 0xa5ee, - 0x4d24, - 0xaa88, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// 381e49cc-a858-4aa2-87f6-e8388e7601b2 -static const AudioUuid kDownmixTypeUUID = {static_cast(0x381e49cc), - 0xa858, - 0x4aa2, - 0x87f6, - {0xe8, 0x38, 0x8e, 0x76, 0x01, 0xb2}}; -// fa8187ba-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kDownmixSwImplUUID = {static_cast(0xfa8187ba), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// 93f04452-e4fe-41cc-91f9-e475b6d1d69f -static const AudioUuid kDownmixImplUUID = {static_cast(0x93f04452), - 0xe4fe, - 0x41cc, - 0x91f9, - {0xe4, 0x75, 0xb6, 0xd1, 0xd6, 0x9f}}; -// 0bed4300-ddd6-11db-8f34-0002a5d5c51b. -static const AudioUuid kEqualizerTypeUUID = {static_cast(0x0bed4300), - 0xddd6, - 0x11db, - 0x8f34, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// 0bed4300-847d-11df-bb17-0002a5d5c51b -static const AudioUuid kEqualizerSwImplUUID = {static_cast(0x0bed4300), - 0x847d, - 0x11df, - 0xbb17, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// ce772f20-847d-11df-bb17-0002a5d5c51b -static const AudioUuid kEqualizerBundleImplUUID = {static_cast(0xce772f20), - 0x847d, - 0x11df, - 0xbb17, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// c8e70ecd-48ca-456e-8a4f-0002a5d5c51b -static const AudioUuid kEqualizerProxyUUID = {static_cast(0xc8e70ecd), - 0x48ca, - 0x456e, - 0x8a4f, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// 7261676f-6d75-7369-6364-28e2fd3ac39e -static const AudioUuid kDynamicsProcessingTypeUUID = {static_cast(0x7261676f), - 0x6d75, - 0x7369, - 0x6364, - {0x28, 0xe2, 0xfd, 0x3a, 0xc3, 0x9e}}; -// fa818d78-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kDynamicsProcessingSwImplUUID = {static_cast(0xfa818d78), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// e0e6539b-1781-7261-676f-6d7573696340 -static const AudioUuid kDynamicsProcessingImplUUID = {static_cast(0xe0e6539b), - 0x1781, - 0x7261, - 0x676f, - {0x6d, 0x75, 0x73, 0x69, 0x63, 0x40}}; -// 1411e6d6-aecd-4021-a1cf-a6aceb0d71e5 -static const AudioUuid kHapticGeneratorTypeUUID = {static_cast(0x1411e6d6), - 0xaecd, - 0x4021, - 0xa1cf, - {0xa6, 0xac, 0xeb, 0x0d, 0x71, 0xe5}}; -// fa819110-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kHapticGeneratorSwImplUUID = {static_cast(0xfa819110), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// 97c4acd1-8b82-4f2f-832e-c2fe5d7a9931 -static const AudioUuid kHapticGeneratorImplUUID = {static_cast(0x97c4acd1), - 0x8b82, - 0x4f2f, - 0x832e, - {0xc2, 0xfe, 0x5d, 0x7a, 0x99, 0x31}}; -// fe3199be-aed0-413f-87bb-11260eb63cf1 -static const AudioUuid kLoudnessEnhancerTypeUUID = {static_cast(0xfe3199be), - 0xaed0, - 0x413f, - 0x87bb, - {0x11, 0x26, 0x0e, 0xb6, 0x3c, 0xf1}}; -// fa819610-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kLoudnessEnhancerSwImplUUID = {static_cast(0xfa819610), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// fa415329-2034-4bea-b5dc-5b381c8d1e2c -static const AudioUuid kLoudnessEnhancerImplUUID = {static_cast(0xfa415329), - 0x2034, - 0x4bea, - 0xb5dc, - {0x5b, 0x38, 0x1c, 0x8d, 0x1e, 0x2c}}; -// c2e5d5f0-94bd-4763-9cac-4e234d06839e -static const AudioUuid kEnvReverbTypeUUID = {static_cast(0xc2e5d5f0), - 0x94bd, - 0x4763, - 0x9cac, - {0x4e, 0x23, 0x4d, 0x06, 0x83, 0x9e}}; -// fa819886-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kEnvReverbSwImplUUID = {static_cast(0xfa819886), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// 4a387fc0-8ab3-11df-8bad-0002a5d5c51b -static const AudioUuid kAuxEnvReverbImplUUID = {static_cast(0x4a387fc0), - 0x8ab3, - 0x11df, - 0x8bad, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// c7a511a0-a3bb-11df-860e-0002a5d5c51b -static const AudioUuid kInsertEnvReverbImplUUID = {static_cast(0xc7a511a0), - 0xa3bb, - 0x11df, - 0x860e, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// 58b4b260-8e06-11e0-aa8e-0002a5d5c51b -static const AudioUuid kNoiseSuppressionTypeUUID = {static_cast(0x58b4b260), - 0x8e06, - 0x11e0, - 0xaa8e, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// c06c8400-8e06-11e0-9cb6-0002a5d5c51b -static const AudioUuid kNoiseSuppressionSwImplUUID = {static_cast(0xc06c8400), - 0x8e06, - 0x11e0, - 0x9cb6, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// 47382d60-ddd8-11db-bf3a-0002a5d5c51b -static const AudioUuid kPresetReverbTypeUUID = {static_cast(0x47382d60), - 0xddd8, - 0x11db, - 0xbf3a, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// fa8199c6-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kPresetReverbSwImplUUID = {static_cast(0xfa8199c6), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// f29a1400-a3bb-11df-8ddc-0002a5d5c51b -static const AudioUuid kAuxPresetReverbImplUUID = {static_cast(0xf29a1400), - 0xa3bb, - 0x11df, - 0x8ddc, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// 172cdf00-a3bc-11df-a72f-0002a5d5c51b -static const AudioUuid kInsertPresetReverbImplUUID = {static_cast(0x172cdf00), - 0xa3bc, - 0x11df, - 0xa72f, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// 37cc2c00-dddd-11db-8577-0002a5d5c51b -static const AudioUuid kVirtualizerTypeUUID = {static_cast(0x37cc2c00), - 0xdddd, - 0x11db, - 0x8577, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// fa819d86-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kVirtualizerSwImplUUID = {static_cast(0xfa819d86), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// 1d4033c0-8557-11df-9f2d-0002a5d5c51b -static const AudioUuid kVirtualizerBundleImplUUID = {static_cast(0x1d4033c0), - 0x8557, - 0x11df, - 0x9f2d, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// d3467faa-acc7-4d34-acaf-0002a5d5c51b -static const AudioUuid kVirtualizerProxyUUID = {static_cast(0xd3467faa), - 0xacc7, - 0x4d34, - 0xacaf, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; -// fa819f3e-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kVisualizerTypeUUID = {static_cast(0xfa819f3e), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// fa81a0f6-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kVisualizerSwImplUUID = {static_cast(0xfa81a0f6), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// fa81a2b8-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kVolumeTypeUUID = {static_cast(0xfa81a2b8), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; - -// fa81a718-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kVolumeSwImplUUID = {static_cast(0xfa81a718), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// 119341a0-8469-11df-81f9-0002a5d5c51b -static const AudioUuid kVolumeBundleImplUUID = {static_cast(0x119341a0), - 0x8469, - 0x11df, - 0x81f9, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; - -static const AudioUuid kExtensionEffectTypeUUID = {static_cast(0xfa81dbde), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; -// fa81dd00-588b-11ed-9b6a-0242ac120002 -static const AudioUuid kExtensionEffectImplUUID = {static_cast(0xfa81dd00), - 0x588b, - 0x11ed, - 0x9b6a, - {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}}; - -// 08b8b058-0590-11e5-ac71-0025b32654a0 -static const AudioUuid kMusicVolumeListenerUUID = {static_cast(0x08b8b058), - 0x0590, - 0x11e5, - 0xac71, - {0x00, 0x25, 0xb3, 0x26, 0x54, 0xa0}}; - -// 0956df94-0590-11e5-bdbe-0025b32654a0 -static const AudioUuid kRingVolumeListenerUUID = {static_cast(0x0956df94), - 0x0590, - 0x11e5, - 0xbdbe, - {0x00, 0x25, 0xb3, 0x26, 0x54, 0xa0}}; - -// 09f303e2-0590-11e5-8fdb-0025b32654a0 -static const AudioUuid kAlarmVolumeListenerUUID = {static_cast(0x09f303e2), - 0x0590, - 0x11e5, - 0x8fdb, - {0x00, 0x25, 0xb3, 0x26, 0x54, 0xa0}}; - -// 0ace5c08-0590-11e5-ae9e-0025b32654a0 -static const AudioUuid kVoiceCallVolumeListenerUUID = {static_cast(0x0ace5c08), - 0x0590, - 0x11e5, - 0xae9e, - {0x00, 0x25, 0xb3, 0x26, 0x54, 0xa0}}; - -// 0b776dde-0590-11e5-81ba-0025b32654a0 -static const AudioUuid kNotificationVolumeListenerUUID = {static_cast(0x0b776dde), - 0x0590, - 0x11e5, - 0x81ba, - {0x00, 0x25, 0xb3, 0x26, 0x54, 0xa0}}; - -// 0f8d0d2a-59e5-45fe-b6e4-248c8a799109 -static const AudioUuid kAcousticEchoCancelerQtiUUID = {static_cast(0x0f8d0d2a), - 0x59e5, - 0x45fe, - 0xb6e4, - {0x24, 0x8c, 0x8a, 0x79, 0x91, 0x09}}; - -// 1d97bb0b-9e2f-4403-9ae3-58c2554306f8 -static const AudioUuid kNoiseSuppressionQtiUUID = {static_cast(0x1d97bb0b), - 0x9e2f, - 0x4403, - 0x9ae3, - {0x58, 0xc2, 0x55, 0x43, 0x06, 0xf8}}; - -// 7a8044a0-1a71-11e3-a184-0002a5d5c51b -static const AudioUuid kVisualizerOffloadQtiUUID = {static_cast(0x7a8044a0), - 0x1a71, - 0x11e3, - 0xa184, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; - -/* Offload bassboost UUID: 2c4a8c24-1581-487f-94f6-0002a5d5c51b */ -static const AudioUuid kBassBoostOffloadQtiUUID = {static_cast(0x2c4a8c24), - 0x1581, - 0x487f, - 0x94f6, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; - -/* Offload Equalizer UUID: a0dac280-401c-11e3-9379-0002a5d5c51b */ -static const AudioUuid kEqualizerOffloadQtiUUID = {static_cast(0xa0dac280), - 0x401c, - 0x11e3, - 0x9379, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; - -/* Offload virtualizer UUID: 2c4a8c24-1581-487f-94f6-0002a5d5c51b */ - -/* 509a4498-561a-4bea-b3b1-0002a5d5c51b*/ -static const AudioUuid kVirtualizerOffloadQtiUUID = {static_cast(0x509a4498), - 0x561a, - 0x4bea, - 0xb3b1, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; - -/* Offload auxiliary environmental reverb UUID: 79a18026-18fd-4185-8233-0002a5d5c51b */ -static const AudioUuid kAuxEnvReverbOffloadQtiUUID = {static_cast(0x79a18026), - 0x18fd, - 0x4185, - 0x8233, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; - -/* Offload insert environmental reverb UUID: eb64ea04-973b-43d2-8f5e-0002a5d5c51b */ -static const AudioUuid kInsertEnvReverbOffloadQtiUUID = {static_cast(0xeb64ea04), - 0x973b, - 0x43d2, - 0x8f5e, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; - -// Offload auxiliary preset reverb UUID: 6987be09-b142-4b41-9056-0002a5d5c51b */ -static const AudioUuid kAuxPresetReverbOffloadQtiUUID = {static_cast(0x6987be09), - 0xb142, - 0x4b41, - 0x9056, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; - -// Offload insert preset reverb UUID: aa2bebf6-47cf-4613-9bca-0002a5d5c51b */ -static const AudioUuid kInsertPresetReverbOffloadQtiUUID = {static_cast(0xaa2bebf6), - 0x47cf, - 0x4613, - 0x9bca, - {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}; - -// quasar UUID: 71d0e2ee-e44d-483d-a809-09e75ee55ecd */ -static const AudioUuid kQuasarEffectQtiUUID = {static_cast(0x71d0e2ee), - 0xe44d, - 0x483d, - 0xa809, - {0x09, 0xe7, 0x5e, 0xe5, 0x5e, 0xcd}}; - -/** - * @brief A map between effect name and effect type UUID. - * All attribution in effect/effectProxy of audio_effects.xml should be listed in this map. - * We need this map is because existing audio_effects.xml don't have a type UUID defined. - */ -static const std::map kUuidNameTypeMap = { - {"aec", kAcousticEchoCancelerTypeUUID}, // TODO aec vs AcousticEcho - {"agc", kAutomaticGainControlV1TypeUUID}, // TODO agc vs Automatic Gain - {"bassboost", kBassBoostTypeUUID}, - {"downmix", kDownmixTypeUUID}, - {"dynamics_processing", kDynamicsProcessingTypeUUID}, - {"equalizer", kEqualizerTypeUUID}, - {"haptic_generator", kHapticGeneratorTypeUUID}, - {"loudness_enhancer", kLoudnessEnhancerTypeUUID}, - {"env_reverb", kEnvReverbTypeUUID}, - {"ns", kNoiseSuppressionTypeUUID}, // TODO ns or noise_suppression - {"preset_reverb", kPresetReverbTypeUUID}, - {"reverb_env_aux", kEnvReverbTypeUUID}, - {"reverb_env_ins", kEnvReverbTypeUUID}, - {"reverb_pre_aux", kPresetReverbTypeUUID}, - {"reverb_pre_ins", kPresetReverbTypeUUID}, - {"virtualizer", kVirtualizerTypeUUID}, - {"visualizer", kVisualizerTypeUUID}, - {"volume", kVolumeTypeUUID}, - {"voice_helper", kVoiceCallVolumeListenerUUID}, - {"music_helper", kMusicVolumeListenerUUID}, - {"alarm_helper", kAlarmVolumeListenerUUID}, - {"ring_helper", kRingVolumeListenerUUID}, - {"notification_helper", kNotificationVolumeListenerUUID}, - // {"audiosphere", kNotificationVolumeListenerUUID}, - {"quasar", kQuasarEffectQtiUUID}, -}; - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effectFactory-impl/EffectConfig.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effectFactory-impl/EffectConfig.h deleted file mode 100755 index 67fa0d20..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effectFactory-impl/EffectConfig.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 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. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include "effect-impl/EffectTypes.h" -#include "effect-impl/EffectUUID.h" - -using aidl::android::hardware::audio::effect::getEffectTypeUuidAcousticEchoCanceler; -using aidl::android::hardware::audio::effect::getEffectTypeUuidAutomaticGainControlV1; -using aidl::android::hardware::audio::effect::getEffectTypeUuidAutomaticGainControlV2; -using aidl::android::hardware::audio::effect::getEffectTypeUuidBassBoost; -using aidl::android::hardware::audio::effect::getEffectTypeUuidDownmix; -using aidl::android::hardware::audio::effect::getEffectTypeUuidDynamicsProcessing; -using aidl::android::hardware::audio::effect::getEffectTypeUuidEqualizer; -using aidl::android::hardware::audio::effect::getEffectTypeUuidHapticGenerator; -using aidl::android::hardware::audio::effect::getEffectTypeUuidLoudnessEnhancer; -using aidl::android::hardware::audio::effect::getEffectTypeUuidEnvReverb; -using aidl::android::hardware::audio::effect::getEffectTypeUuidEnvReverb; -using aidl::android::hardware::audio::effect::getEffectTypeUuidEnvReverb; -using aidl::android::hardware::audio::effect::getEffectTypeUuidPresetReverb; -using aidl::android::hardware::audio::effect::getEffectTypeUuidPresetReverb; -using aidl::android::hardware::audio::effect::getEffectTypeUuidPresetReverb; -using aidl::android::hardware::audio::effect::getEffectTypeUuidNoiseSuppression; -using aidl::android::hardware::audio::effect::getEffectTypeUuidSpatializer; -using aidl::android::hardware::audio::effect::getEffectTypeUuidVirtualizer; -using aidl::android::hardware::audio::effect::getEffectTypeUuidVisualizer; -using aidl::android::hardware::audio::effect::getEffectTypeUuidVolume; -using aidl::android::hardware::audio::effect::getEffectUuidZero; -using aidl::android::hardware::audio::effect::Processing; - -namespace aidl::qti::effects { - -/** - * Library contains a mapping from library name to path. - * Effect contains a mapping from effect name to Libraries and implementation UUID. - * Pre/post processor contains a mapping from processing name to effect names. - */ -class EffectConfig { - public: - explicit EffectConfig(const std::string& file); - - struct Library { - std::string name; // library name - ::aidl::android::media::audio::common::AudioUuid uuid; // implementation UUID - std::optional<::aidl::android::media::audio::common::AudioUuid> type; // optional type UUID - }; - // - struct EffectLibraries { - std::optional proxyLibrary; - std::vector libraries; - }; - - int getSkippedElements() const { return mSkippedElements; } - const std::unordered_map getLibraryMap() const { return mLibraryMap; } - const std::unordered_map getEffectsMap() const { - return mEffectsMap; - } - - static bool findUuid(const std::pair& effectElem, - ::aidl::android::media::audio::common::AudioUuid* uuid); - - using ProcessingLibrariesMap = std::map>; - const ProcessingLibrariesMap& getProcessingMap() const; - - private: - static constexpr const char* kEffectLibPath[] = -#ifdef __LP64__ - {"/odm/lib64/soundfx", "/vendor/lib64/soundfx", "/system/lib64/soundfx"}; -#else - {"/odm/lib/soundfx", "/vendor/lib/soundfx", "/system/lib/soundfx"}; -#endif - - int mSkippedElements; - /* Parsed Libraries result */ - std::unordered_map mLibraryMap; - /* Parsed Effects result */ - std::unordered_map mEffectsMap; - /** - * For parsed pre/post processing result: {key: AudioStreamType/AudioSource, value: - * EffectLibraries} - */ - ProcessingLibrariesMap mProcessingMap; - - /** @return all `node`s children that are elements and match the tag if provided. */ - std::vector> getChildren( - const tinyxml2::XMLNode& node, const char* childTag = nullptr); - - /** Parse a library xml note and push the result in mLibraryMap or return false on failure. */ - bool parseLibrary(const tinyxml2::XMLElement& xml); - - /** Parse an effect from an xml element describing it. - * @return true and pushes the effect in mEffectsMap on success, false on failure. - */ - bool parseEffect(const tinyxml2::XMLElement& xml); - - bool parseProcessing(Processing::Type::Tag typeTag, const tinyxml2::XMLElement& xml); - - // Function to parse effect.library name and effect.uuid from xml - bool parseLibrary(const tinyxml2::XMLElement& xml, struct Library& library, - bool isProxy = false); - - const char* dump(const tinyxml2::XMLElement& element, - tinyxml2::XMLPrinter&& printer = {}) const; - - bool resolveLibrary(const std::string& path, std::string* resolvedPath); - - std::optional stringToProcessingType(Processing::Type::Tag typeTag, - const std::string& type); -}; - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effectFactory-impl/EffectFactory.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effectFactory-impl/EffectFactory.h deleted file mode 100755 index f8ce75fb..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/include/effectFactory-impl/EffectFactory.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -#include -#include -#include "EffectConfig.h" - -using aidl::android::hardware::audio::effect::IEffect; -using aidl::android::hardware::audio::effect::BnFactory; -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::android::hardware::audio::effect::Processing; -namespace aidl::qti::effects { - -class Factory : public BnFactory { - public: - explicit Factory(const std::string& file); - /** - * @brief Get identity of all effects supported by the device, with the optional filter by type - * and/or by instance UUID. - * - * @param in_type Type UUID. - * @param in_instance Instance UUID. - * @param in_proxy Proxy UUID. - * @param out_descriptor List of Descriptors. - * @return ndk::ScopedAStatus - */ - ndk::ScopedAStatus queryEffects( - const std::optional<::aidl::android::media::audio::common::AudioUuid>& in_type, - const std::optional<::aidl::android::media::audio::common::AudioUuid>& in_instance, - const std::optional<::aidl::android::media::audio::common::AudioUuid>& in_proxy, - std::vector* out_descriptor) override; - - /** - * @brief Query list of defined processing, with the optional filter by AudioStreamType - * - * @param in_type Type of processing, could be AudioStreamType or AudioSource. Optional. - * @param _aidl_return List of processing filtered by in_type. - * @return ndk::ScopedAStatus - */ - ndk::ScopedAStatus queryProcessing(const std::optional& in_type, - std::vector* _aidl_return) override; - - /** - * @brief Create an effect instance for a certain implementation (identified by UUID). - * - * @param in_impl_uuid Effect implementation UUID. - * @param _aidl_return A pointer to created effect instance. - * @return ndk::ScopedAStatus - */ - ndk::ScopedAStatus createEffect( - const ::aidl::android::media::audio::common::AudioUuid& in_impl_uuid, - std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>* _aidl_return) - override; - - /** - * @brief Destroy an effect instance. - * - * @param in_handle Effect instance handle. - * @return ndk::ScopedAStatus - */ - ndk::ScopedAStatus destroyEffect( - const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_handle) - override; - - private: - const EffectConfig mConfig; - ~Factory(); - - std::mutex mMutex; - // Set of effect descriptors supported by the devices. - std::set mDescSet GUARDED_BY(mMutex); - std::set mIdentitySet GUARDED_BY(mMutex); - - static constexpr int kMapEntryHandleIndex = 0; - static constexpr int kMapEntryInterfaceIndex = 1; - static constexpr int kMapEntryLibNameIndex = 2; - typedef std::tuple> /* dlHandle */, - std::unique_ptr /* interfaces */, - std::string /* library name */> - DlEntry; - - std::map mEffectLibMap - GUARDED_BY(mMutex); - - typedef std::pair EffectEntry; - std::map, EffectEntry, std::owner_less<>> mEffectMap GUARDED_BY(mMutex); - - ndk::ScopedAStatus destroyEffectImpl_l(const std::shared_ptr& in_handle) - REQUIRES(mMutex); - void cleanupEffectMap_l() REQUIRES(mMutex); - bool openEffectLibrary(const ::aidl::android::media::audio::common::AudioUuid& impl, - const std::string& path); - void createIdentityWithConfig( - const EffectConfig::Library& configLib, - const ::aidl::android::media::audio::common::AudioUuid& typeUuidStr, - const std::optional<::aidl::android::media::audio::common::AudioUuid> proxyUuid); - - ndk::ScopedAStatus getDescriptorWithUuid_l( - const aidl::android::media::audio::common::AudioUuid& uuid, Descriptor* desc) - REQUIRES(mMutex); - - void loadEffectLibs(); - /* Get effect_dl_interface_s from library handle */ - void getDlSyms_l(DlEntry& entry) REQUIRES(mMutex); -}; - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/Android.mk deleted file mode 100755 index 56fe2d9f..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/Android.mk +++ /dev/null @@ -1,20 +0,0 @@ -ifneq ($(AUDIO_USE_STUB_HAL), true) -CURRENT_PATH := $(call my-dir) -ifeq (0,1) -############################################ -#[samsung audio feature - unused -include $(CURRENT_PATH)/offloadbundle/Android.mk -include $(CURRENT_PATH)/offloadvisualizer/Android.mk -include $(CURRENT_PATH)/voiceprocessing/Android.mk -include $(CURRENT_PATH)/volumelistener/Android.mk -#samsung audio feature - unused] -############################################ -else -############################################ -#[samsung audio feature - used -include $(CURRENT_PATH)/voiceprocessing/Android.mk -#samsung audio feature] -############################################ -endif -#include $(call all-subdir-makefiles) -endif \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/Android.mk deleted file mode 100755 index b8c06ec4..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/Android.mk +++ /dev/null @@ -1,31 +0,0 @@ -LOCAL_PATH:= $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE:= libqcompostprocbundle -LOCAL_VENDOR_MODULE := true -LOCAL_MODULE_RELATIVE_PATH := soundfx -LOCAL_MODULE_OWNER := qti - -LOCAL_C_FLAGS += -Werror -Wall -Wextra - -LOCAL_SRC_FILES:= \ - OffloadBundleAidl.cpp \ - OffloadBundleContext.cpp \ - BassBoostContext.cpp \ - EqualizerContext.cpp \ - ReverbContext.cpp \ - VirtualizerContext.cpp \ - ParamDelegator.cpp - -LOCAL_STATIC_LIBRARIES := libaudioeffecthal_base_impl_static - -LOCAL_SHARED_LIBRARIES:= \ - $(EFFECTS_DEFAULTS_SHARED_LIBRARIES) \ - libar-pal - -LOCAL_HEADER_LIBRARIES:= \ - $(EFFECTS_DEFAULTS_HEADERS_LIBRARIES) \ - libacdb_headers - -include $(BUILD_SHARED_LIBRARY) diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/BassBoostContext.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/BassBoostContext.cpp deleted file mode 100755 index a3b73328..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/BassBoostContext.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_Effect_BassBoostQti" - -#include -#include - -#include "OffloadBundleContext.h" -#include "OffloadBundleTypes.h" - -namespace aidl::qti::effects { - -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; - -BassBoostContext::BassBoostContext(const Parameter::Common& common, - const OffloadBundleEffectType& type, bool processData) - : OffloadBundleContext(common, type, processData) { - LOG(DEBUG) << __func__ << type << " ioHandle " << common.ioHandle; - mState = EffectState::INITIALIZED; -} - -BassBoostContext::~BassBoostContext() { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - deInit(); -} - -void BassBoostContext::deInit() { - LOG(DEBUG) << __func__ << " ioHandle" << getIoHandle(); - stop(); -} - -RetCode BassBoostContext::enable() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - if (isEffectActive()) return RetCode::ERROR_ILLEGAL_PARAMETER; - mState = EffectState::ACTIVE; - mBassParams.mEnabled = 1; - setOffloadParameters(BASSBOOST_ENABLE_FLAG); - return RetCode::SUCCESS; -} - -RetCode BassBoostContext::disable() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - if (!isEffectActive()) return RetCode::ERROR_ILLEGAL_PARAMETER; - mState = EffectState::INITIALIZED; - mBassParams.mEnabled = 0; - setOffloadParameters(BASSBOOST_ENABLE_FLAG); - return RetCode::SUCCESS; -} - -RetCode BassBoostContext::start(pal_stream_handle_t* palHandle) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - mPalHandle = palHandle; - if (isEffectActive()) { - setOffloadParameters(BASSBOOST_ENABLE_FLAG | BASSBOOST_STRENGTH); - } else { - LOG(DEBUG) << "Not yet enabled"; - } - return RetCode::SUCCESS; -} - -RetCode BassBoostContext::stop() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - struct BassBoostParams bassParams; // by default enable is 0 - setOffloadParameters(&bassParams, BASSBOOST_ENABLE_FLAG); - mPalHandle = nullptr; - return RetCode::SUCCESS; -} - -bool BassBoostContext::deviceSupportsEffect(const std::vector& devices) { - for (const auto& device : devices) { - if (device != AudioDeviceDescription{AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_ANALOG} && - device != AudioDeviceDescription{AudioDeviceType::OUT_HEADPHONE, - AudioDeviceDescription::CONNECTION_ANALOG} && - device != AudioDeviceDescription{AudioDeviceType::OUT_HEADPHONE, - AudioDeviceDescription::CONNECTION_BT_A2DP} && - device != AudioDeviceDescription{AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_USB}) { - return false; - } - } - return true; -} - -RetCode BassBoostContext::setOutputDevice( - const std::vector& device) { - std::lock_guard lg(mMutex); - mOutputDevice = device; - if (deviceSupportsEffect(mOutputDevice)) { - if (mTempDisabled) { - if (isEffectActive()) { - mBassParams.mEnabled = 1; - setOffloadParameters(BASSBOOST_ENABLE_FLAG); - } - } - mTempDisabled = false; - } else if (!mTempDisabled) { - if (isEffectActive()) { - mBassParams.mEnabled = 0; - setOffloadParameters(BASSBOOST_ENABLE_FLAG); - } - mTempDisabled = true; - } - - return RetCode::SUCCESS; -} - -RetCode BassBoostContext::setBassBoostStrength(int strength) { - LOG(DEBUG) << __func__ << " strength " << strength; - mBassParams.mStrength = strength; - setOffloadParameters(BASSBOOST_ENABLE_FLAG | BASSBOOST_STRENGTH); - return RetCode::SUCCESS; -} - -int BassBoostContext::getBassBoostStrength() { - LOG(DEBUG) << __func__ << " strength " << mBassParams.mStrength; - return mBassParams.mStrength; -} - -int BassBoostContext::setOffloadParameters(uint64_t flags) { - if (mPalHandle) { - LOG(DEBUG) << " Strength " << mBassParams.mStrength << " enabled " << mBassParams.mEnabled; - ParamDelegator::updatePalParameters(mPalHandle, &mBassParams, flags); - } else { - LOG(VERBOSE) << " PalHandle not set"; - } - return 0; -} - -int BassBoostContext::setOffloadParameters(BassBoostParams* bassParams, uint64_t flags) { - if (mPalHandle) { - LOG(DEBUG) << " Strength " << bassParams->mStrength << " enabled " << bassParams->mEnabled; - ParamDelegator::updatePalParameters(mPalHandle, bassParams, flags); - } else { - LOG(VERBOSE) << " PalHandle not set"; - } - return 0; -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/EqualizerContext.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/EqualizerContext.cpp deleted file mode 100755 index 5fddbb39..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/EqualizerContext.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_Effect_EqualizerQti" - -#include -#include -#include "OffloadBundleContext.h" -#include "OffloadBundleTypes.h" - -namespace aidl::qti::effects { - -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; - -EqualizerContext::EqualizerContext(const Parameter::Common& common, - const OffloadBundleEffectType& type, bool processData) - : OffloadBundleContext(common, type, processData) { - LOG(DEBUG) << __func__ << type << " ioHandle " << common.ioHandle; - init(); // init default state - mState = EffectState::INITIALIZED; -} - -EqualizerContext::~EqualizerContext() { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - deInit(); -} - -void EqualizerContext::init() { - // init with pre-defined preset NORMAL - for (std::size_t i = 0; i < MAX_NUM_BANDS; i++) { - mBandLevels[i] = kBandPresetLevels[0 /* normal */][i]; - } - memset(&mEqParams, 0, sizeof(struct EqualizerParams)); - mEqParams.config.presetId = PRESET_INVALID; - mEqParams.config.pregain = Q27_UNITY; - mEqParams.config.numBands = MAX_NUM_BANDS; -} - -void EqualizerContext::deInit() { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - stop(); -} - -RetCode EqualizerContext::enable() { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - std::lock_guard lg(mMutex); - if (isEffectActive()) return RetCode::ERROR_ILLEGAL_PARAMETER; - mState = EffectState::ACTIVE; - mEqParams.enable = 1; - setOffloadParameters(EQ_ENABLE_FLAG | EQ_BANDS_LEVEL); - return RetCode::SUCCESS; -} - -RetCode EqualizerContext::disable() { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - std::lock_guard lg(mMutex); - if (!isEffectActive()) return RetCode::ERROR_ILLEGAL_PARAMETER; - mState = EffectState::INITIALIZED; - mEqParams.enable = 0; - setOffloadParameters(EQ_ENABLE_FLAG); - return RetCode::SUCCESS; -} - -RetCode EqualizerContext::start(pal_stream_handle_t* palHandle) { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - std::lock_guard lg(mMutex); - mPalHandle = palHandle; - if (isEffectActive()) { - setOffloadParameters(EQ_ENABLE_FLAG | EQ_BANDS_LEVEL); - } else { - LOG(DEBUG) << "Not yet enabled"; - } - - return RetCode::SUCCESS; -} - -RetCode EqualizerContext::stop() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - struct EqualizerParams eqParam = {0}; // by default enable bit is 0 - setOffloadParameters(&eqParam, EQ_ENABLE_FLAG); - mPalHandle = nullptr; - return RetCode::SUCCESS; -} - -RetCode EqualizerContext::setEqualizerPreset(const std::size_t presetIdx) { - std::lock_guard lg(mMutex); - if (presetIdx < 0 || presetIdx >= MAX_NUM_PRESETS) { - return RetCode::ERROR_ILLEGAL_PARAMETER; - } - - // Translation from existing implementation, first we update then send config to PAL. - // ideally, send it to PAL and check if operation is successful then only update - mCurrentPreset = presetIdx; - for (std::size_t i = 0; i < MAX_NUM_BANDS; i++) { - mBandLevels[i] = kBandPresetLevels[presetIdx][i]; - } - - updateOffloadParameters(); - - setOffloadParameters(EQ_ENABLE_FLAG | EQ_PRESET); - - return RetCode::SUCCESS; -} - -bool EqualizerContext::isBandLevelIndexInRange( - const std::vector& bandLevels) const { - const auto[min, max] = - std::minmax_element(bandLevels.begin(), bandLevels.end(), - [](const auto& a, const auto& b) { return a.index < b.index; }); - return min->index >= 0 && max->index < MAX_NUM_BANDS; -} - -RetCode EqualizerContext::setEqualizerBandLevels( - const std::vector& bandLevels) { - std::lock_guard lg(mMutex); - RETURN_VALUE_IF(bandLevels.size() > MAX_NUM_BANDS, RetCode::ERROR_ILLEGAL_PARAMETER, - "Exceeds Max Size"); - - RETURN_VALUE_IF(bandLevels.empty(), RetCode::ERROR_ILLEGAL_PARAMETER, "Empty Bands"); - - RETURN_VALUE_IF(!isBandLevelIndexInRange(bandLevels), RetCode::ERROR_ILLEGAL_PARAMETER, - "indexOutOfRange"); - - // Translation from existing implementation, first we update then send config to PAL. - // ideally, send it to PAL and check if operation is successful then only update - for (auto& bandLevel : bandLevels) { - int level = bandLevel.levelMb; - if (level > 0) { - level = (int)((level + 50) / 100); - } else { - level = (int)((level - 50) / 100); - } - LOG(VERBOSE) << __func__ << " level " << bandLevel.index << " level" << bandLevel.levelMb - << " refined level" << level; - mBandLevels[bandLevel.index] = level; - mCurrentPreset = PRESET_CUSTOM; - } - - updateOffloadParameters(); - setOffloadParameters(EQ_ENABLE_FLAG | EQ_BANDS_LEVEL); - - return RetCode::SUCCESS; -} - -std::vector EqualizerContext::getEqualizerBandLevels() const { - std::vector bandLevels; - bandLevels.reserve(MAX_NUM_BANDS); - for (std::size_t i = 0; i < MAX_NUM_BANDS; i++) { - bandLevels.emplace_back( - Equalizer::BandLevel{static_cast(i), mBandLevels[i] * 100}); - } - return bandLevels; -} - -std::vector EqualizerContext::getEqualizerCenterFreqs() { - std::vector result; - - std::for_each(kBandFrequencies.begin(), kBandFrequencies.end(), - [&](const auto& band) { result.emplace_back((band.minMh + band.maxMh) / 2); }); - return result; -} - -void EqualizerContext::updateOffloadParameters() { - for (int i = 0; i < MAX_NUM_BANDS; i++) { - mEqParams.config.presetId = mCurrentPreset; - mEqParams.bandConfig[i].bandIndex = i; - mEqParams.bandConfig[i].filterType = EQ_BAND_BOOST; - mEqParams.bandConfig[i].frequencyMhz = kPresetsFrequencies[i] * 1000; - mEqParams.bandConfig[i].gainMb = mBandLevels[i] * 100; - mEqParams.bandConfig[i].qFactor = Q8_UNITY; - } -} - -int EqualizerContext::setOffloadParameters(uint64_t flags) { - if (mPalHandle) { - ParamDelegator::updatePalParameters(mPalHandle, &mEqParams, flags); - } else { - LOG(VERBOSE) << " PalHandle not set"; - } - return 0; -} - -int EqualizerContext::setOffloadParameters(EqualizerParams* params, uint64_t flags) { - if (mPalHandle) { - ParamDelegator::updatePalParameters(mPalHandle, params, flags); - } else { - LOG(VERBOSE) << " PalHandle not set"; - } - return 0; -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/GlobalOffloadSession.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/GlobalOffloadSession.h deleted file mode 100755 index ffd65a3a..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/GlobalOffloadSession.h +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include - -#include -#include - -#include "OffloadBundleContext.h" -#include "OffloadBundleTypes.h" - -namespace aidl::qti::effects { - -/** - * @brief Maintain all effect offload bundle sessions. - * - */ -class GlobalOffloadSession { - public: - static GlobalOffloadSession& getGlobalSession() { - static GlobalOffloadSession instance; - return instance; - } - - static bool findTypeInContextList(std::vector>& list, - const OffloadBundleEffectType& type, bool remove = false) { - auto itr = std::find_if(list.begin(), list.end(), - [type](const std::shared_ptr& bundle) { - return bundle->getBundleType() == type; - }); - if (itr == list.end()) { - return false; - } - if (remove) { - (*itr)->deInit(); // call release inside of it. - list.erase(itr); - } - return true; - } - - std::shared_ptr createContext(const OffloadBundleEffectType& type, - const Parameter::Common& common, - bool processData) { - switch (type) { - case OffloadBundleEffectType::BASS_BOOST: - return std::make_shared(common, type, processData); - case OffloadBundleEffectType::EQUALIZER: - return std::make_shared(common, type, processData); - case OffloadBundleEffectType::VIRTUALIZER: - return std::make_shared(common, type, processData); - case OffloadBundleEffectType::AUX_ENV_REVERB: - case OffloadBundleEffectType::INSERT_ENV_REVERB: - case OffloadBundleEffectType::AUX_PRESET_REVERB: - case OffloadBundleEffectType::INSERT_PRESET_REVERB: - return std::make_shared(common, type, processData); - } - return nullptr; - } - - /** - * Create a certain type of BundleContext in shared_ptr container, each session must not have - * more than one session for each type. - */ - std::shared_ptr createSession(const OffloadBundleEffectType& type, - const Parameter::Common& common, - bool processData) { - std::lock_guard lg(mMutex); - int ioHandle = common.ioHandle; - int sessionId = common.session; - LOG(DEBUG) << __func__ << " " << type << " with ioHandle " << ioHandle << " sessionId" - << sessionId; - if (mSessionsMap.count(sessionId)) { - if (findTypeInContextList(mSessionsMap[sessionId], type)) { - LOG(ERROR) << __func__ << type << " already exist in " << sessionId; - return nullptr; - } - } - - auto& list = mSessionsMap[sessionId]; - LOG(DEBUG) << __func__ << type << " createContext ioHandle " << ioHandle << " sessionId" - << sessionId; - auto context = createContext(type, common, processData); - RETURN_VALUE_IF(!context, nullptr, "failedToCreateContext"); - - list.push_back(context); - - // find ioHandle in the mActiveIoHandles - for (const auto& pair : mActiveIoHandles) { - if (pair.first == ioHandle) { - LOG(DEBUG) << "IoHandle is active " << ioHandle << " session " << sessionId; - context->start(pair.second); - } - } - return context; - } - - void releaseSession(const OffloadBundleEffectType& type, int sessionId) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " Enter: " << type << " sessionId " << sessionId; - if (mSessionsMap.count(sessionId)) { - auto& list = mSessionsMap[sessionId]; - if (!findTypeInContextList(list, type, true /* remove */)) { - LOG(ERROR) << __func__ << " can't find " << type << "in sessionId " << sessionId; - return; - } - if (list.empty()) { - mSessionsMap.erase(sessionId); - } - } - LOG(DEBUG) << __func__ << " Exit: " << type << " sessionId " << sessionId << " sessions " - << mSessionsMap.size(); - } - - // Used by AudioHal to link effect with output. - void startEffect(int ioHandle, pal_stream_handle_t* palHandle) { - std::lock_guard lg(mMutex); - - LOG(DEBUG) << __func__ << " ioHandle " << ioHandle << " palHandle " << palHandle - << " sessions " << mSessionsMap.size(); - // start the context having same ioHandle - for (const auto& handles : mSessionsMap) { - auto& list = handles.second; - for (const auto& context : list) { - if (context->getIoHandle() == ioHandle) { - context->start(palHandle); - } - } - } - - mActiveIoHandles[ioHandle] = palHandle; - } - - // Used by AudioHal to link effect with output. - void stopEffect(int ioHandle) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << ioHandle << " sessions " << mSessionsMap.size() - << "activeHandles " << mActiveIoHandles.count(ioHandle); - - // stop the context having same ioHandle - for (const auto& handles : mSessionsMap) { - auto& list = handles.second; - for (const auto& context : list) { - if (context->getIoHandle() == ioHandle) { - context->stop(); - } - } - } - - if (mActiveIoHandles.count(ioHandle)) { - mActiveIoHandles.erase(ioHandle); - LOG(VERBOSE) << __func__ << " Removed ioHandle " << ioHandle << " sessions " - << mSessionsMap.size() << " activeHandles " - << mActiveIoHandles.count(ioHandle); - } - } - - private: - // Lock for mSessionsMap access. - std::mutex mMutex; - - // map between sessionId and list of effect contexts for that session - std::unordered_map>> - mSessionsMap GUARDED_BY(mMutex); - - // io Handle to palHandle mapping. - std::unordered_map mActiveIoHandles; -}; -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleAidl.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleAidl.cpp deleted file mode 100755 index a07e23ae..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleAidl.cpp +++ /dev/null @@ -1,647 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_Effect_OffloadBundleQti" -#include -#include -#include - -#include -#include - -#include "OffloadBundleAidl.h" - -using aidl::android::hardware::audio::effect::IEffect; -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::qti::effects::OffloadBundleAidl; -using aidl::qti::effects::kEqualizerOffloadQtiUUID; -using aidl::qti::effects::kBassBoostOffloadQtiUUID; -using aidl::qti::effects::kVirtualizerOffloadQtiUUID; -using aidl::qti::effects::kAuxEnvReverbOffloadQtiUUID; -using aidl::qti::effects::kInsertEnvReverbOffloadQtiUUID; -using aidl::qti::effects::kAuxPresetReverbOffloadQtiUUID; -using aidl::qti::effects::kInsertPresetReverbOffloadQtiUUID; - -using aidl::android::hardware::audio::effect::State; -using aidl::android::media::audio::common::AudioUuid; -using aidl::android::hardware::audio::effect::Parameter; -using aidl::android::hardware::audio::effect::Equalizer; -using aidl::android::hardware::audio::effect::BassBoost; -using aidl::android::hardware::audio::effect::Virtualizer; -using aidl::android::hardware::audio::effect::Parameter; - -bool isUuidSupported(const AudioUuid* uuid) { - return (*uuid == kEqualizerOffloadQtiUUID || *uuid == kBassBoostOffloadQtiUUID || - *uuid == kVirtualizerOffloadQtiUUID || *uuid == kAuxEnvReverbOffloadQtiUUID || - *uuid == kInsertEnvReverbOffloadQtiUUID || *uuid == kAuxPresetReverbOffloadQtiUUID || - *uuid == kInsertPresetReverbOffloadQtiUUID); -} - -extern "C" binder_exception_t createEffect( - const AudioUuid* uuid, - std::shared_ptr* instanceSpp) { - if (uuid == nullptr || !isUuidSupported(uuid)) { - LOG(ERROR) << __func__ << "uuid not supported " << aidl::qti::effects::toString(*uuid); - return EX_ILLEGAL_ARGUMENT; - } - if (instanceSpp) { - *instanceSpp = ndk::SharedRefBase::make(*uuid); - LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created"; - return EX_NONE; - } else { - LOG(ERROR) << __func__ << " invalid input parameter!"; - return EX_ILLEGAL_ARGUMENT; - } -} - -extern "C" void startEffect(int ioHandle, uint64_t* palHandle) { - aidl::qti::effects::GlobalOffloadSession::getGlobalSession().startEffect(ioHandle, palHandle); -} - -extern "C" void stopEffect(int ioHandle) { - aidl::qti::effects::GlobalOffloadSession::getGlobalSession().stopEffect(ioHandle); -} - -extern "C" binder_exception_t queryEffect( - const AudioUuid* in_impl_uuid, - aidl::android::hardware::audio::effect::Descriptor* _aidl_return) { - if (!in_impl_uuid || !isUuidSupported(in_impl_uuid)) { - LOG(ERROR) << __func__ << "uuid not supported " - << aidl::qti::effects::toString(*in_impl_uuid); - return EX_ILLEGAL_ARGUMENT; - } - if (*in_impl_uuid == kEqualizerOffloadQtiUUID) { - *_aidl_return = aidl::qti::effects::kEqualizerDesc; - } else if (*in_impl_uuid == kBassBoostOffloadQtiUUID) { - *_aidl_return = aidl::qti::effects::kBassBoostDesc; - } else if (*in_impl_uuid == kVirtualizerOffloadQtiUUID) { - *_aidl_return = aidl::qti::effects::kVirtualizerDesc; - } else if (*in_impl_uuid == kAuxEnvReverbOffloadQtiUUID) { - *_aidl_return = aidl::qti::effects::kAuxEnvReverbDesc; - } else if (*in_impl_uuid == kInsertEnvReverbOffloadQtiUUID) { - *_aidl_return = aidl::qti::effects::kInsertEnvReverbDesc; - } else if (*in_impl_uuid == kAuxPresetReverbOffloadQtiUUID) { - *_aidl_return = aidl::qti::effects::kAuxPresetReverbDesc; - } else if (*in_impl_uuid == kInsertPresetReverbOffloadQtiUUID) { - *_aidl_return = aidl::qti::effects::kInsertPresetReverbDesc; - } - return EX_NONE; -} - -namespace aidl::qti::effects { - -OffloadBundleAidl::OffloadBundleAidl(const AudioUuid& uuid) { - if (uuid == kEqualizerOffloadQtiUUID) { - mType = OffloadBundleEffectType::EQUALIZER; - mDescriptor = &kEqualizerDesc; - mEffectName = &kEqualizerEffectName; - } else if (uuid == kBassBoostOffloadQtiUUID) { - mType = OffloadBundleEffectType::BASS_BOOST; - mDescriptor = &kBassBoostDesc; - mEffectName = &kBassBoostEffectName; - } else if (uuid == kVirtualizerOffloadQtiUUID) { - mType = OffloadBundleEffectType::VIRTUALIZER; - mDescriptor = &kVirtualizerDesc; - mEffectName = &kVirtualizerEffectName; - } else if (uuid == kAuxEnvReverbOffloadQtiUUID) { - mType = OffloadBundleEffectType::AUX_ENV_REVERB; - mDescriptor = &kAuxEnvReverbDesc; - mEffectName = &kAuxEnvReverbEffectName; - } else if (uuid == kInsertEnvReverbOffloadQtiUUID) { - mType = OffloadBundleEffectType::INSERT_ENV_REVERB; - mDescriptor = &kInsertEnvReverbDesc; - mEffectName = &kInsertEnvReverbEffectName; - } else if (uuid == kAuxPresetReverbOffloadQtiUUID) { - mType = OffloadBundleEffectType::AUX_PRESET_REVERB; - mDescriptor = &kAuxPresetReverbDesc; - mEffectName = &kAuxPresetReverbEffectName; - } else if (uuid == kInsertPresetReverbOffloadQtiUUID) { - mType = OffloadBundleEffectType::INSERT_PRESET_REVERB; - mDescriptor = &kInsertPresetReverbDesc; - mEffectName = &kInsertPresetReverbEffectName; - } else { - LOG(ERROR) << __func__ << toString(uuid) << " not supported!"; - } - LOG(DEBUG) << __func__ << " " << toString(uuid) << " " << mType; -} - -OffloadBundleAidl::~OffloadBundleAidl() { - cleanUp(); - LOG(DEBUG) << __func__ << mType; -} - -ndk::ScopedAStatus OffloadBundleAidl::getDescriptor( - aidl::android::hardware::audio::effect::Descriptor* _aidl_return) { - RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr"); - LOG(DEBUG) << _aidl_return->toString(); - *_aidl_return = *mDescriptor; - return ndk::ScopedAStatus::ok(); -} - -void OffloadBundleAidl::stopEffectIfNeeded(const Parameter::Common& common) { - int ioHandle = common.ioHandle; - int previousHandle = mContext->getIoHandle(); - if (ioHandle != previousHandle) { - LOG(DEBUG) << getEffectName() << __func__ << " stop on previous handle " << previousHandle - << " new handle " << ioHandle; - aidl::qti::effects::GlobalOffloadSession::getGlobalSession().stopEffect(previousHandle); - } -} - -ndk::ScopedAStatus OffloadBundleAidl::setParameterCommon(const Parameter& param) { - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - - const auto& tag = param.getTag(); - - LOG(VERBOSE) << mType << " " << __func__ << param.toString(); - if (tag == Parameter::common) { - stopEffectIfNeeded(param.get()); - RETURN_IF(mContext->setCommon(param.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setCommFailed"); - } else { - // for rest of params use base class. - return EffectImpl::setParameterCommon(param); - } - - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus OffloadBundleAidl::setParameterSpecific(const Parameter::Specific& specific) { - LOG(DEBUG) << __func__ << " specific " << specific.toString(); - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - - auto tag = specific.getTag(); - switch (tag) { - case Parameter::Specific::equalizer: - return setParameterEqualizer(specific); - case Parameter::Specific::bassBoost: - return setParameterBassBoost(specific); - case Parameter::Specific::virtualizer: - return setParameterVirtualizer(specific); - case Parameter::Specific::presetReverb: - return setParameterPresetReverb(specific); - case Parameter::Specific::environmentalReverb: - return setParameterEnvironmentalReverb(specific); - default: - LOG(ERROR) << __func__ << " unsupported tag " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "specificParamNotSupported"); - } -} - -ndk::ScopedAStatus OffloadBundleAidl::setParameterEqualizer(const Parameter::Specific& specific) { - auto& eq = specific.get(); - RETURN_IF(!inRange(eq, kEqRanges), EX_ILLEGAL_ARGUMENT, "outOfRange"); - auto eqTag = eq.getTag(); - switch (eqTag) { - case Equalizer::preset: - RETURN_IF(mContext->setEqualizerPreset(eq.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setBandLevelsFailed"); - return ndk::ScopedAStatus::ok(); - case Equalizer::bandLevels: - RETURN_IF(mContext->setEqualizerBandLevels(eq.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setBandLevelsFailed"); - return ndk::ScopedAStatus::ok(); - default: - LOG(ERROR) << __func__ << " unsupported parameter " << specific.toString(); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "eqTagNotSupported"); - } -} - -ndk::ScopedAStatus OffloadBundleAidl::setParameterBassBoost(const Parameter::Specific& specific) { - auto& bb = specific.get(); - auto bbTag = bb.getTag(); - RETURN_IF(!inRange(bb, kBassBoostRanges), EX_ILLEGAL_ARGUMENT, "outOfRange"); - switch (bbTag) { - case BassBoost::strengthPm: { - RETURN_IF(mContext->setBassBoostStrength(bb.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setStrengthFailed"); - return ndk::ScopedAStatus::ok(); - } - default: - LOG(ERROR) << __func__ << " unsupported parameter " << specific.toString(); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "bbTagNotSupported"); - } -} - -ndk::ScopedAStatus OffloadBundleAidl::setParameterVirtualizer(const Parameter::Specific& specific) { - auto& vr = specific.get(); - RETURN_IF(!inRange(vr, kVirtualizerRanges), EX_ILLEGAL_ARGUMENT, "outOfRange"); - auto vrTag = vr.getTag(); - switch (vrTag) { - case Virtualizer::strengthPm: { - RETURN_IF(mContext->setVirtualizerStrength(vr.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setStrengthFailed"); - return ndk::ScopedAStatus::ok(); - } - case Virtualizer::device: { - RETURN_IF(mContext->setForcedDevice(vr.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setDeviceFailed"); - return ndk::ScopedAStatus::ok(); - } - case Virtualizer::speakerAngles: - FALLTHROUGH_INTENDED; - case Virtualizer::vendor: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(vrTag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "VirtualizerTagNotSupported"); - } - default: - LOG(ERROR) << __func__ << " unsupported parameter " << specific.toString(); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "vrTagNotSupported"); - } -} - -ndk::ScopedAStatus OffloadBundleAidl::getParameterSpecific(const Parameter::Id& id, - Parameter::Specific* specific) { - RETURN_IF(!specific, EX_NULL_POINTER, "nullPtr"); - auto tag = id.getTag(); - - switch (tag) { - case Parameter::Id::equalizerTag: - return getParameterEqualizer(id.get(), specific); - case Parameter::Id::bassBoostTag: - return getParameterBassBoost(id.get(), specific); - case Parameter::Id::virtualizerTag: - return getParameterVirtualizer(id.get(), specific); - case Parameter::Id::environmentalReverbTag: - return getParameterEnvironmentalReverb(id.get(), - specific); - case Parameter::Id::presetReverbTag: - return getParameterPresetReverb(id.get(), specific); - default: - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "wrongIdTag"); - } -} - -ndk::ScopedAStatus OffloadBundleAidl::getParameterEqualizer(const Equalizer::Id& id, - Parameter::Specific* specific) { - RETURN_IF(id.getTag() != Equalizer::Id::commonTag, EX_ILLEGAL_ARGUMENT, - "EqualizerTagNotSupported"); - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - Equalizer eqParam; - - auto tag = id.get(); - switch (tag) { - case Equalizer::bandLevels: { - eqParam.set(mContext->getEqualizerBandLevels()); - break; - } - case Equalizer::preset: { - eqParam.set(mContext->getEqualizerPreset()); - break; - } - case Equalizer::bandFrequencies: { - eqParam.set(kBandFrequencies); - break; - } - case Equalizer::presets: { - eqParam.set(kPresets); - break; - } - case Equalizer::centerFreqMh: { - eqParam.set(mContext->getEqualizerCenterFreqs()); - break; - } - case Equalizer::vendor: { - LOG(ERROR) << __func__ << " not handled tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "unsupportedTag"); - } - default: { - LOG(ERROR) << __func__ << " not handled tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "unsupportedTag"); - } - } - - specific->set(eqParam); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus OffloadBundleAidl::getParameterBassBoost(const BassBoost::Id& id, - Parameter::Specific* specific) { - RETURN_IF(id.getTag() != BassBoost::Id::commonTag, EX_ILLEGAL_ARGUMENT, - "BassBoostTagNotSupported"); - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - BassBoost bbParam; - - auto tag = id.get(); - switch (tag) { - case BassBoost::strengthPm: { - bbParam.set(mContext->getBassBoostStrength()); - break; - } - default: { - LOG(ERROR) << __func__ << " not handled tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "BassBoostTagNotSupported"); - } - } - - specific->set(bbParam); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus OffloadBundleAidl::getParameterVirtualizer(const Virtualizer::Id& id, - Parameter::Specific* specific) { - RETURN_IF((id.getTag() != Virtualizer::Id::commonTag) && - (id.getTag() != Virtualizer::Id::speakerAnglesPayload), - EX_ILLEGAL_ARGUMENT, "VirtualizerTagNotSupported"); - - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - Virtualizer vrParam; - - if (id.getTag() == Virtualizer::Id::speakerAnglesPayload) { - auto angles = mContext->getSpeakerAngles(id.get()); - RETURN_IF(angles.size() == 0, EX_ILLEGAL_ARGUMENT, "getSpeakerAnglesFailed"); - Virtualizer param = Virtualizer::make(angles); - specific->set(param); - return ndk::ScopedAStatus::ok(); - } - - auto tag = id.get(); - switch (tag) { - case Virtualizer::strengthPm: { - vrParam.set(mContext->getVirtualizerStrength()); - break; - } - case Virtualizer::device: { - vrParam.set(mContext->getForcedDevice()); - break; - } - case Virtualizer::speakerAngles: - FALLTHROUGH_INTENDED; - case Virtualizer::vendor: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "VirtualizerTagNotSupported"); - } - } - - specific->set(vrParam); - return ndk::ScopedAStatus::ok(); - -} - -std::shared_ptr OffloadBundleAidl::createContext(const Parameter::Common& common, - bool processData) { - if (mContext) { - LOG(DEBUG) << __func__ << " context already exist"; - } else { - // GlobalSession is a singleton - mContext = - GlobalOffloadSession::getGlobalSession().createSession(mType, common, processData); - } - - return mContext; -} - -ndk::ScopedAStatus OffloadBundleAidl::setParameterPresetReverb( - const Parameter::Specific& specific) { - auto& presetReverbParam = specific.get(); - auto tag = presetReverbParam.getTag(); - RETURN_IF(!inRange(presetReverbParam, kPresetReverbRanges), EX_ILLEGAL_ARGUMENT, "outOfRange"); - switch (tag) { - case PresetReverb::preset: { - RETURN_IF(mContext->setPresetReverbPreset( - presetReverbParam.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setPresetFailed"); - return ndk::ScopedAStatus::ok(); - } - default: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "PresetReverbTagNotSupported"); - } - } -} - -ndk::ScopedAStatus OffloadBundleAidl::setParameterEnvironmentalReverb( - const Parameter::Specific& specific) { - auto& reverbParam = specific.get(); - RETURN_IF(!inRange(reverbParam, kEnvReverbRanges), EX_ILLEGAL_ARGUMENT, "outOfRange"); - auto tag = reverbParam.getTag(); - - switch (tag) { - case EnvironmentalReverb::roomLevelMb: { - RETURN_IF(mContext->setEnvironmentalReverbRoomLevel( - reverbParam.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setRoomLevelFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::roomHfLevelMb: { - RETURN_IF(mContext->setEnvironmentalReverbRoomHfLevel( - reverbParam.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setRoomHfLevelFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::decayTimeMs: { - RETURN_IF(mContext->setEnvironmentalReverbDecayTime( - reverbParam.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setDecayTimeFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::decayHfRatioPm: { - RETURN_IF(mContext->setEnvironmentalReverbDecayHfRatio( - reverbParam.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setDecayHfRatioFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::reflectionsLevelMb: { - RETURN_IF(mContext->setReflectionsLevel( - reverbParam.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setReflectionsLevelFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::reflectionsDelayMs: { - RETURN_IF(mContext->setReflectionsDelay( - reverbParam.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setReflectionsDelayFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::levelMb: { - RETURN_IF(mContext->setEnvironmentalReverbLevel( - reverbParam.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setLevelFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::delayMs: { - RETURN_IF(mContext->setEnvironmentalReverbDelay( - reverbParam.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setDelayFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::diffusionPm: { - RETURN_IF(mContext->setEnvironmentalReverbDiffusion( - reverbParam.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setDiffusionFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::densityPm: { - RETURN_IF( - mContext->setEnvironmentalReverbDensity( - reverbParam.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setDensityFailed"); - return ndk::ScopedAStatus::ok(); - } - case EnvironmentalReverb::bypass: { - RETURN_IF(mContext->setEnvironmentalReverbBypass( - reverbParam.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setBypassFailed"); - return ndk::ScopedAStatus::ok(); - } - default: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage( - EX_ILLEGAL_ARGUMENT, "EnvironmentalReverbTagNotSupported"); - } - } -} - -ndk::ScopedAStatus OffloadBundleAidl::getParameterPresetReverb(const PresetReverb::Id& id, - Parameter::Specific* specific) { - RETURN_IF(id.getTag() != PresetReverb::Id::commonTag, EX_ILLEGAL_ARGUMENT, - "PresetReverbTagNotSupported"); - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - PresetReverb prParam; - auto tag = id.get(); - switch (tag) { - case PresetReverb::preset: { - prParam.set(mContext->getPresetReverbPreset()); - break; - } - default: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "PresetReverbTagNotSupported"); - } - } - - specific->set(prParam); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus OffloadBundleAidl::getParameterEnvironmentalReverb( - const EnvironmentalReverb::Id& id, Parameter::Specific* specific) { - RETURN_IF(id.getTag() != EnvironmentalReverb::Id::commonTag, EX_ILLEGAL_ARGUMENT, - "EnvironmentalReverbTagNotSupported"); - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - EnvironmentalReverb envReverbParam; - - auto tag = id.get(); - switch (tag) { - case EnvironmentalReverb::roomLevelMb: { - envReverbParam.set( - mContext->getEnvironmentalReverbRoomLevel()); - break; - } - case EnvironmentalReverb::roomHfLevelMb: { - envReverbParam.set( - mContext->getEnvironmentalReverbRoomHfLevel()); - break; - } - case EnvironmentalReverb::decayTimeMs: { - envReverbParam.set( - mContext->getEnvironmentalReverbDecayTime()); - break; - } - case EnvironmentalReverb::decayHfRatioPm: { - envReverbParam.set( - mContext->getEnvironmentalReverbDecayHfRatio()); - break; - } - case EnvironmentalReverb::reflectionsLevelMb: { - envReverbParam.set( - mContext->getReflectionsLevel()); - break; - } - case EnvironmentalReverb::reflectionsDelayMs: { - envReverbParam.set( - mContext->getReflectionsDelay()); - break; - } - case EnvironmentalReverb::levelMb: { - envReverbParam.set( - mContext->getEnvironmentalReverbLevel()); - break; - } - case EnvironmentalReverb::delayMs: { - envReverbParam.set( - mContext->getEnvironmentalReverbDelay()); - break; - } - case EnvironmentalReverb::diffusionPm: { - envReverbParam.set( - mContext->getEnvironmentalReverbDiffusion()); - break; - } - case EnvironmentalReverb::densityPm: { - envReverbParam.set( - mContext->getEnvironmentalReverbDensity()); - break; - } - case EnvironmentalReverb::bypass: { - envReverbParam.set( - mContext->getEnvironmentalReverbBypass()); - break; - } - default: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage( - EX_ILLEGAL_ARGUMENT, "EnvironmentalReverbTagNotSupported"); - } - } - - specific->set(envReverbParam); - return ndk::ScopedAStatus::ok(); -} - -RetCode OffloadBundleAidl::releaseContext() { - if (mContext) { - GlobalOffloadSession::getGlobalSession().releaseSession(mType, mContext->getSessionId()); - mContext.reset(); - } - return RetCode::SUCCESS; -} - -ndk::ScopedAStatus OffloadBundleAidl::commandImpl( - aidl::android::hardware::audio::effect::CommandId command) { - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - switch (command) { - case aidl::android::hardware::audio::effect::CommandId::START: - mContext->enable(); - break; - case aidl::android::hardware::audio::effect::CommandId::STOP: - mContext->disable(); - break; - case aidl::android::hardware::audio::effect::CommandId::RESET: - mContext->disable(); - mContext->resetBuffer(); - break; - default: - LOG(ERROR) << __func__ << " commandId " << toString(command) << " not supported"; - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "commandIdNotSupported"); - } - return ndk::ScopedAStatus::ok(); -} - -} // namespace aidl::android::hardware::audio::effect diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleAidl.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleAidl.h deleted file mode 100755 index c41fa96d..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleAidl.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once -#include -#include -#include - -#include -#include - -#include "effect-impl/EffectImpl.h" -#include "effect-impl/EffectUUID.h" - -#include "GlobalOffloadSession.h" -#include "OffloadBundleContext.h" -#include "OffloadBundleTypes.h" - -namespace aidl::qti::effects { - -class OffloadBundleAidl final : public EffectImpl { - public: - explicit OffloadBundleAidl(const AudioUuid& uuid); - ~OffloadBundleAidl() override; - - ndk::ScopedAStatus getDescriptor( - aidl::android::hardware::audio::effect::Descriptor* _aidl_return) override; - - ndk::ScopedAStatus setParameterSpecific( - const aidl::android::hardware::audio::effect::Parameter::Specific& specific) override; - ndk::ScopedAStatus getParameterSpecific( - const aidl::android::hardware::audio::effect::Parameter::Id& id, - aidl::android::hardware::audio::effect::Parameter::Specific* specific) override; - - ndk::ScopedAStatus setParameterCommon(const Parameter& param) override; - - std::shared_ptr createContext( - const aidl::android::hardware::audio::effect::Parameter::Common& common, - bool processData) override; - - RetCode releaseContext() override; - - ndk::ScopedAStatus commandImpl( - aidl::android::hardware::audio::effect::CommandId command) override; - - std::string getEffectName() override { return *mEffectName; } - - private: - void stopEffectIfNeeded(const Parameter::Common& common); - std::shared_ptr mContext; - OffloadBundleEffectType mType = OffloadBundleEffectType::EQUALIZER; - - aidl::android::hardware::audio::effect::IEffect::Status status(binder_status_t status, - size_t consumed, - size_t produced); - - ndk::ScopedAStatus setParameterBassBoost( - const aidl::android::hardware::audio::effect::Parameter::Specific& specific); - ndk::ScopedAStatus getParameterBassBoost( - const aidl::android::hardware::audio::effect::BassBoost::Id& id, - aidl::android::hardware::audio::effect::Parameter::Specific* specific); - - ndk::ScopedAStatus setParameterEqualizer( - const aidl::android::hardware::audio::effect::Parameter::Specific& specific); - ndk::ScopedAStatus getParameterEqualizer( - const aidl::android::hardware::audio::effect::Equalizer::Id& id, - aidl::android::hardware::audio::effect::Parameter::Specific* specific); - ndk::ScopedAStatus setParameterVirtualizer( - const aidl::android::hardware::audio::effect::Parameter::Specific& specific); - ndk::ScopedAStatus getParameterVirtualizer( - const aidl::android::hardware::audio::effect::Virtualizer::Id& id, - aidl::android::hardware::audio::effect::Parameter::Specific* specific); - ndk::ScopedAStatus setParameterPresetReverb(const Parameter::Specific& specific); - ndk::ScopedAStatus getParameterPresetReverb(const PresetReverb::Id& id, - Parameter::Specific* specific); - - ndk::ScopedAStatus setParameterEnvironmentalReverb(const Parameter::Specific& specific); - ndk::ScopedAStatus getParameterEnvironmentalReverb(const EnvironmentalReverb::Id& id, - Parameter::Specific* specific); -}; - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleContext.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleContext.cpp deleted file mode 100755 index 65287445..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleContext.cpp +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#define LOG_TAG "BundleContext" -#include - -#include "OffloadBundleContext.h" -#include "OffloadBundleTypes.h" - -namespace aidl::qti::effects { - -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleContext.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleContext.h deleted file mode 100755 index 69806ccc..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleContext.h +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include - -#include "OffloadBundleTypes.h" -#include "PalDefs.h" -#include "ParamDelegator.h" -#include "effect-impl/EffectContext.h" - -using aidl::android::media::audio::common::AudioDeviceDescription; - -enum class EffectState { - UNINITIALIZED, - INITIALIZED, - ACTIVE, -}; - -namespace aidl::qti::effects { - -class OffloadBundleContext : public EffectContext { - public: - OffloadBundleContext(const Parameter::Common& common, const OffloadBundleEffectType& type, - bool processData) - : EffectContext(common, processData), mType(type) { - LOG(DEBUG) << __func__ << type << " ioHandle " << getIoHandle(); - } - - virtual ~OffloadBundleContext() override { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - } - - // Generic APIS - OffloadBundleEffectType getBundleType() const { return mType; } - // Each effect context needs to implement these methods - virtual void deInit() = 0; - virtual RetCode enable() = 0; - virtual RetCode disable() = 0; - virtual RetCode start(pal_stream_handle_t* palHandle) = 0; - virtual RetCode stop() = 0; - - virtual int setOffloadParameters(uint64_t flags) { return 0; } - // Equalizer methods, implement in EqualizerContext - virtual RetCode setEqualizerPreset(const std::size_t presetIdx) { - return RetCode::ERROR_ILLEGAL_PARAMETER; - } - - virtual RetCode setEqualizerBandLevels(const std::vector& bandLevels) { - return RetCode::ERROR_ILLEGAL_PARAMETER; - } - - virtual std::vector getEqualizerBandLevels() const { return {}; } - - virtual std::vector getEqualizerCenterFreqs() { return {}; } - - virtual int getEqualizerPreset() const { return 0; } - // BassBoost methods, implement in BassBoostContext - virtual RetCode setBassBoostStrength(int strength) { return RetCode::ERROR_ILLEGAL_PARAMETER; } - - virtual int getBassBoostStrength() { return 0; } - // Virtualizer methods, implement in VirtualizerContext - virtual RetCode setVirtualizerStrength(int strength) { - return RetCode::ERROR_ILLEGAL_PARAMETER; - } - virtual int getVirtualizerStrength() const { return 0; } - - virtual RetCode setForcedDevice(const AudioDeviceDescription& device) { - return RetCode::ERROR_ILLEGAL_PARAMETER; - } - - virtual AudioDeviceDescription getForcedDevice() const { return {}; } - - virtual std::vector getSpeakerAngles( - const Virtualizer::SpeakerAnglesPayload payload) { - return {}; - } - - virtual bool deviceSupportsEffect(const std::vector& device) { - return true; - } - // Reverb methods, implement ReverbContext - - virtual RetCode setPresetReverbPreset(const PresetReverb::Presets& preset) { - return RetCode::SUCCESS; - } - virtual PresetReverb::Presets getPresetReverbPreset() const { return {}; } - - virtual RetCode setEnvironmentalReverbRoomLevel(int roomLevel) { return RetCode::SUCCESS; } - virtual int getEnvironmentalReverbRoomLevel() const { return 0; } - virtual RetCode setEnvironmentalReverbRoomHfLevel(int roomHfLevel) { return RetCode::SUCCESS; } - virtual int getEnvironmentalReverbRoomHfLevel() const { return 0; } - virtual RetCode setEnvironmentalReverbDecayTime(int decayTime) { return RetCode::SUCCESS; } - virtual int getEnvironmentalReverbDecayTime() const { return 0; } - virtual RetCode setEnvironmentalReverbDecayHfRatio(int decayHfRatio) { - return RetCode::SUCCESS; - } - virtual int getEnvironmentalReverbDecayHfRatio() const { return 0; } - virtual RetCode setReflectionsLevel(int level) { return RetCode::SUCCESS; } - virtual bool getReflectionsLevel() const { return false; } - virtual RetCode setReflectionsDelay(int delay) { return RetCode::SUCCESS; } - virtual bool getReflectionsDelay() const { return false; } - virtual RetCode setEnvironmentalReverbLevel(int level) { return RetCode::SUCCESS; } - virtual int getEnvironmentalReverbLevel() const { return 0; } - virtual RetCode setEnvironmentalReverbDelay(int delay) { return RetCode::SUCCESS; } - virtual int getEnvironmentalReverbDelay() const { return 0; } - virtual RetCode setEnvironmentalReverbDiffusion(int diffusion) { return RetCode::SUCCESS; } - virtual int getEnvironmentalReverbDiffusion() const { return 0; } - virtual RetCode setEnvironmentalReverbDensity(int density) { return RetCode::SUCCESS; } - virtual int getEnvironmentalReverbDensity() const { return 0; } - virtual RetCode setEnvironmentalReverbBypass(bool bypass) { return RetCode::SUCCESS; } - virtual bool getEnvironmentalReverbBypass() const { return true; } - - protected: - std::mutex mMutex; - const OffloadBundleEffectType mType; - pal_stream_handle_t* mPalHandle; - EffectState mState = EffectState::UNINITIALIZED; - bool isEffectActive() { return mState == EffectState::ACTIVE; } -}; - -class BassBoostContext final : public OffloadBundleContext { - public: - BassBoostContext(const Parameter::Common& common, const OffloadBundleEffectType& type, - bool processData); - ~BassBoostContext() override; - virtual void deInit() override; - virtual RetCode enable() override; - virtual RetCode disable() override; - virtual RetCode start(pal_stream_handle_t* palHandle) override; - virtual RetCode stop() override; - RetCode setOutputDevice(const std::vector& device) override; - RetCode setBassBoostStrength(int strength) override; - int getBassBoostStrength() override; - int setOffloadParameters(uint64_t flags) override; - int setOffloadParameters(BassBoostParams* bassParam, uint64_t flags); - bool deviceSupportsEffect(const std::vector& device) override; - - private: - struct BassBoostParams mBassParams; - bool mTempDisabled = false; -}; - -class EqualizerContext final : public OffloadBundleContext { - public: - EqualizerContext(const Parameter::Common& common, const OffloadBundleEffectType& type, - bool processData); - ~EqualizerContext() override; - void init(); - virtual void deInit() override; - virtual RetCode enable() override; - virtual RetCode disable() override; - virtual RetCode start(pal_stream_handle_t* palHandle) override; - virtual RetCode stop() override; - - RetCode setEqualizerPreset(const std::size_t presetIdx) override; - RetCode setEqualizerBandLevels(const std::vector& bandLevels) override; - std::vector getEqualizerBandLevels() const override; - std::vector getEqualizerCenterFreqs() override; - int getEqualizerPreset() const override { return mCurrentPreset; } - int setOffloadParameters(uint64_t flags) override; - int setOffloadParameters(EqualizerParams* params, uint64_t flags); - void updateOffloadParameters(); - - private: - bool isBandLevelIndexInRange(const std::vector& bandLevels) const; - int mCurrentPreset = PRESET_CUSTOM; // current preset index; - std::array mBandLevels; - struct EqualizerParams mEqParams; -}; - -class VirtualizerContext final : public OffloadBundleContext { - public: - VirtualizerContext(const Parameter::Common& common, const OffloadBundleEffectType& type, - bool processData); - ~VirtualizerContext() override; - - virtual void deInit() override; - virtual RetCode enable() override; - virtual RetCode disable() override; - virtual RetCode start(pal_stream_handle_t* palHandle) override; - virtual RetCode stop() override; - RetCode setOutputDevice( - const std::vector& device) - override; - RetCode setVirtualizerStrength(int strength) override; - int getVirtualizerStrength() const override; - - virtual RetCode setForcedDevice(const AudioDeviceDescription& device) override; - - virtual AudioDeviceDescription getForcedDevice() const override { return mForcedDevice; } - - std::vector getSpeakerAngles( - const Virtualizer::SpeakerAnglesPayload payload) override; - - int setOffloadParameters(uint64_t flags) override; - int setOffloadParameters(VirtualizerParams* virtParams, uint64_t flags); - bool deviceSupportsEffect(const std::vector& device) override; - - private: - bool isConfigSupported(size_t channelCount, const AudioDeviceDescription& device); - - struct VirtualizerParams mVirtParams; - AudioDeviceDescription mForcedDevice; - bool mTempDisabled = false; -}; - -class ReverbContext final : public OffloadBundleContext { - public: - ReverbContext(const Parameter::Common& common, const OffloadBundleEffectType& type, - bool processData); - ~ReverbContext() override; - - virtual void deInit() override; - virtual RetCode enable() override; - virtual RetCode disable() override; - virtual RetCode start(pal_stream_handle_t* palHandle) override; - virtual RetCode stop() override; - RetCode setOutputDevice( - const std::vector& device) - override; - - int setOffloadParameters(uint64_t flags) override; - int setOffloadParameters(ReverbParams* reverbParams, uint64_t flags); - - virtual RetCode setPresetReverbPreset(const PresetReverb::Presets& preset) override; - - virtual PresetReverb::Presets getPresetReverbPreset() const override { return mNextPreset; } - - virtual RetCode setEnvironmentalReverbRoomLevel(int roomLevel) override; - virtual int getEnvironmentalReverbRoomLevel() const override; - virtual RetCode setEnvironmentalReverbRoomHfLevel(int roomHfLevel) override; - virtual int getEnvironmentalReverbRoomHfLevel() const override; - virtual RetCode setEnvironmentalReverbDecayTime(int decayTime) override; - virtual int getEnvironmentalReverbDecayTime() const override; - virtual RetCode setEnvironmentalReverbDecayHfRatio(int decayHfRatio) override; - virtual int getEnvironmentalReverbDecayHfRatio() const override; - virtual RetCode setReflectionsLevel(int level) override; - virtual bool getReflectionsLevel() const override; - virtual RetCode setReflectionsDelay(int delay); - virtual bool getReflectionsDelay() const; - virtual RetCode setEnvironmentalReverbLevel(int level) override; - virtual int getEnvironmentalReverbLevel() const override; - virtual RetCode setEnvironmentalReverbDelay(int delay) override; - virtual int getEnvironmentalReverbDelay() const override; - virtual RetCode setEnvironmentalReverbDiffusion(int diffusion) override; - virtual int getEnvironmentalReverbDiffusion() const override; - virtual RetCode setEnvironmentalReverbDensity(int density) override; - virtual int getEnvironmentalReverbDensity() const override; - virtual RetCode setEnvironmentalReverbBypass(bool bypass) override; - virtual bool getEnvironmentalReverbBypass() const override; - - private: - struct ReverbParams mReverbParams; - - PresetReverb::Presets mPreset; - PresetReverb::Presets mNextPreset; - - bool isPreset(); -}; - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleTypes.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleTypes.h deleted file mode 100755 index a2e44a09..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/OffloadBundleTypes.h +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once -#include - -#include -#include "effect-impl/EffectTypes.h" -#include "effect-impl/EffectUUID.h" - -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::android::hardware::audio::effect::Capability; -using aidl::android::hardware::audio::effect::Flags; -using aidl::android::hardware::audio::effect::Equalizer; -using aidl::android::hardware::audio::effect::BassBoost; -using aidl::android::hardware::audio::effect::Virtualizer; -using aidl::android::hardware::audio::effect::PresetReverb; -using aidl::android::hardware::audio::effect::EnvironmentalReverb; -using aidl::android::hardware::audio::effect::Range; - -namespace aidl::qti::effects { - -static const std::string kEqualizerEffectName = "Qti-Offload-Equalizer"; - -constexpr inline size_t MAX_NUM_PRESETS = 10; -constexpr inline size_t MAX_NUM_BANDS = 5; -constexpr inline int PRESET_CUSTOM = -1; -constexpr inline int PRESET_INVALID = -2; - -static const std::vector kBandFrequencies = {{0, 30000, 120000}, - {1, 120001, 460000}, - {2, 460001, 1800000}, - {3, 1800001, 7000000}, - {4, 7000001, 20000000}}; - -constexpr inline std::array kPresetsFrequencies = {60, 230, 910, 3600, - 14000}; - -constexpr inline std::array, MAX_NUM_PRESETS> kBandPresetLevels = - {{{3, 0, 0, 0, 3}, /* Normal Preset */ - {5, 3, -2, 4, 4}, /* Classical Preset */ - {6, 0, 2, 4, 1}, /* Dance Preset */ - {0, 0, 0, 0, 0}, /* Flat Preset */ - {3, 0, 0, 2, -1}, /* Folk Preset */ - {4, 1, 9, 3, 0}, /* Heavy Metal Preset */ - {5, 3, 0, 1, 3}, /* Hip Hop Preset */ - {4, 2, -2, 2, 5}, /* Jazz Preset */ - {-1, 2, 5, 1, -2}, /* Pop Preset */ - {5, 3, -1, 3, 5}}}; /* Rock Preset */ - -static const std::vector kPresets = { - {0, "Normal"}, {1, "Classical"}, {2, "Dance"}, {3, "Flat"}, {4, "Folk"}, - {5, "Heavy Metal"}, {6, "Hip Hop"}, {7, "Jazz"}, {8, "Pop"}, {9, "Rock"}}; - -static Range::EqualizerRange presetRange = MAKE_RANGE(Equalizer, preset, 0, MAX_NUM_PRESETS - 1); -static Range::EqualizerRange bandLevelRange = MAKE_RANGE( - Equalizer, bandLevels, - std::vector{Equalizer::BandLevel({.index = 0, .levelMb = -1500})}, - std::vector{ - Equalizer::BandLevel({.index = MAX_NUM_BANDS - 1, .levelMb = 1500})}); -static Range::EqualizerRange bandFrequencyRange = - MAKE_RANGE(Equalizer, bandFrequencies, kBandFrequencies, kBandFrequencies); -static Range::EqualizerRange presetsRange = MAKE_RANGE(Equalizer, presets, kPresets, kPresets); -static Range::EqualizerRange centerFreqRange = - MAKE_RANGE(Equalizer, centerFreqMh, std::vector({1}), std::vector({})); - -const std::vector kEqRanges = { - presetRange, bandLevelRange, bandFrequencyRange, presetsRange, centerFreqRange}; - -static const Capability kEqualizerCapabilites = {.range = kEqRanges}; - -static const Descriptor kEqualizerDesc = { - .common = {.id = {.type = kEqualizerTypeUUID, - .uuid = kEqualizerOffloadQtiUUID, - .proxy = kEqualizerProxyUUID}, - .flags = {.type = Flags::Type::INSERT, - .volume = Flags::Volume::CTRL, - .hwAcceleratorMode = Flags::HardwareAccelerator::TUNNEL, - .deviceIndication = true, - .offloadIndication = true}, - .name = kEqualizerEffectName, - .implementor = "Qualcomm Technologies Inc."}, - .capability = kEqualizerCapabilites}; - -static const bool mStrengthSupported = true; -static const int mMaxBBStrengthSupported = 1000; - -const std::vector kBassBoostRanges = { - MAKE_RANGE(BassBoost, strengthPm, 0, mMaxBBStrengthSupported)}; - -static const Capability kBassBoostCap = {.range = kBassBoostRanges}; - -static const std::string kBassBoostEffectName = "Qti-Offload-BassBoost"; - -static const Descriptor kBassBoostDesc = { - .common = {.id = {.type = kBassBoostTypeUUID, - .uuid = kBassBoostOffloadQtiUUID, - .proxy = kBassBoostProxyUUID}, - .flags = {.type = Flags::Type::INSERT, - .volume = Flags::Volume::CTRL, - .hwAcceleratorMode = Flags::HardwareAccelerator::TUNNEL, - .deviceIndication = true, - .offloadIndication = true}, - .name = kBassBoostEffectName, - .implementor = "Qualcomm Technologies Inc."}, - .capability = kBassBoostCap}; - -static const int mMaxVirtualizerStrengthSupported = 1000; -static const std::vector kVirtualizerRanges = { - MAKE_RANGE(Virtualizer, strengthPm, 0, mMaxVirtualizerStrengthSupported)}; - -static const Capability kVirtualizerCap = {.range = kVirtualizerRanges}; - -static const std::string kVirtualizerEffectName = "Qti-Offload-Virtualizer"; - -static const Descriptor kVirtualizerDesc = { - .common = {.id = {.type = kVirtualizerTypeUUID, - .uuid = kVirtualizerOffloadQtiUUID, - .proxy = kVirtualizerProxyUUID}, - .flags = {.type = Flags::Type::INSERT, - .volume = Flags::Volume::CTRL, - .hwAcceleratorMode = Flags::HardwareAccelerator::TUNNEL, - .deviceIndication = true, - .offloadIndication = true}, - .name = kVirtualizerEffectName, - .implementor = "Qualcomm Technologies Inc."}, - .capability = kVirtualizerCap}; - -constexpr inline int kMinLevel = -6000; -constexpr inline int kMaxDecayTime = 7000; - -static const std::vector kEnvReverbRanges = { - MAKE_RANGE(EnvironmentalReverb, roomLevelMb, kMinLevel, 0), - MAKE_RANGE(EnvironmentalReverb, roomHfLevelMb, -4000, 0), - MAKE_RANGE(EnvironmentalReverb, decayTimeMs, 0, kMaxDecayTime), - MAKE_RANGE(EnvironmentalReverb, decayHfRatioPm, 100, 2000), - MAKE_RANGE(EnvironmentalReverb, levelMb, kMinLevel, 0), - MAKE_RANGE(EnvironmentalReverb, delayMs, 0, 65), - MAKE_RANGE(EnvironmentalReverb, diffusionPm, 0, 1000), - MAKE_RANGE(EnvironmentalReverb, densityPm, 0, 1000)}; - -static const Capability kEnvReverbCap = { - .range = Range::make(kEnvReverbRanges)}; - -static const std::string kAuxEnvReverbEffectName = "Qti-Auxiliary Environmental Reverb"; -static const Descriptor kAuxEnvReverbDesc = { - .common = {.id = {.type = kEnvReverbTypeUUID, - .uuid = kAuxEnvReverbOffloadQtiUUID, - .proxy = std::nullopt}, - .flags = {.type = Flags::Type::AUXILIARY, - .volume = Flags::Volume::CTRL, - .hwAcceleratorMode = Flags::HardwareAccelerator::TUNNEL, - .offloadIndication = true}, - .name = kAuxEnvReverbEffectName, - .implementor = "Qualcomm Technologies Inc."}, - .capability = kEnvReverbCap}; - -static const std::string kInsertEnvReverbEffectName = "Qti-Insert Environmental Reverb"; -static const Descriptor kInsertEnvReverbDesc = { - .common = {.id = {.type = kEnvReverbTypeUUID, - .uuid = kInsertEnvReverbOffloadQtiUUID, - .proxy = std::nullopt}, - .flags = {.type = Flags::Type::INSERT, - .insert = Flags::Insert::FIRST, - .volume = Flags::Volume::CTRL, - .hwAcceleratorMode = Flags::HardwareAccelerator::TUNNEL, - .offloadIndication = true}, - .name = kInsertEnvReverbEffectName, - .implementor = "Qualcomm Technologies Inc."}, - .capability = kEnvReverbCap}; - -static const std::vector kSupportedPresets{ - ndk::enum_range().begin(), - ndk::enum_range().end()}; - -static const std::vector kPresetReverbRanges = { - MAKE_RANGE(PresetReverb, supportedPresets, kSupportedPresets, kSupportedPresets)}; - -static const Capability kPresetReverbCap = { - .range = Range::make(kPresetReverbRanges)}; - -static const std::string kAuxPresetReverbEffectName = "Qti-Auxiliary Preset Reverb"; -static const Descriptor kAuxPresetReverbDesc = { - .common = - { - .id = {.type = kPresetReverbTypeUUID, - .uuid = kAuxPresetReverbOffloadQtiUUID, - .proxy = std::nullopt}, - .flags = {.type = Flags::Type::AUXILIARY, - .volume = Flags::Volume::CTRL, - .hwAcceleratorMode = Flags::HardwareAccelerator::TUNNEL, - .offloadIndication = true}, - .name = kAuxPresetReverbEffectName, - .implementor = "Qualcomm Technologies Inc.", - }, - .capability = kPresetReverbCap}; - -static const std::string kInsertPresetReverbEffectName = "Qti-Insert Preset Reverb"; -static const Descriptor kInsertPresetReverbDesc = { - .common = - { - .id = {.type = kPresetReverbTypeUUID, - .uuid = kInsertPresetReverbOffloadQtiUUID, - .proxy = std::nullopt}, - .flags = {.type = Flags::Type::INSERT, - .insert = Flags::Insert::FIRST, - .volume = Flags::Volume::CTRL, - .hwAcceleratorMode = Flags::HardwareAccelerator::TUNNEL, - .offloadIndication = true}, - .name = kInsertPresetReverbEffectName, - .implementor = "Qualcomm Technologies Inc.", - }, - .capability = kPresetReverbCap}; - -enum class OffloadBundleEffectType { - BASS_BOOST, - VIRTUALIZER, - EQUALIZER, - AUX_ENV_REVERB, - INSERT_ENV_REVERB, - AUX_PRESET_REVERB, - INSERT_PRESET_REVERB, -}; - -inline std::ostream& operator<<(std::ostream& out, const OffloadBundleEffectType& type) { - out << " Type "; - switch (type) { - case OffloadBundleEffectType::BASS_BOOST: - return out << "BASS_BOOST"; - case OffloadBundleEffectType::VIRTUALIZER: - return out << "VIRTUALIZER"; - case OffloadBundleEffectType::EQUALIZER: - return out << "EQUALIZER"; - case OffloadBundleEffectType::AUX_ENV_REVERB: - return out << "AUX_ENV_REVERB"; - case OffloadBundleEffectType::INSERT_ENV_REVERB: - return out << "INSERT_ENV_REVERB"; - case OffloadBundleEffectType::AUX_PRESET_REVERB: - return out << "AUX_PRESET_REVERB"; - case OffloadBundleEffectType::INSERT_PRESET_REVERB: - return out << "INSERT_PRESET_REVERB"; - } - return out << "EnumOffloadBundleEffectTypeError"; -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/ParamDelegator.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/ParamDelegator.cpp deleted file mode 100755 index c8d01b0e..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/ParamDelegator.cpp +++ /dev/null @@ -1,326 +0,0 @@ -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_Effect_ParamDelegator" - -#include "ParamDelegator.h" -#include - -namespace aidl::qti::effects { - -#define OFFLOAD_PRESET_START_OFFSET 19 -const int kEqualizerOpenSlToOffloadMap[] = { - OFFLOAD_PRESET_START_OFFSET, /* Normal Preset */ - OFFLOAD_PRESET_START_OFFSET + 1, /* Classical Preset */ - OFFLOAD_PRESET_START_OFFSET + 2, /* Dance Preset */ - OFFLOAD_PRESET_START_OFFSET + 3, /* Flat Preset */ - OFFLOAD_PRESET_START_OFFSET + 4, /* Folk Preset */ - OFFLOAD_PRESET_START_OFFSET + 5, /* Heavy Metal Preset */ - OFFLOAD_PRESET_START_OFFSET + 6, /* Hip Hop Preset */ - OFFLOAD_PRESET_START_OFFSET + 7, /* Jazz Preset */ - OFFLOAD_PRESET_START_OFFSET + 8, /* Pop Preset */ - OFFLOAD_PRESET_START_OFFSET + 9, /* Rock Preset */ - OFFLOAD_PRESET_START_OFFSET + 10 /* FX Booster */ -}; - -const int kReverbOpenSlToOffloadMap[] = {15, 16, 17, 18, 19, 20}; - -#define EXIT_IF_SET_PARAM_FAILS(ret) \ - if (ret) { \ - LOG(ERROR) << __func__ << "pal_set_param failed"; \ - return ret; \ - } - -#define VALUE_OR_RETURN(ptr) \ - ({ \ - auto temp = (ptr); \ - if (temp.get() == nullptr) { \ - LOG(ERROR) << __func__ << "could not allocate memory"; \ - return -ENOMEM; \ - } \ - std::move(temp); \ - }) - -using CustomDeletor = void (*)(void *); -template -std::unique_ptr allocate(int size) { - T *obj = reinterpret_cast(calloc(1, size)); - return std::unique_ptr{obj, free}; -} - -using EffectCustomPayload = pal_effect_custom_payload_t; - -int ParamDelegator::sendKvPayload(pal_stream_handle_t *handle, uint32_t tag, - pal_key_vector_t *kvp) { - uint32_t payloadSize = sizeof(pal_param_payload) + sizeof(effect_pal_payload_t) + - sizeof(pal_key_vector_t) + kvp->num_tkvs * sizeof(pal_key_value_pair_t); - - auto payload = VALUE_OR_RETURN(allocate(payloadSize)); - uint8_t *payloadPtr = payload.get(); - - pal_param_payload *palPayload = (pal_param_payload *)payloadPtr; - palPayload->payload_size = sizeof(effect_pal_payload_t) + sizeof(pal_key_vector_t) + - kvp->num_tkvs * sizeof(pal_key_value_pair_t); - - effect_pal_payload_t *effectPalPayload = - (effect_pal_payload_t *)(payloadPtr + sizeof(pal_param_payload)); - effectPalPayload->isTKV = PARAM_TKV; - effectPalPayload->tag = tag; - effectPalPayload->payloadSize = - sizeof(pal_key_vector_t) + kvp->num_tkvs * sizeof(pal_key_value_pair_t); - - pal_key_vector_t *palKeyVector = (pal_key_vector_t *)(payloadPtr + sizeof(pal_param_payload) + - sizeof(effect_pal_payload_t)); - - palKeyVector->num_tkvs = kvp->num_tkvs; - memcpy(palKeyVector->kvp, kvp->kvp, (kvp->num_tkvs * sizeof(pal_key_value_pair_t))); - - return pal_stream_set_param(handle, PAL_PARAM_ID_UIEFFECT, palPayload); -} - -int ParamDelegator::setCustomPayload(pal_stream_handle_t *handle, uint32_t tag, - pal_effect_custom_payload_t *data, uint32_t customDataSize) { - uint32_t payloadSize = sizeof(pal_param_payload) + sizeof(effect_pal_payload_t) + - sizeof(pal_effect_custom_payload_t) + customDataSize; - - auto payload = VALUE_OR_RETURN(allocate(payloadSize)); - uint8_t *payloadPtr = payload.get(); - - pal_param_payload *palPayload = (pal_param_payload *)payloadPtr; - palPayload->payload_size = - sizeof(effect_pal_payload_t) + sizeof(pal_effect_custom_payload_t) + customDataSize; - - effect_pal_payload_t *effectPalPayload = - (effect_pal_payload_t *)(payloadPtr + sizeof(pal_param_payload)); - effectPalPayload->isTKV = PARAM_NONTKV; - effectPalPayload->tag = tag; - effectPalPayload->payloadSize = sizeof(pal_effect_custom_payload_t) + customDataSize; - - pal_effect_custom_payload_t *customPayload = - (pal_effect_custom_payload_t *)(payloadPtr + sizeof(pal_param_payload) + - sizeof(effect_pal_payload_t)); - - customPayload->paramId = data->paramId; - memcpy(customPayload->data, data->data, customDataSize); - return pal_stream_set_param(handle, PAL_PARAM_ID_UIEFFECT, palPayload); -} - -int ParamDelegator::setCustomPayloadGeneric(pal_stream_handle_t *handle, uint32_t tag, - uint32_t paramId, uint32_t data) { - // All reverb custom params are of same length, so reuse the same size for all params - uint32_t customDataSize = GENERIC_CUSTOM_PARAM_LEN * sizeof(uint32_t); - uint32_t payloadAllocSize = sizeof(pal_effect_custom_payload_t) + customDataSize; - auto customPayload = VALUE_OR_RETURN(allocate(payloadAllocSize)); - customPayload->paramId = paramId; - customPayload->data[0] = data; - LOG(VERBOSE) << __func__ << " tag " << std::hex << tag << " paramId " << paramId << std::dec - << " data " << data; - return setCustomPayload(handle, tag, customPayload.get(), customDataSize); -} - -int ParamDelegator::updatePalParameters(pal_stream_handle_t *handle, - struct BassBoostParams *bassboost, uint64_t flags) { - int ret = 0; - uint32_t streamTag = TAG_STREAM_BASS_BOOST; - LOG(VERBOSE) << __func__ << " flags " << std::hex << flags; - if (flags & BASSBOOST_ENABLE_FLAG) { - uint32_t numberOfKvs = 1; - auto allocSize = sizeof(pal_key_vector_t) + numberOfKvs * sizeof(pal_key_value_pair_t); - auto palKeyVector = VALUE_OR_RETURN(allocate(allocSize)); - - palKeyVector->num_tkvs = numberOfKvs; - palKeyVector->kvp[0].key = BASS_BOOST_SWITCH; - palKeyVector->kvp[0].value = bassboost->mEnabled; - - ret = sendKvPayload(handle, streamTag, palKeyVector.get()); - EXIT_IF_SET_PARAM_FAILS(ret); - } - - if (flags & BASSBOOST_STRENGTH) { - ret = setCustomPayloadGeneric(handle, streamTag, PARAM_ID_BASS_BOOST_STRENGTH, - bassboost->mStrength); - } - - return ret; -} - -int ParamDelegator::updatePalParameters(pal_stream_handle_t *handle, - struct VirtualizerParams *virtualizer, uint64_t flags) { - int ret = 0; - uint32_t streamTag = TAG_STREAM_VIRTUALIZER; - LOG(VERBOSE) << __func__ << " flags " << std::hex << flags; - if (flags & VIRTUALIZER_ENABLE_FLAG) { - uint32_t numberOfKvs = 1; - auto allocSize = sizeof(pal_key_vector_t) + numberOfKvs * sizeof(pal_key_value_pair_t); - auto palKeyVector = VALUE_OR_RETURN(allocate(allocSize)); - - palKeyVector->num_tkvs = numberOfKvs; - palKeyVector->kvp[0].key = VIRTUALIZER_SWITCH; - palKeyVector->kvp[0].value = virtualizer->enable; - - ret = sendKvPayload(handle, streamTag, palKeyVector.get()); - EXIT_IF_SET_PARAM_FAILS(ret); - } - - // only 1 of below flags can be set at a time. - uint32_t paramId = 0, data = 0; - if (flags & VIRTUALIZER_STRENGTH) { - paramId = PARAM_ID_VIRTUALIZER_STRENGTH; - data = virtualizer->strength; - } else if (flags & VIRTUALIZER_OUT_TYPE) { - paramId = PARAM_ID_VIRTUALIZER_OUT_TYPE; - data = virtualizer->type; - } else if (flags & VIRTUALIZER_GAIN_ADJUST) { - paramId = PARAM_ID_VIRTUALIZER_GAIN_ADJUST; - data = virtualizer->gainAdjust; - } else { // no valid flag return - return 0; - } - - return setCustomPayloadGeneric(handle, streamTag, paramId, data); -} - -int ParamDelegator::updatePalParameters(pal_stream_handle_t *handle, struct EqualizerParams *eq, - uint64_t flags) { - int ret = 0; - uint32_t streamTag = TAG_STREAM_EQUALIZER; - if (!handle) { - LOG(ERROR) << __func__ << " stream is not opened, invalid pal handle"; - return -EINVAL; - } - LOG(VERBOSE) << __func__ << " flags " << std::hex << flags; - if ((eq->config.presetId < -1) || ((flags & EQ_PRESET) && (eq->config.presetId == -1))) { - LOG(VERBOSE) << __func__ << " no preset to set"; - return 0; - } - - if (flags & EQ_ENABLE_FLAG) { - LOG(VERBOSE) << __func__ << " Equalizer enable"; - uint32_t numberOfKvs = 1; - auto allocSize = sizeof(pal_key_vector_t) + numberOfKvs * sizeof(pal_key_value_pair_t); - auto palKeyVector = VALUE_OR_RETURN(allocate(allocSize)); - - palKeyVector->num_tkvs = numberOfKvs; - palKeyVector->kvp[0].key = EQUALIZER_SWITCH; - palKeyVector->kvp[0].value = eq->enable; - ret = sendKvPayload(handle, streamTag, palKeyVector.get()); - LOG(VERBOSE) << __func__ << " Equalizer enable: ret " << ret; - EXIT_IF_SET_PARAM_FAILS(ret); - } - - // at a time only 1 of below flags can be set. - if (flags & EQ_PRESET) { - LOG(VERBOSE) << __func__ << " Equalizer preset"; - uint32_t customDataSize = EQ_CONFIG_PARAM_LEN * sizeof(uint32_t); - uint32_t allocSize = sizeof(pal_effect_custom_payload_t) + customDataSize; - auto customPayload = VALUE_OR_RETURN(allocate(allocSize)); - customPayload->paramId = PARAM_ID_EQ_CONFIG; - customPayload->data[0] = eq->config.pregain; - customPayload->data[1] = kEqualizerOpenSlToOffloadMap[eq->config.presetId]; - customPayload->data[2] = 0; // num_of_band must be 0 for preset - - ret = setCustomPayload(handle, streamTag, customPayload.get(), customDataSize); - } else if (flags & EQ_BANDS_LEVEL) { - LOG(VERBOSE) << __func__ << " Equalizer band levels"; - uint32_t customDataSize = - (EQ_CONFIG_PARAM_LEN + (eq->config.numBands * EQ_CONFIG_PER_BAND_PARAM_LEN)) * - sizeof(uint32_t); - - uint32_t allocSize = sizeof(pal_effect_custom_payload_t) + customDataSize; - auto customPayload = VALUE_OR_RETURN(allocate(allocSize)); - - customPayload->paramId = PARAM_ID_EQ_CONFIG; - int index = 0; - customPayload->data[index++] = eq->config.pregain; - customPayload->data[index++] = CUSTOM_OPENSL_PRESET; - customPayload->data[index++] = eq->config.numBands; - for (int i = 0; i < eq->config.numBands; i++) { - LOG(VERBOSE) << __func__ << " band " << i << " filter " << eq->bandConfig[i].filterType - << " frequency " << eq->bandConfig[i].frequencyMhz << " gain " - << eq->bandConfig[i].gainMb << " quality factor " - << eq->bandConfig[i].qFactor << " index " << eq->bandConfig[i].bandIndex; - customPayload->data[index++] = eq->bandConfig[i].filterType; - customPayload->data[index++] = eq->bandConfig[i].frequencyMhz; - customPayload->data[index++] = eq->bandConfig[i].gainMb; - customPayload->data[index++] = eq->bandConfig[i].qFactor; - customPayload->data[index++] = eq->bandConfig[i].bandIndex; - } - ret = setCustomPayload(handle, streamTag, customPayload.get(), customDataSize); - LOG(VERBOSE) << __func__ << " Equalizer band levels ret " << ret; - } - - return ret; -} - -int ParamDelegator::updatePalParameters(pal_stream_handle_t *handle, struct ReverbParams *reverb, - uint64_t flags) { - int ret = 0; - uint32_t streamTag = TAG_STREAM_REVERB; - LOG(VERBOSE) << __func__ << " flags " << std::hex << flags; - if (flags & REVERB_ENABLE_FLAG) { - uint32_t numberOfKvs = 1; - auto memSize = sizeof(pal_key_vector_t) + numberOfKvs * sizeof(pal_key_value_pair_t); - auto palKeyVector = VALUE_OR_RETURN(allocate(memSize)); - - palKeyVector->num_tkvs = numberOfKvs; - palKeyVector->kvp[0].key = REVERB_SWITCH; - palKeyVector->kvp[0].value = reverb->enable; - ret = sendKvPayload(handle, streamTag, palKeyVector.get()); - EXIT_IF_SET_PARAM_FAILS(ret); - } - - // Only 1 of these is possible at a time. - uint32_t paramId = 0, data = 0; - if (flags & REVERB_MODE) { - paramId = PARAM_ID_REVERB_MODE; - data = reverb->mode; - } else if (flags & REVERB_PRESET) { - paramId = PARAM_ID_REVERB_PRESET; - data = kReverbOpenSlToOffloadMap[reverb->preset - 1]; - } else if (flags & REVERB_WET_MIX) { - paramId = PARAM_ID_REVERB_WET_MIX; - data = reverb->wetMix; - } else if (flags & REVERB_GAIN_ADJUST) { - paramId = PARAM_ID_REVERB_GAIN_ADJUST; - data = reverb->gainAdjust; - } else if (flags & REVERB_ROOM_LEVEL) { - paramId = PARAM_ID_REVERB_ROOM_LEVEL; - data = reverb->roomLevel; - } else if (flags & REVERB_ROOM_HF_LEVEL) { - paramId = PARAM_ID_REVERB_ROOM_HF_LEVEL; - data = reverb->roomHfLevel; - } else if (flags & REVERB_DECAY_TIME) { - paramId = PARAM_ID_REVERB_DECAY_TIME; - data = reverb->decayTime; - } else if (flags & REVERB_DECAY_HF_RATIO) { - paramId = PARAM_ID_REVERB_DECAY_HF_RATIO; - data = reverb->decayHfRatio; - } else if (flags & REVERB_REFLECTIONS_LEVEL) { - paramId = PARAM_ID_REVERB_REFLECTIONS_LEVEL; - data = reverb->reflectionsLevel; - } else if (flags & REVERB_REFLECTIONS_DELAY) { - paramId = PARAM_ID_REVERB_REFLECTIONS_DELAY; - data = reverb->reflectionsDelay; - } else if (flags & REVERB_LEVEL) { - paramId = PARAM_ID_REVERB_LEVEL; - data = reverb->level; - } else if (flags & REVERB_DELAY) { - paramId = PARAM_ID_REVERB_DELAY; - data = reverb->delay; - } else if (flags & REVERB_DIFFUSION) { - paramId = PARAM_ID_REVERB_DIFFUSION; - data = reverb->diffusion; - } else if (flags & REVERB_DENSITY) { - paramId = PARAM_ID_REVERB_DENSITY; - data = reverb->density; - } else { // no flag found - return 0; - } - - return setCustomPayloadGeneric(handle, streamTag, paramId, data); -} - -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/ParamDelegator.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/ParamDelegator.h deleted file mode 100755 index 2d290908..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/ParamDelegator.h +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include "PalApi.h" -#include "kvh2xml.h" - -namespace aidl::qti::effects { - -// All existing virtualizer, reverb, bass parameters are of length 1 -#define GENERIC_CUSTOM_PARAM_LEN 1 - -#define EQ_ENABLE_PARAM_LEN 1 -#define EQ_CONFIG_PARAM_LEN 3 -#define EQ_CONFIG_PER_BAND_PARAM_LEN 5 -#define EQ_NUM_BANDS_PARAM_LEN 1 -#define EQ_BAND_LEVELS_PARAM_LEN 13 -#define EQ_BAND_LEVEL_RANGE_PARAM_LEN 2 -#define EQ_BAND_FREQS_PARAM_LEN 13 -#define EQ_SINGLE_BAND_FREQ_RANGE_PARAM_LEN 2 -#define EQ_SINGLE_BAND_FREQ_PARAM_LEN 1 -#define EQ_BAND_INDEX_PARAM_LEN 1 -#define EQ_PRESET_ID_PARAM_LEN 1 -#define EQ_NUM_PRESETS_PARAM_LEN 1 -#define EQ_PRESET_NAME_PARAM_LEN 32 - -#define EQ_BAND_BOOST 5 - -#define Q27_UNITY (1 << 27) -#define Q8_UNITY (1 << 8) -#define CUSTOM_OPENSL_PRESET 18 - -struct VirtualizerParams { - uint32_t enable = 0; - uint32_t strength = 0; - uint32_t type = 0; - uint32_t gainAdjust = 0; -}; - -struct ReverbParams { - uint32_t enable = 0; - uint32_t mode = 0; - uint32_t preset = 0; - uint32_t wetMix = 0; - int32_t gainAdjust = 0; - int32_t roomLevel = 0; - int32_t roomHfLevel = 0; - uint32_t decayTime = 0; - uint32_t decayHfRatio = 0; - int32_t reflectionsLevel = 0; - uint32_t reflectionsDelay = 0; - int32_t level = 0; - uint32_t delay = 0; - uint32_t diffusion = 0; - uint32_t density = 0; - uint32_t bypass = 0; -}; - -struct BassBoostParams { - uint32_t mEnabled = 0; - uint32_t mStrength = 0; -}; - -#define MAX_EQ_BANDS 12 -#define MAX_OSL_EQ_BANDS 5 -struct EqualizerConfig { - int32_t pregain; - int32_t presetId; - uint32_t numBands; -}; -struct EqualizerBandConfig { - int32_t bandIndex = 0; - uint32_t filterType = 0; - uint32_t frequencyMhz = 0; - int32_t gainMb = 0; - uint32_t qFactor = 0; -}; - -struct EqualizerParams { - uint32_t enable = 0; - struct EqualizerConfig config; - struct EqualizerBandConfig bandConfig[MAX_EQ_BANDS]; -}; - -#define PARAM_ID_MODULE_ENABLE 0x8001026 -#define PARAM_ID_EQ_CONFIG 0x800110c -#define PARAM_ID_PBE_PARAMS_CONFIG 0x8001150 -#define PARAM_ID_BASS_BOOST_MODE 0x800112c -#define PARAM_ID_BASS_BOOST_STRENGTH 0x800112D -#define PARAM_ID_REVERB_MODE 0x80010fd -#define PARAM_ID_REVERB_PRESET 0x80010fe -#define PARAM_ID_REVERB_WET_MIX 0x80010ff -#define PARAM_ID_REVERB_GAIN_ADJUST 0x8001100 -#define PARAM_ID_REVERB_ROOM_LEVEL 0x8001101 -#define PARAM_ID_REVERB_ROOM_HF_LEVEL 0x8001102 -#define PARAM_ID_REVERB_DECAY_TIME 0x8001103 -#define PARAM_ID_REVERB_DECAY_HF_RATIO 0x8001104 -#define PARAM_ID_REVERB_REFLECTIONS_LEVEL 0x8001105 -#define PARAM_ID_REVERB_REFLECTIONS_DELAY 0x8001106 -#define PARAM_ID_REVERB_LEVEL 0x8001107 -#define PARAM_ID_REVERB_DELAY 0x8001108 -#define PARAM_ID_REVERB_DIFFUSION 0x8001109 -#define PARAM_ID_REVERB_DENSITY 0x800110a - -#define PARAM_ID_VIRTUALIZER_STRENGTH 0x8001136 -#define PARAM_ID_VIRTUALIZER_OUT_TYPE 0x8001137 -#define PARAM_ID_VIRTUALIZER_GAIN_ADJUST 0x8001138 - -#define BASSBOOST_ENABLE_FLAG (1 << 0) -#define BASSBOOST_STRENGTH (BASSBOOST_ENABLE_FLAG << 1) -#define BASSBOOST_MODE (BASSBOOST_STRENGTH << 1) - -#define VIRTUALIZER_ENABLE_FLAG (1 << 0) -#define VIRTUALIZER_STRENGTH (VIRTUALIZER_ENABLE_FLAG << 1) -#define VIRTUALIZER_OUT_TYPE (VIRTUALIZER_STRENGTH << 1) -#define VIRTUALIZER_GAIN_ADJUST (VIRTUALIZER_OUT_TYPE << 1) - -#define EQ_ENABLE_FLAG (1 << 0) -#define EQ_PRESET (EQ_ENABLE_FLAG << 1) -#define EQ_BANDS_LEVEL (EQ_PRESET << 1) - -#define REVERB_ENABLE_FLAG (1 << 0) -#define REVERB_MODE (REVERB_ENABLE_FLAG << 1) -#define REVERB_PRESET (REVERB_MODE << 1) -#define REVERB_WET_MIX (REVERB_PRESET << 1) -#define REVERB_GAIN_ADJUST (REVERB_WET_MIX << 1) -#define REVERB_ROOM_LEVEL (REVERB_GAIN_ADJUST << 1) -#define REVERB_ROOM_HF_LEVEL (REVERB_ROOM_LEVEL << 1) -#define REVERB_DECAY_TIME (REVERB_ROOM_HF_LEVEL << 1) -#define REVERB_DECAY_HF_RATIO (REVERB_DECAY_TIME << 1) -#define REVERB_REFLECTIONS_LEVEL (REVERB_DECAY_HF_RATIO << 1) -#define REVERB_REFLECTIONS_DELAY (REVERB_REFLECTIONS_LEVEL << 1) -#define REVERB_LEVEL (REVERB_REFLECTIONS_DELAY << 1) -#define REVERB_DELAY (REVERB_LEVEL << 1) -#define REVERB_DIFFUSION (REVERB_DELAY << 1) -#define REVERB_DENSITY (REVERB_DIFFUSION << 1) - -struct ParamDelegator { - public: - /** - * @brief updatePalParameters sends the pal parameters to update offload parameters - * for bass boost effect. - * @param handle valid pal stream handle - * @param bassboost bassboost configuration - * @param flags flags related to bassboost - */ - static int updatePalParameters(pal_stream_handle_t *handle, struct BassBoostParams *bassboost, - uint64_t flags); - - /** - * @brief updatePalParameters sends the pal parameters to update offload parameters - * for virtualizer - * @param handle valid pal stream handle - * @param virtualizer virtualizer configuration - * @param flags flags related to virtualizer - */ - static int updatePalParameters(pal_stream_handle_t *handle, - struct VirtualizerParams *virtualizer, uint64_t flags); - - /** - * @brief updatePalParameters sends the pal parameters to update offload parameters - * for Equalizer effect. - * @param handle valid pal stream handle - * @param eq Equalizer configuration - * @param flags flags related to Equalizer - */ - static int updatePalParameters(pal_stream_handle_t *handle, struct EqualizerParams *eq, - uint64_t flags); - - /** - * @brief updatePalParameters sends the pal parameters to update offload parameters - * for reverb effect. - * @param handle valid pal stream handle - * @param reverb reverb configuration - * @param flags flags related to reverb - */ - static int updatePalParameters(pal_stream_handle_t *handle, struct ReverbParams *reverb, - uint64_t flags); - - private: - /** - * @brief sendKvPayload sends the pal key vector to PAL for TKVs config of effects - * @param handle valid pal stream handle - * @param tag stream tag - * @param kvp pal key vector - */ - static int sendKvPayload(pal_stream_handle_t *handle, uint32_t tag, pal_key_vector_t *kvp); - - /** - * @brief setCustomPayload sends the pal_effect_custom_payload_t for non TKV config - * @param handle valid pal stream handle - * @param data custom payload - * @param customDataSize size of custom payload - */ - static int setCustomPayload(pal_stream_handle_t *hanlde, uint32_t tag, - pal_effect_custom_payload_t *data, uint32_t customDataSize); - - /** - * @brief setCustomPayloadGeneric create a custom payload for BB, Virtualizer, Reverb - * from paramId and data as these all parameters are of size 1. - * @param handle valid pal stream handle - * @param tag stream tag - * @param paramId param id - * @param data data related to param - */ - static int setCustomPayloadGeneric(pal_stream_handle_t *handle, uint32_t tag, uint32_t paramId, - uint32_t data); -}; -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/ReverbContext.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/ReverbContext.cpp deleted file mode 100755 index 57ebe57b..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/ReverbContext.cpp +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_Effect_ReverbQti" -#include -#include - -#include "OffloadBundleContext.h" -#include "OffloadBundleTypes.h" - -namespace aidl::qti::effects { - -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; - -bool ReverbContext::isPreset() { - return (mType == OffloadBundleEffectType::AUX_PRESET_REVERB || - mType == OffloadBundleEffectType::INSERT_PRESET_REVERB); -} - -ReverbContext::ReverbContext(const Parameter::Common& common, const OffloadBundleEffectType& type, - bool processData) - : OffloadBundleContext(common, type, processData) { - LOG(DEBUG) << __func__ << type << " ioHandle " << common.ioHandle; - if (isPreset()) { - mPreset = PresetReverb::Presets::NONE; - mNextPreset = PresetReverb::Presets::NONE; - } - mState = EffectState::INITIALIZED; -} - -ReverbContext::~ReverbContext() { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - deInit(); -} - -void ReverbContext::deInit() { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - stop(); -} - -RetCode ReverbContext::enable() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - if (isEffectActive()) return RetCode::ERROR_ILLEGAL_PARAMETER; - mState = EffectState::ACTIVE; - if (isPreset() && mNextPreset == PresetReverb::Presets::NONE) { - return RetCode::SUCCESS; - } - mReverbParams.enable = 1; - return RetCode::SUCCESS; -} - -RetCode ReverbContext::disable() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - if (!isEffectActive()) return RetCode::ERROR_ILLEGAL_PARAMETER; - mState = EffectState::INITIALIZED; - mReverbParams.enable = 0; - setOffloadParameters(&mReverbParams, REVERB_ENABLE_FLAG); - return RetCode::SUCCESS; -} - -RetCode ReverbContext::start(pal_stream_handle_t* palHandle) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - - mPalHandle = palHandle; - if (isEffectActive() && isPreset()) { - setOffloadParameters(&mReverbParams, REVERB_ENABLE_FLAG | REVERB_PRESET); - } else { - LOG(DEBUG) << __func__ << mType << " inactive or non preset"; - } - - return RetCode::SUCCESS; -} - -RetCode ReverbContext::stop() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - struct ReverbParams reverbParam; - setOffloadParameters(&reverbParam, REVERB_ENABLE_FLAG); - mPalHandle = nullptr; - return RetCode::SUCCESS; -} - -RetCode ReverbContext::setOutputDevice( - const std::vector& device) { - mOutputDevice = device; - return RetCode::SUCCESS; -} - -RetCode ReverbContext::setPresetReverbPreset(const PresetReverb::Presets& preset) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " preset " << toString(preset); - mNextPreset = preset; - mReverbParams.preset = static_cast(preset); - if (preset != PresetReverb::Presets::NONE) { - mReverbParams.enable = 1; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_PRESET); - } - return RetCode::SUCCESS; -} - -RetCode ReverbContext::setEnvironmentalReverbRoomLevel(int roomLevel) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << roomLevel; - mReverbParams.roomLevel = roomLevel; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_ROOM_LEVEL); - return RetCode::SUCCESS; -} - -int ReverbContext::getEnvironmentalReverbRoomLevel() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << mReverbParams.roomLevel; - return mReverbParams.roomLevel; -} - -RetCode ReverbContext::setEnvironmentalReverbRoomHfLevel(int roomHfLevel) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << roomHfLevel; - mReverbParams.roomHfLevel = roomHfLevel; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_ROOM_HF_LEVEL); - return RetCode::SUCCESS; -} - -int ReverbContext::getEnvironmentalReverbRoomHfLevel() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << mReverbParams.roomHfLevel; - return mReverbParams.roomHfLevel; -} - -RetCode ReverbContext::setEnvironmentalReverbDecayTime(int decayTime) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << decayTime; - mReverbParams.decayTime = decayTime; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_DECAY_TIME); - return RetCode::SUCCESS; -} - -int ReverbContext::getEnvironmentalReverbDecayTime() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << mReverbParams.decayTime; - return mReverbParams.decayTime; -} - -RetCode ReverbContext::setEnvironmentalReverbDecayHfRatio(int decayHfRatio) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << decayHfRatio; - mReverbParams.decayHfRatio = decayHfRatio; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_DECAY_HF_RATIO); - return RetCode::SUCCESS; -} - -int ReverbContext::getEnvironmentalReverbDecayHfRatio() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << mReverbParams.decayHfRatio; - return mReverbParams.decayHfRatio; -} - -RetCode ReverbContext::setEnvironmentalReverbLevel(int level) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << level; - mReverbParams.level = level; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_LEVEL); - return RetCode::SUCCESS; -} - -int ReverbContext::getEnvironmentalReverbLevel() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << mReverbParams.level; - return mReverbParams.level; -} - -RetCode ReverbContext::setEnvironmentalReverbDelay(int delay) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << delay; - mReverbParams.delay = delay; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_DELAY); - return RetCode::SUCCESS; -} - -int ReverbContext::getEnvironmentalReverbDelay() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << mReverbParams.delay; - return mReverbParams.delay; -} - -RetCode ReverbContext::setEnvironmentalReverbDiffusion(int diffusion) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << diffusion; - mReverbParams.diffusion = diffusion; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_DIFFUSION); - return RetCode::SUCCESS; -} - -int ReverbContext::getEnvironmentalReverbDiffusion() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << mReverbParams.diffusion; - return mReverbParams.diffusion; -} - -RetCode ReverbContext::setEnvironmentalReverbDensity(int density) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << density; - mReverbParams.density = density; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_DENSITY); - return RetCode::SUCCESS; -} - -int ReverbContext::getEnvironmentalReverbDensity() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << mReverbParams.density; - return mReverbParams.density; -} - -RetCode ReverbContext::setEnvironmentalReverbBypass(bool bypass) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << bypass; - mReverbParams.bypass = bypass; - return RetCode::SUCCESS; -} - -bool ReverbContext::getEnvironmentalReverbBypass() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << mReverbParams.bypass; - return mReverbParams.bypass; -} - -RetCode ReverbContext::setReflectionsLevel(int level) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << level; - mReverbParams.reflectionsLevel = level; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_DENSITY); - return RetCode::SUCCESS; -} - -bool ReverbContext::getReflectionsLevel() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " - << mReverbParams.reflectionsLevel; - return mReverbParams.reflectionsLevel; -} - -RetCode ReverbContext::setReflectionsDelay(int delay) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " << delay; - mReverbParams.reflectionsDelay = delay; - setOffloadParameters(REVERB_ENABLE_FLAG | REVERB_REFLECTIONS_DELAY); - return RetCode::SUCCESS; -} - -bool ReverbContext::getReflectionsDelay() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " " - << mReverbParams.reflectionsDelay; - return mReverbParams.reflectionsDelay; -} - -int ReverbContext::setOffloadParameters(ReverbParams* reverbParams, uint64_t flags) { - if (mPalHandle) { - ParamDelegator::updatePalParameters(mPalHandle, reverbParams, flags); - } else { - LOG(VERBOSE) << " PalHandle not set"; - } - return 0; -} - -int ReverbContext::setOffloadParameters(uint64_t flags) { - if (mPalHandle) { - ParamDelegator::updatePalParameters(mPalHandle, &mReverbParams, flags); - } else { - LOG(VERBOSE) << " PalHandle not set"; - } - return 0; -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/VirtualizerContext.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/VirtualizerContext.cpp deleted file mode 100755 index 61c71937..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadbundle/VirtualizerContext.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/* - - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_Effect_VirtualizerQti" - -#include -#include - -#include "OffloadBundleContext.h" -#include "OffloadBundleTypes.h" - -namespace aidl::qti::effects { - -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; -using android::media::audio::common::AudioChannelLayout; - -VirtualizerContext::VirtualizerContext(const Parameter::Common& common, - const OffloadBundleEffectType& type, bool processData) - : OffloadBundleContext(common, type, processData) { - LOG(DEBUG) << __func__ << type << " ioHandle " << common.ioHandle; - mState = EffectState::INITIALIZED; -} - -VirtualizerContext::~VirtualizerContext() { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - deInit(); -} - -void VirtualizerContext::deInit() { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - stop(); -} - -RetCode VirtualizerContext::enable() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - if (isEffectActive()) return RetCode::ERROR_ILLEGAL_PARAMETER; - mState = EffectState::ACTIVE; - mVirtParams.enable = 1; - setOffloadParameters(VIRTUALIZER_ENABLE_FLAG | VIRTUALIZER_STRENGTH); - return RetCode::SUCCESS; -} - -RetCode VirtualizerContext::disable() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - if (!isEffectActive()) return RetCode::ERROR_ILLEGAL_PARAMETER; - - mState = EffectState::INITIALIZED; - mVirtParams.enable = 0; - setOffloadParameters(VIRTUALIZER_ENABLE_FLAG); - return RetCode::SUCCESS; -} - -RetCode VirtualizerContext::start(pal_stream_handle_t* palHandle) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - mPalHandle = palHandle; - if (isEffectActive()) { - setOffloadParameters(VIRTUALIZER_ENABLE_FLAG | VIRTUALIZER_STRENGTH); - } else { - LOG(DEBUG) << __func__ << "Not yet enabled " - << " ioHandle " << getIoHandle(); - } - - return RetCode::SUCCESS; -} - -RetCode VirtualizerContext::stop() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - - struct VirtualizerParams virtParams; // by default enable is 0. - setOffloadParameters(&virtParams, VIRTUALIZER_ENABLE_FLAG); - mPalHandle = nullptr; - return RetCode::SUCCESS; -} - -RetCode VirtualizerContext::setOutputDevice( - const std::vector& device) { - std::lock_guard lg(mMutex); - mOutputDevice = device; - if (deviceSupportsEffect(mOutputDevice)) { - if (mTempDisabled) { - if (isEffectActive()) { - mVirtParams.enable = 1; - setOffloadParameters(VIRTUALIZER_ENABLE_FLAG); - } - } - mTempDisabled = false; - } else if (!mTempDisabled) { - if (isEffectActive()) { - mVirtParams.enable = 0; - setOffloadParameters(VIRTUALIZER_ENABLE_FLAG); - } - mTempDisabled = true; - } - return RetCode::SUCCESS; -} - -RetCode VirtualizerContext::setVirtualizerStrength(int strength) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " strength " << strength; - mVirtParams.strength = strength; - setOffloadParameters(VIRTUALIZER_ENABLE_FLAG | VIRTUALIZER_STRENGTH); - return RetCode::SUCCESS; -} - -int VirtualizerContext::getVirtualizerStrength() const { - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle() << " strength " << mVirtParams.strength; - return mVirtParams.strength; -} - -RetCode VirtualizerContext::setForcedDevice(const AudioDeviceDescription& device) { - std::lock_guard lg(mMutex); - AudioDeviceDescription noneDevice; - if (device != noneDevice) { - RETURN_VALUE_IF(true != deviceSupportsEffect({device}), RetCode::ERROR_EFFECT_LIB_ERROR, - " deviceNotSupportVirtualizer"); - } - mForcedDevice = device; - return RetCode::SUCCESS; -} - -std::vector VirtualizerContext::getSpeakerAngles( - const Virtualizer::SpeakerAnglesPayload payload) { - std::vector angles; - auto channels = ::aidl::android::hardware::audio::common::getChannelCount(payload.layout); - RETURN_VALUE_IF(!isConfigSupported(channels, payload.device), angles, "unsupportedConfig"); - - if (channels == 1) { - angles = {{.channel = (int32_t)AudioChannelLayout::CHANNEL_FRONT_LEFT, - .azimuthDegree = 0, - .elevationDegree = 0}}; - } else { - angles = {{.channel = (int32_t)AudioChannelLayout::CHANNEL_FRONT_LEFT, - .azimuthDegree = -90, - .elevationDegree = 0}, - {.channel = (int32_t)AudioChannelLayout::CHANNEL_FRONT_RIGHT, - .azimuthDegree = 90, - .elevationDegree = 0}}; - } - return angles; -} - -int VirtualizerContext::setOffloadParameters(uint64_t flags) { - if (mPalHandle) { - ParamDelegator::updatePalParameters(mPalHandle, &mVirtParams, flags); - } else { - LOG(VERBOSE) << " PalHandle not set"; - } - return 0; -} - -int VirtualizerContext::setOffloadParameters(VirtualizerParams* virtParams, uint64_t flags) { - if (mPalHandle) { - ParamDelegator::updatePalParameters(mPalHandle, virtParams, flags); - } else { - LOG(VERBOSE) << " PalHandle not set"; - } - return 0; -} - -bool VirtualizerContext::isConfigSupported(size_t channelCount, - const AudioDeviceDescription& device) { - return ((channelCount == 1 || channelCount == 2) && deviceSupportsEffect({device})); -} - -bool VirtualizerContext::deviceSupportsEffect(const std::vector& devices) { - for (const auto& device : devices) { - if (device != AudioDeviceDescription{AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_ANALOG} && - device != AudioDeviceDescription{AudioDeviceType::OUT_HEADPHONE, - AudioDeviceDescription::CONNECTION_ANALOG} && - device != AudioDeviceDescription{AudioDeviceType::OUT_HEADPHONE, - AudioDeviceDescription::CONNECTION_BT_A2DP} && - device != AudioDeviceDescription{AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_USB}) { - return false; - } - } - return true; -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/Android.mk deleted file mode 100755 index 3f2b24e9..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/Android.mk +++ /dev/null @@ -1,25 +0,0 @@ -LOCAL_PATH:= $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE:= libqcomvisualizer -LOCAL_VENDOR_MODULE := true -LOCAL_MODULE_RELATIVE_PATH := soundfx -LOCAL_MODULE_OWNER := qti - -LOCAL_SRC_FILES:= \ - VisualizerOffload.cpp \ - VisualizerOffloadContext.cpp - - -LOCAL_STATIC_LIBRARIES := libaudioeffecthal_base_impl_static - -LOCAL_SHARED_LIBRARIES:= \ - $(EFFECTS_DEFAULTS_SHARED_LIBRARIES) \ - libar-pal - -LOCAL_HEADER_LIBRARIES:= \ - $(EFFECTS_DEFAULTS_HEADERS_LIBRARIES) \ - libaudioutils_headers - -include $(BUILD_SHARED_LIBRARY) diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffload.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffload.cpp deleted file mode 100755 index 38d76f33..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffload.cpp +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -#define LOG_TAG "AHAL_Effect_VisualizerQti" -#include "VisualizerOffload.h" -#include -#include "VisualizerOffloadContext.h" - -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::android::hardware::audio::effect::Capability; -using aidl::android::hardware::audio::effect::Range; -using aidl::android::hardware::audio::effect::IEffect; -using aidl::android::hardware::audio::effect::Flags; -using aidl::qti::effects::VisualizerOffload; -using aidl::qti::effects::VisualizerOffloadContext; -using aidl::qti::effects::GlobalVisualizerSession; -using aidl::qti::effects::kVisualizerOffloadQtiUUID; -using aidl::android::hardware::audio::effect::State; -using aidl::android::media::audio::common::AudioUuid; - -extern "C" void startEffect(int ioHandle, uint64_t* palHandle __unused) { - GlobalVisualizerSession::getSession().startEffect(ioHandle); -} - -extern "C" void stopEffect(int ioHandle) { - GlobalVisualizerSession::getSession().stopEffect(ioHandle); -} - -extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid, - std::shared_ptr* instanceSpp) { - if (!in_impl_uuid || *in_impl_uuid != kVisualizerOffloadQtiUUID) { - LOG(ERROR) << __func__ << " uuid not supported " - << aidl::qti::effects::toString(*in_impl_uuid) << " vs " - << aidl::qti::effects::toString(kVisualizerOffloadQtiUUID); - return EX_ILLEGAL_ARGUMENT; - } - if (instanceSpp) { - *instanceSpp = ndk::SharedRefBase::make(); - LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created"; - return EX_NONE; - } else { - LOG(ERROR) << __func__ << " invalid input parameter!"; - return EX_ILLEGAL_ARGUMENT; - } -} - -extern "C" binder_exception_t queryEffect(const AudioUuid* in_impl_uuid, Descriptor* _aidl_return) { - if (!in_impl_uuid || *in_impl_uuid != kVisualizerOffloadQtiUUID) { - LOG(ERROR) << __func__ << " uuid not supported " - << aidl::qti::effects::toString(*in_impl_uuid) << " vs " - << aidl::qti::effects::toString(kVisualizerOffloadQtiUUID); - return EX_ILLEGAL_ARGUMENT; - } - *_aidl_return = VisualizerOffload::kDescriptor; - return EX_NONE; -} - -namespace aidl::qti::effects { -const std::string VisualizerOffload::kEffectName = "Visualizer"; -const std::vector VisualizerOffload::kRanges = { - MAKE_RANGE(Visualizer, latencyMs, 0, VisualizerOffloadContext::kMaxLatencyMs), - MAKE_RANGE(Visualizer, captureSamples, 0, VisualizerOffloadContext::kMaxCaptureBufSize), - /* get only parameters, set invalid range (min > max) to indicate not support set */ - MAKE_RANGE(Visualizer, measurement, Visualizer::Measurement({.peak = 1, .rms = 1}), - Visualizer::Measurement({.peak = 0, .rms = 0})), - MAKE_RANGE(Visualizer, captureSampleBuffer, std::vector({1}), - std::vector({0}))}; -const Capability VisualizerOffload::kCapability = { - .range = Range::make(VisualizerOffload::kRanges)}; -const Descriptor VisualizerOffload::kDescriptor = { - .common = {.id = {.type = kVisualizerTypeUUID, - .uuid = kVisualizerOffloadQtiUUID, - .proxy = std::nullopt}, - .flags = {.hwAcceleratorMode = Flags::HardwareAccelerator::TUNNEL, - .offloadIndication = true}, - .name = VisualizerOffload::kEffectName, - .implementor = "Qualcomm Technologies Inc."}, - .capability = VisualizerOffload::kCapability}; -ndk::ScopedAStatus VisualizerOffload::getDescriptor(Descriptor* _aidl_return) { - RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr"); - LOG(DEBUG) << __func__ << kDescriptor.toString(); - *_aidl_return = kDescriptor; - return ndk::ScopedAStatus::ok(); -} - -VisualizerOffload::VisualizerOffload() { - LOG(VERBOSE) << __func__; - mDescriptor = &kDescriptor; - mEffectName = &kEffectName; -} - -ndk::ScopedAStatus VisualizerOffload::commandImpl(CommandId command) { - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - switch (command) { - case CommandId::START: - mContext->enable(); - break; - case CommandId::STOP: - mContext->disable(); - break; - case CommandId::RESET: - mContext->disable(); - mContext->resetBuffer(); - break; - default: - LOG(ERROR) << __func__ << " commandId " << toString(command) << " not supported"; - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "commandIdNotSupported"); - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus VisualizerOffload::setParameterSpecific(const Parameter::Specific& specific) { - RETURN_IF(Parameter::Specific::visualizer != specific.getTag(), EX_ILLEGAL_ARGUMENT, - "EffectNotSupported"); - - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - auto& param = specific.get(); - - RETURN_IF(!inRange(param, kRanges), EX_ILLEGAL_ARGUMENT, "outOfRange"); - const auto tag = param.getTag(); - - switch (tag) { - case Visualizer::captureSamples: { - RETURN_IF(mContext->setCaptureSamples(param.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setCaptureSizeFailed"); - return ndk::ScopedAStatus::ok(); - } - case Visualizer::scalingMode: { - RETURN_IF(mContext->setScalingMode(param.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setScalingModeFailed"); - return ndk::ScopedAStatus::ok(); - } - case Visualizer::measurementMode: { - RETURN_IF(mContext->setMeasurementMode(param.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setMeasurementModeFailed"); - return ndk::ScopedAStatus::ok(); - } - case Visualizer::latencyMs: { - RETURN_IF(mContext->setDownstreamLatency(param.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setLatencyFailed"); - return ndk::ScopedAStatus::ok(); - } - default: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "VisualizerTagNotSupported"); - } - } -} - -ndk::ScopedAStatus VisualizerOffload::getParameterSpecific(const Parameter::Id& id, - Parameter::Specific* specific) { - RETURN_IF(!specific, EX_NULL_POINTER, "nullPtr"); - auto tag = id.getTag(); - RETURN_IF(Parameter::Id::visualizerTag != tag, EX_ILLEGAL_ARGUMENT, "wrongIdTag"); - auto specificId = id.get(); - auto specificTag = specificId.getTag(); - - switch (specificTag) { - case Visualizer::Id::commonTag: { - return getParameterVisualizer(specificId.get(), specific); - } - default: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(specificTag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "VisualizerTagNotSupported"); - } - } - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus VisualizerOffload::getParameterVisualizer(const Visualizer::Tag& tag, - Parameter::Specific* specific) { - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - Visualizer param; - - switch (tag) { - case Visualizer::captureSamples: { - param.set(mContext->getCaptureSamples()); - break; - } - case Visualizer::scalingMode: { - param.set(mContext->getScalingMode()); - break; - } - case Visualizer::measurementMode: { - param.set(mContext->getMeasurementMode()); - break; - } - case Visualizer::measurement: { - param.set(mContext->getMeasure()); - break; - } - case Visualizer::captureSampleBuffer: { - param.set(mContext->capture()); - break; - } - case Visualizer::latencyMs: { - param.set(mContext->getDownstreamLatency()); - break; - } - default: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "VisualizerTagNotSupported"); - } - } - specific->set(param); - return ndk::ScopedAStatus::ok(); -} - -std::shared_ptr VisualizerOffload::createContext(const Parameter::Common& common, - bool processData) { - if (mContext) - LOG(DEBUG) << __func__ << " context already exist"; - else { - // GlobalVisualizerSession is a singleton - mContext = GlobalVisualizerSession::getSession().createSession(common, processData); - } - return mContext; -} - -RetCode VisualizerOffload::releaseContext() { - if (mContext) { - GlobalVisualizerSession::getSession().releaseSession(mContext); - mContext.reset(); - } - return RetCode::SUCCESS; -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffload.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffload.h deleted file mode 100755 index 6a143983..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffload.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include - -#include "effect-impl/EffectImpl.h" -#include "effect-impl/EffectUUID.h" - -#include "VisualizerOffloadContext.h" - -namespace aidl::qti::effects { - -class VisualizerOffload final : public EffectImpl { - public: - static const std::string kEffectName; - static const Capability kCapability; - static const Descriptor kDescriptor; - VisualizerOffload(); - ~VisualizerOffload() { LOG(DEBUG) << __func__; } - - ndk::ScopedAStatus commandImpl(CommandId command) override; - ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override; - ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override; - ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, - Parameter::Specific* specific) override; - std::shared_ptr createContext(const Parameter::Common& common, - bool processData) override; - RetCode releaseContext() override; - - std::string getEffectName() override { return kEffectName; } - - private: - static const std::vector kRanges; - std::shared_ptr mContext; - ndk::ScopedAStatus getParameterVisualizer(const Visualizer::Tag& tag, - Parameter::Specific* specific); -}; - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffloadContext.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffloadContext.cpp deleted file mode 100755 index bf673757..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffloadContext.cpp +++ /dev/null @@ -1,483 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -#define LOG_TAG "AHAL_Effect_VisualizerQti" -#include "VisualizerOffloadContext.h" -#include -#include -#include -#include -#include -#include -#include - -using ::aidl::android::hardware::audio::common::getChannelCount; - -namespace aidl::qti::effects { -void GlobalVisualizerSession::startEffect(int ioHandle) { - std::lock_guard lg(mMutex); - for (auto context : mCreatedEffectsList) { - if (context->getIoHandle() == ioHandle) { - if (auto ret = context->startThreadLoop(); ret) - LOG(ERROR) << __func__ << " failed to start capture thread loop" << ret; - break; - } - } - mActiveOutputsList.push_back(ioHandle); -} - -void GlobalVisualizerSession::stopEffect(int ioHandle) { - std::lock_guard lg(mMutex); - for (auto context : mCreatedEffectsList) { - if (context->getIoHandle() == ioHandle) { - if (auto ret = context->stopThreadLoop(); ret) - LOG(ERROR) << __func__ << " failed to stop capture thread loop"; - break; - } - } - - auto iter = std::find(mActiveOutputsList.begin(), mActiveOutputsList.end(), ioHandle); - if (iter != mActiveOutputsList.end()) mActiveOutputsList.erase(iter); -} - -std::shared_ptr GlobalVisualizerSession::createSession( - const Parameter::Common& common, bool processData) { - std::lock_guard lg(mMutex); - auto context = std::make_shared(common, processData); - RETURN_VALUE_IF(!context, nullptr, "failedToCreateContext"); - for (auto output : mActiveOutputsList) { - if (common.ioHandle == output) { - if (auto ret = context->startThreadLoop(); ret) - LOG(ERROR) << __func__ << " failed to start capture thread loop"; - break; - } - } - mCreatedEffectsList.push_back(context); - return context; -} - -void GlobalVisualizerSession::releaseSession(std::shared_ptr context) { - std::lock_guard lg(mMutex); - if (context) { - context->disable(); - context->resetBuffer(); - for (auto output : mActiveOutputsList) { - if (context->getIoHandle() == output) { - if (auto ret = context->stopThreadLoop(); ret) - LOG(ERROR) << __func__ << " failed to stop capture thread loop"; - break; - } - } - } - auto iter = std::find(mCreatedEffectsList.begin(), mCreatedEffectsList.end(), context); - if (iter != mCreatedEffectsList.end()) - mCreatedEffectsList.erase(iter); - else - LOG(ERROR) << __func__ << " context is not present"; -} -StreamProxy::StreamProxy() { - init(); -} -StreamProxy::~StreamProxy() { - cleanUp(); -} -void StreamProxy::init() { - memset(&data, 0, sizeof(data)); - - chInfo.channels = AUDIO_CAPTURE_CHANNEL_COUNT; - chInfo.ch_map[0] = PAL_CHMAP_CHANNEL_FL; - chInfo.ch_map[1] = PAL_CHMAP_CHANNEL_FR; - streamAttr.type = PAL_STREAM_PROXY; - streamAttr.direction = PAL_AUDIO_INPUT; - streamAttr.in_media_config.sample_rate = AUDIO_CAPTURE_SMP_RATE; - streamAttr.in_media_config.bit_width = AUDIO_CAPTURE_BIT_WIDTH; - streamAttr.in_media_config.ch_info = chInfo; - streamAttr.in_media_config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - devices.id = PAL_DEVICE_IN_PROXY; - devices.config.sample_rate = AUDIO_CAPTURE_SMP_RATE; - devices.config.bit_width = AUDIO_CAPTURE_BIT_WIDTH; - devices.config.ch_info = chInfo; - devices.config.aud_fmt_id = PAL_AUDIO_FMT_PCM_S16_LE; - - if (openStream()) { - if (!startStream()) cleanUp(); - } -} - -bool StreamProxy::openStream() { - if (auto ret = pal_stream_open(&streamAttr, noOfDevices, &devices, 0, NULL, NULL, 0, - &inStreamHandle); - ret) { - LOG(ERROR) << __func__ << "pal_stream_open failed" << ret; - return false; - } - mStreamOpened = true; - return true; -} - -bool StreamProxy::startStream() { - inBufferCfg.buf_size = inBufferSize; - inBufferCfg.buf_count = inBuffCount; - - if (auto ret = pal_stream_set_buffer_size(inStreamHandle, &inBufferCfg, NULL); ret) { - LOG(ERROR) << __func__ << "pal_stream_set_buffer_size failed with err" << ret; - return false; - } - - inBufferSize = inBufferCfg.buf_size; - if (auto ret = pal_stream_start(inStreamHandle); ret) { - LOG(ERROR) << __func__ << "pal_stream_start failed with err" << ret; - return false; - } - mStreamStarted = true; - return true; -} - -void StreamProxy::cleanUp() { - if (mStreamStarted) { - if (auto ret = pal_stream_stop(inStreamHandle); ret) - LOG(ERROR) << __func__ << "pal_stream_stop failed with err" << ret; - } - mStreamStarted = false; - if (mStreamOpened) { - if (auto ret = pal_stream_close(inStreamHandle); ret) - LOG(ERROR) << __func__ << "pal_stream_close failed with err" << ret; - } - mStreamOpened = false; -} - -int16_t* StreamProxy::read() { - int readStatus = 0; - memset(&inBuffer, 0, sizeof(struct pal_buffer)); - inBuffer.buffer = (uint8_t*)&data[0]; - inBuffer.size = inBufferSize; - readStatus = pal_stream_read(inStreamHandle, &inBuffer); - if (readStatus > 0) { - LOG(VERBOSE) << __func__ << " pal_stream_read success no_of_bytes_read =" << readStatus; - return data; - } - LOG(ERROR) << __func__ << "pal_stream_read failed with read status " << readStatus; - return nullptr; -} - -bool StreamProxy::isStreamStarted() { - return mStreamStarted; -} - -int VisualizerOffloadContext::startThreadLoop() { - std::lock_guard lg(mMutex); - mCaptureThreadHandler = std::thread(&VisualizerOffloadContext::captureThreadLoop, this); - if (!mCaptureThreadHandler.joinable()) { - LOG(ERROR) << __func__ << "fail to create captureThreadLoop"; - return -EINVAL; - } - mExitThread = false; - mCaptureThreadCondition.notify_one(); - return 0; -} - -int VisualizerOffloadContext::stopThreadLoop() { - if (mCaptureThreadHandler.joinable()) { - { - std::lock_guard lg(mMutex); - mExitThread = true; - } - mCaptureThreadCondition.notify_one(); - mCaptureThreadHandler.join(); - LOG(DEBUG) << __func__ << " capture thread joined"; - } - return 0; -} - -void VisualizerOffloadContext::captureThreadLoop() { - int status = 0; - bool captureEnabled = false; - StreamProxy streamProxy; - - if (!streamProxy.isStreamStarted()) return; - LOG(INFO) << __func__ << "Capture Thread Enter "; - - while (true) { - { - std::unique_lock lck(mMutex); - LOG(VERBOSE) << __func__ << " waiting for active state"; - mCaptureThreadCondition.wait(lck, - [this] { return mState == State::ACTIVE || mExitThread; }); - LOG(VERBOSE) << __func__ << " done waiting for active state"; - - if (mExitThread) break; - } - process(streamProxy.read()); - } - - LOG(DEBUG) << __func__ << " Capture Thread Exit "; -} - -VisualizerOffloadContext::VisualizerOffloadContext( - const aidl::android::hardware::audio::effect::Parameter::Common& common, bool processData) - : EffectContext(common, processData) { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__ << " ioHandle " << getIoHandle(); - if (common.input != common.output) { - LOG(ERROR) << __func__ << " mismatch input: " << common.input.toString() - << " and output: " << common.output.toString(); - } - mState = State::INITIALIZED; - auto channelCount = getChannelCount(common.input.base.channelMask); - mChannelCount = channelCount; -} - -VisualizerOffloadContext::~VisualizerOffloadContext() { - std::lock_guard lg(mMutex); - LOG(DEBUG) << __func__; - mState = State::UNINITIALIZED; -} - -RetCode VisualizerOffloadContext::enable() { - std::lock_guard lg(mMutex); - if (mState != State::INITIALIZED) { - return RetCode::ERROR_EFFECT_LIB_ERROR; - } - mState = State::ACTIVE; - mCaptureThreadCondition.notify_one(); - return RetCode::SUCCESS; -} - -RetCode VisualizerOffloadContext::disable() { - std::lock_guard lg(mMutex); - if (mState != State::ACTIVE) { - return RetCode::ERROR_EFFECT_LIB_ERROR; - } - mState = State::INITIALIZED; - mCaptureThreadCondition.notify_one(); - return RetCode::SUCCESS; -} - -void VisualizerOffloadContext::reset() { - std::lock_guard lg(mMutex); - std::fill_n(mCaptureBuf.begin(), kMaxCaptureBufSize, 0x80); -} - -RetCode VisualizerOffloadContext::setCaptureSamples(int samples) { - std::lock_guard lg(mMutex); - mCaptureSamples = samples; - return RetCode::SUCCESS; -} - -int VisualizerOffloadContext::getCaptureSamples() { - std::lock_guard lg(mMutex); - return mCaptureSamples; -} - -RetCode VisualizerOffloadContext::setMeasurementMode( - aidl::android::hardware::audio::effect::Visualizer::MeasurementMode mode) { - std::lock_guard lg(mMutex); - mMeasurementMode = mode; - return RetCode::SUCCESS; -} - -Visualizer::MeasurementMode VisualizerOffloadContext::getMeasurementMode() { - std::lock_guard lg(mMutex); - return mMeasurementMode; -} - -RetCode VisualizerOffloadContext::setScalingMode(Visualizer::ScalingMode mode) { - std::lock_guard lg(mMutex); - mScalingMode = mode; - return RetCode::SUCCESS; -} - -Visualizer::ScalingMode VisualizerOffloadContext::getScalingMode() { - std::lock_guard lg(mMutex); - return mScalingMode; -} - -RetCode VisualizerOffloadContext::setDownstreamLatency(int latency) { - std::lock_guard lg(mMutex); - mDownstreamLatency = latency; - return RetCode::SUCCESS; -} - -int VisualizerOffloadContext::getDownstreamLatency() { - std::lock_guard lg(mMutex); - return mDownstreamLatency; -} - -uint32_t VisualizerOffloadContext::getDeltaTimeMsFromUpdatedTime_l() { - uint32_t deltaMs = 0; - if (mBufferUpdateTime.tv_sec != 0) { - struct timespec ts; - if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { - time_t secs = ts.tv_sec - mBufferUpdateTime.tv_sec; - long nsec = ts.tv_nsec - mBufferUpdateTime.tv_nsec; - if (nsec < 0) { - --secs; - nsec += 1000000000; - } - deltaMs = secs * 1000 + nsec / 1000000; - } - } - return deltaMs; -} - -Visualizer::Measurement VisualizerOffloadContext::getMeasure() { - uint16_t peakU16 = 0; - float sumRmsSquared = 0.0f; - uint8_t nbValidMeasurements = 0; - { - std::lock_guard lg(mMutex); - // reset measurements if last measurement was too long ago (which implies stored - // measurements aren't relevant anymore and shouldn't bias the new one) - const uint32_t delayMs = getDeltaTimeMsFromUpdatedTime_l(); - if (delayMs > kDiscardMeasurementsTimeMs) { - LOG(INFO) << __func__ << " Discarding " << delayMs << " ms old measurements"; - for (uint32_t i = 0; i < mMeasurementWindowSizeInBuffers; i++) { - mPastMeasurements[i].mIsValid = false; - mPastMeasurements[i].mPeakU16 = 0; - mPastMeasurements[i].mRmsSquared = 0; - } - mMeasurementBufferIdx = 0; - } else { - // only use actual measurements, otherwise the first RMS measure happening before - // MEASUREMENT_WINDOW_MAX_SIZE_IN_BUFFERS have been played will always be artificially - // low - for (uint32_t i = 0; i < mMeasurementWindowSizeInBuffers; i++) { - if (mPastMeasurements[i].mIsValid) { - if (mPastMeasurements[i].mPeakU16 > peakU16) { - peakU16 = mPastMeasurements[i].mPeakU16; - } - sumRmsSquared += mPastMeasurements[i].mRmsSquared; - nbValidMeasurements++; - } - } - } - } - float rms = nbValidMeasurements == 0 ? 0.0f : sqrtf(sumRmsSquared / nbValidMeasurements); - Visualizer::Measurement measure; - // convert from I16 sample values to mB and write results - measure.rms = (rms < 0.000016f) ? -9600 : (int32_t)(2000 * log10(rms / 32767.0f)); - measure.peak = (peakU16 == 0) ? -9600 : (int32_t)(2000 * log10(peakU16 / 32767.0f)); - LOG(DEBUG) << __func__ << " peak " << peakU16 << " (" << measure.peak << "mB), rms " << rms - << " (" << measure.rms << "mB)"; - return measure; -} - -std::vector VisualizerOffloadContext::capture() { - std::vector result; - std::lock_guard lg(mMutex); - if (mState != State::ACTIVE) { - result.resize(mCaptureSamples); - memset(result.data(), 0x80, mCaptureSamples); - return result; - } - int32_t latencyMs = mDownstreamLatency; - const int32_t deltaMs = getDeltaTimeMsFromUpdatedTime_l(); - // if audio framework has stopped playing audio although the effect is still active we must - // clear the capture buffer to return silence - if ((mLastCaptureIdx == mCaptureIdx) && (mBufferUpdateTime.tv_sec != 0) && - (deltaMs > kMaxStallTimeMs)) { - LOG(DEBUG) << __func__ << " capture going to idle"; - mBufferUpdateTime.tv_sec = 0; - return result; - } - __builtin_sub_overflow((int32_t)latencyMs, deltaMs, &latencyMs); - if (latencyMs < 0) latencyMs = 0; - uint32_t deltaSamples = mCommon.input.base.sampleRate * latencyMs / 1000; - int64_t capturePoint = mCaptureIdx; - capturePoint -= mCaptureSamples; - capturePoint -= deltaSamples; - int64_t captureSize = mCaptureSamples; - if (capturePoint < 0) { - int64_t size = -capturePoint; - if (size > captureSize) { - size = captureSize; - } - result.insert(result.end(), &mCaptureBuf[kMaxCaptureBufSize + capturePoint], - &mCaptureBuf[kMaxCaptureBufSize + capturePoint + size]); - captureSize -= size; - capturePoint = 0; - } - result.insert(result.end(), &mCaptureBuf[capturePoint], - &mCaptureBuf[capturePoint + captureSize]); - mLastCaptureIdx = mCaptureIdx; - return result; -} - -int VisualizerOffloadContext::process(int16_t* inBuffer) { - if (!inBuffer || mState != State::ACTIVE) return -EINVAL; - - // perform measurements if needed - if (mMeasurementMode == Visualizer::MeasurementMode::PEAK_RMS) { - // find the peak and RMS squared for the new buffer - float rmsSqAcc = 0; - int16_t maxSample = 0; - for (size_t inIdx = 0; inIdx < AUDIO_CAPTURE_PERIOD_SIZE * mChannelCount; ++inIdx) { - if (inBuffer[inIdx] > maxSample) { - maxSample = inBuffer[inIdx]; - } else if (-inBuffer[inIdx] > maxSample) { - maxSample = -inBuffer[inIdx]; - } - rmsSqAcc += inBuffer[inIdx] * inBuffer[inIdx]; - } - mPastMeasurements[mMeasurementBufferIdx] = { - .mPeakU16 = (uint16_t)maxSample, - .mRmsSquared = rmsSqAcc / (AUDIO_CAPTURE_PERIOD_SIZE * mChannelCount), - .mIsValid = true}; - if (++mMeasurementBufferIdx >= mMeasurementWindowSizeInBuffers) { - mMeasurementBufferIdx = 0; - } - } - /* all code below assumes stereo 16 bit PCM output and input */ - int32_t shift; - if (mScalingMode == Visualizer::ScalingMode::NORMALIZED) { - /* derive capture scaling factor from peak value in current buffer - * this gives more interesting captures for display. */ - shift = 32; - int len = AUDIO_CAPTURE_PERIOD_SIZE * 2; - for (int idx = 0; idx < len; idx++) { - int32_t smp = inBuffer[idx]; - if (smp < 0) smp = -smp - 1; /* take care to keep the max negative in range */ - int32_t clz = __builtin_clz(smp); - if (shift > clz) shift = clz; - } - /* A maximum amplitude signal will have 17 leading zeros, which we want to - * translate to a shift of 8 (for converting 16 bit to 8 bit) */ - shift = 25 - shift; - /* Never scale by less than 8 to avoid returning unaltered PCM signal. */ - if (shift < 3) { - shift = 3; - } - /* add one to combine the division by 2 needed after summing - * left and right channels below */ - shift++; - } else { - assert(mScalingMode == Visualizer::ScalingMode::AS_PLAYED); - // Note: if channels are uncorrelated, 1/sqrt(N) could be used at the risk of clipping. - shift = 9; - } - uint32_t captIdx; - uint32_t inIdx; - for (inIdx = 0, captIdx = mCaptureIdx; inIdx < AUDIO_CAPTURE_PERIOD_SIZE; inIdx++, captIdx++) { - // wrap - if (captIdx >= kMaxCaptureBufSize) { - captIdx = 0; - } - int32_t smp = inBuffer[2 * inIdx] + inBuffer[2 * inIdx + 1]; - smp = smp >> shift; - mCaptureBuf[captIdx] = ((uint8_t)smp) ^ 0x80; - } - // the following two should really be atomic, though it probably doesn't - // matter much for visualization purposes - mCaptureIdx = captIdx; - // update last buffer update time stamp - if (clock_gettime(CLOCK_MONOTONIC, &mBufferUpdateTime) < 0) { - mBufferUpdateTime.tv_sec = 0; - } - if (mState != State::ACTIVE) { - LOG(DEBUG) << __func__ << "DONE inactive"; - return -ENODATA; - } - return 0; -} -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffloadContext.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffloadContext.h deleted file mode 100755 index 602bd40d..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/offloadvisualizer/VisualizerOffloadContext.h +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include "PalApi.h" -#include "effect-impl/EffectContext.h" - -using aidl::android::hardware::audio::effect::Parameter; -using aidl::android::hardware::audio::effect::CommandId; -using aidl::android::hardware::audio::effect::Capability; -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::android::hardware::audio::effect::Range; -using aidl::android::hardware::audio::effect::Visualizer; - -/* Proxy port supports only MMAP read and those fixed parameters*/ -#define AUDIO_CAPTURE_CHANNEL_COUNT 2 -#define AUDIO_CAPTURE_SMP_RATE (48000) -#define AUDIO_CAPTURE_PERIOD_SIZE (768) -#define AUDIO_CAPTURE_PERIOD_COUNT (32) -#define AUDIO_CAPTURE_BIT_WIDTH (16) -#define BUFFERSIZE AUDIO_CAPTURE_PERIOD_SIZE* AUDIO_CAPTURE_CHANNEL_COUNT * sizeof(int16_t) - -namespace aidl::qti::effects { -class VisualizerOffloadContext final : public EffectContext { - public: - static const uint32_t kMaxCaptureBufSize = 65536; - static const uint32_t kMaxLatencyMs = 3000; // 3 seconds of latency for audio pipeline - - VisualizerOffloadContext(const Parameter::Common& common, bool processData); - ~VisualizerOffloadContext(); - - RetCode enable(); - RetCode disable(); - // keep all parameters and reset buffer. - void reset(); - - RetCode setCaptureSamples(int captureSize); - int getCaptureSamples(); - RetCode setMeasurementMode(Visualizer::MeasurementMode mode); - Visualizer::MeasurementMode getMeasurementMode(); - RetCode setScalingMode(Visualizer::ScalingMode mode); - Visualizer::ScalingMode getScalingMode(); - RetCode setDownstreamLatency(int latency); - int getDownstreamLatency(); - - int process(int16_t*); - // Gets the current measurements, measured by process() and consumed by getParameter() - Visualizer::Measurement getMeasure(); - // Gets the latest PCM capture, data captured by process() and consumed by getParameter() - std::vector capture(); - - int startThreadLoop(); - int stopThreadLoop(); - void captureThreadLoop(); - - struct BufferStats { - bool mIsValid; - uint16_t mPeakU16; // the positive peak of the absolute value of the samples in a buffer - float mRmsSquared; // the average square of the samples in a buffer - }; - - enum State { - UNINITIALIZED, - INITIALIZED, - ACTIVE, - }; - - private: - // maximum time since last capture buffer update before resetting capture buffer. This means - // that the framework has stopped playing audio and we must start returning silence - static const uint32_t kMaxStallTimeMs = 1000; - // discard measurements older than this number of ms - static const uint32_t kDiscardMeasurementsTimeMs = 2000; - // maximum number of buffers for which we keep track of the measurements - // note: buffer index is stored in uint8_t - static const uint32_t kMeasurementWindowMaxSizeInBuffers = 25; - - // serialize process() and parameter setting - std::mutex mMutex; - Parameter::Common mCommon GUARDED_BY(mMutex); - State mState GUARDED_BY(mMutex) = State::UNINITIALIZED; - uint32_t mCaptureIdx GUARDED_BY(mMutex) = 0; - uint32_t mLastCaptureIdx GUARDED_BY(mMutex) = 0; - Visualizer::ScalingMode mScalingMode GUARDED_BY(mMutex) = Visualizer::ScalingMode::NORMALIZED; - struct timespec mBufferUpdateTime GUARDED_BY(mMutex); - // capture buf with 8 bits PCM - std::array mCaptureBuf GUARDED_BY(mMutex); - uint32_t mDownstreamLatency GUARDED_BY(mMutex) = 0; - uint32_t mCaptureSamples GUARDED_BY(mMutex) = 1024; - - // to avoid recomputing it every time a buffer is processed - uint32_t mChannelCount GUARDED_BY(mMutex) = 0; - Visualizer::MeasurementMode mMeasurementMode GUARDED_BY(mMutex) = - Visualizer::MeasurementMode::NONE; - uint8_t mMeasurementWindowSizeInBuffers = kMeasurementWindowMaxSizeInBuffers; - uint8_t mMeasurementBufferIdx GUARDED_BY(mMutex) = 0; - std::thread mCaptureThreadHandler; - std::condition_variable mCaptureThreadCondition; - bool mExitThread; - std::array mPastMeasurements; - void initParams(); - uint32_t getDeltaTimeMsFromUpdatedTime_l() REQUIRES(mMutex); -}; - -class StreamProxy { - public: - StreamProxy(); - ~StreamProxy(); - void init(); - bool openStream(); - bool startStream(); - void cleanUp(); - int16_t* read(); - pal_stream_handle_t* getStreamHandle() { return inStreamHandle; }; - bool isStreamStarted(); - - private: - pal_stream_handle_t* inStreamHandle = NULL; - uint32_t noOfDevices = 1; - struct pal_stream_attributes streamAttr; - struct pal_device devices; - struct pal_channel_info chInfo; - uint32_t inBufferSize = BUFFERSIZE; - int16_t data[BUFFERSIZE]; - struct pal_buffer_config inBufferCfg = {0, 0, 0}; - uint32_t inBuffCount = 1; - struct pal_buffer inBuffer; - bool mStreamStarted = false; - bool mStreamOpened = false; -}; - -class GlobalVisualizerSession { - public: - static GlobalVisualizerSession& getSession() { - static GlobalVisualizerSession instance; - return instance; - } - std::shared_ptr createSession(const Parameter::Common& common, - bool processData); - void releaseSession(std::shared_ptr context); - void startEffect(int ioHandle); - void stopEffect(int ioHandle); - - private: - GlobalVisualizerSession(){}; - std::mutex mMutex; - // List of call created visualizer effects - std::vector> mCreatedEffectsList; - // List of active outputs - std::vector mActiveOutputsList; -}; -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/Android.mk deleted file mode 100755 index 13d03fc1..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/Android.mk +++ /dev/null @@ -1,21 +0,0 @@ -LOCAL_PATH:= $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE:= libqcomvoiceprocessing -LOCAL_VENDOR_MODULE := true -LOCAL_MODULE_RELATIVE_PATH := soundfx -LOCAL_MODULE_OWNER := qti - -LOCAL_SRC_FILES:= \ - VoiceProcessing.cpp \ - VoiceProcessingContext.cpp - -LOCAL_STATIC_LIBRARIES := libaudioeffecthal_base_impl_static - -LOCAL_SHARED_LIBRARIES:= \ - $(EFFECTS_DEFAULTS_SHARED_LIBRARIES) - -LOCAL_HEADER_LIBRARIES:= $(EFFECTS_DEFAULTS_HEADERS_LIBRARIES) - -include $(BUILD_SHARED_LIBRARY) diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/GlobalVoiceProcessingSession.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/GlobalVoiceProcessingSession.h deleted file mode 100755 index 92d54d94..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/GlobalVoiceProcessingSession.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include - -#include -#include - -#include "VoiceProcessingContext.h" -#include "VoiceProcessingTypes.h" - -namespace aidl::qti::effects { -using VoiceProcessingContextList = std::vector>; - -class GlobalVoiceProcessingSession { - public: - static GlobalVoiceProcessingSession& getSession() { - static GlobalVoiceProcessingSession instance; - return instance; - } - - static bool findEffectTypeInList(VoiceProcessingContextList& list, - const VoiceProcessingType& type, bool remove = false) { - auto itr = std::find_if(list.begin(), list.end(), - [type](const std::shared_ptr& obj) { - return obj->getVoiceProcessingType() == type; - }); - if (itr == list.end()) { - return false; - } - if (remove) { - list.erase(itr); - } - return true; - } - - std::shared_ptr createSession(const VoiceProcessingType& type, - const Parameter::Common& common, - bool processData) { - int sessionId = common.session; - LOG(DEBUG) << __func__ << type << " with sessionId " << sessionId; - std::lock_guard lg(mMutex); - - if (mSessionMap.count(sessionId)) { - LOG(INFO) << __func__ << type << " new effect in existing session " << sessionId; - // How about same effect in same session? What to do there? - } else { - LOG(INFO) << __func__ << type << " new session created " << sessionId; - } - - // For first check if it can work? // TODO - auto& list = mSessionMap[sessionId]; - auto context = std::make_shared(common, type, processData); - RETURN_VALUE_IF(!context, nullptr, "failedToCreateContext"); - list.push_back(context); - - return context; - } - - void releaseSession(const VoiceProcessingType& type, int sessionId) { - LOG(DEBUG) << __func__ << type << " sessionId " << sessionId; - std::lock_guard lg(mMutex); - if (mSessionMap.count(sessionId)) { - auto& list = mSessionMap[sessionId]; - if (!findEffectTypeInList(list, type, true /* remove */)) { - LOG(ERROR) << __func__ << " can't find " << type << "in session " << sessionId; - return; - } - if (list.empty()) { - mSessionMap.erase(sessionId); - } - } - } - - private: - std::mutex mMutex; - // Each session can have both AEC/NS, maintain per session list of effects - std::unordered_map mSessionMap - GUARDED_BY(mMutex); -}; -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessing.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessing.cpp deleted file mode 100755 index 9f92445b..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessing.cpp +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_VoiceProcessingQti" - -#include "VoiceProcessing.h" -#include -#include - -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::android::hardware::audio::effect::IEffect; -using aidl::qti::effects::kAcousticEchoCancelerQtiUUID; -using aidl::qti::effects::kNoiseSuppressionQtiUUID; -using aidl::android::media::audio::common::AudioUuid; -using aidl::qti::effects::VoiceProcessing; - -bool isUuidSupported(const AudioUuid* uuid) { - return (*uuid == kAcousticEchoCancelerQtiUUID || *uuid == kNoiseSuppressionQtiUUID); -} - -extern "C" binder_exception_t createEffect(const AudioUuid* uuid, - std::shared_ptr* instanceSpp) { - if (!uuid || !isUuidSupported(uuid)) { - LOG(ERROR) << __func__ << "uuid not supported"; - return EX_ILLEGAL_ARGUMENT; - } - if (instanceSpp) { - *instanceSpp = ndk::SharedRefBase::make(*uuid); - LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created"; - return EX_NONE; - } else { - LOG(ERROR) << __func__ << " invalid input parameter!"; - return EX_ILLEGAL_ARGUMENT; - } -} - -extern "C" binder_exception_t queryEffect(const AudioUuid* uuid, Descriptor* _aidl_return) { - if (uuid == nullptr || !isUuidSupported(uuid)) { - LOG(ERROR) << __func__ << "uuid not supported"; - return EX_ILLEGAL_ARGUMENT; - } - if (*uuid == kAcousticEchoCancelerQtiUUID) { - *_aidl_return = aidl::qti::effects::kAcousticEchoCancelerDesc; - } else if (*uuid == kNoiseSuppressionQtiUUID) { - *_aidl_return = aidl::qti::effects::kNoiseSuppressionDesc; - } - return EX_NONE; -} - -namespace aidl::qti::effects { - -VoiceProcessing::VoiceProcessing(const AudioUuid& uuid) { - LOG(DEBUG) << __func__ << toString(uuid); - if (uuid == kAcousticEchoCancelerQtiUUID) { - mType = VoiceProcessingType::AcousticEchoCanceler; - mDescriptor = &kAcousticEchoCancelerDesc; - mEffectName = &kAcousticEchoCancelerEffectName; - } else if (uuid == kNoiseSuppressionQtiUUID) { - mType = VoiceProcessingType::NoiseSuppression; - mDescriptor = &kNoiseSuppressionDesc; - mEffectName = &kNoiseSuppressionEffectName; - } else { - LOG(ERROR) << __func__ << uuid.toString() << " not supported yet!"; - } -} - -ndk::ScopedAStatus VoiceProcessing::getDescriptor(Descriptor* _aidl_return) { - RETURN_IF(!_aidl_return, EX_ILLEGAL_ARGUMENT, "Parameter:nullptr"); - - *_aidl_return = *mDescriptor; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus VoiceProcessing::commandImpl(CommandId command) { - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - switch (command) { - case CommandId::START: - mContext->enable(); - break; - case CommandId::STOP: - mContext->disable(); - break; - case CommandId::RESET: - mContext->reset(); - break; - default: - LOG(ERROR) << __func__ << " commandId " << toString(command) << " not supported"; - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "commandIdNotSupported"); - } - return ndk::ScopedAStatus::ok(); -} - -std::shared_ptr VoiceProcessing::createContext(const Parameter::Common& common, - bool processData) { - if (mContext) { - LOG(DEBUG) << __func__ << " context already exist"; - } else { - // GlobalVoiceProcessingSession is a singleton - mContext = GlobalVoiceProcessingSession::getSession().createSession(mType, common, - processData); - } - - return mContext; -} - -RetCode VoiceProcessing::releaseContext() { - if (mContext) { - GlobalVoiceProcessingSession::getSession().releaseSession(mType, mContext->getSessionId()); - mContext.reset(); - } - return RetCode::SUCCESS; -} - -ndk::ScopedAStatus VoiceProcessing::setParameterSpecific(const Parameter::Specific& specific) { - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "ParamUnsupported"); -} - -ndk::ScopedAStatus VoiceProcessing::getParameterNoiseSuppression(const NoiseSuppression::Id& id, - Parameter::Specific* specific) { - RETURN_IF(id.getTag() != NoiseSuppression::Id::commonTag, EX_ILLEGAL_ARGUMENT, - "NoiseSuppressionTagNotSupported"); - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - NoiseSuppression param; - - auto tag = id.get(); - switch (tag) { - case NoiseSuppression::level: { - param.set(mContext->getNoiseSuppressionLevel()); - break; - } - default: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage( - EX_ILLEGAL_ARGUMENT, "NoiseSuppressionTagNotSupported"); - } - } - - specific->set(param); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus VoiceProcessing::getParameterAcousticEchoCanceler( - const AcousticEchoCanceler::Id& id, Parameter::Specific* specific) { - RETURN_IF(id.getTag() != AcousticEchoCanceler::Id::commonTag, EX_ILLEGAL_ARGUMENT, - "AcousticEchoCancelerTagNotSupported"); - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - AcousticEchoCanceler param; - auto tag = id.get(); - switch (tag) { - case AcousticEchoCanceler::echoDelayUs: { - param.set( - mContext->getAcousticEchoCancelerEchoDelay()); - break; - } - case AcousticEchoCanceler::mobileMode: { - param.set( - mContext->getAcousticEchoCancelerMobileMode()); - break; - } - default: { - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage( - EX_ILLEGAL_ARGUMENT, "AcousticEchoCancelerTagNotSupported"); - } - } - - specific->set(param); - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus VoiceProcessing::getParameterSpecific(const Parameter::Id& id, - Parameter::Specific* specific) { - RETURN_IF(!specific, EX_NULL_POINTER, "nullPtr"); - auto tag = id.getTag(); - - switch (tag) { - case Parameter::Id::acousticEchoCancelerTag: - return getParameterAcousticEchoCanceler( - id.get(), specific); - case Parameter::Id::noiseSuppressionTag: - return getParameterNoiseSuppression(id.get(), - specific); - default: - LOG(ERROR) << __func__ << " unsupported tag: " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "wrongIdTag"); - } - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "ParamUnsupported"); -} - -// Processing method running in EffectWorker thread. -IEffect::Status VoiceProcessing::effectProcessImpl(float* in, float* out, int sampleToProcess) { - if (!mContext) { - LOG(ERROR) << __func__ << " nullContext"; - return {EX_NULL_POINTER, 0, 0}; - } - for (int i = 0; i < sampleToProcess; i++) { - *out++ = *in++; - } - return {STATUS_OK, sampleToProcess, sampleToProcess}; -} - -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessing.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessing.h deleted file mode 100755 index 3811942d..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessing.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include - -#include "GlobalVoiceProcessingSession.h" -#include "VoiceProcessingContext.h" -#include "VoiceProcessingTypes.h" -#include "effect-impl/EffectImpl.h" -#include "effect-impl/EffectUUID.h" - -namespace aidl::qti::effects { - -class VoiceProcessing final : public EffectImpl { - public: - VoiceProcessingType mType = VoiceProcessingType::AcousticEchoCanceler; - - VoiceProcessing(const AudioUuid& uuid); - ~VoiceProcessing() { - cleanUp(); - LOG(DEBUG) << __func__; - } - - ndk::ScopedAStatus commandImpl(CommandId command) override; - ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override; - - ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override; - ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, - Parameter::Specific* specific) override; - - std::shared_ptr createContext(const Parameter::Common& common, - bool processData) override; - - RetCode releaseContext() override; - - std::string getEffectName() override { return *mEffectName; }; - IEffect::Status effectProcessImpl(float* in, float* out, int samples) override; - - ndk::ScopedAStatus getParameterAcousticEchoCanceler(const AcousticEchoCanceler::Id& id, - Parameter::Specific* specific); - - ndk::ScopedAStatus getParameterNoiseSuppression(const NoiseSuppression::Id& id, - Parameter::Specific* specific); - - private: - std::shared_ptr mContext; -}; -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessingContext.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessingContext.cpp deleted file mode 100755 index 955efe36..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessingContext.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "AHAL_VoiceProcessingContextQti" - -#include - -#include "VoiceProcessingContext.h" -#include "VoiceProcessingTypes.h" - -using aidl::android::hardware::audio::effect::IEffect; - -namespace aidl::qti::effects { - -VoiceProcessingContext::VoiceProcessingContext(const Parameter::Common& common, - const VoiceProcessingType& type, bool processData) - : EffectContext(common, processData), mType(type) { - LOG(DEBUG) << __func__; - mState = UNINITIALIZED; -} - -VoiceProcessingContext::~VoiceProcessingContext() { - LOG(DEBUG) << __func__; - mState = UNINITIALIZED; -} - -RetCode VoiceProcessingContext::enable() { - LOG(DEBUG) << __func__; - if (mState != INITIALIZED) { - return RetCode::ERROR_EFFECT_LIB_ERROR; - } - mState = ACTIVE; - return RetCode::SUCCESS; -} - -RetCode VoiceProcessingContext::disable() { - LOG(DEBUG) << __func__; - if (mState != ACTIVE) { - return RetCode::ERROR_EFFECT_LIB_ERROR; - } - mState = INITIALIZED; - return RetCode::SUCCESS; -} - -void VoiceProcessingContext::reset() { - LOG(DEBUG) << __func__; - disable(); - resetBuffer(); -} - -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessingContext.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessingContext.h deleted file mode 100755 index 63afcc8f..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessingContext.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include "VoiceProcessingTypes.h" -#include "effect-impl/EffectContext.h" - -namespace aidl::qti::effects { - -enum VoiceProcessingState { - UNINITIALIZED, - INITIALIZED, - ACTIVE, -}; - -class VoiceProcessingContext final : public EffectContext { - public: - VoiceProcessingContext(const Parameter::Common& common, const VoiceProcessingType& type, - bool processData); - ~VoiceProcessingContext(); - VoiceProcessingType getVoiceProcessingType() const { return mType; } - RetCode enable(); - RetCode disable(); - void reset(); - int getAcousticEchoCancelerEchoDelay() const { return 0; } - bool getAcousticEchoCancelerMobileMode() const { return false; } - NoiseSuppression::Level getNoiseSuppressionLevel() const { - return NoiseSuppression::Level::MEDIUM; - } - - private: - VoiceProcessingState mState = UNINITIALIZED; - VoiceProcessingType mType; -}; - -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessingTypes.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessingTypes.h deleted file mode 100755 index 2ffe15a1..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/voiceprocessing/VoiceProcessingTypes.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include "effect-impl/EffectImpl.h" -#include "effect-impl/EffectUUID.h" - -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::android::hardware::audio::effect::Capability; -using aidl::android::hardware::audio::effect::Flags; -using aidl::android::hardware::audio::effect::Range; -using aidl::android::hardware::audio::effect::AcousticEchoCanceler; -using aidl::android::hardware::audio::effect::NoiseSuppression; - -namespace aidl::qti::effects { - -enum class VoiceProcessingType { - AcousticEchoCanceler, - NoiseSuppression, -}; - -static const std::string kAcousticEchoCancelerEffectName = "aec"; -static const std::string kNoiseSuppressionEffectName = "ns"; - -static Flags kVoiceProcessingFlags = { - .type = Flags::Type::PRE_PROC, - .deviceIndication = true, - .hwAcceleratorMode = Flags::HardwareAccelerator::TUNNEL, - .offloadIndication = true, -}; - -static const std::vector kAcousticEchoCancelerRanges = { - MAKE_RANGE(AcousticEchoCanceler, echoDelayUs, 0, -1), - MAKE_RANGE(AcousticEchoCanceler, mobileMode, true, false), -}; - -static const Capability kAcousticEchoCancelerCap = {.range = kAcousticEchoCancelerRanges}; - -static const Descriptor kAcousticEchoCancelerDesc = { - .common = {.id = {.type = kAcousticEchoCancelerTypeUUID, - .uuid = kAcousticEchoCancelerQtiUUID, - .proxy = std::nullopt}, - .flags = kVoiceProcessingFlags, - .name = kAcousticEchoCancelerEffectName, - .implementor = "Qualcomm Technologies Inc"}, - .capability = kAcousticEchoCancelerCap, -}; - -static const std::vector kNoiseSuppressionRanges = { - MAKE_RANGE(NoiseSuppression, level, NoiseSuppression::Level::MEDIUM, - NoiseSuppression::Level::LOW), - MAKE_RANGE(NoiseSuppression, type, NoiseSuppression::Type::MULTI_CHANNEL, - NoiseSuppression::Type::SINGLE_CHANNEL), -}; - -static const Capability kNoiseSuppresionCap = {.range = kNoiseSuppressionRanges}; - -static const Descriptor kNoiseSuppressionDesc = { - .common = {.id = {.type = kNoiseSuppressionTypeUUID, - .uuid = kNoiseSuppressionQtiUUID, - .proxy = std::nullopt}, - .flags = kVoiceProcessingFlags, - .name = kNoiseSuppressionEffectName, - .implementor = "Qualcomm Technologies Inc"}, - .capability = kNoiseSuppresionCap, -}; - -inline std::ostream& operator<<(std::ostream& out, const VoiceProcessingType& type) { - switch (type) { - case VoiceProcessingType::AcousticEchoCanceler: - return out << "AcousticEchoCanceler"; - case VoiceProcessingType::NoiseSuppression: - return out << "NoiseSuppression"; - } - return out << "Enum_VoiceProcessingError"; -} - -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/Android.mk deleted file mode 100755 index 998289a2..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/Android.mk +++ /dev/null @@ -1,27 +0,0 @@ -LOCAL_PATH:= $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE:= libvolumelistener -LOCAL_VENDOR_MODULE := true -LOCAL_MODULE_RELATIVE_PATH := soundfx -LOCAL_MODULE_OWNER := qti - -LOCAL_CLANG := true -LOCAL_TIDY := true -LOCAL_CFLAGS += -v -Wall -Wthread-safety - -LOCAL_SRC_FILES:= \ - VolumeListener.cpp \ - VolumeListenerContext.cpp \ - GlobalVolumeListenerSession.cpp - -LOCAL_STATIC_LIBRARIES := libaudioeffecthal_base_impl_static - -LOCAL_SHARED_LIBRARIES:= \ - $(EFFECTS_DEFAULTS_SHARED_LIBRARIES) \ - libar-pal - -LOCAL_HEADER_LIBRARIES:= $(EFFECTS_DEFAULTS_HEADERS_LIBRARIES) - -include $(BUILD_SHARED_LIBRARY) diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/GlobalVolumeListenerSession.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/GlobalVolumeListenerSession.cpp deleted file mode 100755 index 5581761f..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/GlobalVolumeListenerSession.cpp +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#include -#include -#define LOG_TAG "AHAL_Effect_VolumeListenerQti" -#include -#include - -#include "GlobalVolumeListenerSession.h" - -namespace aidl::qti::effects { - -GlobalConfigs::GlobalConfigs() { - initGainMappings(); - mHeadsetCalEnabled = property_get_bool("vendor.audio.volume.headset.gain.depcal", false); -} - -void GlobalConfigs::initGainMappings() { - size_t payloadSize = 0; - pal_param_gain_lvl_map_t gainLevelMap; - gainLevelMap.mapping_tbl = mGainMappingTable; - gainLevelMap.table_size = MAX_VOLUME_CAL_STEPS; - gainLevelMap.filled_size = 0; - - printVolumeTable(); - - int ret = - pal_get_param(PAL_PARAM_ID_GAIN_LVL_MAP, (void **)&gainLevelMap, &payloadSize, nullptr); - - if (ret != 0) { - LOG(ERROR) << "fail to get PAL_PARAM_ID_GAIN_LVL_MAP " << ret; - gainLevelMap.filled_size = 0; - } - - int maxTableEntries = gainLevelMap.filled_size; - - if (maxTableEntries > 0 && maxTableEntries <= MAX_VOLUME_CAL_STEPS) { - if (maxTableEntries < mTotalVolumeCalSteps) { - for (int i = maxTableEntries; i < mTotalVolumeCalSteps; i++) { - mGainMappingTable[i].amp = 0; - mGainMappingTable[i].db = 0; - mGainMappingTable[i].level = 0; - } - } - mTotalVolumeCalSteps = maxTableEntries; - LOG(DEBUG) << "Using custom volume table"; - } else { - LOG(DEBUG) << "Using default volume table"; - } - printVolumeTable(); -} - -void GlobalConfigs::printVolumeTable() { - for (int i = 0; i < mTotalVolumeCalSteps; i++) { - LOG(VERBOSE) << "Index: " << i << " (amp, db, level)" << mGainMappingTable[i].amp << " " - << mGainMappingTable[i].db << " " << mGainMappingTable[i].level; - } -} - -GlobalVolumeListenerSession::GlobalVolumeListenerSession() { - LOG(VERBOSE) << __func__ << "Global Session created"; - mTotalVolumeSteps = mConfig.getVolumeCalSteps(); - mGainTable = mConfig.getGainTable(); -} - -std::shared_ptr GlobalVolumeListenerSession::createSession( - const VolumeListenerType &type, const Parameter::Common &common, bool processData) { - int sessionId = common.session; - LOG(VERBOSE) << __func__ << type << " with sessionId " << sessionId; - std::lock_guard lg(mSessionMutex); - - auto context = std::make_shared(common, type, processData); - RETURN_VALUE_IF(!context, nullptr, "failedToCreateContext"); - - mSessionsMap[sessionId] = context; - return context; -} - -void GlobalVolumeListenerSession::releaseSession(int sessionId) { - LOG(VERBOSE) << __func__ << "Enter: sessionId " << sessionId << "total sessions " - << mSessionsMap.size(); - std::lock_guard lg(mSessionMutex); - - if (mSessionsMap.find(sessionId) != mSessionsMap.end()) { - mSessionsMap.erase(sessionId); - } - // recalculate the checkAndSetGainDepCal once any sesesion closes. - checkAndSetGainDepCal_l(); - LOG(VERBOSE) << __func__ << "Exit: sessionId " << sessionId << "total sessions " - << mSessionsMap.size(); -} - -RetCode GlobalVolumeListenerSession::setOutputDevice(int sessionId, - const AudioDeviceDescriptionVector &devices) { - LOG(VERBOSE) << __func__ << " sessionId " << sessionId; - std::lock_guard lg(mSessionMutex); - if (mSessionsMap.find(sessionId) != mSessionsMap.end()) { - auto &context = mSessionsMap[sessionId]; - context->setOutputDevice(devices); - checkAndSetGainDepCal_l(); - } - return RetCode::SUCCESS; -} - -RetCode GlobalVolumeListenerSession::setVolumeStereo(int sessionId, - const Parameter::VolumeStereo &volumeStereo) { - LOG(VERBOSE) << __func__ << " sessionId " << sessionId; - std::lock_guard lg(mSessionMutex); - if (mSessionsMap.find(sessionId) != mSessionsMap.end()) { - auto &context = mSessionsMap[sessionId]; - context->setVolumeStereo(volumeStereo); - checkAndSetGainDepCal_l(); - } - return RetCode::SUCCESS; -} - -RetCode GlobalVolumeListenerSession::enable(int sessionId) { - LOG(VERBOSE) << __func__ << " sessionId " << sessionId; - std::lock_guard lg(mSessionMutex); - RetCode status = RetCode::SUCCESS; - if (mSessionsMap.find(sessionId) != mSessionsMap.end()) { - auto &context = mSessionsMap[sessionId]; - status = context->enable(); - checkAndSetGainDepCal_l(); - } - return status; -} - -RetCode GlobalVolumeListenerSession::disable(int sessionId) { - LOG(VERBOSE) << __func__ << " sessionId " << sessionId; - std::lock_guard lg(mSessionMutex); - RetCode status = RetCode::SUCCESS; - if (mSessionsMap.find(sessionId) != mSessionsMap.end()) { - auto &context = mSessionsMap[sessionId]; - status = context->disable(); - checkAndSetGainDepCal_l(); - } - return status; -} - -void GlobalVolumeListenerSession::checkAndSetGainDepCal_l() { - // iterate through list and make decision to set new gain dep cal level for speaker device - // 1. find all usecase active on speaker - // 2. find energy sum for each usecase - // 3. find the highest of all the active usecase - // 4. if new value is different than the current value then load new calibration - - float newVolume = -1.0f; - auto sumEnergy = getSumEnergy_l(); - - if (sumEnergy != 0.0f) { - newVolume = fmin(sqrt(sumEnergy), 1.0); - } - - uint32_t gain = (uint32_t)(round(newVolume * (1 << LIN_VOLUME_QFACTOR_28))); - LOG(DEBUG) << __func__ << " use volume " << ::android::internal::ToString(newVolume) << " gain " - << gain; - sendLinearGain(gain); - applyUpdatedCalibration(newVolume); -} - -void GlobalVolumeListenerSession::applyUpdatedCalibration(float newVolume) { - if (newVolume != mCurrentVolume) { - // send Gain dep cal level - int gainDepCalLevel = -1; - if (newVolume >= 1 && mTotalVolumeSteps > 0) { // max amplitude, use highest DRC level - gainDepCalLevel = mGainTable[mTotalVolumeSteps - 1].level; - } else if (newVolume == -1) { - gainDepCalLevel = DEFAULT_CAL_STEP; - } else if (newVolume == 0) { - gainDepCalLevel = mGainTable[0].level; - } else { - for (int index = 0; index < mTotalVolumeSteps - 1; index++) { - if (newVolume < mGainTable[index + 1].amp && newVolume >= mGainTable[index].amp) { - gainDepCalLevel = mGainTable[index].level; - LOG(VERBOSE) << __func__ << " found " << newVolume << " at " << index - << " gain " << gainDepCalLevel; - break; - } - } - } - - // check here if previous gain dep cal level was not same - if (gainDepCalLevel != mCurrentGainDepCalLevel) { - // decision made .. send new level now - if (!sendGainDepCalibration(gainDepCalLevel)) { - LOG(ERROR) << __func__ << " Failed to set gain dep cal level"; - } else { - // Success in setting the gain dep cal level, store new level and Volume - mCurrentGainDepCalLevel = gainDepCalLevel; - mCurrentVolume = newVolume; - } - } - } else { - LOG(VERBOSE) << "volume unchanged"; - } -} - -float GlobalVolumeListenerSession::getSumEnergy_l() { - // iterate through list and make decision to set new gain dep cal level for speaker device - // 1. find all usecase active on speaker - // 2. find energy sum for each usecase - // 3. find the highest of all the active usecase - float sumEnergy = 0.0f, tempVolume; - for (auto &sessionEntry : mSessionsMap) { - auto &session = sessionEntry.second; - if (session->isEffectActiveAndApplicable()) { - tempVolume = session->getMaxOfLeftRightChannels(); - sumEnergy += tempVolume * tempVolume; - LOG(VERBOSE) << __func__ << " size " << mSessionsMap.size() << " sum energy " - << sumEnergy; - } - } - LOG(VERBOSE) << __func__ << " size " << mSessionsMap.size() << " sum energy " << sumEnergy; - return sumEnergy; -} - -bool GlobalVolumeListenerSession::sendGainDepCalibration(int level) { - int32_t ret = 0; - pal_param_gain_lvl_cal_t gainLevelCal; - gainLevelCal.level = level; - LOG(VERBOSE) << __func__ << " level " << level; - ret = pal_set_param(PAL_PARAM_ID_GAIN_LVL_CAL, (void *)&gainLevelCal, - sizeof(pal_param_gain_lvl_cal_t)); - if (ret != 0) { - LOG(ERROR) << "fail to set PAL_PARAM_ID_GAIN_LVL_CAL " << ret; - } - - return (ret == 0); -} - -bool GlobalVolumeListenerSession::sendLinearGain(int32_t gain) { - int32_t ret = 0; - pal_param_mspp_linear_gain_t linearGain; - linearGain.gain = gain; - LOG(VERBOSE) << __func__ << " gain " << gain; - ret = pal_set_param(PAL_PARAM_ID_MSPP_LINEAR_GAIN, (void *)&linearGain, - sizeof(pal_param_mspp_linear_gain_t)); - if (ret != 0) { - LOG(ERROR) << "fail to set PAL_PARAM_ID_MSPP_LINEAR_GAIN " << ret; - } - - return (ret == 0); -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/GlobalVolumeListenerSession.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/GlobalVolumeListenerSession.h deleted file mode 100755 index bd63c7d6..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/GlobalVolumeListenerSession.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include - -#include -#include - -#include "VolumeListenerContext.h" -#include "VolumeListenerTypes.h" - -namespace aidl::qti::effects { - -using VolumeListenerContextList = std::vector>; - -#define LIN_VOLUME_QFACTOR_28 28 -#define MAX_VOLUME_CAL_STEPS 15 -#define MAX_GAIN_LEVELS 5 -#define DEFAULT_CAL_STEP 0 - -class GlobalConfigs { - public: - GlobalConfigs(); - int getVolumeCalSteps() { return mTotalVolumeCalSteps; } - bool isHeadsetCalEnabled() { return mHeadsetCalEnabled; } - struct pal_amp_db_and_gain_table* getGainTable() { - return mGainMappingTable; - } - - private: - void initGainMappings(); - void printVolumeTable(); - struct pal_amp_db_and_gain_table mGainMappingTable[MAX_VOLUME_CAL_STEPS] = { - /* Level 0 in the calibration database contains default calibration */ - {0.001774, -55, 5}, {0.501187, -6, 4}, {0.630957, -4, 3}, {0.794328, -2, 2}, - {1.0, 0, 1}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, - {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, - {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, - }; - - int mTotalVolumeCalSteps = MAX_GAIN_LEVELS; - bool mHeadsetCalEnabled = false; -}; - -class GlobalVolumeListenerSession { - public: - static GlobalVolumeListenerSession& getSession() { - static GlobalVolumeListenerSession instance; - return instance; - } - std::shared_ptr createSession(const VolumeListenerType& type, - const Parameter::Common& common, - bool processData); - void releaseSession(int sessionId); - - RetCode setOutputDevice(int sessionId, const AudioDeviceDescriptionVector& devices); - RetCode setVolumeStereo(int sessionId, const Parameter::VolumeStereo& volumeStereo); - RetCode enable(int sessionId); - RetCode disable(int sessionId); - - // compute energy sum for the active speaker device (pick loudest of both channels) - GlobalConfigs& getConfig() { return mConfig; } - - private: - GlobalVolumeListenerSession(); - - float getSumEnergy_l(); - void checkAndSetGainDepCal_l(); - - void applyUpdatedCalibration(float newVolume); - bool sendLinearGain(int32_t gain); - bool sendGainDepCalibration(int level); - - GlobalConfigs mConfig; - - int mCurrentGainDepCalLevel = -1; - int mTotalVolumeSteps; - struct pal_amp_db_and_gain_table* mGainTable; - float mCurrentVolume = 0.0f; - - // session id to context map - std::unordered_map> mSessionsMap; - std::mutex mSessionMutex; -}; - -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListener.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListener.cpp deleted file mode 100755 index 78f83150..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListener.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#include -#include -#define LOG_TAG "AHAL_Effect_VolumeListenerQti" - -#include -#include -#include - -#include "VolumeListener.h" - -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::android::hardware::audio::effect::IEffect; -using aidl::android::hardware::audio::effect::State; -using aidl::qti::effects::kMusicVolumeListenerUUID; -using aidl::qti::effects::kRingVolumeListenerUUID; -using aidl::qti::effects::kAlarmVolumeListenerUUID; -using aidl::qti::effects::kVoiceCallVolumeListenerUUID; -using aidl::qti::effects::kNotificationVolumeListenerUUID; -using aidl::qti::effects::VolumeListener; -using aidl::android::media::audio::common::AudioUuid; - -bool isUuidSupported(const AudioUuid* uuid) { - return (*uuid == kMusicVolumeListenerUUID || *uuid == kRingVolumeListenerUUID || - *uuid == kAlarmVolumeListenerUUID || *uuid == kVoiceCallVolumeListenerUUID || - *uuid == kNotificationVolumeListenerUUID); -} - -extern "C" binder_exception_t createEffect(const AudioUuid* uuid, - std::shared_ptr* instanceSpp) { - if (uuid == nullptr || !isUuidSupported(uuid)) { - LOG(ERROR) << __func__ << "uuid not supported"; - return EX_ILLEGAL_ARGUMENT; - } - if (instanceSpp) { - *instanceSpp = ndk::SharedRefBase::make(*uuid); - LOG(VERBOSE) << __func__ << " instance " << instanceSpp->get() << " created"; - return EX_NONE; - } else { - LOG(ERROR) << __func__ << " invalid input parameter!"; - return EX_ILLEGAL_ARGUMENT; - } -} - -extern "C" binder_exception_t queryEffect(const AudioUuid* uuid, Descriptor* _aidl_return) { - if (uuid == nullptr || !isUuidSupported(uuid)) { - LOG(ERROR) << __func__ << "uuid not supported"; - return EX_ILLEGAL_ARGUMENT; - } - if (*uuid == kAlarmVolumeListenerUUID) { - *_aidl_return = aidl::qti::effects::kAlarmVolumeListenerDesc; - } else if (*uuid == kMusicVolumeListenerUUID) { - *_aidl_return = aidl::qti::effects::kMusicVolumeListenerDesc; - } else if (*uuid == kNotificationVolumeListenerUUID) { - *_aidl_return = aidl::qti::effects::kNotificationVolumeListenerDesc; - } else if (*uuid == kVoiceCallVolumeListenerUUID) { - *_aidl_return = aidl::qti::effects::kVoiceCallVolumeListenerDesc; - } else if (*uuid == kRingVolumeListenerUUID) { - *_aidl_return = aidl::qti::effects::kRingVolumeListenerDesc; - } - return EX_NONE; -} - -namespace aidl::qti::effects { - -VolumeListener::VolumeListener(const AudioUuid& uuid) { - LOG(VERBOSE) << __func__ << toString(uuid); - if (uuid == kAlarmVolumeListenerUUID) { - mType = VolumeListenerType::ALARM; - mDescriptor = &kAlarmVolumeListenerDesc; - mEffectName = &kAlarmVolumeListenerEffectName; - } else if (uuid == kMusicVolumeListenerUUID) { - mType = VolumeListenerType::MUSIC; - mDescriptor = &kMusicVolumeListenerDesc; - mEffectName = &kMusicVolumeListenerEffectName; - } else if (uuid == kNotificationVolumeListenerUUID) { - mType = VolumeListenerType::NOTIFICATION; - mDescriptor = &kNotificationVolumeListenerDesc; - mEffectName = &kNotificationVolumeListenerEffectName; - } else if (uuid == kVoiceCallVolumeListenerUUID) { - mType = VolumeListenerType::VOICECALL; - mDescriptor = &kVoiceCallVolumeListenerDesc; - mEffectName = &kVoiceCallVolumeListenerEffectName; - } else if (uuid == kRingVolumeListenerUUID) { - mType = VolumeListenerType::RING; - mDescriptor = &kRingVolumeListenerDesc; - mEffectName = &kRingVolumeListenerEffectName; - } else { - LOG(ERROR) << __func__ << toString(uuid) << " not supported yet!"; - } -} - -ndk::ScopedAStatus VolumeListener::getDescriptor(Descriptor* _aidl_return) { - LOG(VERBOSE) << __func__ << (*mDescriptor).toString(); - *_aidl_return = *mDescriptor; - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus VolumeListener::commandImpl(CommandId command) { - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - LOG(VERBOSE) << __func__ << toString(command); - switch (command) { - case CommandId::START: - mContext->enable(); - break; - case CommandId::STOP: - mContext->disable(); - break; - case CommandId::RESET: - mContext->reset(); - break; - default: - LOG(ERROR) << __func__ << " commandId " << toString(command) << " not supported"; - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "commandIdNotSupported"); - } - return ndk::ScopedAStatus::ok(); -} - -std::shared_ptr VolumeListener::createContext(const Parameter::Common& common, - bool processData) { - LOG(VERBOSE) << __func__; - if (mContext) { - LOG(DEBUG) << __func__ << " context already exist"; - } else { - // GlobalVolumeListenerSession is a singleton - mContext = - GlobalVolumeListenerSession::getSession().createSession(mType, common, processData); - } - return mContext; -} - -RetCode VolumeListener::releaseContext() { - if (mContext) { - GlobalVolumeListenerSession::getSession().releaseSession(mContext->getSessionId()); - mContext.reset(); - } - return RetCode::SUCCESS; -} - -ndk::ScopedAStatus VolumeListener::setParameterSpecific(const Parameter::Specific& specific) { - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus VolumeListener::getParameterSpecific(const Parameter::Id& id, - Parameter::Specific* specific) { - return ndk::ScopedAStatus::ok(); -} - -ndk::ScopedAStatus VolumeListener::setParameterCommon(const Parameter& param) { - RETURN_IF(!mContext, EX_NULL_POINTER, "nullContext"); - - auto tag = param.getTag(); - switch (tag) { - case Parameter::common: - RETURN_IF(mContext->setCommon(param.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setCommFailed"); - break; - case Parameter::deviceDescription: { - auto ret = GlobalVolumeListenerSession::getSession().setOutputDevice( - mContext->getSessionId(), param.get()); - RETURN_IF(ret != RetCode::SUCCESS, EX_ILLEGAL_ARGUMENT, "setDeviceFailed"); - } break; - case Parameter::mode: - RETURN_IF(mContext->setAudioMode(param.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setModeFailed"); - break; - case Parameter::source: - RETURN_IF(mContext->setAudioSource(param.get()) != RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setSourceFailed"); - break; - case Parameter::volumeStereo: { - auto ret = GlobalVolumeListenerSession::getSession().setVolumeStereo( - mContext->getSessionId(), param.get()); - RETURN_IF(ret != RetCode::SUCCESS, EX_ILLEGAL_ARGUMENT, "setDeviceFailed"); - } - RETURN_IF(mContext->setVolumeStereo(param.get()) != - RetCode::SUCCESS, - EX_ILLEGAL_ARGUMENT, "setVolumeStereoFailed"); - break; - default: { - LOG(ERROR) << __func__ << " unsupportedParameterTag " << toString(tag); - return ndk::ScopedAStatus::fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT, - "commonParamNotSupported"); - } - } - return ndk::ScopedAStatus::ok(); -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListener.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListener.h deleted file mode 100755 index 152faeed..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListener.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include -#include - -#include "effect-impl/EffectImpl.h" -#include "effect-impl/EffectUUID.h" - -#include "GlobalVolumeListenerSession.h" -#include "VolumeListenerContext.h" -#include "VolumeListenerTypes.h" -namespace aidl::qti::effects { - -class VolumeListener final : public EffectImpl { - public: - VolumeListenerType mType = VolumeListenerType::ALARM; - - VolumeListener(const AudioUuid& uuid); - ~VolumeListener() { - cleanUp(); - } - - ndk::ScopedAStatus commandImpl(CommandId command) override; - ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override; - - std::shared_ptr createContext(const Parameter::Common& common, - bool processData) override; - - RetCode releaseContext() override; - - ndk::ScopedAStatus setParameterCommon(const Parameter& param) override; - ndk::ScopedAStatus setParameterSpecific(const Parameter::Specific& specific) override; - ndk::ScopedAStatus getParameterSpecific(const Parameter::Id& id, - Parameter::Specific* specific) override; - - std::string getEffectName() override { return *mEffectName; }; - - private: - std::shared_ptr mContext; -}; -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListenerContext.cpp b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListenerContext.cpp deleted file mode 100755 index af1ce3dc..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListenerContext.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include -#include -#include -#define LOG_TAG "AHAL_Effect_VolumeListenerQti" -#include - -#include -#include "GlobalVolumeListenerSession.h" -#include "VolumeListenerContext.h" - -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; - -namespace aidl::qti::effects { - -bool VolumeListenerContext::sHeadsetCalEnabled = - GlobalVolumeListenerSession::getSession().getConfig().isHeadsetCalEnabled(); - -bool VolumeListenerContext::isEarpiece(AudioDeviceDescriptionVector& devices) { - for (const auto& device : devices) { - if (device != AudioDeviceDescription{AudioDeviceType::OUT_SPEAKER_EARPIECE, ""}) { - return false; - } - } - return true; -} - -bool VolumeListenerContext::isWiredHeadset(AudioDeviceDescriptionVector& devices) { - for (const auto& device : devices) { - if (device != AudioDeviceDescription{AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_ANALOG} && - device != AudioDeviceDescription{AudioDeviceType::OUT_HEADPHONE, - AudioDeviceDescription::CONNECTION_ANALOG}) { - return false; - } - } - return true; -} - -// Adapted from dev & OUT_SPK, any of the device is a speaker device. -bool VolumeListenerContext::isSpeaker(AudioDeviceDescriptionVector& devices) { - const AudioDeviceDescriptionVector& dev = devices; - return isSpeaker(dev); -} - -bool VolumeListenerContext::isSpeaker(const AudioDeviceDescriptionVector& devices) { - for (const auto& device : devices) { - if (device == AudioDeviceDescription{AudioDeviceType::OUT_SPEAKER, ""} || - device == AudioDeviceDescription{AudioDeviceType::OUT_SPEAKER_SAFE, ""}) { - return true; - } - } - return false; -} - -VolumeListenerContext::VolumeListenerContext(const Parameter::Common& common, - VolumeListenerType type, bool processData) - : EffectContext(common, processData) { - mType = type; - LOG(VERBOSE) << __func__ << details(); - mState = VolumeListenerState::INITIALIZED; -} - -VolumeListenerContext::~VolumeListenerContext() { - LOG(VERBOSE) << __func__ << details(); - mState = VolumeListenerState::UNINITIALIZED; -} - -bool VolumeListenerContext::isValidVoiceCallContext() { - return mType == VolumeListenerType::VOICECALL && sHeadsetCalEnabled && - (isEarpiece(mOutputDevice) || isWiredHeadset(mOutputDevice)); -} - -bool VolumeListenerContext::isValidContext() { - return isValidVoiceCallContext() || isSpeaker(mOutputDevice); -} - -RetCode VolumeListenerContext::enable() { - LOG(VERBOSE) << __func__ << details(); - if (mState != VolumeListenerState::INITIALIZED) { - LOG(ERROR) << __func__ << "state not initialized"; - return RetCode::ERROR_EFFECT_LIB_ERROR; - } - mState = VolumeListenerState::ACTIVE; - return RetCode::SUCCESS; -} - -RetCode VolumeListenerContext::disable() { - LOG(VERBOSE) << __func__ << details(); - if (mState != VolumeListenerState::ACTIVE) { - LOG(ERROR) << __func__ << "state not active"; - return RetCode::ERROR_EFFECT_LIB_ERROR; - } - mState = VolumeListenerState::INITIALIZED; - return RetCode::SUCCESS; -} - -void VolumeListenerContext::reset() { - LOG(VERBOSE) << __func__ << details(); - disable(); - resetBuffer(); -} - -RetCode VolumeListenerContext::setOutputDevice( - const std::vector& devices) { - mOutputDevice = devices; - return RetCode::SUCCESS; -} - -RetCode VolumeListenerContext::setVolumeStereo(const Parameter::VolumeStereo& volumeStereo) { - LOG(VERBOSE) << __func__ << details() << " " << volumeStereo.toString(); - mVolumeStereo = volumeStereo; - return RetCode::SUCCESS; -} - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListenerContext.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListenerContext.h deleted file mode 100755 index 6f84e177..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListenerContext.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include "PalApi.h" -#include "PalDefs.h" -#include "VolumeListenerTypes.h" -#include "effect-impl/EffectContext.h" - -#define LIN_VOLUME_QFACTOR_28 28 -#define MAX_VOLUME_CAL_STEPS 15 -#define MAX_GAIN_LEVELS 5 -#define DEFAULT_CAL_STEP 0 - -namespace aidl::qti::effects { - -enum class VolumeListenerState { - UNINITIALIZED, - INITIALIZED, - ACTIVE, -}; - -using AudioDeviceDescriptionVector = - std::vector; - -class VolumeListenerContext final : public EffectContext { - public: - VolumeListenerContext(const Parameter::Common& common, VolumeListenerType type, - bool processData); - ~VolumeListenerContext(); - virtual RetCode setOutputDevice(const AudioDeviceDescriptionVector& devices) override; - virtual RetCode setVolumeStereo(const Parameter::VolumeStereo& volumeStereo) override; - RetCode enable(); - RetCode disable(); - void reset(); - - bool isActive() { return mState == VolumeListenerState::ACTIVE; } - bool isEffectActiveAndApplicable() { return isActive() && isValidContext(); } - float getMaxOfLeftRightChannels() { return fmax(mVolumeStereo.left, mVolumeStereo.right); } - - private: - bool isValidVoiceCallContext(); - bool isValidContext(); - bool isSpeaker(AudioDeviceDescriptionVector& devices); - bool isSpeaker(const AudioDeviceDescriptionVector& devices); - bool isWiredHeadset(AudioDeviceDescriptionVector& devices); - bool isEarpiece(AudioDeviceDescriptionVector& devices); - - static bool sHeadsetCalEnabled; - - VolumeListenerState mState; - VolumeListenerType mType; - - std::string details() { - std::ostringstream os; - os << " "; - os << mType; - os << " session "; - os << mCommon.session; - return os.str(); - } -}; - -} // namespace aidl::qti::effects diff --git a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListenerTypes.h b/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListenerTypes.h deleted file mode 100755 index a97f17aa..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/effects/qcom-effects/volumelistener/VolumeListenerTypes.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include "effect-impl/EffectImpl.h" -#include "effect-impl/EffectUUID.h" - -using aidl::android::hardware::audio::effect::Descriptor; -using aidl::android::hardware::audio::effect::Flags; - -namespace aidl::qti::effects { - -static const std::string kAlarmVolumeListenerEffectName = "Qti-AlarmVolumeListener"; -static const std::string kMusicVolumeListenerEffectName = "Qti-MusicVolumeListener"; -static const std::string kNotificationVolumeListenerEffectName = "Qti-NotificationVolumeListener"; -static const std::string kRingVolumeListenerEffectName = "Qti-RingVolumeListener"; -static const std::string kVoiceCallVolumeListenerEffectName = "Qti-VoiceCallVolumeListener"; - -enum class VolumeListenerType { ALARM, MUSIC, NOTIFICATION, RING, VOICECALL }; - -static Flags kVolumeFlags = {.type = Flags::Type::INSERT, - .volume = Flags::Volume::IND, - .offloadIndication = true, - .deviceIndication = true, - .bypass = true}; - -static const Descriptor kAlarmVolumeListenerDesc = { - .common = {.id = {.type = kAlarmVolumeListenerUUID, - .uuid = kAlarmVolumeListenerUUID, - .proxy = std::nullopt}, - .flags = kVolumeFlags, - .name = kAlarmVolumeListenerEffectName, - .implementor = "Qualcomm Technologies Inc"}}; - -static const Descriptor kMusicVolumeListenerDesc = { - .common = {.id = {.type = kMusicVolumeListenerUUID, - .uuid = kMusicVolumeListenerUUID, - .proxy = std::nullopt}, - .flags = kVolumeFlags, - .name = kMusicVolumeListenerEffectName, - .implementor = "Qualcomm Technologies Inc"}}; - -static const Descriptor kNotificationVolumeListenerDesc = { - .common = {.id = {.type = kNotificationVolumeListenerUUID, - .uuid = kNotificationVolumeListenerUUID, - .proxy = std::nullopt}, - .flags = kVolumeFlags, - .name = kNotificationVolumeListenerEffectName, - .implementor = "Qualcomm Technologies Inc"}}; - -static const Descriptor kVoiceCallVolumeListenerDesc = { - .common = {.id = {.type = kVoiceCallVolumeListenerUUID, - .uuid = kVoiceCallVolumeListenerUUID, - .proxy = std::nullopt}, - .flags = kVolumeFlags, - .name = kVoiceCallVolumeListenerEffectName, - .implementor = "Qualcomm Technologies Inc"}}; - -static const Descriptor kRingVolumeListenerDesc = { - .common = {.id = {.type = kRingVolumeListenerUUID, - .uuid = kRingVolumeListenerUUID, - .proxy = std::nullopt}, - .flags = kVolumeFlags, - .name = kRingVolumeListenerEffectName, - .implementor = "Qualcomm Technologies Inc"}}; - -inline std::ostream& operator<<(std::ostream& out, const VolumeListenerType& type) { - switch (type) { - case VolumeListenerType::ALARM: - return out << "ALARM"; - case VolumeListenerType::MUSIC: - return out << "MUSIC"; - case VolumeListenerType::NOTIFICATION: - return out << "NOTIFICATION"; - case VolumeListenerType::RING: - return out << "RING"; - case VolumeListenerType::VOICECALL: - return out << "VOICECALL"; - } - return out << "Enum_VolumeListenerError"; -} - -} // namespace aidl::qti::effects \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/Android.mk b/qcom/opensource/audio-hal/primary-hal/hal/fuzz/Android.mk deleted file mode 100755 index 40078c43..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/Android.mk +++ /dev/null @@ -1,62 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := fuzz-audio-hal -LOCAL_VENDOR_MODULE := true - -LOCAL_SRC_FILES := \ - main.cpp - -LOCAL_C_INCLUDES := \ - $(LOCAL_PATH)/../core/include \ - $(LOCAL_PATH)/../core/extensions/include \ - $(LOCAL_PATH)/../core/module_config/include \ - $(LOCAL_PATH)/../core/platform/include \ - $(LOCAL_PATH)/../core/utils/include \ - system/media/audio/include \ - hardware/libhardware/include \ - system/core/libsystem/include - -# { SEC_AUDIO_COMMON -SEC_AUDIO_VARS := vendor/samsung/variant/audio/sec_audioreach_vars.mk -include $(SEC_AUDIO_VARS) -# } SEC_AUDIO_COMMON - -LOCAL_SHARED_LIBRARIES := \ - libagmipcservice \ - libaudioaidlcommon \ - libbase \ - libbinder_ndk \ - libcutils \ - libdl \ - libhidlbase \ - libhardware \ - libfmq \ - libmedia_helper \ - libstagefright_foundation \ - libutils \ - libaudioutils \ - libxml2 \ - $(LATEST_ANDROID_HARDWARE_COMMON) \ - $(LATEST_ANDROID_HARDWARE_COMMON_FMQ) \ - $(LATEST_ANDROID_MEDIA_ADUIO_COMMON_TYPES) \ - android.hardware.audio.core-V2-ndk \ - $(LATEST_ANDROID_HARDWARE_AUDIO_EFFECT) \ - android.hardware.audio.core.sounddose-V2-ndk \ - libar-pal \ - libaudioserviceexampleimpl \ - libaudioplatformconverter.qti \ - qti-audio-types-aidl-V1-ndk \ - libaudiocorehal.qti \ - libclang_rt.ubsan_standalone - -LOCAL_HEADER_LIBRARIES := \ - libxsdc-utils \ - libaudioeffects \ - liberror_headers \ - libaudioclient_headers \ - libaudio_system_headers \ - libmedia_helper_headers - -include $(BUILD_FUZZ_TEST) diff --git a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/base.h b/qcom/opensource/audio-hal/primary-hal/hal/fuzz/base.h deleted file mode 100755 index 5614a85e..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/base.h +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause-Clear - -#pragma once - -#include - -template -class FuzzerBase { -protected: - P *provider = nullptr; - T *target = nullptr; - -public: - FuzzerBase() {} - FuzzerBase(P *provider, T *target): provider(provider), target(target) {} - ~FuzzerBase() {} -}; diff --git a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/gen.h b/qcom/opensource/audio-hal/primary-hal/hal/fuzz/gen.h deleted file mode 100755 index 7606270a..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/gen.h +++ /dev/null @@ -1,2066 +0,0 @@ -// GENERATED. DO NOT EDIT. -// Using: out/host/linux-x86/bin/aidl --lang=cpp-fuzzer -h /dev/null -o /dev/null --structured --stability vintf -Nhardware/interfaces/audio/aidl -Nsystem/hardware/interfaces/media/aidl -Nhardware/interfaces/common/aidl -Nhardware/interfaces/common/fmq/aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IBluetoothA2dp.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IBluetooth.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IBluetoothLe.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IConfig.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IModule.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IStreamCallback.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IStreamCommon.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IStreamIn.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IStreamOut.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/IStreamOutEventCallback.aidl hardware/interfaces/audio/aidl/android/hardware/audio/core/ITelephony.aidl - -#include "aidl/android/hardware/audio/common/AudioOffloadMetadata.h" -#include "aidl/android/hardware/audio/common/PlaybackTrackMetadata.h" -#include "aidl/android/hardware/audio/common/RecordTrackMetadata.h" -#include "aidl/android/hardware/audio/common/SinkMetadata.h" -#include "aidl/android/hardware/audio/common/SourceMetadata.h" -#include "aidl/android/hardware/audio/core/AudioPatch.h" -#include "aidl/android/hardware/audio/core/IStreamCallback.h" -#include "aidl/android/hardware/audio/core/IStreamOutEventCallback.h" -#include "aidl/android/hardware/audio/core/ModuleDebug.h" -#include "aidl/android/hardware/audio/core/VendorParameter.h" -#include "aidl/android/hardware/audio/effect/IEffect.h" -#include "aidl/android/media/audio/common/AudioChannelLayout.h" -#include "aidl/android/media/audio/common/AudioConfigBase.h" -#include "aidl/android/media/audio/common/AudioContentType.h" -#include "aidl/android/media/audio/common/AudioDevice.h" -#include "aidl/android/media/audio/common/AudioDeviceAddress.h" -#include "aidl/android/media/audio/common/AudioDeviceDescription.h" -#include "aidl/android/media/audio/common/AudioDeviceType.h" -#include "aidl/android/media/audio/common/AudioDualMonoMode.h" -#include "aidl/android/media/audio/common/AudioEncapsulationMode.h" -#include "aidl/android/media/audio/common/AudioEncapsulationType.h" -#include "aidl/android/media/audio/common/AudioFormatDescription.h" -#include "aidl/android/media/audio/common/AudioFormatType.h" -#include "aidl/android/media/audio/common/AudioGain.h" -#include "aidl/android/media/audio/common/AudioGainConfig.h" -#include "aidl/android/media/audio/common/AudioIoFlags.h" -#include "aidl/android/media/audio/common/AudioLatencyMode.h" -#include "aidl/android/media/audio/common/AudioMMapPolicyType.h" -#include "aidl/android/media/audio/common/AudioMode.h" -#include "aidl/android/media/audio/common/AudioOffloadInfo.h" -#include "aidl/android/media/audio/common/AudioPlaybackRate.h" -#include "aidl/android/media/audio/common/AudioPort.h" -#include "aidl/android/media/audio/common/AudioPortConfig.h" -#include "aidl/android/media/audio/common/AudioPortDeviceExt.h" -#include "aidl/android/media/audio/common/AudioPortExt.h" -#include "aidl/android/media/audio/common/AudioPortMixExt.h" -#include "aidl/android/media/audio/common/AudioPortMixExtUseCase.h" -#include "aidl/android/media/audio/common/AudioProfile.h" -#include "aidl/android/media/audio/common/AudioSource.h" -#include "aidl/android/media/audio/common/AudioStandard.h" -#include "aidl/android/media/audio/common/AudioStreamType.h" -#include "aidl/android/media/audio/common/AudioUsage.h" -#include "aidl/android/media/audio/common/ExtraAudioDescriptor.h" -#include "aidl/android/media/audio/common/PcmType.h" -#include "aidl/android/hardware/audio/core/IBluetooth.h" -#include "aidl/android/hardware/audio/core/IBluetoothA2dp.h" -#include "aidl/android/hardware/audio/core/IBluetoothLe.h" -#include "aidl/android/hardware/audio/core/IConfig.h" -#include "aidl/android/hardware/audio/core/IModule.h" -#include "aidl/android/hardware/audio/core/IStreamCallback.h" -#include "aidl/android/hardware/audio/core/IStreamCommon.h" -#include "aidl/android/hardware/audio/core/IStreamIn.h" -#include "aidl/android/hardware/audio/core/IStreamOut.h" -#include "aidl/android/hardware/audio/core/IStreamOutEventCallback.h" -#include "aidl/android/hardware/audio/core/ITelephony.h" - -using aidl::android::hardware::audio::common::AudioOffloadMetadata; -using aidl::android::hardware::audio::common::PlaybackTrackMetadata; -using aidl::android::hardware::audio::common::RecordTrackMetadata; -using aidl::android::hardware::audio::common::SinkMetadata; -using aidl::android::hardware::audio::common::SourceMetadata; -using aidl::android::hardware::audio::core::AudioPatch; -using aidl::android::hardware::audio::core::IStreamCallback; -using aidl::android::hardware::audio::core::IStreamOutEventCallback; -using aidl::android::hardware::audio::core::ModuleDebug; -using aidl::android::hardware::audio::core::VendorParameter; -using aidl::android::hardware::audio::effect::IEffect; -using aidl::android::media::audio::common::AudioChannelLayout; -using aidl::android::media::audio::common::AudioConfigBase; -using aidl::android::media::audio::common::AudioContentType; -using aidl::android::media::audio::common::AudioDevice; -using aidl::android::media::audio::common::AudioDeviceAddress; -using aidl::android::media::audio::common::AudioDeviceDescription; -using aidl::android::media::audio::common::AudioDeviceType; -using aidl::android::media::audio::common::AudioDualMonoMode; -using aidl::android::media::audio::common::AudioEncapsulationMode; -using aidl::android::media::audio::common::AudioEncapsulationType; -using aidl::android::media::audio::common::AudioFormatDescription; -using aidl::android::media::audio::common::AudioFormatType; -using aidl::android::media::audio::common::AudioGain; -using aidl::android::media::audio::common::AudioGainConfig; -using aidl::android::media::audio::common::AudioIoFlags; -using aidl::android::media::audio::common::AudioLatencyMode; -using aidl::android::media::audio::common::AudioMMapPolicyType; -using aidl::android::media::audio::common::AudioMode; -using aidl::android::media::audio::common::AudioOffloadInfo; -using aidl::android::media::audio::common::AudioPlaybackRate; -using aidl::android::media::audio::common::AudioPort; -using aidl::android::media::audio::common::AudioPortConfig; -using aidl::android::media::audio::common::AudioPortDeviceExt; -using aidl::android::media::audio::common::AudioPortExt; -using aidl::android::media::audio::common::AudioPortMixExt; -using aidl::android::media::audio::common::AudioPortMixExtUseCase; -using aidl::android::media::audio::common::AudioProfile; -using aidl::android::media::audio::common::AudioSource; -using aidl::android::media::audio::common::AudioStandard; -using aidl::android::media::audio::common::AudioStreamType; -using aidl::android::media::audio::common::AudioUsage; -using aidl::android::media::audio::common::ExtraAudioDescriptor; -using aidl::android::media::audio::common::PcmType; -using aidl::android::hardware::audio::core::IBluetooth; -using aidl::android::hardware::audio::core::IBluetoothA2dp; -using aidl::android::hardware::audio::core::IBluetoothLe; -using aidl::android::hardware::audio::core::IConfig; -using aidl::android::hardware::audio::core::IModule; -using aidl::android::hardware::audio::core::IStreamCallback; -using aidl::android::hardware::audio::core::IStreamCommon; -using aidl::android::hardware::audio::core::IStreamIn; -using aidl::android::hardware::audio::core::IStreamOut; -using aidl::android::hardware::audio::core::IStreamOutEventCallback; -using aidl::android::hardware::audio::core::ITelephony; - -struct DataProvider : public DataProviderBase { - DataProvider(const char *data, size_t size): DataProviderBase(data, size) {} - virtual ~DataProvider() {} - - virtual void genAudioOffloadMetadata(AudioOffloadMetadata &out) { - gen(out.sampleRate); - genAudioChannelLayout(out.channelMask); - gen(out.averageBitRatePerSecond); - gen(out.delayFrames); - gen(out.paddingFrames); - } - - virtual void genPlaybackTrackMetadata(PlaybackTrackMetadata &out) { - genAudioUsage(out.usage); - genAudioContentType(out.contentType); - gen(out.gain); - genAudioChannelLayout(out.channelMask); - gen(out.sourceDevice, [this](auto &v) { genAudioDevice(v); }); - gen(out.tags, [this](auto &v) { gen(v); }); - } - - virtual void genRecordTrackMetadata(RecordTrackMetadata &out) { - genAudioSource(out.source); - gen(out.gain); - gen(out.destinationDevice, [this](auto &v) { genAudioDevice(v); }); - genAudioChannelLayout(out.channelMask); - gen(out.tags, [this](auto &v) { gen(v); }); - } - - virtual void genSinkMetadata(SinkMetadata &out) { - gen(out.tracks, [this](auto &v) { genRecordTrackMetadata(v); }); - } - - virtual void genSourceMetadata(SourceMetadata &out) { - gen(out.tracks, [this](auto &v) { genPlaybackTrackMetadata(v); }); - } - - virtual void genAudioPatch(AudioPatch &out) { - gen(out.id); - gen(out.sourcePortConfigIds, [this](auto &v) { gen(v); }); - gen(out.sinkPortConfigIds, [this](auto &v) { gen(v); }); - gen(out.minimumStreamBufferSizeFrames); - gen(out.latenciesMs, [this](auto &v) { gen(v); }); - } - - virtual void genHfpConfig(IBluetooth::HfpConfig &out) { - gen(out.isEnabled, [this](auto &v) { genBoolean(v); }); - gen(out.sampleRate, [this](auto &v) { genInt(v); }); - gen(out.volume, [this](auto &v) { genFloat(v); }); - } - - virtual void genScoConfig(IBluetooth::ScoConfig &out) { - gen(out.isEnabled, [this](auto &v) { genBoolean(v); }); - gen(out.isNrecEnabled, [this](auto &v) { genBoolean(v); }); - genMode(out.mode); - gen(out.debugName, [this](auto &v) { gen(v); }); - } - - virtual void genMode(IBluetooth::ScoConfig::Mode &out) { - const IBluetooth::ScoConfig::Mode values[] = { - IBluetooth::ScoConfig::Mode::UNSPECIFIED, - IBluetooth::ScoConfig::Mode::SCO, - IBluetooth::ScoConfig::Mode::SCO_WB, - IBluetooth::ScoConfig::Mode::SCO_SWB, - }; - out = pick(values); - } - - virtual void genOpenInputStreamArguments(IModule::OpenInputStreamArguments &out) { - gen(out.portConfigId); - genSinkMetadata(out.sinkMetadata); - gen(out.bufferSizeFrames); - } - - virtual void genOpenOutputStreamArguments(IModule::OpenOutputStreamArguments &out) { - gen(out.portConfigId); - genSourceMetadata(out.sourceMetadata); - gen(out.offloadInfo, [this](auto &v) { genAudioOffloadInfo(v); }); - gen(out.bufferSizeFrames); - // NOTE: `out.callback' is an interface - // NOTE: `out.eventCallback' is an interface - } - - virtual void genScreenRotation(IModule::ScreenRotation &out) { - const IModule::ScreenRotation values[] = { - IModule::ScreenRotation::DEG_0, - IModule::ScreenRotation::DEG_90, - IModule::ScreenRotation::DEG_180, - IModule::ScreenRotation::DEG_270, - }; - out = pick(values); - } - - - virtual void genMicrophoneDirection(IStreamIn::MicrophoneDirection &out) { - const IStreamIn::MicrophoneDirection values[] = { - IStreamIn::MicrophoneDirection::UNSPECIFIED, - IStreamIn::MicrophoneDirection::FRONT, - IStreamIn::MicrophoneDirection::BACK, - IStreamIn::MicrophoneDirection::EXTERNAL, - }; - out = pick(values); - } - - - virtual void genTelecomConfig(ITelephony::TelecomConfig &out) { - gen(out.voiceVolume, [this](auto &v) { genFloat(v); }); - genTtyMode(out.ttyMode); - gen(out.isHacEnabled, [this](auto &v) { genBoolean(v); }); - } - - virtual void genTtyMode(ITelephony::TelecomConfig::TtyMode &out) { - const ITelephony::TelecomConfig::TtyMode values[] = { - ITelephony::TelecomConfig::TtyMode::UNSPECIFIED, - ITelephony::TelecomConfig::TtyMode::OFF, - ITelephony::TelecomConfig::TtyMode::FULL, - ITelephony::TelecomConfig::TtyMode::HCO, - ITelephony::TelecomConfig::TtyMode::VCO, - }; - out = pick(values); - } - - virtual void genModuleDebug(ModuleDebug &out) { - gen(out.simulateDeviceConnections); - gen(out.streamTransientStateDelayMs); - } - - virtual void genVendorParameter(VendorParameter &out) { - gen(out.id); - // NOTE: `out.ext' is a ParcelableHolder - } - - - virtual void genAudioChannelLayout(AudioChannelLayout &out) { - int tag = p.ConsumeIntegralInRange(0, 4); - switch (tag) { - case 0: { - int32_t val; - gen(val); - out.set(val); - break; - } - case 1: { - int32_t val; - gen(val); - out.set(val); - break; - } - case 2: { - int32_t val; - gen(val); - out.set(val); - break; - } - case 3: { - int32_t val; - gen(val); - out.set(val); - break; - } - case 4: { - int32_t val; - gen(val); - out.set(val); - break; - } - } - } - - virtual void genAudioConfigBase(AudioConfigBase &out) { - gen(out.sampleRate); - genAudioChannelLayout(out.channelMask); - genAudioFormatDescription(out.format); - } - - virtual void genAudioContentType(AudioContentType &out) { - const AudioContentType values[] = { - AudioContentType::UNKNOWN, - AudioContentType::SPEECH, - AudioContentType::MUSIC, - AudioContentType::MOVIE, - AudioContentType::SONIFICATION, - AudioContentType::ULTRASOUND, - }; - out = pick(values); - } - - virtual void genAudioDevice(AudioDevice &out) { - genAudioDeviceDescription(out.type); - genAudioDeviceAddress(out.address); - } - - virtual void genAudioDeviceAddress(AudioDeviceAddress &out) { - int tag = p.ConsumeIntegralInRange(0, 4); - switch (tag) { - case 0: { - ::std::string val; - gen(val); - out.set(val); - break; - } - case 1: { - ::std::vector val; - gen(val, [this](auto &v) { gen(v); }); - out.set(val); - break; - } - case 2: { - ::std::vector val; - gen(val, [this](auto &v) { gen(v); }); - out.set(val); - break; - } - case 3: { - ::std::vector val; - gen(val, [this](auto &v) { gen(v); }); - out.set(val); - break; - } - case 4: { - ::std::vector val; - gen(val, [this](auto &v) { gen(v); }); - out.set(val); - break; - } - } - } - - virtual void genAudioDeviceDescription(AudioDeviceDescription &out) { - genAudioDeviceType(out.type); - gen(out.connection); - } - - virtual void genAudioDeviceType(AudioDeviceType &out) { - const AudioDeviceType values[] = { - AudioDeviceType::NONE, - AudioDeviceType::IN_DEFAULT, - AudioDeviceType::IN_ACCESSORY, - AudioDeviceType::IN_AFE_PROXY, - AudioDeviceType::IN_DEVICE, - AudioDeviceType::IN_ECHO_REFERENCE, - AudioDeviceType::IN_FM_TUNER, - AudioDeviceType::IN_HEADSET, - AudioDeviceType::IN_LOOPBACK, - AudioDeviceType::IN_MICROPHONE, - AudioDeviceType::IN_MICROPHONE_BACK, - AudioDeviceType::IN_SUBMIX, - AudioDeviceType::IN_TELEPHONY_RX, - AudioDeviceType::IN_TV_TUNER, - AudioDeviceType::IN_DOCK, - AudioDeviceType::IN_BUS, - AudioDeviceType::OUT_DEFAULT, - AudioDeviceType::OUT_ACCESSORY, - AudioDeviceType::OUT_AFE_PROXY, - AudioDeviceType::OUT_CARKIT, - AudioDeviceType::OUT_DEVICE, - AudioDeviceType::OUT_ECHO_CANCELLER, - AudioDeviceType::OUT_FM, - AudioDeviceType::OUT_HEADPHONE, - AudioDeviceType::OUT_HEADSET, - AudioDeviceType::OUT_HEARING_AID, - AudioDeviceType::OUT_LINE_AUX, - AudioDeviceType::OUT_SPEAKER, - AudioDeviceType::OUT_SPEAKER_EARPIECE, - AudioDeviceType::OUT_SPEAKER_SAFE, - AudioDeviceType::OUT_SUBMIX, - AudioDeviceType::OUT_TELEPHONY_TX, - AudioDeviceType::OUT_DOCK, - AudioDeviceType::OUT_BROADCAST, - AudioDeviceType::OUT_BUS, - }; - out = pick(values); - } - - virtual void genAudioDualMonoMode(AudioDualMonoMode &out) { - const AudioDualMonoMode values[] = { - AudioDualMonoMode::OFF, - AudioDualMonoMode::LR, - AudioDualMonoMode::LL, - AudioDualMonoMode::RR, - }; - out = pick(values); - } - - virtual void genAudioEncapsulationMode(AudioEncapsulationMode &out) { - const AudioEncapsulationMode values[] = { - AudioEncapsulationMode::INVALID, - AudioEncapsulationMode::NONE, - AudioEncapsulationMode::ELEMENTARY_STREAM, - AudioEncapsulationMode::HANDLE, - }; - out = pick(values); - } - - virtual void genAudioEncapsulationType(AudioEncapsulationType &out) { - const AudioEncapsulationType values[] = { - AudioEncapsulationType::NONE, - AudioEncapsulationType::IEC61937, - AudioEncapsulationType::PCM, - }; - out = pick(values); - } - - virtual void genAudioFormatDescription(AudioFormatDescription &out) { - genAudioFormatType(out.type); - genPcmType(out.pcm); - gen(out.encoding); - } - - virtual void genAudioFormatType(AudioFormatType &out) { - const AudioFormatType values[] = { - AudioFormatType::DEFAULT, - AudioFormatType::NON_PCM, - AudioFormatType::PCM, - AudioFormatType::SYS_RESERVED_INVALID, - }; - out = pick(values); - } - - virtual void genAudioGain(AudioGain &out) { - gen(out.mode); - genAudioChannelLayout(out.channelMask); - gen(out.minValue); - gen(out.maxValue); - gen(out.defaultValue); - gen(out.stepValue); - gen(out.minRampMs); - gen(out.maxRampMs); - gen(out.useForVolume); - } - - virtual void genAudioGainConfig(AudioGainConfig &out) { - gen(out.index); - gen(out.mode); - genAudioChannelLayout(out.channelMask); - gen(out.values, [this](auto &v) { gen(v); }); - gen(out.rampDurationMs); - } - - virtual void genAudioIoFlags(AudioIoFlags &out) { - int tag = p.ConsumeIntegralInRange(0, 1); - switch (tag) { - case 0: { - int32_t val; - gen(val); - out.set(val); - break; - } - case 1: { - int32_t val; - gen(val); - out.set(val); - break; - } - } - } - - virtual void genAudioLatencyMode(AudioLatencyMode &out) { - const AudioLatencyMode values[] = { - AudioLatencyMode::FREE, - AudioLatencyMode::LOW, - AudioLatencyMode::DYNAMIC_SPATIAL_AUDIO_SOFTWARE, - AudioLatencyMode::DYNAMIC_SPATIAL_AUDIO_HARDWARE, - }; - out = pick(values); - } - - virtual void genAudioMMapPolicyType(AudioMMapPolicyType &out) { - const AudioMMapPolicyType values[] = { - AudioMMapPolicyType::DEFAULT, - AudioMMapPolicyType::EXCLUSIVE, - }; - out = pick(values); - } - - virtual void genAudioMode(AudioMode &out) { - const AudioMode values[] = { - AudioMode::SYS_RESERVED_INVALID, - AudioMode::SYS_RESERVED_CURRENT, - AudioMode::NORMAL, - AudioMode::RINGTONE, - AudioMode::IN_CALL, - AudioMode::IN_COMMUNICATION, - AudioMode::CALL_SCREEN, - AudioMode::SYS_RESERVED_CALL_REDIRECT, - AudioMode::SYS_RESERVED_COMMUNICATION_REDIRECT, - }; - out = pick(values); - } - - virtual void genAudioOffloadInfo(AudioOffloadInfo &out) { - genAudioConfigBase(out.base); - genAudioStreamType(out.streamType); - gen(out.bitRatePerSecond); - gen(out.durationUs); - gen(out.hasVideo); - gen(out.isStreaming); - gen(out.bitWidth); - gen(out.offloadBufferSize); - genAudioUsage(out.usage); - genAudioEncapsulationMode(out.encapsulationMode); - gen(out.contentId); - gen(out.syncId); - } - - virtual void genAudioPlaybackRate(AudioPlaybackRate &out) { - gen(out.speed); - gen(out.pitch); - genTimestretchMode(out.timestretchMode); - genTimestretchFallbackMode(out.fallbackMode); - } - - virtual void genTimestretchFallbackMode(AudioPlaybackRate::TimestretchFallbackMode &out) { - const AudioPlaybackRate::TimestretchFallbackMode values[] = { - AudioPlaybackRate::TimestretchFallbackMode::SYS_RESERVED_CUT_REPEAT, - AudioPlaybackRate::TimestretchFallbackMode::SYS_RESERVED_DEFAULT, - AudioPlaybackRate::TimestretchFallbackMode::MUTE, - AudioPlaybackRate::TimestretchFallbackMode::FAIL, - }; - out = pick(values); - } - - virtual void genTimestretchMode(AudioPlaybackRate::TimestretchMode &out) { - const AudioPlaybackRate::TimestretchMode values[] = { - AudioPlaybackRate::TimestretchMode::DEFAULT, - AudioPlaybackRate::TimestretchMode::VOICE, - }; - out = pick(values); - } - - virtual void genAudioPort(AudioPort &out) { - gen(out.id); - gen(out.name); - gen(out.profiles, [this](auto &v) { genAudioProfile(v); }); - genAudioIoFlags(out.flags); - gen(out.extraAudioDescriptors, [this](auto &v) { genExtraAudioDescriptor(v); }); - gen(out.gains, [this](auto &v) { genAudioGain(v); }); - genAudioPortExt(out.ext); - } - - virtual void genAudioPortConfig(AudioPortConfig &out) { - gen(out.id); - gen(out.portId); - gen(out.sampleRate, [this](auto &v) { genInt(v); }); - gen(out.channelMask, [this](auto &v) { genAudioChannelLayout(v); }); - gen(out.format, [this](auto &v) { genAudioFormatDescription(v); }); - gen(out.gain, [this](auto &v) { genAudioGainConfig(v); }); - gen(out.flags, [this](auto &v) { genAudioIoFlags(v); }); - genAudioPortExt(out.ext); - } - - virtual void genAudioPortDeviceExt(AudioPortDeviceExt &out) { - genAudioDevice(out.device); - gen(out.flags); - gen(out.encodedFormats, [this](auto &v) { genAudioFormatDescription(v); }); - gen(out.encapsulationModes); - gen(out.encapsulationMetadataTypes); - } - - virtual void genAudioPortExt(AudioPortExt &out) { - int tag = p.ConsumeIntegralInRange(0, 3); - switch (tag) { - case 0: { - bool val; - gen(val); - out.set(val); - break; - } - case 1: { - aidl::android::media::audio::common::AudioPortDeviceExt val; - genAudioPortDeviceExt(val); - out.set(val); - break; - } - case 2: { - aidl::android::media::audio::common::AudioPortMixExt val; - genAudioPortMixExt(val); - out.set(val); - break; - } - case 3: { - int32_t val; - gen(val); - out.set(val); - break; - } - } - } - - virtual void genAudioPortMixExt(AudioPortMixExt &out) { - gen(out.handle); - genAudioPortMixExtUseCase(out.usecase); - gen(out.maxOpenStreamCount); - gen(out.maxActiveStreamCount); - gen(out.recommendedMuteDurationMs); - } - - virtual void genAudioPortMixExtUseCase(AudioPortMixExtUseCase &out) { - int tag = p.ConsumeIntegralInRange(0, 2); - switch (tag) { - case 0: { - bool val; - gen(val); - out.set(val); - break; - } - case 1: { - aidl::android::media::audio::common::AudioStreamType val; - genAudioStreamType(val); - out.set(val); - break; - } - case 2: { - aidl::android::media::audio::common::AudioSource val; - genAudioSource(val); - out.set(val); - break; - } - } - } - - virtual void genAudioProfile(AudioProfile &out) { - gen(out.name); - genAudioFormatDescription(out.format); - gen(out.channelMasks, [this](auto &v) { genAudioChannelLayout(v); }); - gen(out.sampleRates, [this](auto &v) { gen(v); }); - genAudioEncapsulationType(out.encapsulationType); - } - - virtual void genAudioSource(AudioSource &out) { - const AudioSource values[] = { - AudioSource::SYS_RESERVED_INVALID, - AudioSource::DEFAULT, - AudioSource::MIC, - AudioSource::VOICE_UPLINK, - AudioSource::VOICE_DOWNLINK, - AudioSource::VOICE_CALL, - AudioSource::CAMCORDER, - AudioSource::VOICE_RECOGNITION, - AudioSource::VOICE_COMMUNICATION, - AudioSource::REMOTE_SUBMIX, - AudioSource::UNPROCESSED, - AudioSource::VOICE_PERFORMANCE, - AudioSource::ECHO_REFERENCE, - AudioSource::FM_TUNER, - AudioSource::HOTWORD, - AudioSource::ULTRASOUND, - }; - out = pick(values); - } - - virtual void genAudioStandard(AudioStandard &out) { - const AudioStandard values[] = { - AudioStandard::NONE, - AudioStandard::EDID, - AudioStandard::SADB, - AudioStandard::VSADB, - }; - out = pick(values); - } - - virtual void genAudioStreamType(AudioStreamType &out) { - const AudioStreamType values[] = { - AudioStreamType::INVALID, - AudioStreamType::SYS_RESERVED_DEFAULT, - AudioStreamType::VOICE_CALL, - AudioStreamType::SYSTEM, - AudioStreamType::RING, - AudioStreamType::MUSIC, - AudioStreamType::ALARM, - AudioStreamType::NOTIFICATION, - AudioStreamType::BLUETOOTH_SCO, - AudioStreamType::ENFORCED_AUDIBLE, - AudioStreamType::DTMF, - AudioStreamType::TTS, - AudioStreamType::ACCESSIBILITY, - AudioStreamType::ASSISTANT, - AudioStreamType::SYS_RESERVED_REROUTING, - AudioStreamType::SYS_RESERVED_PATCH, - AudioStreamType::CALL_ASSISTANT, - }; - out = pick(values); - } - - virtual void genAudioUsage(AudioUsage &out) { - const AudioUsage values[] = { - AudioUsage::INVALID, - AudioUsage::UNKNOWN, - AudioUsage::MEDIA, - AudioUsage::VOICE_COMMUNICATION, - AudioUsage::VOICE_COMMUNICATION_SIGNALLING, - AudioUsage::ALARM, - AudioUsage::NOTIFICATION, - AudioUsage::NOTIFICATION_TELEPHONY_RINGTONE, - AudioUsage::SYS_RESERVED_NOTIFICATION_COMMUNICATION_REQUEST, - AudioUsage::SYS_RESERVED_NOTIFICATION_COMMUNICATION_INSTANT, - AudioUsage::SYS_RESERVED_NOTIFICATION_COMMUNICATION_DELAYED, - AudioUsage::NOTIFICATION_EVENT, - AudioUsage::ASSISTANCE_ACCESSIBILITY, - AudioUsage::ASSISTANCE_NAVIGATION_GUIDANCE, - AudioUsage::ASSISTANCE_SONIFICATION, - AudioUsage::GAME, - AudioUsage::VIRTUAL_SOURCE, - AudioUsage::ASSISTANT, - AudioUsage::CALL_ASSISTANT, - AudioUsage::EMERGENCY, - AudioUsage::SAFETY, - AudioUsage::VEHICLE_STATUS, - AudioUsage::ANNOUNCEMENT, - }; - out = pick(values); - } - - virtual void genExtraAudioDescriptor(ExtraAudioDescriptor &out) { - genAudioStandard(out.standard); - gen(out.audioDescriptor, [this](auto &v) { gen(v); }); - genAudioEncapsulationType(out.encapsulationType); - } - - virtual void genPcmType(PcmType &out) { - const PcmType values[] = { - PcmType::DEFAULT, - PcmType::UINT_8_BIT, - PcmType::INT_16_BIT, - PcmType::INT_32_BIT, - PcmType::FIXED_Q_8_24, - PcmType::FLOAT_32_BIT, - PcmType::INT_24_BIT, - }; - out = pick(values); - } - -}; -template -struct IBluetoothFuzzer: public FuzzerBase { - IBluetoothFuzzer() {} - IBluetoothFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IBluetoothFuzzer() {} - - virtual std::optional<::aidl::android::hardware::audio::core::IBluetooth::ScoConfig> fuzz_setScoConfig() { - ::aidl::android::hardware::audio::core::IBluetooth::ScoConfig in_config; - this->provider->genScoConfig(in_config); - ::aidl::android::hardware::audio::core::IBluetooth::ScoConfig _aidl_return; - - if (this->target->setScoConfig(in_config, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional<::aidl::android::hardware::audio::core::IBluetooth::HfpConfig> fuzz_setHfpConfig() { - ::aidl::android::hardware::audio::core::IBluetooth::HfpConfig in_config; - this->provider->genHfpConfig(in_config); - ::aidl::android::hardware::audio::core::IBluetooth::HfpConfig _aidl_return; - - if (this->target->setHfpConfig(in_config, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_setScoConfig(); - break; - } - case 1: { - fuzz_setHfpConfig(); - break; - } - } - } -}; - -template -struct IBluetoothA2dpFuzzer: public FuzzerBase { - IBluetoothA2dpFuzzer() {} - IBluetoothA2dpFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IBluetoothA2dpFuzzer() {} - - virtual std::optional fuzz_isEnabled() { - bool _aidl_return; - - if (this->target->isEnabled(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setEnabled() { - bool in_enabled; - this->provider->gen(in_enabled); - - this->target->setEnabled(in_enabled); - } - - virtual std::optional fuzz_supportsOffloadReconfiguration() { - bool _aidl_return; - - if (this->target->supportsOffloadReconfiguration(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_reconfigureOffload() { - std::vector<::aidl::android::hardware::audio::core::VendorParameter> in_parameters; - this->provider->gen(in_parameters, [this](auto &v) { this->provider->genVendorParameter(v); }); - - this->target->reconfigureOffload(in_parameters); - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_isEnabled(); - break; - } - case 1: { - fuzz_setEnabled(); - break; - } - case 2: { - fuzz_supportsOffloadReconfiguration(); - break; - } - case 3: { - fuzz_reconfigureOffload(); - break; - } - } - } -}; - -template -struct IBluetoothLeFuzzer: public FuzzerBase { - IBluetoothLeFuzzer() {} - IBluetoothLeFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IBluetoothLeFuzzer() {} - - virtual std::optional fuzz_isEnabled() { - bool _aidl_return; - - if (this->target->isEnabled(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setEnabled() { - bool in_enabled; - this->provider->gen(in_enabled); - - this->target->setEnabled(in_enabled); - } - - virtual std::optional fuzz_supportsOffloadReconfiguration() { - bool _aidl_return; - - if (this->target->supportsOffloadReconfiguration(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_reconfigureOffload() { - std::vector<::aidl::android::hardware::audio::core::VendorParameter> in_parameters; - this->provider->gen(in_parameters, [this](auto &v) { this->provider->genVendorParameter(v); }); - - this->target->reconfigureOffload(in_parameters); - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_isEnabled(); - break; - } - case 1: { - fuzz_setEnabled(); - break; - } - case 2: { - fuzz_supportsOffloadReconfiguration(); - break; - } - case 3: { - fuzz_reconfigureOffload(); - break; - } - } - } -}; - -template -struct IConfigFuzzer: public FuzzerBase { - IConfigFuzzer() {} - IConfigFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IConfigFuzzer() {} - - virtual std::optional<::aidl::android::hardware::audio::core::SurroundSoundConfig> fuzz_getSurroundSoundConfig() { - ::aidl::android::hardware::audio::core::SurroundSoundConfig _aidl_return; - - if (this->target->getSurroundSoundConfig(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional<::aidl::android::media::audio::common::AudioHalEngineConfig> fuzz_getEngineConfig() { - ::aidl::android::media::audio::common::AudioHalEngineConfig _aidl_return; - - if (this->target->getEngineConfig(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_getSurroundSoundConfig(); - break; - } - case 1: { - fuzz_getEngineConfig(); - break; - } - } - } -}; - -template -struct IModuleFuzzer: public FuzzerBase { - IModuleFuzzer() {} - IModuleFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IModuleFuzzer() {} - - virtual void fuzz_setModuleDebug() { - ::aidl::android::hardware::audio::core::ModuleDebug in_debug; - this->provider->genModuleDebug(in_debug); - - this->target->setModuleDebug(in_debug); - } - - virtual std::optional> fuzz_getTelephony() { - std::shared_ptr<::aidl::android::hardware::audio::core::ITelephony> _aidl_return; - - if (this->target->getTelephony(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getBluetooth() { - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetooth> _aidl_return; - - if (this->target->getBluetooth(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getBluetoothA2dp() { - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothA2dp> _aidl_return; - - if (this->target->getBluetoothA2dp(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getBluetoothLe() { - std::shared_ptr<::aidl::android::hardware::audio::core::IBluetoothLe> _aidl_return; - - if (this->target->getBluetoothLe(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional<::aidl::android::media::audio::common::AudioPort> fuzz_connectExternalDevice() { - ::aidl::android::media::audio::common::AudioPort in_templateIdAndAdditionalData; - this->provider->genAudioPort(in_templateIdAndAdditionalData); - ::aidl::android::media::audio::common::AudioPort _aidl_return; - - if (this->target->connectExternalDevice(in_templateIdAndAdditionalData, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_disconnectExternalDevice() { - int32_t in_portId; - this->provider->gen(in_portId); - - this->target->disconnectExternalDevice(in_portId); - } - - virtual std::optional> fuzz_getAudioPatches() { - std::vector<::aidl::android::hardware::audio::core::AudioPatch> _aidl_return; - - if (this->target->getAudioPatches(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional<::aidl::android::media::audio::common::AudioPort> fuzz_getAudioPort() { - int32_t in_portId; - this->provider->gen(in_portId); - ::aidl::android::media::audio::common::AudioPort _aidl_return; - - if (this->target->getAudioPort(in_portId, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getAudioPortConfigs() { - std::vector<::aidl::android::media::audio::common::AudioPortConfig> _aidl_return; - - if (this->target->getAudioPortConfigs(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getAudioPorts() { - std::vector<::aidl::android::media::audio::common::AudioPort> _aidl_return; - - if (this->target->getAudioPorts(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getAudioRoutes() { - std::vector<::aidl::android::hardware::audio::core::AudioRoute> _aidl_return; - - if (this->target->getAudioRoutes(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getAudioRoutesForAudioPort() { - int32_t in_portId; - this->provider->gen(in_portId); - std::vector<::aidl::android::hardware::audio::core::AudioRoute> _aidl_return; - - if (this->target->getAudioRoutesForAudioPort(in_portId, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional<::aidl::android::hardware::audio::core::IModule::OpenInputStreamReturn> fuzz_openInputStream() { - ::aidl::android::hardware::audio::core::IModule::OpenInputStreamArguments in_args; - this->provider->genOpenInputStreamArguments(in_args); - ::aidl::android::hardware::audio::core::IModule::OpenInputStreamReturn _aidl_return; - - if (this->target->openInputStream(in_args, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional<::aidl::android::hardware::audio::core::IModule::OpenOutputStreamReturn> fuzz_openOutputStream() { - ::aidl::android::hardware::audio::core::IModule::OpenOutputStreamArguments in_args; - this->provider->genOpenOutputStreamArguments(in_args); - ::aidl::android::hardware::audio::core::IModule::OpenOutputStreamReturn _aidl_return; - - if (this->target->openOutputStream(in_args, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional<::aidl::android::hardware::audio::core::IModule::SupportedPlaybackRateFactors> fuzz_getSupportedPlaybackRateFactors() { - ::aidl::android::hardware::audio::core::IModule::SupportedPlaybackRateFactors _aidl_return; - - if (this->target->getSupportedPlaybackRateFactors(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional<::aidl::android::hardware::audio::core::AudioPatch> fuzz_setAudioPatch() { - ::aidl::android::hardware::audio::core::AudioPatch in_requested; - this->provider->genAudioPatch(in_requested); - ::aidl::android::hardware::audio::core::AudioPatch _aidl_return; - - if (this->target->setAudioPatch(in_requested, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional fuzz_setAudioPortConfig() { - ::aidl::android::media::audio::common::AudioPortConfig in_requested; - this->provider->genAudioPortConfig(in_requested); - ::aidl::android::media::audio::common::AudioPortConfig out_suggested; - bool _aidl_return; - - if (this->target->setAudioPortConfig(in_requested, &out_suggested, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_resetAudioPatch() { - int32_t in_patchId; - this->provider->gen(in_patchId); - - this->target->resetAudioPatch(in_patchId); - } - - virtual void fuzz_resetAudioPortConfig() { - int32_t in_portConfigId; - this->provider->gen(in_portConfigId); - - this->target->resetAudioPortConfig(in_portConfigId); - } - - virtual std::optional fuzz_getMasterMute() { - bool _aidl_return; - - if (this->target->getMasterMute(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setMasterMute() { - bool in_mute; - this->provider->gen(in_mute); - - this->target->setMasterMute(in_mute); - } - - virtual std::optional fuzz_getMasterVolume() { - float _aidl_return; - - if (this->target->getMasterVolume(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setMasterVolume() { - float in_volume; - this->provider->gen(in_volume); - - this->target->setMasterVolume(in_volume); - } - - virtual std::optional fuzz_getMicMute() { - bool _aidl_return; - - if (this->target->getMicMute(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setMicMute() { - bool in_mute; - this->provider->gen(in_mute); - - this->target->setMicMute(in_mute); - } - - virtual std::optional> fuzz_getMicrophones() { - std::vector<::aidl::android::media::audio::common::MicrophoneInfo> _aidl_return; - - if (this->target->getMicrophones(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_updateAudioMode() { - ::aidl::android::media::audio::common::AudioMode in_mode; - this->provider->genAudioMode(in_mode); - - this->target->updateAudioMode(in_mode); - } - - virtual void fuzz_updateScreenRotation() { - ::aidl::android::hardware::audio::core::IModule::ScreenRotation in_rotation; - this->provider->genScreenRotation(in_rotation); - - this->target->updateScreenRotation(in_rotation); - } - - virtual void fuzz_updateScreenState() { - bool in_isTurnedOn; - this->provider->gen(in_isTurnedOn); - - this->target->updateScreenState(in_isTurnedOn); - } - - virtual std::optional> fuzz_getSoundDose() { - std::shared_ptr<::aidl::android::hardware::audio::core::sounddose::ISoundDose> _aidl_return; - - if (this->target->getSoundDose(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional fuzz_generateHwAvSyncId() { - int32_t _aidl_return; - - if (this->target->generateHwAvSyncId(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getVendorParameters() { - std::vector in_ids; - this->provider->gen(in_ids, [this](auto &v) { this->provider->gen(v); }); - std::vector<::aidl::android::hardware::audio::core::VendorParameter> _aidl_return; - - if (this->target->getVendorParameters(in_ids, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setVendorParameters() { - std::vector<::aidl::android::hardware::audio::core::VendorParameter> in_parameters; - this->provider->gen(in_parameters, [this](auto &v) { this->provider->genVendorParameter(v); }); - bool in_async; - this->provider->gen(in_async); - - this->target->setVendorParameters(in_parameters, in_async); - } - - virtual void fuzz_addDeviceEffect() { - int32_t in_portConfigId; - this->provider->gen(in_portConfigId); - std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> in_effect; - // NOTE: `in_effect' is an interface - - this->target->addDeviceEffect(in_portConfigId, in_effect); - } - - virtual void fuzz_removeDeviceEffect() { - int32_t in_portConfigId; - this->provider->gen(in_portConfigId); - std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> in_effect; - // NOTE: `in_effect' is an interface - - this->target->removeDeviceEffect(in_portConfigId, in_effect); - } - - virtual std::optional> fuzz_getMmapPolicyInfos() { - ::aidl::android::media::audio::common::AudioMMapPolicyType in_mmapPolicyType; - this->provider->genAudioMMapPolicyType(in_mmapPolicyType); - std::vector<::aidl::android::media::audio::common::AudioMMapPolicyInfo> _aidl_return; - - if (this->target->getMmapPolicyInfos(in_mmapPolicyType, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional fuzz_supportsVariableLatency() { - bool _aidl_return; - - if (this->target->supportsVariableLatency(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional fuzz_getAAudioMixerBurstCount() { - int32_t _aidl_return; - - if (this->target->getAAudioMixerBurstCount(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional fuzz_getAAudioHardwareBurstMinUsec() { - int32_t _aidl_return; - - if (this->target->getAAudioHardwareBurstMinUsec(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_prepareToDisconnectExternalDevice() { - int32_t in_portId; - this->provider->gen(in_portId); - - this->target->prepareToDisconnectExternalDevice(in_portId); - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_setModuleDebug(); - break; - } - case 1: { - fuzz_getTelephony(); - break; - } - case 2: { - fuzz_getBluetooth(); - break; - } - case 3: { - fuzz_getBluetoothA2dp(); - break; - } - case 4: { - fuzz_getBluetoothLe(); - break; - } - case 5: { - fuzz_connectExternalDevice(); - break; - } - case 6: { - fuzz_disconnectExternalDevice(); - break; - } - case 7: { - fuzz_getAudioPatches(); - break; - } - case 8: { - fuzz_getAudioPort(); - break; - } - case 9: { - fuzz_getAudioPortConfigs(); - break; - } - case 10: { - fuzz_getAudioPorts(); - break; - } - case 11: { - fuzz_getAudioRoutes(); - break; - } - case 12: { - fuzz_getAudioRoutesForAudioPort(); - break; - } - case 13: { - fuzz_openInputStream(); - break; - } - case 14: { - fuzz_openOutputStream(); - break; - } - case 15: { - fuzz_getSupportedPlaybackRateFactors(); - break; - } - case 16: { - fuzz_setAudioPatch(); - break; - } - case 17: { - fuzz_setAudioPortConfig(); - break; - } - case 18: { - fuzz_resetAudioPatch(); - break; - } - case 19: { - fuzz_resetAudioPortConfig(); - break; - } - case 20: { - fuzz_getMasterMute(); - break; - } - case 21: { - fuzz_setMasterMute(); - break; - } - case 22: { - fuzz_getMasterVolume(); - break; - } - case 23: { - fuzz_setMasterVolume(); - break; - } - case 24: { - fuzz_getMicMute(); - break; - } - case 25: { - fuzz_setMicMute(); - break; - } - case 26: { - fuzz_getMicrophones(); - break; - } - case 27: { - fuzz_updateAudioMode(); - break; - } - case 28: { - fuzz_updateScreenRotation(); - break; - } - case 29: { - fuzz_updateScreenState(); - break; - } - case 30: { - fuzz_getSoundDose(); - break; - } - case 31: { - fuzz_generateHwAvSyncId(); - break; - } - case 32: { - fuzz_getVendorParameters(); - break; - } - case 33: { - fuzz_setVendorParameters(); - break; - } - case 34: { - fuzz_addDeviceEffect(); - break; - } - case 35: { - fuzz_removeDeviceEffect(); - break; - } - case 36: { - fuzz_getMmapPolicyInfos(); - break; - } - case 37: { - fuzz_supportsVariableLatency(); - break; - } - case 38: { - fuzz_getAAudioMixerBurstCount(); - break; - } - case 39: { - fuzz_getAAudioHardwareBurstMinUsec(); - break; - } - case 40: { - fuzz_prepareToDisconnectExternalDevice(); - break; - } - } - } -}; - -template -struct IStreamCallbackFuzzer: public FuzzerBase { - IStreamCallbackFuzzer() {} - IStreamCallbackFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IStreamCallbackFuzzer() {} - - virtual void fuzz_onTransferReady() { - - this->target->onTransferReady(); - } - - virtual void fuzz_onError() { - - this->target->onError(); - } - - virtual void fuzz_onDrainReady() { - - this->target->onDrainReady(); - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_onTransferReady(); - break; - } - case 1: { - fuzz_onError(); - break; - } - case 2: { - fuzz_onDrainReady(); - break; - } - } - } -}; - -template -struct IStreamCommonFuzzer: public FuzzerBase { - IStreamCommonFuzzer() {} - IStreamCommonFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IStreamCommonFuzzer() {} - - virtual void fuzz_close() { - - this->target->close(); - } - - virtual void fuzz_prepareToClose() { - - this->target->prepareToClose(); - } - - virtual void fuzz_updateHwAvSyncId() { - int32_t in_hwAvSyncId; - this->provider->gen(in_hwAvSyncId); - - this->target->updateHwAvSyncId(in_hwAvSyncId); - } - - virtual std::optional> fuzz_getVendorParameters() { - std::vector in_ids; - this->provider->gen(in_ids, [this](auto &v) { this->provider->gen(v); }); - std::vector<::aidl::android::hardware::audio::core::VendorParameter> _aidl_return; - - if (this->target->getVendorParameters(in_ids, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setVendorParameters() { - std::vector<::aidl::android::hardware::audio::core::VendorParameter> in_parameters; - this->provider->gen(in_parameters, [this](auto &v) { this->provider->genVendorParameter(v); }); - bool in_async; - this->provider->gen(in_async); - - this->target->setVendorParameters(in_parameters, in_async); - } - - virtual void fuzz_addEffect() { - std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> in_effect; - // NOTE: `in_effect' is an interface - - this->target->addEffect(in_effect); - } - - virtual void fuzz_removeEffect() { - std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> in_effect; - // NOTE: `in_effect' is an interface - - this->target->removeEffect(in_effect); - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_close(); - break; - } - case 1: { - fuzz_prepareToClose(); - break; - } - case 2: { - fuzz_updateHwAvSyncId(); - break; - } - case 3: { - fuzz_getVendorParameters(); - break; - } - case 4: { - fuzz_setVendorParameters(); - break; - } - case 5: { - fuzz_addEffect(); - break; - } - case 6: { - fuzz_removeEffect(); - break; - } - } - } -}; - -template -struct IStreamInFuzzer: public FuzzerBase { - IStreamInFuzzer() {} - IStreamInFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IStreamInFuzzer() {} - - virtual std::optional> fuzz_getStreamCommon() { - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCommon> _aidl_return; - - if (this->target->getStreamCommon(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getActiveMicrophones() { - std::vector<::aidl::android::media::audio::common::MicrophoneDynamicInfo> _aidl_return; - - if (this->target->getActiveMicrophones(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional<::aidl::android::hardware::audio::core::IStreamIn::MicrophoneDirection> fuzz_getMicrophoneDirection() { - ::aidl::android::hardware::audio::core::IStreamIn::MicrophoneDirection _aidl_return; - - if (this->target->getMicrophoneDirection(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setMicrophoneDirection() { - ::aidl::android::hardware::audio::core::IStreamIn::MicrophoneDirection in_direction; - this->provider->genMicrophoneDirection(in_direction); - - this->target->setMicrophoneDirection(in_direction); - } - - virtual std::optional fuzz_getMicrophoneFieldDimension() { - float _aidl_return; - - if (this->target->getMicrophoneFieldDimension(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setMicrophoneFieldDimension() { - float in_zoom; - this->provider->gen(in_zoom); - - this->target->setMicrophoneFieldDimension(in_zoom); - } - - virtual void fuzz_updateMetadata() { - ::aidl::android::hardware::audio::common::SinkMetadata in_sinkMetadata; - this->provider->genSinkMetadata(in_sinkMetadata); - - this->target->updateMetadata(in_sinkMetadata); - } - - virtual std::optional> fuzz_getHwGain() { - std::vector _aidl_return; - - if (this->target->getHwGain(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setHwGain() { - std::vector in_channelGains; - this->provider->gen(in_channelGains, [this](auto &v) { this->provider->gen(v); }); - - this->target->setHwGain(in_channelGains); - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_getStreamCommon(); - break; - } - case 1: { - fuzz_getActiveMicrophones(); - break; - } - case 2: { - fuzz_getMicrophoneDirection(); - break; - } - case 3: { - fuzz_setMicrophoneDirection(); - break; - } - case 4: { - fuzz_getMicrophoneFieldDimension(); - break; - } - case 5: { - fuzz_setMicrophoneFieldDimension(); - break; - } - case 6: { - fuzz_updateMetadata(); - break; - } - case 7: { - fuzz_getHwGain(); - break; - } - case 8: { - fuzz_setHwGain(); - break; - } - } - } -}; - -template -struct IStreamOutFuzzer: public FuzzerBase { - IStreamOutFuzzer() {} - IStreamOutFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IStreamOutFuzzer() {} - - virtual std::optional> fuzz_getStreamCommon() { - std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCommon> _aidl_return; - - if (this->target->getStreamCommon(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_updateMetadata() { - ::aidl::android::hardware::audio::common::SourceMetadata in_sourceMetadata; - this->provider->genSourceMetadata(in_sourceMetadata); - - this->target->updateMetadata(in_sourceMetadata); - } - - virtual void fuzz_updateOffloadMetadata() { - ::aidl::android::hardware::audio::common::AudioOffloadMetadata in_offloadMetadata; - this->provider->genAudioOffloadMetadata(in_offloadMetadata); - - this->target->updateOffloadMetadata(in_offloadMetadata); - } - - virtual std::optional> fuzz_getHwVolume() { - std::vector _aidl_return; - - if (this->target->getHwVolume(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setHwVolume() { - std::vector in_channelVolumes; - this->provider->gen(in_channelVolumes, [this](auto &v) { this->provider->gen(v); }); - - this->target->setHwVolume(in_channelVolumes); - } - - virtual std::optional fuzz_getAudioDescriptionMixLevel() { - float _aidl_return; - - if (this->target->getAudioDescriptionMixLevel(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setAudioDescriptionMixLevel() { - float in_leveldB; - this->provider->gen(in_leveldB); - - this->target->setAudioDescriptionMixLevel(in_leveldB); - } - - virtual std::optional<::aidl::android::media::audio::common::AudioDualMonoMode> fuzz_getDualMonoMode() { - ::aidl::android::media::audio::common::AudioDualMonoMode _aidl_return; - - if (this->target->getDualMonoMode(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setDualMonoMode() { - ::aidl::android::media::audio::common::AudioDualMonoMode in_mode; - this->provider->genAudioDualMonoMode(in_mode); - - this->target->setDualMonoMode(in_mode); - } - - virtual std::optional> fuzz_getRecommendedLatencyModes() { - std::vector<::aidl::android::media::audio::common::AudioLatencyMode> _aidl_return; - - if (this->target->getRecommendedLatencyModes(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setLatencyMode() { - ::aidl::android::media::audio::common::AudioLatencyMode in_mode; - this->provider->genAudioLatencyMode(in_mode); - - this->target->setLatencyMode(in_mode); - } - - virtual std::optional<::aidl::android::media::audio::common::AudioPlaybackRate> fuzz_getPlaybackRateParameters() { - ::aidl::android::media::audio::common::AudioPlaybackRate _aidl_return; - - if (this->target->getPlaybackRateParameters(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_setPlaybackRateParameters() { - ::aidl::android::media::audio::common::AudioPlaybackRate in_playbackRate; - this->provider->genAudioPlaybackRate(in_playbackRate); - - this->target->setPlaybackRateParameters(in_playbackRate); - } - - virtual void fuzz_selectPresentation() { - int32_t in_presentationId; - this->provider->gen(in_presentationId); - int32_t in_programId; - this->provider->gen(in_programId); - - this->target->selectPresentation(in_presentationId, in_programId); - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_getStreamCommon(); - break; - } - case 1: { - fuzz_updateMetadata(); - break; - } - case 2: { - fuzz_updateOffloadMetadata(); - break; - } - case 3: { - fuzz_getHwVolume(); - break; - } - case 4: { - fuzz_setHwVolume(); - break; - } - case 5: { - fuzz_getAudioDescriptionMixLevel(); - break; - } - case 6: { - fuzz_setAudioDescriptionMixLevel(); - break; - } - case 7: { - fuzz_getDualMonoMode(); - break; - } - case 8: { - fuzz_setDualMonoMode(); - break; - } - case 9: { - fuzz_getRecommendedLatencyModes(); - break; - } - case 10: { - fuzz_setLatencyMode(); - break; - } - case 11: { - fuzz_getPlaybackRateParameters(); - break; - } - case 12: { - fuzz_setPlaybackRateParameters(); - break; - } - case 13: { - fuzz_selectPresentation(); - break; - } - } - } -}; - -template -struct IStreamOutEventCallbackFuzzer: public FuzzerBase { - IStreamOutEventCallbackFuzzer() {} - IStreamOutEventCallbackFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~IStreamOutEventCallbackFuzzer() {} - - virtual void fuzz_onCodecFormatChanged() { - std::vector in_audioMetadata; - this->provider->gen(in_audioMetadata, [this](auto &v) { this->provider->gen(v); }); - - this->target->onCodecFormatChanged(in_audioMetadata); - } - - virtual void fuzz_onRecommendedLatencyModeChanged() { - std::vector<::aidl::android::media::audio::common::AudioLatencyMode> in_modes; - this->provider->gen(in_modes, [this](auto &v) { this->provider->genAudioLatencyMode(v); }); - - this->target->onRecommendedLatencyModeChanged(in_modes); - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_onCodecFormatChanged(); - break; - } - case 1: { - fuzz_onRecommendedLatencyModeChanged(); - break; - } - } - } -}; - -template -struct ITelephonyFuzzer: public FuzzerBase { - ITelephonyFuzzer() {} - ITelephonyFuzzer(P *provider, T *target): FuzzerBase(provider, target) {} - virtual ~ITelephonyFuzzer() {} - - virtual std::optional> fuzz_getSupportedAudioModes() { - std::vector<::aidl::android::media::audio::common::AudioMode> _aidl_return; - - if (this->target->getSupportedAudioModes(&_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz_switchAudioMode() { - ::aidl::android::media::audio::common::AudioMode in_mode; - this->provider->genAudioMode(in_mode); - - this->target->switchAudioMode(in_mode); - } - - virtual std::optional<::aidl::android::hardware::audio::core::ITelephony::TelecomConfig> fuzz_setTelecomConfig() { - ::aidl::android::hardware::audio::core::ITelephony::TelecomConfig in_config; - this->provider->genTelecomConfig(in_config); - ::aidl::android::hardware::audio::core::ITelephony::TelecomConfig _aidl_return; - - if (this->target->setTelecomConfig(in_config, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual void fuzz() { - char id = this->provider->inner().template ConsumeIntegral(); - switch (id) { - case 0: { - fuzz_getSupportedAudioModes(); - break; - } - case 1: { - fuzz_switchAudioMode(); - break; - } - case 2: { - fuzz_setTelecomConfig(); - break; - } - } - } -}; - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/main.cpp b/qcom/opensource/audio-hal/primary-hal/hal/fuzz/main.cpp deleted file mode 100755 index 688e7725..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/main.cpp +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause-Clear - -#include -#include -#include -#include -#include - -#include "base.h" -#include "provider.h" -#include "gen.h" - -#include -#include -#include - -using qti::audio::core::Module; -using qti::audio::core::ModulePrimary; - -// data that persists between LLVMFuzzerTestOneInput() calls -struct AudioPersistData { - std::vector portIds; - std::vector portConfigIds; - std::vector> inStreams; - std::vector> outStreams; -}; - -class AudioDataProvider : public DataProvider { -public: - AudioDataProvider(const char *data, size_t size, AudioPersistData *persistData): - DataProvider(data, size), persistData(persistData) {} - AudioPersistData *getPersistData() { return persistData; } - - virtual void genAudioPort(AudioPort &out) override { - DataProvider::genAudioPort(out); - pickPortId(out.id); - } - - virtual void genAudioPortConfig(AudioPortConfig &out) override { - DataProvider::genAudioPortConfig(out); - pickPortConfigId(out.id); - pickPortId(out.portId); - } - - virtual void genOpenInputStreamArguments(IModule::OpenInputStreamArguments &out) override { - DataProvider::genOpenInputStreamArguments(out); - pickPortConfigId(out.portConfigId); - } - - virtual void genOpenOutputStreamArguments(IModule::OpenOutputStreamArguments &out) override { - DataProvider::genOpenOutputStreamArguments(out); - pickPortConfigId(out.portConfigId); - } - - virtual void genVendorParameter(VendorParameter &out) override { - out.id = pickVendorParameter(); - } - - std::string pickVendorParameter() { - using namespace qti::audio::core::Parameters; - std::vector parameters = { - kHdrRecord, - kWnr, - kAns, - kOrientation, - kInverted, - kHdrChannelCount, - kHdrSamplingRate, - kFacing, - kVoiceCallState, - kVoiceCallType, - kVoiceVSID, - kVoiceCRSCall, - kVoiceCRSVolume, - kVolumeBoost, - kVoiceSlowTalk, - kVoiceHDVoice, - kVoiceDeviceMute, - kVoiceDirection, - kInCallMusic, - kUHQA, - kFbspCfgWaitTime, - kFbspFTMWaitTime, - kFbspValiWaitTime, - kFbspValiValiTime, - kTriggerSpeakerCall, - kWfdChannelMap, - kHapticsVolume, - kHapticsIntensity - }; - return pick(parameters); - } - -private: - // most of the time, pick a valid port id - void pickPortId(int &id) { - const auto &portIds = persistData->portIds; - auto v = uint(); - if (v < 8) { - id = 0; - } else if (v < 250 && !portIds.empty()) { - id = pick(portIds); - } - } - - // most of the time, pick a valid port config id - void pickPortConfigId(int &id) { - const auto &portConfigIds = persistData->portConfigIds; - auto v = uint(); - if (v < 8) { - id = 0; - } else if (v < 250 && !portConfigIds.empty()) { - id = pick(portConfigIds); - } - } - - AudioPersistData *persistData; -}; - -struct AudioStreamCommonFuzzer: public IStreamCommonFuzzer { - bool closed = false; - - AudioStreamCommonFuzzer(AudioDataProvider *provider, IStreamCommon *stream): IStreamCommonFuzzer(provider, stream) {} - - void fuzz_close() override { - IStreamCommonFuzzer::fuzz_close(); - closed = true; - } -}; - -struct AudioStreamInFuzzer : public IStreamInFuzzer { - AudioStreamInFuzzer(AudioDataProvider *provider, IStreamIn *stream): IStreamInFuzzer(provider, stream) {} - - std::shared_ptr getStreamCommon() { - std::shared_ptr stream; - target->getStreamCommon(&stream); - return std::move(stream); - } -}; - -struct AudioStreamOutFuzzer : public IStreamOutFuzzer { - AudioStreamOutFuzzer(AudioDataProvider *provider, IStreamOut *stream): IStreamOutFuzzer(provider, stream) {} - - std::shared_ptr getStreamCommon() { - std::shared_ptr stream; - target->getStreamCommon(&stream); - return std::move(stream); - } -}; - -struct AudioModuleFuzzer : public IModuleFuzzer { - AudioModuleFuzzer(AudioDataProvider *provider, Module *mod): IModuleFuzzer(provider, mod) {} - - std::optional fuzz_openInputStream() override { - auto ret = IModuleFuzzer::fuzz_openInputStream(); - if (ret) { - provider->getPersistData()->inStreams.push_back(ret.value().stream); - } - return ret; - } - - std::optional fuzz_openOutputStream() override { - auto ret = IModuleFuzzer::fuzz_openOutputStream(); - if (ret) { - provider->getPersistData()->outStreams.push_back(ret.value().stream); - } - return ret; - } - - // avoid assertion in connectExternalDevice call in get() - std::optional fuzz_connectExternalDevice() override { - AudioPort inData; - provider->genAudioPort(inData); - - if (inData.ext.getTag() == AudioPortExt::Tag::device) { - AudioPort _aidl_return; - if (target->connectExternalDevice(inData, &_aidl_return).isOk()) { - return _aidl_return; - } - } - return std::nullopt; - } - - // record port IDs in persist data - virtual std::optional> fuzz_getAudioPorts() override { - std::vector ports; - if (target->getAudioPorts(&ports).isOk()) { - auto &portIds = provider->getPersistData()->portIds; - portIds.clear(); - for (const auto &port : ports) { - portIds.push_back(port.id); - } - return std::move(ports); - } - return std::nullopt; - } - - // record port config IDs in persist data - virtual std::optional> fuzz_getAudioPortConfigs() override { - std::vector configs; - if (target->getAudioPortConfigs(&configs).isOk()) { - auto &portConfigIds = provider->getPersistData()->portConfigIds; - portConfigIds.clear(); - for (const auto &config : configs) { - portConfigIds.push_back(config.id); - } - return std::move(configs); - } else { - return std::nullopt; - } - } - - virtual std::optional fuzz_setAudioPortConfig() override { - AudioPortConfig config; - provider->genAudioPortConfig(config); - if (provider->getPersistData()->portConfigIds.size() < 4) { - // if there are not many port configs, let's try to generate some legitimate data that - // can pass checks in setAudioPortConfig() - const auto &portIds = provider->getPersistData()->portIds; - if (portIds.empty()) { - return std::nullopt; - } - config.portId = provider->pick(portIds); - config.id = 0; - - AudioPort port; - if (!target->getAudioPort(config.portId, &port).isOk()) { - return std::nullopt; - } - config.flags = port.flags; - - if (port.profiles.empty()) { - return std::nullopt; - } - const auto &profile = provider->pick(port.profiles); - config.format = profile.format; - - if (profile.channelMasks.empty() || profile.sampleRates.empty()) { - return std::nullopt; - } - config.channelMask = provider->pick(profile.channelMasks); - auto sampleRate = provider->pick(profile.sampleRates); - config.sampleRate = aidl::android::media::audio::common::Int(sampleRate); - } - - AudioPortConfig out_suggested; - bool _aidl_return; - - if (target->setAudioPortConfig(config, &out_suggested, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } - - virtual std::optional> fuzz_getVendorParameters() override { - std::vector in_ids; - provider->gen(in_ids, [this](auto &v) { v = provider->pickVendorParameter(); }); - std::vector<::aidl::android::hardware::audio::core::VendorParameter> _aidl_return; - - if (target->getVendorParameters(in_ids, &_aidl_return).isOk()) { - return std::move(_aidl_return); - } else { - return std::nullopt; - } - } -}; - -template -void fuzzStream(AudioDataProvider *provider, std::vector> &streams) { - if (!streams.empty()) { - auto index = provider->inner().ConsumeIntegralInRange(0, streams.size() - 1); - auto stream = streams[index]; - - auto fuzzer = F(provider, stream.get()); - fuzzer.fuzz(); - - std::shared_ptr common = fuzzer.getStreamCommon(); - AudioStreamCommonFuzzer commonFuzzer(provider, common.get()); - commonFuzzer.fuzz(); - if (commonFuzzer.closed) { - commonFuzzer.closed = false; - streams.erase(streams.begin() + index); - } - } -} - -extern "C" binder_status_t registerService(void); - -class AudioFuzzer { -public: - void setProvider(AudioDataProvider *provider) { - this->provider = provider; - } - - void fuzz() { - if (!modulePrimary) { - // register agm service - registerService(); - modulePrimary = ndk::SharedRefBase::make(); - } - moduleFuzzer = std::make_unique(provider, modulePrimary.get()); - moduleFuzzer->fuzz(); - - fuzzStream(provider, provider->getPersistData()->inStreams); - fuzzStream(provider, provider->getPersistData()->outStreams); - } - -private: - AudioDataProvider *provider = nullptr; - std::shared_ptr modulePrimary = nullptr; - std::unique_ptr moduleFuzzer = nullptr; -}; - -extern "C" int LLVMFuzzerTestOneInput(const char *data, size_t size) { - static AudioFuzzer fuzzer; - static AudioPersistData persistData; - - AudioDataProvider provider(data, size, &persistData); - fuzzer.setProvider(&provider); - - fuzzer.fuzz(); - return 0; -} diff --git a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/provider.h b/qcom/opensource/audio-hal/primary-hal/hal/fuzz/provider.h deleted file mode 100755 index 9bffdfa9..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/fuzz/provider.h +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause-Clear - -#include -#include -#include -#include - -#include -#include -#include - -class DataProviderBase { -protected: - FuzzedDataProvider p; - -public: - DataProviderBase(const char *data, size_t size): - p(reinterpret_cast(data), size) {} - virtual ~DataProviderBase() {} - - FuzzedDataProvider &inner() { return p; } - - template - T pick(const std::vector &v) { - assert(!v.empty()); - return v[p.ConsumeIntegralInRange(0, v.size() - 1)]; - } - - template - T pick(T (&array)[N]) { - assert(N > 0); - return array[p.ConsumeIntegralInRange(0, N - 1)]; - } - - // primitive types - void gen(bool &out) { out = p.ConsumeBool(); } - void gen(uint8_t &out) { out = p.ConsumeIntegral(); } - void gen(float &out) { out = p.ConsumeFloatingPoint(); } - void gen(double &out) { out = p.ConsumeFloatingPoint(); } - void gen(int8_t &out) { out = genSignedInteger(); } - void gen(char16_t &out) { out = genSignedInteger(); } - void gen(int32_t &out) { out = genSignedInteger(); } - void gen(int64_t &out) { out = genSignedInteger(); } - - void genInt(aidl::android::media::audio::common::Int &out) { - out.value = genSignedInteger(); - } - - void genFloat(aidl::android::media::audio::common::Float &out) { - out.value = p.ConsumeFloatingPoint(); - } - - void genBoolean(aidl::android::media::audio::common::Boolean &out) { - out.value = p.ConsumeBool(); - } - - void gen(std::string &out) { - std::string s; - int size = p.ConsumeIntegralInRange(0, 16); - for (int i = 0; i < size; ++i) { - char ch = 'a' + p.ConsumeIntegralInRange(0, 26); - out.push_back(ch); - } - out = s; - } - - template - void gen(std::vector &out, F f, int max = 4) { - std::vector v; - int size = p.ConsumeIntegralInRange(0, max); - v.resize(size); - for (auto &val : v) { - f(val); - } - out = v; - } - - template - void gen(std::optional &out, F f) { - bool v = p.ConsumeBool(); - if (v) { - T val; - f(val); - out = std::optional(val); - } - } - - // generate a random number in the range [0, 255] - unsigned int uint() { - uint8_t v; - gen(v); - return v; - } - -private: - // to avoid ubsan error like: - // FuzzedDataProvider.h:212:47: runtime error: unsigned integer overflow: - // 2147483647 - 18446744071562067968 cannot be represented in type 'uint64_t' - template - I genSignedInteger() { - union { - I i; - U u; - } val; - val.u = p.ConsumeIntegral(); - return val.i; - } -}; diff --git a/qcom/opensource/audio-hal/primary-hal/hal/service/Android.bp b/qcom/opensource/audio-hal/primary-hal/hal/service/Android.bp deleted file mode 100755 index 7fabd50a..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/service/Android.bp +++ /dev/null @@ -1,30 +0,0 @@ -cc_binary { - name: "audiohalservice.qti", - vendor: true, - relative_install_path: "hw", - init_rc: ["audiohalservice_qti.rc"], - - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - "-Wthread-safety", - ], - - srcs: - ["Service.cpp", - "ConfigManager.cpp", - ], - - shared_libs: [ - "libcutils", - "libbinder", - "libbinder_ndk", - "liblog", - "libutils", - "libtinyxml2", - "libbase", - ], - header_libs: ["libaudio_system_headers"], -} - diff --git a/qcom/opensource/audio-hal/primary-hal/hal/service/ConfigManager.cpp b/qcom/opensource/audio-hal/primary-hal/hal/service/ConfigManager.cpp deleted file mode 100755 index e97d15bc..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/service/ConfigManager.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_NDEBUG 0 -#define LOG_TAG "AHAL_Service_QTI" - -#include "ConfigManager.h" -#include -#include -#include - -#include - -using namespace tinyxml2; - -/** @return xml dump of the provided element. - * By not providing a printer, it is implicitly created in the caller context. - * In such case the return pointer has the same lifetime as the expression containing dump(). - */ -const char *dump(const XMLElement &element, XMLPrinter &&printer = {}) { - element.Accept(&printer); - return printer.CStr(); -} - -/** @return all `node`s children that are elements and match the tag if provided. */ -std::vector> getChildren(const XMLNode &node, - const char *childTag = nullptr) { - std::vector> children; - for (auto *child = node.FirstChildElement(childTag); child != nullptr; - child = child->NextSiblingElement(childTag)) { - children.emplace_back(*child); - } - return children; -} - -void parseLibrary(const XMLElement &xmlLibrary, Interfaces &interfaces) { - const char *name = xmlLibrary.Attribute("name"); - const char *libraryName = xmlLibrary.Attribute("libraryName"); - const char *method = xmlLibrary.Attribute("method"); - const char *mandatory = xmlLibrary.Attribute("mandatory"); - if (name == nullptr || method == nullptr || mandatory == nullptr || libraryName == nullptr) { - ALOGE("library must have a name and a method: %s", dump(xmlLibrary)); - return; - } - bool mandatoryValue = false; - if (strcmp(mandatory, "true") == 0) mandatoryValue = true; - interfaces.push_back({name, libraryName, method, mandatoryValue}); -} - -Interfaces parseWithPath(std::string &&path) { - ALOGI("parse interfaces %s ", path.c_str()); - XMLDocument doc; - doc.LoadFile(path.c_str()); - if (doc.Error()) { - ALOGE("Failed to parse %s: Tinyxml2 error (%d): %s", path.c_str(), doc.ErrorID(), - doc.ErrorStr()); - return {}; - } - Interfaces interfaces; - - for (auto &xmlLibraries : getChildren(doc, "libraries")) { - for (auto &xmlLibrary : getChildren(xmlLibraries, "library")) { - parseLibrary(xmlLibrary, interfaces); - } - } - return interfaces; -} - -Interfaces parseInterfaces() { - for (const std::string &location : ::android::audio_get_configuration_paths()) { - std::string defaultPath = location + '/' + DEFAULT_NAME; - if (access(defaultPath.c_str(), R_OK) != 0) { - continue; - } - auto result = parseWithPath(std::move(defaultPath)); - return result; - } - return {}; -} \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/service/ConfigManager.h b/qcom/opensource/audio-hal/primary-hal/hal/service/ConfigManager.h deleted file mode 100755 index a8662856..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/service/ConfigManager.h +++ /dev/null @@ -1,35 +0,0 @@ - -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include -#include -#include - -/** Default path of service interface **/ -constexpr const char* DEFAULT_NAME = "vendor_audio_interfaces.xml"; - -struct Interface { - std::string name; // interface name - std::string libraryName; // name of library - std::string method; // function pointer used to register to ServiceManager - bool mandatory; // Interface is mandatory or not - - std::string toString() const { - std::ostringstream os; - os << "Interface: ["; - os << "name: " << name << " "; - os << "path: " << libraryName << " "; - os << "mandatory: " << mandatory; - os << "]"; - return os.str(); - } -}; - -using Interfaces = std::vector; - -Interfaces parseInterfaces(); \ No newline at end of file diff --git a/qcom/opensource/audio-hal/primary-hal/hal/service/Service.cpp b/qcom/opensource/audio-hal/primary-hal/hal/service/Service.cpp deleted file mode 100755 index 851bf7b9..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/service/Service.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_NDEBUG 0 -#define LOG_TAG "AHAL_Service_QTI" - -#include -#include -#include - -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include "ConfigManager.h" - -#define REGISTER_RETRY_COUNT 10 -#define SLEEP_TIME_SECONDS 1 - -static bool registerServiceImplementation(const Interface& interface) { - auto libraryName = interface.libraryName; - auto interfaceMethod = interface.method; - void* handle = dlopen(libraryName.c_str(), RTLD_LAZY); - if (handle == nullptr) { - const char* error = dlerror(); - ALOGE("Failed to dlopen %s: %s", libraryName.c_str(), - error != nullptr ? error : "unknown error"); - return false; - } - auto instantiate = - reinterpret_cast(dlsym(handle, interfaceMethod.c_str())); - if (instantiate == nullptr) { - const char* error = dlerror(); - ALOGE("Factory function %s not found in libName %s: %s", interfaceMethod.c_str(), - libraryName.c_str(), error != nullptr ? error : "unknown error"); - dlclose(handle); - return false; - } - return (instantiate() == STATUS_OK); -} - -void registerInterfaces(const Interfaces& interfaces) { - for (const auto& interface : interfaces) { - if (registerServiceImplementation(interface)) { - ALOGI("successfully registered %s", interface.toString().c_str()); - } else if (interface.mandatory) { - int32_t retryCount = 0; - bool isRegistered = false; - while (retryCount < REGISTER_RETRY_COUNT) { - ALOGI("failed to register service: %s, retry count: %d", - interface.toString().c_str(), retryCount + 1); - isRegistered = registerServiceImplementation(interface); - if (isRegistered) { - ALOGI("successfully registered %s", interface.toString().c_str()); - break; - } else { - //the service may failed to register due to resource busy, sleep and try again - sleep(SLEEP_TIME_SECONDS); - } - ++retryCount; - } - LOG_ALWAYS_FATAL_IF(!isRegistered, "failed to register %s ", - interface.toString().c_str()); - } else { - ALOGW("failed to register optional %s ", interface.toString().c_str()); - } - } -} - -bool registerFromConfigs() { - auto interfaces = parseInterfaces(); - registerInterfaces(interfaces); - return !interfaces.empty(); -} - -/* -* Don't modify default entries unless the library is a must for stub mode bootup. -*/ -void registerDefaultInterfaces() { - Interfaces defaultInterfaces = { - {.name = "audiohal-default", - .libraryName = "libaudiocorehal.default.so", - .method = "registerServices", - .mandatory = true}, - {.name = "audioeffecthal", - .libraryName = "libaudioeffecthal.qti.so", - .method = "registerService", - .mandatory = true}, - {.name = "bthal", - .libraryName = "android.hardware.bluetooth.audio_sw.so", - .method = "registerIModuleBluetoothSWQti", - .mandatory = false}, - }; - - registerInterfaces(defaultInterfaces); -} - -void registerAvailableInterfaces() { - auto stubmode = ::android::base::GetIntProperty("vendor.audio.hal.stubmode", 0); - if (stubmode || !registerFromConfigs()) { - ALOGI("registerDefaultInterfaces stub mode %d", stubmode); - registerDefaultInterfaces(); - } -} - -void setLogSeverity() { - // by default use DEBUG logging enabled - auto logLevel = ::android::base::GetIntProperty("vendor.audio.hal.loglevel", 1); - // system/libbase/include/android-base/logging.h, check LogSeverity for types - android::base::SetMinimumLogSeverity(static_cast<::android::base::LogSeverity>(logLevel)); -} - -int main() { - auto startTime = std::chrono::steady_clock::now(); - // Random values are used in the implementation. - std::srand(std::time(nullptr)); - setLogSeverity(); - - ABinderProcess_setThreadPoolMaxThreadCount(16); - ABinderProcess_startThreadPool(); - - registerAvailableInterfaces(); - auto endTime = std::chrono::steady_clock::now(); - float timeTaken = - std::chrono::duration_cast>(endTime - startTime).count(); - ALOGI("registration took %.2f seconds ", timeTaken); - ABinderProcess_joinThreadPool(); - return EXIT_FAILURE; -} diff --git a/qcom/opensource/audio-hal/primary-hal/hal/service/audiohalservice_qti.rc b/qcom/opensource/audio-hal/primary-hal/hal/service/audiohalservice_qti.rc deleted file mode 100755 index 10a2bc3a..00000000 --- a/qcom/opensource/audio-hal/primary-hal/hal/service/audiohalservice_qti.rc +++ /dev/null @@ -1,36 +0,0 @@ -service vendor.audio-hal-aidl /vendor/bin/hw/audiohalservice.qti - class hal - user audioserver - group audio media mediadrm drmrpc inet net_bt net_bt_admin net_bw_acct wakelock context_hub oem_2901 oem_2912 - capabilities BLOCK_SUSPEND SYS_NICE - # setting RLIMIT_RTPRIO allows binder RT priority inheritance - rlimit rtprio 10 10 - ioprio rt 4 - task_profiles ProcessCapacityHigh HighPerformance - writepid /dev/cpuset/foreground/tasks /dev/stune/foreground/tasks - onrestart restart audioserver - -# SSR trigger for audio subsystem -on property:vendor.audio.ssr.trigger=1 - write /sys/kernel/boot_adsp/ssr 1 - -# crash trigger for audio subsystem -on property:vendor.audio.crash.kernel.trigger=1 - write /sys/kernel/boot_adsp/crash 1 - -on boot - chown media audio /sys/kernel/snd_card/card_state - -on post-fs-data - # Create directory used by audio subsystem - mkdir /data/vendor/audio 0770 audio audio - mkdir /data/vendor/audio_dsp 0770 media media - mkdir /data/vendor/audio/audio_feature_stats 0770 audio audio - mkdir /data/vendor/audio/memlog 0770 audio audio - - # Create directory for audio delta files - mkdir /data/vendor/audio/acdbdata 0770 media audio - mkdir /data/vendor/audio/acdbdata/delta 0770 media audio - -on property:sys.boot_completed=1 - chown media audio /sys/kernel/aud_dev/state \ No newline at end of file diff --git a/qcom/opensource/commonsys-intf/audio/Android.bp b/qcom/opensource/commonsys-intf/audio/Android.bp deleted file mode 100755 index 167f69b8..00000000 --- a/qcom/opensource/commonsys-intf/audio/Android.bp +++ /dev/null @@ -1,37 +0,0 @@ -prebuilt_hidl_interfaces { - name: "hidl_audio_agm_pal_interfaces", - interfaces: [ - "vendor.qti.hardware.AGMIPC@1.0::IAGM", - "vendor.qti.hardware.pal@1.0::IPAL", - ], -} - -aidl_interface { - name: "vendor.qti.hardware.paleventnotifier", - srcs: ["vendor/qti/hardware/paleventnotifier/*.aidl"], - vendor: true, - stability: "vintf", - imports: [ - "android.hardware.common-V2", - ], - backend: { - cpp: { - enabled: false, - }, - java: { - sdk_version: "module_current", - }, - ndk: { - enabled: true, - }, - }, - owner: "qti", - frozen: true, - versions_with_info: [ - { - version: "1", - imports: ["android.hardware.common-V2"], - }, - ], - -} diff --git a/qcom/opensource/commonsys-intf/audio/Android.mk b/qcom/opensource/commonsys-intf/audio/Android.mk deleted file mode 100755 index 5053e7d6..00000000 --- a/qcom/opensource/commonsys-intf/audio/Android.mk +++ /dev/null @@ -1 +0,0 @@ -include $(call all-subdir-makefiles) diff --git a/qcom/opensource/commonsys-intf/audio/agm/current.txt b/qcom/opensource/commonsys-intf/audio/agm/current.txt deleted file mode 100755 index 2a0f602a..00000000 --- a/qcom/opensource/commonsys-intf/audio/agm/current.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (c) 2020, The Linux Foundation. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials provided -# with the distribution. -# * Neither the name of The Linux Foundation nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -39b7ce561257438aec03c282e3c4f93ed7bcc9d6ba46b0f6389fe46eb391e1f4 vendor.qti.hardware.AGMIPC@1.0::types -3a1b66b36548e0bd981576253961d66d922ab3b5cc8bfc5404d576dec9c42564 vendor.qti.hardware.AGMIPC@1.0::IAGM -ecef4c3bfa0e08d5e1f44a4bb0a449ffd1be283751deebad724b325e8e46c79e vendor.qti.hardware.AGMIPC@1.0::IAGMCallback diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/.hash b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/.hash deleted file mode 100755 index 361323f5..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/.hash +++ /dev/null @@ -1 +0,0 @@ -32411223bd2f598ecc48cf09141845ae01ab8230 diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/IPALEventNotifier.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/IPALEventNotifier.aidl deleted file mode 100755 index 9236a7b8..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/IPALEventNotifier.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -interface IPALEventNotifier { - int ipc_pal_notify_register_callback(in vendor.qti.hardware.paleventnotifier.IPALEventNotifierCallback callback); -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/IPALEventNotifierCallback.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/IPALEventNotifierCallback.aidl deleted file mode 100755 index fa20fad5..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/IPALEventNotifierCallback.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -interface IPALEventNotifierCallback { - oneway void onStart(in vendor.qti.hardware.paleventnotifier.PalCallbackConfig Config); - oneway void onStop(in vendor.qti.hardware.paleventnotifier.PalCallbackConfig Config); - oneway void onDeviceSwitch(in vendor.qti.hardware.paleventnotifier.PalCallbackConfig Config); -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalAudioFmt.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalAudioFmt.aidl deleted file mode 100755 index 50d3dd18..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalAudioFmt.aidl +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalAudioFmt { - PAL_AUDIO_FMT_DEFAULT_PCM = 0x1, - PAL_AUDIO_FMT_PCM_S16_LE = PAL_AUDIO_FMT_DEFAULT_PCM /* 1 */, - PAL_AUDIO_FMT_DEFAULT_COMPRESSED = 0x2, - PAL_AUDIO_FMT_MP3 = PAL_AUDIO_FMT_DEFAULT_COMPRESSED /* 2 */, - PAL_AUDIO_FMT_AAC = 0x3, - PAL_AUDIO_FMT_AAC_ADTS = 0x4, - PAL_AUDIO_FMT_AAC_ADIF = 0x5, - PAL_AUDIO_FMT_AAC_LATM = 0x6, - PAL_AUDIO_FMT_WMA_STD = 0x7, - PAL_AUDIO_FMT_ALAC = 0x8, - PAL_AUDIO_FMT_APE = 0x9, - PAL_AUDIO_FMT_WMA_PRO = 0xA, - PAL_AUDIO_FMT_FLAC = 0xB, - PAL_AUDIO_FMT_FLAC_OGG = 0xC, - PAL_AUDIO_FMT_VORBIS = 0xD, - PAL_AUDIO_FMT_AMR_NB = 0xE, - PAL_AUDIO_FMT_AMR_WB = 0xF, - PAL_AUDIO_FMT_AMR_WB_PLUS = 0x10, - PAL_AUDIO_FMT_EVRC = 0x11, - PAL_AUDIO_FMT_G711 = 0x12, - PAL_AUDIO_FMT_QCELP = 0x13, - PAL_AUDIO_FMT_PCM_S8 = 0x14, - PAL_AUDIO_FMT_PCM_S24_3LE = 0x15, - PAL_AUDIO_FMT_PCM_S24_LE = 0x16, - PAL_AUDIO_FMT_PCM_S32_LE = 0x17, - PAL_AUDIO_FMT_OPUS = 0x18, - PAL_AUDIO_FMT_COMPRESSED_RANGE_BEGIN = 0xF0000000, - PAL_AUDIO_FMT_COMPRESSED_EXTENDED_RANGE_BEGIN = 0xF0000F00, - PAL_AUDIO_FMT_COMPRESSED_EXTENDED_RANGE_END = 0xF0000FFF, - PAL_AUDIO_FMT_COMPRESSED_RANGE_END = PAL_AUDIO_FMT_COMPRESSED_EXTENDED_RANGE_END /* -268431361 */, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalCallbackConfig.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalCallbackConfig.aidl deleted file mode 100755 index 2de8bc36..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalCallbackConfig.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalCallbackConfig { - int noOfPrevDevices; - int noOfCurrentDevices; - vendor.qti.hardware.paleventnotifier.PalDeviceId[] prevDevices; - vendor.qti.hardware.paleventnotifier.PalDeviceId[] currentDevices; - vendor.qti.hardware.paleventnotifier.PalStreamAttributes streamAttributes; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalChannelInfo.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalChannelInfo.aidl deleted file mode 100755 index e6e3376e..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalChannelInfo.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalChannelInfo { - char channels; - byte[64] chMap; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalDeviceId.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalDeviceId.aidl deleted file mode 100755 index af42805a..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalDeviceId.aidl +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalDeviceId { - PAL_DEVICE_OUT_MIN = 0, - PAL_DEVICE_NONE = 1, - PAL_DEVICE_OUT_HANDSET = 2, - PAL_DEVICE_OUT_SPEAKER = 3, - PAL_DEVICE_OUT_WIRED_HEADSET = 4, - PAL_DEVICE_OUT_WIRED_HEADPHONE = 5, - PAL_DEVICE_OUT_LINE = 6, - PAL_DEVICE_OUT_BLUETOOTH_SCO = 7, - PAL_DEVICE_OUT_BLUETOOTH_A2DP = 8, - PAL_DEVICE_OUT_AUX_DIGITAL = 9, - PAL_DEVICE_OUT_HDMI = 10, - PAL_DEVICE_OUT_USB_DEVICE = 11, - PAL_DEVICE_OUT_USB_HEADSET = 12, - PAL_DEVICE_OUT_SPDIF = 13, - PAL_DEVICE_OUT_FM = 14, - PAL_DEVICE_OUT_AUX_LINE = 15, - PAL_DEVICE_OUT_PROXY = 16, - PAL_DEVICE_OUT_AUX_DIGITAL_1 = 17, - PAL_DEVICE_OUT_HEARING_AID = 18, - PAL_DEVICE_OUT_HAPTICS_DEVICE = 19, - PAL_DEVICE_OUT_ULTRASOUND = 20, - PAL_DEVICE_OUT_ULTRASOUND_DEDICATED = 21, - PAL_DEVICE_OUT_BLUETOOTH_BLE = 22, - PAL_DEVICE_OUT_BLUETOOTH_BLE_BROADCAST = 23, - PAL_DEVICE_OUT_DUMMY = 24, - PAL_DEVICE_OUT_RECORD_PROXY = 25, - PAL_DEVICE_OUT_MAX = 26, - PAL_DEVICE_IN_MIN = PAL_DEVICE_OUT_MAX /* 26 */, - PAL_DEVICE_IN_HANDSET_MIC = (PAL_DEVICE_IN_MIN + 1) /* 27 */, - PAL_DEVICE_IN_SPEAKER_MIC = (PAL_DEVICE_IN_MIN + 2) /* 28 */, - PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET = (PAL_DEVICE_IN_MIN + 3) /* 29 */, - PAL_DEVICE_IN_WIRED_HEADSET = (PAL_DEVICE_IN_MIN + 4) /* 30 */, - PAL_DEVICE_IN_AUX_DIGITAL = (PAL_DEVICE_IN_MIN + 5) /* 31 */, - PAL_DEVICE_IN_HDMI = (PAL_DEVICE_IN_MIN + 6) /* 32 */, - PAL_DEVICE_IN_USB_ACCESSORY = (PAL_DEVICE_IN_MIN + 7) /* 33 */, - PAL_DEVICE_IN_USB_DEVICE = (PAL_DEVICE_IN_MIN + 8) /* 34 */, - PAL_DEVICE_IN_USB_HEADSET = (PAL_DEVICE_IN_MIN + 9) /* 35 */, - PAL_DEVICE_IN_FM_TUNER = (PAL_DEVICE_IN_MIN + 10) /* 36 */, - PAL_DEVICE_IN_LINE = (PAL_DEVICE_IN_MIN + 11) /* 37 */, - PAL_DEVICE_IN_SPDIF = (PAL_DEVICE_IN_MIN + 12) /* 38 */, - PAL_DEVICE_IN_PROXY = (PAL_DEVICE_IN_MIN + 13) /* 39 */, - PAL_DEVICE_IN_HANDSET_VA_MIC = (PAL_DEVICE_IN_MIN + 14) /* 40 */, - PAL_DEVICE_IN_BLUETOOTH_A2DP = (PAL_DEVICE_IN_MIN + 15) /* 41 */, - PAL_DEVICE_IN_HEADSET_VA_MIC = (PAL_DEVICE_IN_MIN + 16) /* 42 */, - PAL_DEVICE_IN_VI_FEEDBACK = (PAL_DEVICE_IN_MIN + 17) /* 43 */, - PAL_DEVICE_IN_TELEPHONY_RX = (PAL_DEVICE_IN_MIN + 18) /* 44 */, - PAL_DEVICE_IN_ULTRASOUND_MIC = (PAL_DEVICE_IN_MIN + 19) /* 45 */, - PAL_DEVICE_IN_EXT_EC_REF = (PAL_DEVICE_IN_MIN + 20) /* 46 */, - PAL_DEVICE_IN_ECHO_REF = (PAL_DEVICE_IN_MIN + 21) /* 47 */, - PAL_DEVICE_IN_HAPTICS_VI_FEEDBACK = (PAL_DEVICE_IN_MIN + 22) /* 48 */, - PAL_DEVICE_IN_BLUETOOTH_BLE = (PAL_DEVICE_IN_MIN + 23) /* 49 */, - PAL_DEVICE_IN_CPS_FEEDBACK = (PAL_DEVICE_IN_MIN + 24) /* 50 */, - PAL_DEVICE_IN_DUMMY = (PAL_DEVICE_IN_MIN + 25) /* 51 */, - PAL_DEVICE_IN_CPS2_FEEDBACK = (PAL_DEVICE_IN_MIN + 26) /* 52 */, - PAL_DEVICE_IN_RECORD_PROXY = (PAL_DEVICE_IN_MIN + 27) /* 53 */, - PAL_DEVICE_IN_MAX = (PAL_DEVICE_IN_MIN + 28) /* 54 */, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalMediaConfig.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalMediaConfig.aidl deleted file mode 100755 index f309fc4b..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalMediaConfig.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalMediaConfig { - int sampleRate; - int bitwidth; - vendor.qti.hardware.paleventnotifier.PalChannelInfo chInfo; - vendor.qti.hardware.paleventnotifier.PalAudioFmt audioFormatId; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamAttributes.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamAttributes.aidl deleted file mode 100755 index ab0ecc33..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamAttributes.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalStreamAttributes { - vendor.qti.hardware.paleventnotifier.PalStreamType type; - vendor.qti.hardware.paleventnotifier.PalStreamInfo info; - vendor.qti.hardware.paleventnotifier.PalStreamFlag flags; - vendor.qti.hardware.paleventnotifier.PalStreamDirection direction; - vendor.qti.hardware.paleventnotifier.PalMediaConfig inMediaConfig; - vendor.qti.hardware.paleventnotifier.PalMediaConfig outMediaConfig; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamDirection.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamDirection.aidl deleted file mode 100755 index 273bf123..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamDirection.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalStreamDirection { - PAL_AUDIO_OUTPUT = 0x1, - PAL_AUDIO_INPUT = 0x2, - PAL_AUDIO_INPUT_OUTPUT = 0x3, - PAL_AUDIO_INVALID = 0x4, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamFlag.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamFlag.aidl deleted file mode 100755 index d4ad3c12..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamFlag.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalStreamFlag { - PAL_STREAM_FLAG_TIMESTAMP = 0x1, - PAL_STREAM_FLAG_NON_BLOCKING = 0x2, - PAL_STREAM_FLAG_MMAP = 0x4, - PAL_STREAM_FLAG_MMAP_NO_IRQ = 0x8, - PAL_STREAM_FLAG_EXTERN_MEM = 0x10, - PAL_STREAM_FLAG_SRCM_INBAND = 0x20, - PAL_STREAM_FLAG_INVALID, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamInfo.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamInfo.aidl deleted file mode 100755 index f987b6ab..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamInfo.aidl +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalStreamInfo { - long version; - long size; - long durationUs; - boolean hasVideo; - int txProxyType; - int rxProxyType; - boolean isStreaming; - int loopbackType; - int hapticsType; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamType.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamType.aidl deleted file mode 100755 index e1b84349..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/PalStreamType.aidl +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalStreamType { - PAL_STREAM_LOW_LATENCY = 1, - PAL_STREAM_DEEP_BUFFER = 2, - PAL_STREAM_COMPRESSED = 3, - PAL_STREAM_VOIP = 4, - PAL_STREAM_VOIP_RX = 5, - PAL_STREAM_VOIP_TX = 6, - PAL_STREAM_VOICE_CALL_MUSIC = 7, - PAL_STREAM_GENERIC = 8, - PAL_STREAM_RAW = 9, - PAL_STREAM_VOICE_RECOGNITION = 10, - PAL_STREAM_VOICE_CALL_RECORD = 11, - PAL_STREAM_VOICE_CALL_TX = 12, - PAL_STREAM_VOICE_CALL_RX_TX = 13, - PAL_STREAM_VOICE_CALL = 14, - PAL_STREAM_LOOPBACK = 15, - PAL_STREAM_TRANSCODE = 16, - PAL_STREAM_VOICE_UI = 17, - PAL_STREAM_PCM_OFFLOAD = 18, - PAL_STREAM_ULTRA_LOW_LATENCY = 19, - PAL_STREAM_PROXY = 20, - PAL_STREAM_NON_TUNNEL = 21, - PAL_STREAM_HAPTICS = 22, - PAL_STREAM_ACD = 23, - PAL_STREAM_CONTEXT_PROXY = 24, - PAL_STREAM_SENSOR_PCM_DATA = 25, - PAL_STREAM_ULTRASOUND = 26, - PAL_STREAM_SPATIAL_AUDIO = 27, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/Status.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/Status.aidl deleted file mode 100755 index 1971838f..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/1/vendor/qti/hardware/paleventnotifier/Status.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum Status { - UNKNOWN = (-1) /* -1 */, - SUCCESS = 0, - IO_ERROR, - BUSY, - NO_SPACE, - INVALID_FD, - ADVERTISE_ERROR, - PROTOCOL_NOT_AVAILABLE, - NOT_SUPPORTED, - DOWN_WITH_SSR, - NOW_INPROGRESS, - ALREADY_INPROGRESS, - CANCELLED, - NOT_RECOVERABLE, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/IPALEventNotifier.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/IPALEventNotifier.aidl deleted file mode 100755 index 9236a7b8..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/IPALEventNotifier.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -interface IPALEventNotifier { - int ipc_pal_notify_register_callback(in vendor.qti.hardware.paleventnotifier.IPALEventNotifierCallback callback); -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/IPALEventNotifierCallback.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/IPALEventNotifierCallback.aidl deleted file mode 100755 index fa20fad5..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/IPALEventNotifierCallback.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -interface IPALEventNotifierCallback { - oneway void onStart(in vendor.qti.hardware.paleventnotifier.PalCallbackConfig Config); - oneway void onStop(in vendor.qti.hardware.paleventnotifier.PalCallbackConfig Config); - oneway void onDeviceSwitch(in vendor.qti.hardware.paleventnotifier.PalCallbackConfig Config); -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalAudioFmt.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalAudioFmt.aidl deleted file mode 100755 index 50d3dd18..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalAudioFmt.aidl +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalAudioFmt { - PAL_AUDIO_FMT_DEFAULT_PCM = 0x1, - PAL_AUDIO_FMT_PCM_S16_LE = PAL_AUDIO_FMT_DEFAULT_PCM /* 1 */, - PAL_AUDIO_FMT_DEFAULT_COMPRESSED = 0x2, - PAL_AUDIO_FMT_MP3 = PAL_AUDIO_FMT_DEFAULT_COMPRESSED /* 2 */, - PAL_AUDIO_FMT_AAC = 0x3, - PAL_AUDIO_FMT_AAC_ADTS = 0x4, - PAL_AUDIO_FMT_AAC_ADIF = 0x5, - PAL_AUDIO_FMT_AAC_LATM = 0x6, - PAL_AUDIO_FMT_WMA_STD = 0x7, - PAL_AUDIO_FMT_ALAC = 0x8, - PAL_AUDIO_FMT_APE = 0x9, - PAL_AUDIO_FMT_WMA_PRO = 0xA, - PAL_AUDIO_FMT_FLAC = 0xB, - PAL_AUDIO_FMT_FLAC_OGG = 0xC, - PAL_AUDIO_FMT_VORBIS = 0xD, - PAL_AUDIO_FMT_AMR_NB = 0xE, - PAL_AUDIO_FMT_AMR_WB = 0xF, - PAL_AUDIO_FMT_AMR_WB_PLUS = 0x10, - PAL_AUDIO_FMT_EVRC = 0x11, - PAL_AUDIO_FMT_G711 = 0x12, - PAL_AUDIO_FMT_QCELP = 0x13, - PAL_AUDIO_FMT_PCM_S8 = 0x14, - PAL_AUDIO_FMT_PCM_S24_3LE = 0x15, - PAL_AUDIO_FMT_PCM_S24_LE = 0x16, - PAL_AUDIO_FMT_PCM_S32_LE = 0x17, - PAL_AUDIO_FMT_OPUS = 0x18, - PAL_AUDIO_FMT_COMPRESSED_RANGE_BEGIN = 0xF0000000, - PAL_AUDIO_FMT_COMPRESSED_EXTENDED_RANGE_BEGIN = 0xF0000F00, - PAL_AUDIO_FMT_COMPRESSED_EXTENDED_RANGE_END = 0xF0000FFF, - PAL_AUDIO_FMT_COMPRESSED_RANGE_END = PAL_AUDIO_FMT_COMPRESSED_EXTENDED_RANGE_END /* -268431361 */, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalCallbackConfig.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalCallbackConfig.aidl deleted file mode 100755 index 2de8bc36..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalCallbackConfig.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalCallbackConfig { - int noOfPrevDevices; - int noOfCurrentDevices; - vendor.qti.hardware.paleventnotifier.PalDeviceId[] prevDevices; - vendor.qti.hardware.paleventnotifier.PalDeviceId[] currentDevices; - vendor.qti.hardware.paleventnotifier.PalStreamAttributes streamAttributes; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalChannelInfo.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalChannelInfo.aidl deleted file mode 100755 index e6e3376e..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalChannelInfo.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalChannelInfo { - char channels; - byte[64] chMap; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalDeviceId.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalDeviceId.aidl deleted file mode 100755 index af42805a..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalDeviceId.aidl +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalDeviceId { - PAL_DEVICE_OUT_MIN = 0, - PAL_DEVICE_NONE = 1, - PAL_DEVICE_OUT_HANDSET = 2, - PAL_DEVICE_OUT_SPEAKER = 3, - PAL_DEVICE_OUT_WIRED_HEADSET = 4, - PAL_DEVICE_OUT_WIRED_HEADPHONE = 5, - PAL_DEVICE_OUT_LINE = 6, - PAL_DEVICE_OUT_BLUETOOTH_SCO = 7, - PAL_DEVICE_OUT_BLUETOOTH_A2DP = 8, - PAL_DEVICE_OUT_AUX_DIGITAL = 9, - PAL_DEVICE_OUT_HDMI = 10, - PAL_DEVICE_OUT_USB_DEVICE = 11, - PAL_DEVICE_OUT_USB_HEADSET = 12, - PAL_DEVICE_OUT_SPDIF = 13, - PAL_DEVICE_OUT_FM = 14, - PAL_DEVICE_OUT_AUX_LINE = 15, - PAL_DEVICE_OUT_PROXY = 16, - PAL_DEVICE_OUT_AUX_DIGITAL_1 = 17, - PAL_DEVICE_OUT_HEARING_AID = 18, - PAL_DEVICE_OUT_HAPTICS_DEVICE = 19, - PAL_DEVICE_OUT_ULTRASOUND = 20, - PAL_DEVICE_OUT_ULTRASOUND_DEDICATED = 21, - PAL_DEVICE_OUT_BLUETOOTH_BLE = 22, - PAL_DEVICE_OUT_BLUETOOTH_BLE_BROADCAST = 23, - PAL_DEVICE_OUT_DUMMY = 24, - PAL_DEVICE_OUT_RECORD_PROXY = 25, - PAL_DEVICE_OUT_MAX = 26, - PAL_DEVICE_IN_MIN = PAL_DEVICE_OUT_MAX /* 26 */, - PAL_DEVICE_IN_HANDSET_MIC = (PAL_DEVICE_IN_MIN + 1) /* 27 */, - PAL_DEVICE_IN_SPEAKER_MIC = (PAL_DEVICE_IN_MIN + 2) /* 28 */, - PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET = (PAL_DEVICE_IN_MIN + 3) /* 29 */, - PAL_DEVICE_IN_WIRED_HEADSET = (PAL_DEVICE_IN_MIN + 4) /* 30 */, - PAL_DEVICE_IN_AUX_DIGITAL = (PAL_DEVICE_IN_MIN + 5) /* 31 */, - PAL_DEVICE_IN_HDMI = (PAL_DEVICE_IN_MIN + 6) /* 32 */, - PAL_DEVICE_IN_USB_ACCESSORY = (PAL_DEVICE_IN_MIN + 7) /* 33 */, - PAL_DEVICE_IN_USB_DEVICE = (PAL_DEVICE_IN_MIN + 8) /* 34 */, - PAL_DEVICE_IN_USB_HEADSET = (PAL_DEVICE_IN_MIN + 9) /* 35 */, - PAL_DEVICE_IN_FM_TUNER = (PAL_DEVICE_IN_MIN + 10) /* 36 */, - PAL_DEVICE_IN_LINE = (PAL_DEVICE_IN_MIN + 11) /* 37 */, - PAL_DEVICE_IN_SPDIF = (PAL_DEVICE_IN_MIN + 12) /* 38 */, - PAL_DEVICE_IN_PROXY = (PAL_DEVICE_IN_MIN + 13) /* 39 */, - PAL_DEVICE_IN_HANDSET_VA_MIC = (PAL_DEVICE_IN_MIN + 14) /* 40 */, - PAL_DEVICE_IN_BLUETOOTH_A2DP = (PAL_DEVICE_IN_MIN + 15) /* 41 */, - PAL_DEVICE_IN_HEADSET_VA_MIC = (PAL_DEVICE_IN_MIN + 16) /* 42 */, - PAL_DEVICE_IN_VI_FEEDBACK = (PAL_DEVICE_IN_MIN + 17) /* 43 */, - PAL_DEVICE_IN_TELEPHONY_RX = (PAL_DEVICE_IN_MIN + 18) /* 44 */, - PAL_DEVICE_IN_ULTRASOUND_MIC = (PAL_DEVICE_IN_MIN + 19) /* 45 */, - PAL_DEVICE_IN_EXT_EC_REF = (PAL_DEVICE_IN_MIN + 20) /* 46 */, - PAL_DEVICE_IN_ECHO_REF = (PAL_DEVICE_IN_MIN + 21) /* 47 */, - PAL_DEVICE_IN_HAPTICS_VI_FEEDBACK = (PAL_DEVICE_IN_MIN + 22) /* 48 */, - PAL_DEVICE_IN_BLUETOOTH_BLE = (PAL_DEVICE_IN_MIN + 23) /* 49 */, - PAL_DEVICE_IN_CPS_FEEDBACK = (PAL_DEVICE_IN_MIN + 24) /* 50 */, - PAL_DEVICE_IN_DUMMY = (PAL_DEVICE_IN_MIN + 25) /* 51 */, - PAL_DEVICE_IN_CPS2_FEEDBACK = (PAL_DEVICE_IN_MIN + 26) /* 52 */, - PAL_DEVICE_IN_RECORD_PROXY = (PAL_DEVICE_IN_MIN + 27) /* 53 */, - PAL_DEVICE_IN_MAX = (PAL_DEVICE_IN_MIN + 28) /* 54 */, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalMediaConfig.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalMediaConfig.aidl deleted file mode 100755 index f309fc4b..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalMediaConfig.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalMediaConfig { - int sampleRate; - int bitwidth; - vendor.qti.hardware.paleventnotifier.PalChannelInfo chInfo; - vendor.qti.hardware.paleventnotifier.PalAudioFmt audioFormatId; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamAttributes.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamAttributes.aidl deleted file mode 100755 index ab0ecc33..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamAttributes.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalStreamAttributes { - vendor.qti.hardware.paleventnotifier.PalStreamType type; - vendor.qti.hardware.paleventnotifier.PalStreamInfo info; - vendor.qti.hardware.paleventnotifier.PalStreamFlag flags; - vendor.qti.hardware.paleventnotifier.PalStreamDirection direction; - vendor.qti.hardware.paleventnotifier.PalMediaConfig inMediaConfig; - vendor.qti.hardware.paleventnotifier.PalMediaConfig outMediaConfig; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamDirection.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamDirection.aidl deleted file mode 100755 index 273bf123..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamDirection.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalStreamDirection { - PAL_AUDIO_OUTPUT = 0x1, - PAL_AUDIO_INPUT = 0x2, - PAL_AUDIO_INPUT_OUTPUT = 0x3, - PAL_AUDIO_INVALID = 0x4, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamFlag.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamFlag.aidl deleted file mode 100755 index d4ad3c12..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamFlag.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalStreamFlag { - PAL_STREAM_FLAG_TIMESTAMP = 0x1, - PAL_STREAM_FLAG_NON_BLOCKING = 0x2, - PAL_STREAM_FLAG_MMAP = 0x4, - PAL_STREAM_FLAG_MMAP_NO_IRQ = 0x8, - PAL_STREAM_FLAG_EXTERN_MEM = 0x10, - PAL_STREAM_FLAG_SRCM_INBAND = 0x20, - PAL_STREAM_FLAG_INVALID, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamInfo.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamInfo.aidl deleted file mode 100755 index f987b6ab..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamInfo.aidl +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@VintfStability -parcelable PalStreamInfo { - long version; - long size; - long durationUs; - boolean hasVideo; - int txProxyType; - int rxProxyType; - boolean isStreaming; - int loopbackType; - int hapticsType; -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamType.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamType.aidl deleted file mode 100755 index e1b84349..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/PalStreamType.aidl +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum PalStreamType { - PAL_STREAM_LOW_LATENCY = 1, - PAL_STREAM_DEEP_BUFFER = 2, - PAL_STREAM_COMPRESSED = 3, - PAL_STREAM_VOIP = 4, - PAL_STREAM_VOIP_RX = 5, - PAL_STREAM_VOIP_TX = 6, - PAL_STREAM_VOICE_CALL_MUSIC = 7, - PAL_STREAM_GENERIC = 8, - PAL_STREAM_RAW = 9, - PAL_STREAM_VOICE_RECOGNITION = 10, - PAL_STREAM_VOICE_CALL_RECORD = 11, - PAL_STREAM_VOICE_CALL_TX = 12, - PAL_STREAM_VOICE_CALL_RX_TX = 13, - PAL_STREAM_VOICE_CALL = 14, - PAL_STREAM_LOOPBACK = 15, - PAL_STREAM_TRANSCODE = 16, - PAL_STREAM_VOICE_UI = 17, - PAL_STREAM_PCM_OFFLOAD = 18, - PAL_STREAM_ULTRA_LOW_LATENCY = 19, - PAL_STREAM_PROXY = 20, - PAL_STREAM_NON_TUNNEL = 21, - PAL_STREAM_HAPTICS = 22, - PAL_STREAM_ACD = 23, - PAL_STREAM_CONTEXT_PROXY = 24, - PAL_STREAM_SENSOR_PCM_DATA = 25, - PAL_STREAM_ULTRASOUND = 26, - PAL_STREAM_SPATIAL_AUDIO = 27, -} diff --git a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/Status.aidl b/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/Status.aidl deleted file mode 100755 index 1971838f..00000000 --- a/qcom/opensource/commonsys-intf/audio/aidl_api/vendor.qti.hardware.paleventnotifier/current/vendor/qti/hardware/paleventnotifier/Status.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.paleventnotifier; -@Backing(type="int") @VintfStability -enum Status { - UNKNOWN = (-1) /* -1 */, - SUCCESS = 0, - IO_ERROR, - BUSY, - NO_SPACE, - INVALID_FD, - ADVERTISE_ERROR, - PROTOCOL_NOT_AVAILABLE, - NOT_SUPPORTED, - DOWN_WITH_SSR, - NOW_INPROGRESS, - ALREADY_INPROGRESS, - CANCELLED, - NOT_RECOVERABLE, -} diff --git a/qcom/opensource/commonsys-intf/audio/ams/current.txt b/qcom/opensource/commonsys-intf/audio/ams/current.txt deleted file mode 100755 index ff051627..00000000 --- a/qcom/opensource/commonsys-intf/audio/ams/current.txt +++ /dev/null @@ -1,2 +0,0 @@ -6b0951f26301a69b992c4e32ffc2b138421364f0ec7ebc008aff730bf5c17cea vendor.qti.hardware.AMSIPC@1.0::types -c587d2afcdb5515ea90cb04e7756f3710a95497dd5a6dfaad14da9149566e0a2 vendor.qti.hardware.AMSIPC@1.0::IAMS diff --git a/qcom/opensource/commonsys-intf/audio/pal/current.txt b/qcom/opensource/commonsys-intf/audio/pal/current.txt deleted file mode 100755 index acd8a0df..00000000 --- a/qcom/opensource/commonsys-intf/audio/pal/current.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (c) 2020, The Linux Foundation. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials provided -# with the distribution. -# * Neither the name of The Linux Foundation nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -8f6dbce99b3683c75e2deffd6cec20acdeb1b5d6cfe6067e28668b437366be1f vendor.qti.hardware.pal@1.0::types -0c0044fa5fe7fe10fcb1fdd37c2d794894e76167fcf44e5a1cc1a4cf97fbf784 vendor.qti.hardware.pal@1.0::IPAL -af350d9ab3a17fceee66276978a27c90e74fa21ab741c3b3030a021ec1111c9d vendor.qti.hardware.pal@1.0::IPALCallback diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/IPALEventNotifier.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/IPALEventNotifier.aidl deleted file mode 100755 index f585e789..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/IPALEventNotifier.aidl +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -import vendor.qti.hardware.paleventnotifier.IPALEventNotifierCallback; - -@VintfStability -interface IPALEventNotifier { - - int ipc_pal_notify_register_callback(in IPALEventNotifierCallback callback); - -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/IPALEventNotifierCallback.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/IPALEventNotifierCallback.aidl deleted file mode 100755 index cfe8f275..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/IPALEventNotifierCallback.aidl +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -import vendor.qti.hardware.paleventnotifier.PalCallbackConfig; - -@VintfStability -interface IPALEventNotifierCallback { - oneway void onStart(in PalCallbackConfig Config); - oneway void onStop(in PalCallbackConfig Config); - oneway void onDeviceSwitch(in PalCallbackConfig Config); -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalAudioFmt.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalAudioFmt.aidl deleted file mode 100755 index f334e48e..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalAudioFmt.aidl +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -/** - * PAL Audio format enumeration - */ -@VintfStability -@Backing(type="int") -enum PalAudioFmt { - PAL_AUDIO_FMT_DEFAULT_PCM = 0x1, - PAL_AUDIO_FMT_PCM_S16_LE = PAL_AUDIO_FMT_DEFAULT_PCM, - PAL_AUDIO_FMT_DEFAULT_COMPRESSED = 0x2, - PAL_AUDIO_FMT_MP3 = PAL_AUDIO_FMT_DEFAULT_COMPRESSED, - PAL_AUDIO_FMT_AAC = 0x3, - PAL_AUDIO_FMT_AAC_ADTS = 0x4, - PAL_AUDIO_FMT_AAC_ADIF = 0x5, - PAL_AUDIO_FMT_AAC_LATM = 0x6, - PAL_AUDIO_FMT_WMA_STD = 0x7, - PAL_AUDIO_FMT_ALAC = 0x8, - PAL_AUDIO_FMT_APE = 0x9, - PAL_AUDIO_FMT_WMA_PRO = 0xA, - PAL_AUDIO_FMT_FLAC = 0xB, - PAL_AUDIO_FMT_FLAC_OGG = 0xC, - PAL_AUDIO_FMT_VORBIS = 0xD, - PAL_AUDIO_FMT_AMR_NB = 0xE, - PAL_AUDIO_FMT_AMR_WB = 0xF, - PAL_AUDIO_FMT_AMR_WB_PLUS = 0x10, - PAL_AUDIO_FMT_EVRC = 0x11, - PAL_AUDIO_FMT_G711 = 0x12, - PAL_AUDIO_FMT_QCELP = 0x13, - PAL_AUDIO_FMT_PCM_S8 = 0x14, - PAL_AUDIO_FMT_PCM_S24_3LE = 0x15, - PAL_AUDIO_FMT_PCM_S24_LE = 0x16, - PAL_AUDIO_FMT_PCM_S32_LE = 0x17, - PAL_AUDIO_FMT_OPUS = 0x18, - PAL_AUDIO_FMT_COMPRESSED_RANGE_BEGIN = 0xF0000000, - PAL_AUDIO_FMT_COMPRESSED_EXTENDED_RANGE_BEGIN = 0xF0000F00, - PAL_AUDIO_FMT_COMPRESSED_EXTENDED_RANGE_END = 0xF0000FFF, - PAL_AUDIO_FMT_COMPRESSED_RANGE_END = PAL_AUDIO_FMT_COMPRESSED_EXTENDED_RANGE_END, -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalCallbackConfig.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalCallbackConfig.aidl deleted file mode 100755 index eed49c5e..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalCallbackConfig.aidl +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -import vendor.qti.hardware.paleventnotifier.PalDeviceId; -import vendor.qti.hardware.paleventnotifier.PalStreamAttributes; - -@VintfStability -parcelable PalCallbackConfig { - int noOfPrevDevices; - int noOfCurrentDevices; - PalDeviceId[] prevDevices; - PalDeviceId[] currentDevices; - PalStreamAttributes streamAttributes; -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalChannelInfo.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalChannelInfo.aidl deleted file mode 100755 index 5b956f0a..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalChannelInfo.aidl +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -/** - * Audio channel info data structure - */ -@VintfStability -parcelable PalChannelInfo { - char channels; - byte[64] chMap; -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalDeviceId.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalDeviceId.aidl deleted file mode 100755 index 1e4ddc5a..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalDeviceId.aidl +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -@VintfStability -@Backing(type="int") -enum PalDeviceId { - PAL_DEVICE_OUT_MIN = 0, - PAL_DEVICE_NONE = 1, /**< for transcode usecases*/ - PAL_DEVICE_OUT_HANDSET = 2, - PAL_DEVICE_OUT_SPEAKER = 3, - PAL_DEVICE_OUT_WIRED_HEADSET = 4, - PAL_DEVICE_OUT_WIRED_HEADPHONE = 5, /**< Wired headphones without mic*/ - PAL_DEVICE_OUT_LINE = 6, - PAL_DEVICE_OUT_BLUETOOTH_SCO = 7, - PAL_DEVICE_OUT_BLUETOOTH_A2DP = 8, - PAL_DEVICE_OUT_AUX_DIGITAL = 9, - PAL_DEVICE_OUT_HDMI = 10, - PAL_DEVICE_OUT_USB_DEVICE = 11, - PAL_DEVICE_OUT_USB_HEADSET = 12, - PAL_DEVICE_OUT_SPDIF = 13, - PAL_DEVICE_OUT_FM = 14, - PAL_DEVICE_OUT_AUX_LINE = 15, - PAL_DEVICE_OUT_PROXY = 16, - PAL_DEVICE_OUT_AUX_DIGITAL_1 = 17, - PAL_DEVICE_OUT_HEARING_AID = 18, - PAL_DEVICE_OUT_HAPTICS_DEVICE = 19, - PAL_DEVICE_OUT_ULTRASOUND = 20, - PAL_DEVICE_OUT_ULTRASOUND_DEDICATED = 21, - PAL_DEVICE_OUT_BLUETOOTH_BLE = 22, - PAL_DEVICE_OUT_BLUETOOTH_BLE_BROADCAST = 23, - PAL_DEVICE_OUT_DUMMY = 24, - PAL_DEVICE_OUT_RECORD_PROXY = 25, - // Add new OUT devices here, increment MAX and MIN below when you do so - PAL_DEVICE_OUT_MAX = 26, - //INPUT DEVICES - PAL_DEVICE_IN_MIN = PAL_DEVICE_OUT_MAX, - PAL_DEVICE_IN_HANDSET_MIC = PAL_DEVICE_IN_MIN +1, - PAL_DEVICE_IN_SPEAKER_MIC = PAL_DEVICE_IN_MIN + 2, - PAL_DEVICE_IN_BLUETOOTH_SCO_HEADSET = PAL_DEVICE_IN_MIN + 3, - PAL_DEVICE_IN_WIRED_HEADSET = PAL_DEVICE_IN_MIN + 4, - PAL_DEVICE_IN_AUX_DIGITAL = PAL_DEVICE_IN_MIN + 5, - PAL_DEVICE_IN_HDMI = PAL_DEVICE_IN_MIN + 6, - PAL_DEVICE_IN_USB_ACCESSORY = PAL_DEVICE_IN_MIN + 7, - PAL_DEVICE_IN_USB_DEVICE = PAL_DEVICE_IN_MIN + 8, - PAL_DEVICE_IN_USB_HEADSET = PAL_DEVICE_IN_MIN + 9, - PAL_DEVICE_IN_FM_TUNER = PAL_DEVICE_IN_MIN + 10, - PAL_DEVICE_IN_LINE = PAL_DEVICE_IN_MIN + 11, - PAL_DEVICE_IN_SPDIF = PAL_DEVICE_IN_MIN + 12, - PAL_DEVICE_IN_PROXY = PAL_DEVICE_IN_MIN + 13, - PAL_DEVICE_IN_HANDSET_VA_MIC = PAL_DEVICE_IN_MIN + 14, - PAL_DEVICE_IN_BLUETOOTH_A2DP = PAL_DEVICE_IN_MIN + 15, - PAL_DEVICE_IN_HEADSET_VA_MIC = PAL_DEVICE_IN_MIN + 16, - PAL_DEVICE_IN_VI_FEEDBACK = PAL_DEVICE_IN_MIN + 17, - PAL_DEVICE_IN_TELEPHONY_RX = PAL_DEVICE_IN_MIN + 18, - PAL_DEVICE_IN_ULTRASOUND_MIC = PAL_DEVICE_IN_MIN +19, - PAL_DEVICE_IN_EXT_EC_REF = PAL_DEVICE_IN_MIN + 20, - PAL_DEVICE_IN_ECHO_REF = PAL_DEVICE_IN_MIN + 21, - PAL_DEVICE_IN_HAPTICS_VI_FEEDBACK = PAL_DEVICE_IN_MIN + 22, - PAL_DEVICE_IN_BLUETOOTH_BLE = PAL_DEVICE_IN_MIN + 23, - PAL_DEVICE_IN_CPS_FEEDBACK = PAL_DEVICE_IN_MIN + 24, - PAL_DEVICE_IN_DUMMY = PAL_DEVICE_IN_MIN + 25, - PAL_DEVICE_IN_CPS2_FEEDBACK = PAL_DEVICE_IN_MIN + 26, - PAL_DEVICE_IN_RECORD_PROXY = PAL_DEVICE_IN_MIN + 27, - // Add new IN devices here, increment MAX and MIN below when you do so - PAL_DEVICE_IN_MAX = PAL_DEVICE_IN_MIN + 28, -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalMediaConfig.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalMediaConfig.aidl deleted file mode 100755 index a83ff9fa..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalMediaConfig.aidl +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -import vendor.qti.hardware.paleventnotifier.PalAudioFmt; -import vendor.qti.hardware.paleventnotifier.PalChannelInfo; - -/** - * Media configuraiton - */ -@VintfStability -parcelable PalMediaConfig { - int sampleRate; - int bitwidth; - PalChannelInfo chInfo; - PalAudioFmt audioFormatId; -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamAttributes.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamAttributes.aidl deleted file mode 100755 index 6aeff8cc..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamAttributes.aidl +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -import vendor.qti.hardware.paleventnotifier.PalMediaConfig; -import vendor.qti.hardware.paleventnotifier.PalStreamDirection; -import vendor.qti.hardware.paleventnotifier.PalStreamFlag; -import vendor.qti.hardware.paleventnotifier.PalStreamInfo; -import vendor.qti.hardware.paleventnotifier.PalStreamType; - -/** - * < PAL stream attributes to be specified, used in pal_stream_open cmd - */ -@VintfStability -parcelable PalStreamAttributes { - PalStreamType type; - PalStreamInfo info; - PalStreamFlag flags; - PalStreamDirection direction; - PalMediaConfig inMediaConfig; - PalMediaConfig outMediaConfig; -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamDirection.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamDirection.aidl deleted file mode 100755 index 69642131..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamDirection.aidl +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -/** - * Audio stream direction enumeration - */ -@VintfStability -@Backing(type="int") -enum PalStreamDirection { - PAL_AUDIO_OUTPUT = 0x1, - PAL_AUDIO_INPUT = 0x2, - PAL_AUDIO_INPUT_OUTPUT = 0x3, - PAL_AUDIO_INVALID = 0x4, -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamFlag.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamFlag.aidl deleted file mode 100755 index 13140ac8..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamFlag.aidl +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -/** - * Available stream flags of an audio session - */ -@VintfStability -@Backing(type="int") -enum PalStreamFlag { - PAL_STREAM_FLAG_TIMESTAMP = 0x1, - PAL_STREAM_FLAG_NON_BLOCKING = 0x2, - PAL_STREAM_FLAG_MMAP = 0x4, - PAL_STREAM_FLAG_MMAP_NO_IRQ = 0x8, - PAL_STREAM_FLAG_EXTERN_MEM = 0x10, - PAL_STREAM_FLAG_SRCM_INBAND = 0x20, - PAL_STREAM_FLAG_INVALID, -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamInfo.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamInfo.aidl deleted file mode 100755 index 032eb505..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamInfo.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -@VintfStability -parcelable PalStreamInfo { - long version; - long size; - long durationUs; - boolean hasVideo; - int txProxyType; - int rxProxyType; - boolean isStreaming; - int loopbackType; - int hapticsType; -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamType.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamType.aidl deleted file mode 100755 index 7c4225be..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/PalStreamType.aidl +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -/** - * Audio stream types - */ -@VintfStability -@Backing(type="int") -enum PalStreamType { - PAL_STREAM_LOW_LATENCY = 1, - /** - * < :low latency, higher power - */ - PAL_STREAM_DEEP_BUFFER = 2, - /** - * < :low power, higher latency - */ - PAL_STREAM_COMPRESSED = 3, - /** - * < :compresssed audio - */ - PAL_STREAM_VOIP = 4, - /** - * < :pcm voip audio - */ - PAL_STREAM_VOIP_RX = 5, - /** - * < :pcm voip audio downlink - */ - PAL_STREAM_VOIP_TX = 6, - /** - * < :pcm voip audio uplink - */ - PAL_STREAM_VOICE_CALL_MUSIC = 7, - /** - * < :incall music - */ - PAL_STREAM_GENERIC = 8, - /** - * < :generic playback audio - */ - PAL_STREAM_RAW = 9, - /** - * < pcm no post processing - */ - PAL_STREAM_VOICE_RECOGNITION = 10, - /** - * < voice recognition - */ - PAL_STREAM_VOICE_CALL_RECORD = 11, - /** - * < incall record - */ - PAL_STREAM_VOICE_CALL_TX = 12, - /** - * < incall record, uplink - */ - PAL_STREAM_VOICE_CALL_RX_TX = 13, - /** - * < incall record, uplink & Downlink - */ - PAL_STREAM_VOICE_CALL = 14, - /** - * < voice call - */ - PAL_STREAM_LOOPBACK = 15, - /** - * < loopback - */ - PAL_STREAM_TRANSCODE = 16, - /** - * < audio transcode - */ - PAL_STREAM_VOICE_UI = 17, - /** - * < voice ui - */ - PAL_STREAM_PCM_OFFLOAD = 18, - /** - * < pcm offload audio - */ - PAL_STREAM_ULTRA_LOW_LATENCY = 19, - /** - * < pcm ULL audio - */ - PAL_STREAM_PROXY = 20, - /** - * < pcm proxy audio - */ - PAL_STREAM_NON_TUNNEL = 21, - /** - * < NT Mode session - */ - PAL_STREAM_HAPTICS = 22, - /** - * < Haptics Stream - */ - PAL_STREAM_ACD = 23, - /** - * < ACD Stream - */ - PAL_STREAM_CONTEXT_PROXY = 24, - /** - * < Context Proxy Stream - */ - PAL_STREAM_SENSOR_PCM_DATA = 25, - /** - * < Sensor PCM Data Stream - */ - PAL_STREAM_ULTRASOUND = 26, - /** - * < Ultrasound Proximity detection - */ - PAL_STREAM_SPATIAL_AUDIO = 27, -} diff --git a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/Status.aidl b/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/Status.aidl deleted file mode 100755 index 505e937e..00000000 --- a/qcom/opensource/commonsys-intf/audio/vendor/qti/hardware/paleventnotifier/Status.aidl +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.paleventnotifier; - -@Backing(type="int") @VintfStability -enum Status { - UNKNOWN = -1, - SUCCESS = 0, - IO_ERROR, - BUSY, - NO_SPACE, - INVALID_FD, - ADVERTISE_ERROR, - PROTOCOL_NOT_AVAILABLE, - NOT_SUPPORTED, - DOWN_WITH_SSR, - NOW_INPROGRESS, - ALREADY_INPROGRESS, - CANCELLED, - NOT_RECOVERABLE, -} diff --git a/qcom/opensource/commonsys-intf/display/Android.bp b/qcom/opensource/commonsys-intf/display/Android.bp index 408e9046..1e4931a1 100755 --- a/qcom/opensource/commonsys-intf/display/Android.bp +++ b/qcom/opensource/commonsys-intf/display/Android.bp @@ -1,5 +1,6 @@ cc_library_headers { name: "display_intf_headers", + enabled: false, vendor_available: true, export_include_dirs: [ "gralloc", diff --git a/qcom/opensource/commonsys-intf/display/aidl/aiqe/Android.bp b/qcom/opensource/commonsys-intf/display/aidl/aiqe/Android.bp deleted file mode 100755 index 909aa72f..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/aiqe/Android.bp +++ /dev/null @@ -1,35 +0,0 @@ -aidl_interface { - name: "vendor.qti.hardware.display.aiqe", - vendor_available: true, - owner: "qti", - srcs: ["vendor/qti/hardware/display/aiqe/*.aidl"], - stability: "vintf", - backend: { - cpp: { - enabled: false, - }, - java: { - enabled: true, - sdk_version: "module_current", - }, - ndk: { - enabled: true, - }, - }, - versions_with_info: [ - { - version: "1", - imports: [], - }, - { - version: "2", - imports: [], - }, - { - version: "3", - imports: [], - }, - - ], - frozen: true, -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/1/.hash b/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/1/.hash deleted file mode 100755 index 9703ef52..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/1/.hash +++ /dev/null @@ -1 +0,0 @@ -c31a3caf975b3ef452b146660e13f51c248fa31e diff --git a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/1/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl b/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/1/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl deleted file mode 100755 index 0c3caaad..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/1/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.display.aiqe; -@VintfStability -interface IDisplayAiqe { - void setSsrcMode(in int disp_id, in String mode_name); - void enableCopr(in int disp_id, in boolean enable); - int[] getCoprStats(in int disp_id); -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/2/.hash b/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/2/.hash deleted file mode 100755 index cabafaa9..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/2/.hash +++ /dev/null @@ -1 +0,0 @@ -5a9915340b07c7501cfca4107ada6c15474402b1 diff --git a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/2/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl b/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/2/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl deleted file mode 100755 index 698b0ca1..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/2/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Changes from Qualcomm Innovation Center, Inc. are provided under the following license: - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.display.aiqe; -@VintfStability -interface IDisplayAiqe { - void setSsrcMode(in int disp_id, in String mode_name); - void enableCopr(in int disp_id, in boolean enable); - int[] getCoprStats(in int disp_id); - void setABCState(in int dispId, in int enable); - void setABCReconfig(in int dispId); - void setABCMode(in int dispId, in String mode_name); -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/3/.hash b/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/3/.hash deleted file mode 100755 index a5d26865..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/3/.hash +++ /dev/null @@ -1 +0,0 @@ -1862f2ce86c1703b98e994b5d200c2b58dd8661b diff --git a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/3/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl b/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/3/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl deleted file mode 100755 index 78d487d0..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/3/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.display.aiqe; -@VintfStability -interface IDisplayAiqe { - void setSsrcMode(in int disp_id, in String mode_name); - void enableCopr(in int disp_id, in boolean enable); - int[] getCoprStats(in int disp_id); - void setABCState(in int dispId, in int enable); - void setABCReconfig(in int dispId); - void setABCMode(in int dispId, in String mode_name); - void setMdnieMode(in String mode_name); -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/current/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl b/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/current/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl deleted file mode 100755 index 78d487d0..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/aiqe/aidl_api/vendor.qti.hardware.display.aiqe/current/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.display.aiqe; -@VintfStability -interface IDisplayAiqe { - void setSsrcMode(in int disp_id, in String mode_name); - void enableCopr(in int disp_id, in boolean enable); - int[] getCoprStats(in int disp_id); - void setABCState(in int dispId, in int enable); - void setABCReconfig(in int dispId); - void setABCMode(in int dispId, in String mode_name); - void setMdnieMode(in String mode_name); -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/aiqe/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl b/qcom/opensource/commonsys-intf/display/aidl/aiqe/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl deleted file mode 100755 index 3831d9b8..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/aiqe/vendor/qti/hardware/display/aiqe/IDisplayAiqe.aidl +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - - package vendor.qti.hardware.display.aiqe; - - @VintfStability -interface IDisplayAiqe { - /** - * Set the active SSRC mode for the specified display. - * The SSRC feature must be active for this to have an effect - * - * @param dispId ID of the display to target. - * @param mode_name Name of the SSRC mode to set. - * @return OK on success or error if any parameters are invalid. - */ - void setSsrcMode(in int disp_id, in String mode_name); - /** - * Enable COPR feature for the specified display. - * - * @param dispId ID of the display to target. - * @param enable enable/disable COPR feature - * @return OK on success or error if any parameters are invalid. - */ - void enableCopr(in int disp_id, in boolean enable); - /** - * Query the COPR statistics for the specified display. - * COPR feature must be active for this to work - * - * @param dispId ID of the display to target. - * @return vector of COPR statistic data - */ - int[] getCoprStats(in int disp_id); - /** - * Set ABC feature State - * - * @param dispId ID of the display to target. - * @param enable control ABC feature enable/disable - * @return error is NONE upon success - */ - void setABCState(in int dispId, in int enable); - /** - * Set ABC feature Reconfig - * - * @param dispId ID of the display to target. - * @return error is NONE upon success - */ - void setABCReconfig(in int dispId); - /** - * Set ABC feature mode - * - * @param dispId ID of the display to target. - * @param mode name of the ABC feature - * @return error is NONE upon success - */ - void setABCMode(in int dispId, in String mode_name); - - /** - * Set the Mdnie mode. - * - * @param mode_name Name of the Mdnie Mode to set. - * @return OK on success or error if any parameters are invalid. - */ - void setMdnieMode(in String mode_name); -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/demura/Android.bp b/qcom/opensource/commonsys-intf/display/aidl/demura/Android.bp deleted file mode 100755 index 18a6fdc3..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/demura/Android.bp +++ /dev/null @@ -1,24 +0,0 @@ -aidl_interface { - name: "vendor.qti.hardware.display.demura", - owner: "qti", - vendor_available: true, - srcs: ["vendor/qti/hardware/display/demura/*.aidl"], - stability: "vintf", - backend: { - cpp: { - enabled: false, - }, - java: { - sdk_version: "module_current", - }, - ndk: { - enabled: true, - }, - }, - versions_with_info: [ - { - version: "1", - imports: [], - }, - ], -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/demura/aidl_api/vendor.qti.hardware.display.demura/1/.hash b/qcom/opensource/commonsys-intf/display/aidl/demura/aidl_api/vendor.qti.hardware.display.demura/1/.hash deleted file mode 100755 index 112d9ae2..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/demura/aidl_api/vendor.qti.hardware.display.demura/1/.hash +++ /dev/null @@ -1 +0,0 @@ -e333c843c65c9b04c9b18f0231caef5e077682ae diff --git a/qcom/opensource/commonsys-intf/display/aidl/demura/aidl_api/vendor.qti.hardware.display.demura/1/vendor/qti/hardware/display/demura/IDemuraFileFinder.aidl b/qcom/opensource/commonsys-intf/display/aidl/demura/aidl_api/vendor.qti.hardware.display.demura/1/vendor/qti/hardware/display/demura/IDemuraFileFinder.aidl deleted file mode 100755 index 31bd1eb0..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/demura/aidl_api/vendor.qti.hardware.display.demura/1/vendor/qti/hardware/display/demura/IDemuraFileFinder.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.display.demura; -@VintfStability -interface IDemuraFileFinder { - void getDemuraFilePaths(in long panel_id, out vendor.qti.hardware.display.demura.IDemuraFileFinder.DemuraFilePaths file_paths); - @VintfStability - parcelable DemuraFilePaths { - String configFilePath; - String signatureFilePath; - String publickeyFilePath; - } -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/demura/aidl_api/vendor.qti.hardware.display.demura/current/vendor/qti/hardware/display/demura/IDemuraFileFinder.aidl b/qcom/opensource/commonsys-intf/display/aidl/demura/aidl_api/vendor.qti.hardware.display.demura/current/vendor/qti/hardware/display/demura/IDemuraFileFinder.aidl deleted file mode 100755 index 31bd1eb0..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/demura/aidl_api/vendor.qti.hardware.display.demura/current/vendor/qti/hardware/display/demura/IDemuraFileFinder.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.display.demura; -@VintfStability -interface IDemuraFileFinder { - void getDemuraFilePaths(in long panel_id, out vendor.qti.hardware.display.demura.IDemuraFileFinder.DemuraFilePaths file_paths); - @VintfStability - parcelable DemuraFilePaths { - String configFilePath; - String signatureFilePath; - String publickeyFilePath; - } -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/demura/vendor/qti/hardware/display/demura/IDemuraFileFinder.aidl b/qcom/opensource/commonsys-intf/display/aidl/demura/vendor/qti/hardware/display/demura/IDemuraFileFinder.aidl deleted file mode 100755 index 4d5d02f4..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/demura/vendor/qti/hardware/display/demura/IDemuraFileFinder.aidl +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.display.demura; - -@VintfStability -interface IDemuraFileFinder { - @VintfStability - parcelable DemuraFilePaths { - String configFilePath; - String signatureFilePath; - String publickeyFilePath; - } - - /** - * Get file paths of demura files - * @param panel_id id of panel - * @param out file_paths paths of demura files - */ - void getDemuraFilePaths(in long panel_id, out DemuraFilePaths file_paths); -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/postproc/Android.bp b/qcom/opensource/commonsys-intf/display/aidl/postproc/Android.bp deleted file mode 100755 index 9fe59967..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/postproc/Android.bp +++ /dev/null @@ -1,25 +0,0 @@ -aidl_interface { - name: "vendor.qti.hardware.display.postproc", - vendor_available: true, - owner: "qti", - srcs: ["vendor/qti/hardware/display/postproc/*.aidl"], - stability: "vintf", - backend: { - cpp: { - enabled: false, - }, - java: { - enabled: true, - sdk_version: "module_current", - }, - ndk: { - enabled: true, - }, - }, - versions_with_info: [ - { - version: "1", - imports: [], - }, - ], -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/postproc/aidl_api/vendor.qti.hardware.display.postproc/1/.hash b/qcom/opensource/commonsys-intf/display/aidl/postproc/aidl_api/vendor.qti.hardware.display.postproc/1/.hash deleted file mode 100755 index f549ecab..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/postproc/aidl_api/vendor.qti.hardware.display.postproc/1/.hash +++ /dev/null @@ -1 +0,0 @@ -717b637207e7b53e81228f9ebc0b2418cf873f2b diff --git a/qcom/opensource/commonsys-intf/display/aidl/postproc/aidl_api/vendor.qti.hardware.display.postproc/1/vendor/qti/hardware/display/postproc/IDisplayPostproc.aidl b/qcom/opensource/commonsys-intf/display/aidl/postproc/aidl_api/vendor.qti.hardware.display.postproc/1/vendor/qti/hardware/display/postproc/IDisplayPostproc.aidl deleted file mode 100755 index 235806ba..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/postproc/aidl_api/vendor.qti.hardware.display.postproc/1/vendor/qti/hardware/display/postproc/IDisplayPostproc.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.display.postproc; -@VintfStability -interface IDisplayPostproc { - String sendDPPSCommand(in String cmd); -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/postproc/aidl_api/vendor.qti.hardware.display.postproc/current/vendor/qti/hardware/display/postproc/IDisplayPostproc.aidl b/qcom/opensource/commonsys-intf/display/aidl/postproc/aidl_api/vendor.qti.hardware.display.postproc/current/vendor/qti/hardware/display/postproc/IDisplayPostproc.aidl deleted file mode 100755 index 235806ba..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/postproc/aidl_api/vendor.qti.hardware.display.postproc/current/vendor/qti/hardware/display/postproc/IDisplayPostproc.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package vendor.qti.hardware.display.postproc; -@VintfStability -interface IDisplayPostproc { - String sendDPPSCommand(in String cmd); -} diff --git a/qcom/opensource/commonsys-intf/display/aidl/postproc/vendor/qti/hardware/display/postproc/IDisplayPostproc.aidl b/qcom/opensource/commonsys-intf/display/aidl/postproc/vendor/qti/hardware/display/postproc/IDisplayPostproc.aidl deleted file mode 100755 index c3268616..00000000 --- a/qcom/opensource/commonsys-intf/display/aidl/postproc/vendor/qti/hardware/display/postproc/IDisplayPostproc.aidl +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package vendor.qti.hardware.display.postproc; - -@VintfStability -interface IDisplayPostproc { - /** - * Send command to DPPS. - * @param cmd string command to control post processing features. - * @return response string response for the input dpps command. - */ - String sendDPPSCommand(in String cmd); -} diff --git a/qcom/opensource/commonsys/audio/hal_adapter/Android.bp b/qcom/opensource/commonsys/audio/hal_adapter/Android.bp deleted file mode 100755 index 3be77074..00000000 --- a/qcom/opensource/commonsys/audio/hal_adapter/Android.bp +++ /dev/null @@ -1,56 +0,0 @@ -aidl_interface { - name: "qti-audio-types-aidl", - stability: "vintf", - owner: "qcom", - system_ext_specific: true, - vendor_available: true, - local_include_dir: "aidl", - srcs: [ - "aidl/qti/audio/core/VString.aidl", - ], - backend: { - cpp: { - enabled: false, - }, - java: { - enabled: false, - }, - }, - versions_with_info: [ - { - version: "1", - imports: [], - }, - - ], - frozen: true, -} - -cc_library { - name: "libaudiohalvendorextn", - system_ext_specific: true, - srcs: ["HalAdapterVendorExtension.cpp"], - - export_include_dirs: [ - "include", - ], - - header_libs: [ - "libsystem_headers", - ], - - shared_libs: [ - "av-audio-types-aidl-V1-ndk", - "libbinder_ndk", - "libbase", - "qti-audio-types-aidl-V1-ndk", - ], - - cflags: [ - "-Wall", - "-Wextra", - "-Werror", - "-Wthread-safety", - "-DBACKEND_NDK", - ], -} diff --git a/qcom/opensource/commonsys/audio/hal_adapter/HalAdapterVendorExtension.cpp b/qcom/opensource/commonsys/audio/hal_adapter/HalAdapterVendorExtension.cpp deleted file mode 100755 index 0cb6cb89..00000000 --- a/qcom/opensource/commonsys/audio/hal_adapter/HalAdapterVendorExtension.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2023-2024 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#define LOG_TAG "QHAVExt" - -#include -#include -#include -#include -#include -#include -#include - -#include - -// no headers below these - -namespace qti::audio::core { - -/* sfsfc;dvfrg=1;yupp => {sfsfc,dvfrg=1,yupp} */ -auto getVectorFromString = - [](const std::string& keyString) -> std::vector { - const auto keyLength = keyString.length(); - if (keyString.length() == 0) { - return {}; - } - std::vector result; - size_t i = 0; - const std::string delimiter{";"}; - size_t foundPos = 0; - while ((foundPos = keyString.find(delimiter, i)) != std::string::npos) { - std::cout << "foundPos: " << foundPos << std::endl; - std::string key = keyString.substr(i, foundPos - i); - key.empty() ? (void)0 : (void)result.push_back(key); - i = foundPos + 1; - } - if (i != keyLength) { - std::string key = keyString.substr(i, keyLength); - result.push_back(key); - } - return result; -}; - -/* {sfsfc=???,one=1,yupp=okay} => {{sfsfc,???},{one,1},{yupp,okay}} */ -auto getPairsFromVector = [](const std::vector& keyValues) { - std::vector> keyValuePairs; - for (const auto& keyValue : keyValues) { - const std::string delimiter{"="}; - auto foundPos = keyValue.find(delimiter, 0); - if (foundPos == std::string::npos) { - keyValuePairs.push_back({keyValue, ""}); - continue; - } - std::string key = keyValue.substr(0, foundPos); - std::string value = keyValue.substr(foundPos + 1, keyValue.size()); - keyValuePairs.push_back({key, value}); - } - return keyValuePairs; -}; - -::aidl::android::hardware::audio::core::VendorParameter -getVendorParameterAsVString(const std::string& key, const std::string& value) { - ::aidl::android::hardware::audio::core::VendorParameter param; - ::aidl::qti::audio::core::VString parcel; - param.id = key; - parcel.value = value; - if (param.ext.setParcelable(parcel) != android::OK) { - LOG(ERROR) << __func__ << ": failed to set parcel for " - << parcel.descriptor; - } - return std::move(param); -} - -std::optional getStringForVendorParameterAsVString( - const ::aidl::android::hardware::audio::core::VendorParameter& param) { - std::optional<::aidl::qti::audio::core::VString> parcel; - param.ext.getParcelable(&parcel); - if (!parcel.has_value()) { - LOG(ERROR) << __func__ - << " unable to get parcelable for key:" << param.id; - return std::nullopt; - } - return param.id + "=" + parcel.value().value; -} - -::ndk::ScopedAStatus HalAdapterVendorExtension::parseVendorParameterIds( - ::aidl::android::media::audio::IHalAdapterVendorExtension::ParameterScope - in_scope, - const std::string& in_rawKeys, std::vector* _aidl_return) { - *_aidl_return = getVectorFromString(in_rawKeys); - - LOG(VERBOSE) << __func__ - << ": scope:" << ::aidl::android::media::audio::toString(in_scope) - << ", raw keys:" << in_rawKeys << " ==> VendorParameter Ids:" - << std::accumulate(_aidl_return->cbegin(), _aidl_return->cend(), - std::string(""), [](auto prev, auto ele) { - return std::move(prev) + " " + ele; - }); - - return ndk::ScopedAStatus::ok(); -} - -::ndk::ScopedAStatus HalAdapterVendorExtension::parseVendorParameters( - ::aidl::android::media::audio::IHalAdapterVendorExtension::ParameterScope - in_scope, - const std::string& in_rawKeysAndValues, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* - out_syncParameters, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* - out_asyncParameters) { - const auto& keyValues = getVectorFromString(in_rawKeysAndValues); - - const auto& keyValuesPairs = getPairsFromVector(keyValues); - - std::vector<::aidl::android::hardware::audio::core::VendorParameter> result; - - for (const auto& [key, value] : keyValuesPairs) { - result.push_back(getVendorParameterAsVString(key, value)); - } - - *out_syncParameters = result; - *out_asyncParameters = {}; - - LOG(VERBOSE) - << __func__ - << ": scope:" << ::aidl::android::media::audio::toString(in_scope) - << ", raw keyandvalues:" << in_rawKeysAndValues - << ", VendorParameters Ids size:" << out_syncParameters->size() - << " ==> " - << std::accumulate( - out_syncParameters->cbegin(), out_syncParameters->cend(), - std::string(""), [](auto prev, auto ele) { - std::optional<::aidl::qti::audio::core::VString> parcel; - ele.ext.getParcelable(&parcel); - return std::move(prev) + " {" + ele.id + "," + - (parcel ? parcel.value().value : " not parcelled ") + - "}"; - }); - - return ndk::ScopedAStatus::ok(); -} - -::ndk::ScopedAStatus -HalAdapterVendorExtension::parseBluetoothA2dpReconfigureOffload( - const std::string& in_rawValue, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* - _aidl_return) { - LOG(ERROR) << __func__ << "not implemented"; - return ndk::ScopedAStatus::ok(); -} - -::ndk::ScopedAStatus -HalAdapterVendorExtension::parseBluetoothLeReconfigureOffload( - const std::string& in_rawValue, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* - _aidl_return) { - LOG(ERROR) << __func__ << "not implemented"; - return ndk::ScopedAStatus::ok(); -} - -::ndk::ScopedAStatus HalAdapterVendorExtension::processVendorParameters( - ::aidl::android::media::audio::IHalAdapterVendorExtension::ParameterScope - in_scope, - const std::vector<::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - std::string* _aidl_return) { - std::string keyValuesString{""}; - for (const auto& param : in_parameters) { - const auto& out = getStringForVendorParameterAsVString(param); - if (!out.has_value()) { - continue; - } - if (keyValuesString == "") { - keyValuesString = out.value(); - } else { - keyValuesString.append(";").append(out.value()); - } - } - *_aidl_return = keyValuesString; - LOG(VERBOSE) << __func__ - << ": scope:" << ::aidl::android::media::audio::toString(in_scope) - << ", parameters size: " << in_parameters.size() - << ", VendorParameters Ids:" - << std::accumulate(in_parameters.cbegin(), in_parameters.cend(), - std::string(""), - [](auto prev, auto ele) { - return std::move(prev) + " " + ele.id; - }) - << " ==> raw key and values: " << *_aidl_return; - return ndk::ScopedAStatus::ok(); -} - -} // namespace qti::audio::core - -/** - * in case, if someone want to dlopen this library and - * register this as AIDL service. - * - * Also, as per the interface expectation, - * one needs to set the system property - * 'ro.audio.ihaladaptervendorextension_enabled' to be true - * - **/ -static std::shared_ptr<::qti::audio::core::HalAdapterVendorExtension> - gHalAdapterVendorExtension; - -extern "C" __attribute__((visibility("default"))) void registerInterface() { - gHalAdapterVendorExtension = ndk::SharedRefBase::make< - ::qti::audio::core::HalAdapterVendorExtension>(); - const auto kServiceName = - std::string(gHalAdapterVendorExtension->descriptor) - .append("/") - .append("default"); - AIBinder_setMinSchedulerPolicy(gHalAdapterVendorExtension->asBinder().get(), - SCHED_NORMAL, ANDROID_PRIORITY_AUDIO); - binder_exception_t status = AServiceManager_addService( - gHalAdapterVendorExtension->asBinder().get(), kServiceName.c_str()); - if (status != EX_NONE) { - LOG(ERROR) << __func__ << " failed to register " << kServiceName - << " ret:" << status; - } -} \ No newline at end of file diff --git a/qcom/opensource/commonsys/audio/hal_adapter/aidl/qti/audio/core/VString.aidl b/qcom/opensource/commonsys/audio/hal_adapter/aidl/qti/audio/core/VString.aidl deleted file mode 100755 index 80e00bf2..00000000 --- a/qcom/opensource/commonsys/audio/hal_adapter/aidl/qti/audio/core/VString.aidl +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -package qti.audio.core; - -/** - * This is a simple wrapper around an 'string', putting it in a parcelable, so it - * can be used as an 'inout' parameter, be made '@nullable', etc. - * - * {@hide} - */ -@JavaDerive(equals=true, toString=true) -@VintfStability -parcelable VString { - @utf8InCpp String value; -} diff --git a/qcom/opensource/commonsys/audio/hal_adapter/aidl_api/qti-audio-types-aidl/1/.hash b/qcom/opensource/commonsys/audio/hal_adapter/aidl_api/qti-audio-types-aidl/1/.hash deleted file mode 100755 index 54a44287..00000000 --- a/qcom/opensource/commonsys/audio/hal_adapter/aidl_api/qti-audio-types-aidl/1/.hash +++ /dev/null @@ -1 +0,0 @@ -97fa0e47495973748d210f63c7acdc748fbea3ac diff --git a/qcom/opensource/commonsys/audio/hal_adapter/aidl_api/qti-audio-types-aidl/1/qti/audio/core/VString.aidl b/qcom/opensource/commonsys/audio/hal_adapter/aidl_api/qti-audio-types-aidl/1/qti/audio/core/VString.aidl deleted file mode 100755 index 26449106..00000000 --- a/qcom/opensource/commonsys/audio/hal_adapter/aidl_api/qti-audio-types-aidl/1/qti/audio/core/VString.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package qti.audio.core; -/* @hide */ -@JavaDerive(equals=true, toString=true) @VintfStability -parcelable VString { - @utf8InCpp String value; -} diff --git a/qcom/opensource/commonsys/audio/hal_adapter/aidl_api/qti-audio-types-aidl/current/qti/audio/core/VString.aidl b/qcom/opensource/commonsys/audio/hal_adapter/aidl_api/qti-audio-types-aidl/current/qti/audio/core/VString.aidl deleted file mode 100755 index 26449106..00000000 --- a/qcom/opensource/commonsys/audio/hal_adapter/aidl_api/qti-audio-types-aidl/current/qti/audio/core/VString.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ -/////////////////////////////////////////////////////////////////////////////// -// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // -/////////////////////////////////////////////////////////////////////////////// - -// This file is a snapshot of an AIDL file. Do not edit it manually. There are -// two cases: -// 1). this is a frozen version file - do not edit this in any case. -// 2). this is a 'current' file. If you make a backwards compatible change to -// the interface (from the latest frozen version), the build system will -// prompt you to update this file with `m -update-api`. -// -// You must not make a backward incompatible change to any AIDL file built -// with the aidl_interface module type with versions property set. The module -// type is used to build AIDL files in a way that they can be used across -// independently updatable components of the system. If a device is shipped -// with such a backward incompatible change, it has a high risk of breaking -// later when a module using the interface is updated, e.g., Mainline modules. - -package qti.audio.core; -/* @hide */ -@JavaDerive(equals=true, toString=true) @VintfStability -parcelable VString { - @utf8InCpp String value; -} diff --git a/qcom/opensource/commonsys/audio/hal_adapter/include/qti-audio-core/HalAdapterVendorExtension.h b/qcom/opensource/commonsys/audio/hal_adapter/include/qti-audio-core/HalAdapterVendorExtension.h deleted file mode 100755 index 6b85d673..00000000 --- a/qcom/opensource/commonsys/audio/hal_adapter/include/qti-audio-core/HalAdapterVendorExtension.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#pragma once - -#include - -namespace qti::audio::core { - -/** - * This is responsible for validating the parameters like key, key length validation -**/ -class HalAdapterVendorExtension - : public ::aidl::android::media::audio::BnHalAdapterVendorExtension { - public: - ::ndk::ScopedAStatus parseVendorParameterIds( - ::aidl::android::media::audio::IHalAdapterVendorExtension:: - ParameterScope in_scope, - const std::string& in_rawKeys, - std::vector* _aidl_return) override; - ::ndk::ScopedAStatus parseVendorParameters( - ::aidl::android::media::audio::IHalAdapterVendorExtension:: - ParameterScope in_scope, - const std::string& in_rawKeysAndValues, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* - out_syncParameters, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* - out_asyncParameters) override; - ::ndk::ScopedAStatus parseBluetoothA2dpReconfigureOffload( - const std::string& in_rawValue, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* - _aidl_return) override; - ::ndk::ScopedAStatus parseBluetoothLeReconfigureOffload( - const std::string& in_rawValue, - std::vector<::aidl::android::hardware::audio::core::VendorParameter>* - _aidl_return) override; - ::ndk::ScopedAStatus processVendorParameters( - ::aidl::android::media::audio::IHalAdapterVendorExtension:: - ParameterScope in_scope, - const std::vector< - ::aidl::android::hardware::audio::core::VendorParameter>& - in_parameters, - std::string* _aidl_return) override; -}; -} // namespace qti::audio::core \ No newline at end of file diff --git a/qcom/opensource/commonsys/cryptfs_hw/Android.bp b/qcom/opensource/commonsys/cryptfs_hw/Android.bp deleted file mode 100755 index 4c458193..00000000 --- a/qcom/opensource/commonsys/cryptfs_hw/Android.bp +++ /dev/null @@ -1,30 +0,0 @@ -sourceFiles = ["cryptfs_hw.cpp"] - -commonSharedLibraries = [ - "libcutils", - "libutils", - "libdl", - "libhardware", - "liblog", - "libhwbinder", - "libhidlbase", - "libhidltransport", - "libbinder", - "vendor.qti.hardware.cryptfshw@1.0", -] - -cc_library_shared { - name: "libcryptfs_hw", - header_libs: ["libhardware_headers", - "libcryptfshw_hidl_headers",], - srcs: sourceFiles, - shared_libs: commonSharedLibraries, - - owner: "qti", - system_ext_specific: true, -} - -cc_library_headers { - name: "libcryptfs_hw_headers", - export_include_dirs: ["."], -} diff --git a/qcom/opensource/commonsys/cryptfs_hw/NOTICE b/qcom/opensource/commonsys/cryptfs_hw/NOTICE deleted file mode 100755 index 7d243cad..00000000 --- a/qcom/opensource/commonsys/cryptfs_hw/NOTICE +++ /dev/null @@ -1,31 +0,0 @@ -Copyright (c) 2014, 2017, The Linux Foundation. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted (subject to the limitations in the -disclaimer below) provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - - * Neither the name of The Linux Foundation nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE -GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT -HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/qcom/opensource/commonsys/cryptfs_hw/cryptfs_hw.cpp b/qcom/opensource/commonsys/cryptfs_hw/cryptfs_hw.cpp deleted file mode 100755 index 6cd634db..00000000 --- a/qcom/opensource/commonsys/cryptfs_hw/cryptfs_hw.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* Copyright (c) 2014, 2017, 2019 The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include -#include "cutils/log.h" -#include "cutils/properties.h" -#include "cryptfs_hw.h" -#include "CryptfsHw.h" - -using android::sp; -using vendor::qti::hardware::cryptfshw::V1_0::ICryptfsHw; -using ::android::hardware::Return; -using ::android::hardware::Void; - -#define QTI_ICE_STORAGE_UFS 1 -#define QTI_ICE_STORAGE_SDCC 2 - -int set_ice_param(int flag) -{ - int rc = -1; - sp cryptfshwService = ICryptfsHw::getService(); - if (cryptfshwService.get() == nullptr) { - ALOGE("Failed to get Cryptfshw service"); - return rc; - } - rc = cryptfshwService->setIceParam(flag); - return rc; -} - -int set_hw_device_encryption_key(const char* passwd, const char* enc_mode) -{ - int rc = -1; - sp cryptfshwService = ICryptfsHw::getService(); - if (cryptfshwService.get() == nullptr) { - ALOGE("Failed to get Cryptfshw service"); - return rc; - } - rc = cryptfshwService->setKey(passwd, enc_mode); - return rc; -} - -int update_hw_device_encryption_key(const char* oldpw, const char* newpw, const char* enc_mode) -{ - int rc = -1; - sp cryptfshwService = ICryptfsHw::getService(); - if (cryptfshwService.get() == nullptr) { - ALOGE("Failed to get Cryptfshw service"); - return rc; - } - rc = cryptfshwService->updateKey(oldpw, newpw, enc_mode); - return rc; -} - -unsigned int is_hw_disk_encryption(const char* encryption_mode) -{ - int ret = 0; - if(encryption_mode) { - if (!strcmp(encryption_mode, "aes-xts")) { - SLOGD("HW based disk encryption is enabled \n"); - ret = 1; - } - } - return ret; -} - -int is_ice_enabled(void) -{ - char prop_storage[PATH_MAX]; - int storage_type = 0; - - if (property_get("ro.boot.bootdevice", prop_storage, "")) { - if (strstr(prop_storage, "ufs")) { - /* All UFS based devices has ICE in it. So we dont need - * to check if corresponding device exists or not - */ - storage_type = QTI_ICE_STORAGE_UFS; - } else if (strstr(prop_storage, "sdhc")) { - if (access("/dev/icesdcc", F_OK) != -1) - storage_type = QTI_ICE_STORAGE_SDCC; - } - } - return storage_type; -} - -int clear_hw_device_encryption_key() -{ - int rc = -1; - sp cryptfshwService = ICryptfsHw::getService(); - if (cryptfshwService.get() == nullptr) { - ALOGE("Failed to get Cryptfshw service"); - return rc; - } - rc = cryptfshwService->clearKey(); - return rc; -} - diff --git a/qcom/opensource/commonsys/cryptfs_hw/cryptfs_hw.h b/qcom/opensource/commonsys/cryptfs_hw/cryptfs_hw.h deleted file mode 100755 index d7ed51e0..00000000 --- a/qcom/opensource/commonsys/cryptfs_hw/cryptfs_hw.h +++ /dev/null @@ -1,52 +0,0 @@ -/* Copyright (c) 2014, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __CRYPTFS_HW_H_ -#define __CRYPTFS_HW_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/*This is equivalent of MAX_CRYPTO_TYPE_NAME_LEN*/ -#define CRYPTO_ALGO_LENGTH 64 -#define START_ENC 0x1 -#define START_ENCDEC 0x3 - -int set_hw_device_encryption_key(const char*, const char*); -int update_hw_device_encryption_key(const char*, const char*, const char*); -int clear_hw_device_encryption_key(); -unsigned int is_hw_disk_encryption(const char*); -int is_ice_enabled(void); -inline int should_use_keymaster(){return 1;} -int set_ice_param(int flag); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/qcom/opensource/commonsys/display/.clang-format b/qcom/opensource/commonsys/display/.clang-format deleted file mode 100755 index 26ce4fe4..00000000 --- a/qcom/opensource/commonsys/display/.clang-format +++ /dev/null @@ -1,14 +0,0 @@ ---- -Language: Cpp -BasedOnStyle: Google -Standard : C++11 -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false -AllowShortFunctionsOnASingleLine: Inline -AllowShortBlocksOnASingleLine: false -ColumnLimit: 100 -ConstructorInitializerAllOnOneLineOrOnePerLine: true -ConstructorInitializerIndentWidth: 4 -DerivePointerAlignment: false -PointerAlignment: Right -#ReflowComments: false diff --git a/qcom/opensource/commonsys/display/config/display-product-commonsys.mk b/qcom/opensource/commonsys/display/config/display-product-commonsys.mk deleted file mode 100755 index 0b913da7..00000000 --- a/qcom/opensource/commonsys/display/config/display-product-commonsys.mk +++ /dev/null @@ -1,27 +0,0 @@ -PRODUCT_PACKAGES += libdisplayconfig.system \ - libgralloc.system.qti \ - libdrm \ - liblayerext.qti \ - libsmomoconfig.qti \ - libcomposerextn.qti \ - libdisplayconfig.system.qti - -SOONG_CONFIG_NAMESPACES += qtidisplaycommonsys -# Soong Keys -SOONG_CONFIG_qtidisplaycommonsys := displayextension composer3ext -# Soong Values - -# displayextension controls global compile time disablement of SF extensions -SOONG_CONFIG_qtidisplaycommonsys_displayextension := false - -# Variables can be added here on a transient basis to merge -# features that are not yet consumed in keystone -# Once the feature has been consumed, these can be removed -# and the feature can be enabled/disabled at run time via android -# properties -SOONG_CONFIG_qtidisplaycommonsys_composer3ext := false - -ifeq ($(call is-vendor-board-platform,QCOM),true) - SOONG_CONFIG_qtidisplaycommonsys_displayextension := true - SOONG_CONFIG_qtidisplaycommonsys_composer3ext := true -endif diff --git a/qcom/opensource/commonsys/display/gralloc/Android.bp b/qcom/opensource/commonsys/display/gralloc/Android.bp deleted file mode 100755 index 2c28cf61..00000000 --- a/qcom/opensource/commonsys/display/gralloc/Android.bp +++ /dev/null @@ -1,22 +0,0 @@ -cc_library_shared { - name: "libgralloc.system.qti", - system_ext_specific: true, - cflags: [ - "-Wno-sign-conversion", - "-DLOG_TAG=\"qtigralloc\"", - ], - shared_libs: [ - "liblog", - "libcutils", - "libutils", - "libgralloctypes", - "libhidlbase", - "libhardware", - "android.hardware.graphics.mapper@4.0", - ], - - srcs: ["QtiGralloc.cpp"], - - header_libs: ["display_intf_headers"], -} - diff --git a/qcom/opensource/commonsys/display/gralloc/QtiGralloc.cpp b/qcom/opensource/commonsys/display/gralloc/QtiGralloc.cpp deleted file mode 100755 index 5cde30aa..00000000 --- a/qcom/opensource/commonsys/display/gralloc/QtiGralloc.cpp +++ /dev/null @@ -1,583 +0,0 @@ -/* - * Copyright (c) 2020, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - /* - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause-Clear - */ - -#include "QtiGralloc.h" - -#include -#include "color_extensions.h" - -namespace qtigralloc { - -using android::hardware::graphics::mapper::V4_0::IMapper; - -static sp getInstance() { - static sp mapper = IMapper::getService(); - return mapper; -} - -Error decodeMetadataState(hidl_vec &in, bool *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - memcpy(out, in.data(), METADATA_SET_SIZE); - return Error::NONE; -} - -Error encodeMetadataState(bool *in, hidl_vec *out) { - if (!in || !out) { - return Error::BAD_VALUE; - } - out->resize(sizeof(bool) * METADATA_SET_SIZE); - memcpy(out->data(), in, sizeof(bool) * METADATA_SET_SIZE); - return Error::NONE; -} - -Error decodeColorMetadata(hidl_vec &in, ColorMetaData *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - memcpy(out, in.data(), sizeof(ColorMetaData)); - return Error::NONE; -} - -Error encodeColorMetadata(ColorMetaData &in, hidl_vec *out) { - if (!out) { - return Error::BAD_VALUE; - } - out->resize(sizeof(ColorMetaData)); - memcpy(out->data(), &in, sizeof(ColorMetaData)); - return Error::NONE; -} - -// decode the raw graphics metadata from bytestream and store it in 'data' member of -// GraphicsMetadata struct during mapper->set call, 'size' member is unused. -Error decodeGraphicsMetadata(hidl_vec &in, GraphicsMetadata *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - memcpy(&(out->data), in.data(), GRAPHICS_METADATA_SIZE_IN_BYTES); - return Error::NONE; -} - -// encode only 'data' member of GraphicsMetadata struct for retrieval of -// graphics metadata during mapper->get call -Error encodeGraphicsMetadata(GraphicsMetadata &in, hidl_vec *out) { - if (!out) { - return Error::BAD_VALUE; - } - out->resize(GRAPHICS_METADATA_SIZE_IN_BYTES); - memcpy(out->data(), &(in.data), GRAPHICS_METADATA_SIZE_IN_BYTES); - return Error::NONE; -} - -// decode the raw graphics metadata from bytestream before presenting it to caller -Error decodeGraphicsMetadataRaw(hidl_vec &in, void *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - memcpy(out, in.data(), GRAPHICS_METADATA_SIZE_IN_BYTES); - return Error::NONE; -} - -// encode the raw graphics metadata in bytestream before calling mapper->set -Error encodeGraphicsMetadataRaw(void *in, hidl_vec *out) { - if (!in || !out) { - return Error::BAD_VALUE; - } - out->resize(GRAPHICS_METADATA_SIZE_IN_BYTES); - memcpy(out->data(), in, GRAPHICS_METADATA_SIZE_IN_BYTES); - return Error::NONE; -} - -Error decodeUBWCStats(hidl_vec &in, UBWCStats *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - memcpy(out, in.data(), UBWC_STATS_ARRAY_SIZE * sizeof(UBWCStats)); - return Error::NONE; -} - -Error encodeUBWCStats(UBWCStats *in, hidl_vec *out) { - if (!in || !out) { - return Error::BAD_VALUE; - } - out->resize(UBWC_STATS_ARRAY_SIZE * sizeof(UBWCStats)); - memcpy(out->data(), in, UBWC_STATS_ARRAY_SIZE * sizeof(UBWCStats)); - return Error::NONE; -} - -Error decodeCVPMetadata(hidl_vec &in, CVPMetadata *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - memcpy(out, in.data(), sizeof(CVPMetadata)); - return Error::NONE; -} - -Error encodeCVPMetadata(CVPMetadata &in, hidl_vec *out) { - if (!out) { - return Error::BAD_VALUE; - } - out->resize(sizeof(CVPMetadata)); - memcpy(out->data(), &in, sizeof(CVPMetadata)); - return Error::NONE; -} - -Error decodeVideoHistogramMetadata(hidl_vec &in, VideoHistogramMetadata *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - memcpy(out, in.data(), sizeof(VideoHistogramMetadata)); - return Error::NONE; -} - -Error encodeVideoHistogramMetadata(VideoHistogramMetadata &in, hidl_vec *out) { - if (!out) { - return Error::BAD_VALUE; - } - out->resize(sizeof(VideoHistogramMetadata)); - memcpy(out->data(), &in, sizeof(VideoHistogramMetadata)); - return Error::NONE; -} - -Error decodeVideoTranscodeStatsMetadata(hidl_vec &in, VideoTranscodeStatsMetadata *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - memcpy(out, in.data(), sizeof(VideoTranscodeStatsMetadata)); - return Error::NONE; -} - -Error encodeVideoTranscodeStatsMetadata(VideoTranscodeStatsMetadata &in, hidl_vec *out) { - if (!out) { - return Error::BAD_VALUE; - } - out->resize(sizeof(VideoTranscodeStatsMetadata)); - memcpy(out->data(), &in, sizeof(VideoTranscodeStatsMetadata)); - return Error::NONE; -} - -Error decodeVideoTimestampInfo(hidl_vec &in, VideoTimestampInfo *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - memcpy(out, in.data(), sizeof(VideoTimestampInfo)); - return Error::NONE; -} - -Error encodeVideoTimestampInfo(VideoTimestampInfo &in, hidl_vec *out) { - if (!out) { - return Error::BAD_VALUE; - } - out->resize(sizeof(VideoTimestampInfo)); - memcpy(out->data(), &in, sizeof(VideoTimestampInfo)); - return Error::NONE; -} - -Error decodeYUVPlaneInfoMetadata(hidl_vec &in, qti_ycbcr *out) { - if (!in.size() || !out) { - return Error::BAD_VALUE; - } - qti_ycbcr *p = reinterpret_cast(in.data()); - memcpy(out, in.data(), (YCBCR_LAYOUT_ARRAY_SIZE * sizeof(qti_ycbcr))); - return Error::NONE; -} - -Error encodeYUVPlaneInfoMetadata(qti_ycbcr *in, hidl_vec *out) { - if (!out) { - return Error::BAD_VALUE; - } - out->resize(YCBCR_LAYOUT_ARRAY_SIZE * sizeof(qti_ycbcr)); - memcpy(out->data(), in, YCBCR_LAYOUT_ARRAY_SIZE * sizeof(qti_ycbcr)); - return Error::NONE; -} - -Error decodeCustomContentMetadata(hidl_vec &in, void *out) { - static size_t target_size = sizeof(CustomContentMetadata); - - if (in.size() != target_size || !out) { - return Error::BAD_VALUE; - } - - CustomContentMetadata *c_md_in = reinterpret_cast(in.data()); - CustomContentMetadata *c_md_out = reinterpret_cast(out); - - if (c_md_in->size > CUSTOM_METADATA_SIZE_BYTES) { - return Error::BAD_VALUE; - } - - c_md_out->size = c_md_in->size; - memcpy(c_md_out->metadataPayload, c_md_in->metadataPayload, c_md_in->size); - return Error::NONE; -} - -Error encodeCustomContentMetadata(const void *in, hidl_vec *out) { - static size_t target_size = sizeof(CustomContentMetadata); - - if (!in || !out) { - return Error::BAD_VALUE; - } - - out->resize(target_size); - - memcpy(out->data(), in, target_size); - return Error::NONE; -} - -MetadataType getMetadataType(uint32_t in) { - switch (in) { - case QTI_VT_TIMESTAMP: - return MetadataType_VTTimestamp; - case QTI_VIDEO_PERF_MODE: - return MetadataType_VideoPerfMode; - case QTI_LINEAR_FORMAT: - return MetadataType_LinearFormat; - case QTI_SINGLE_BUFFER_MODE: - return MetadataType_SingleBufferMode; - case QTI_PP_PARAM_INTERLACED: - return MetadataType_PPParamInterlaced; - case QTI_MAP_SECURE_BUFFER: - return MetadataType_MapSecureBuffer; - case QTI_COLOR_METADATA: - return MetadataType_ColorMetadata; - case QTI_GRAPHICS_METADATA: - return MetadataType_GraphicsMetadata; - case QTI_UBWC_CR_STATS_INFO: - return MetadataType_UBWCCRStatsInfo; - case QTI_REFRESH_RATE: - return MetadataType_RefreshRate; - case QTI_CVP_METADATA: - return MetadataType_CVPMetadata; - case QTI_VIDEO_HISTOGRAM_STATS: - return MetadataType_VideoHistogramStats; - case QTI_VIDEO_TRANSCODE_STATS: - return MetadataType_VideoTranscodeStats; - case QTI_VIDEO_TS_INFO: - return MetadataType_VideoTimestampInfo; - case QTI_FD: - return MetadataType_FD; - case QTI_PRIVATE_FLAGS: - return MetadataType_PrivateFlags; - case QTI_ALIGNED_WIDTH_IN_PIXELS: - return MetadataType_AlignedWidthInPixels; - case QTI_ALIGNED_HEIGHT_IN_PIXELS: - return MetadataType_AlignedHeightInPixels; - case QTI_STANDARD_METADATA_STATUS: - return MetadataType_StandardMetadataStatus; - case QTI_VENDOR_METADATA_STATUS: - return MetadataType_VendorMetadataStatus; - case QTI_BUFFER_TYPE: - return MetadataType_BufferType; - case QTI_CUSTOM_DIMENSIONS_STRIDE: - return MetadataType_CustomDimensionsStride; - case QTI_CUSTOM_DIMENSIONS_HEIGHT: - return MetadataType_CustomDimensionsHeight; - case QTI_RGB_DATA_ADDRESS: - return MetadataType_RgbDataAddress; - case QTI_COLORSPACE: - return MetadataType_ColorSpace; - case QTI_YUV_PLANE_INFO: - return MetadataType_YuvPlaneInfo; - case QTI_TIMED_RENDERING: - return MetadataType_TimedRendering; - case QTI_CUSTOM_CONTENT_METADATA: - return MetadataType_CustomContentMetadata; - case QTI_BUFFER_DEQUEUE_DURATION: - return MetadataType_BufferDequeueDuration; - default: - return MetadataType_Invalid; - } -} - -Error get(void *buffer, uint32_t type, void *param) { - hidl_vec bytestream; - sp mapper = getInstance(); - - MetadataType metadata_type = getMetadataType(type); - if (metadata_type == MetadataType_Invalid) { - param = nullptr; - return Error::UNSUPPORTED; - } - - auto err = Error::UNSUPPORTED; - mapper->get(buffer, metadata_type, [&](const auto &tmpError, const auto &tmpByteStream) { - err = tmpError; - bytestream = tmpByteStream; - }); - - if (err != Error::NONE) { - return err; - } - - switch (type) { - case QTI_VT_TIMESTAMP: - err = static_cast(android::gralloc4::decodeUint64( - qtigralloc::MetadataType_VTTimestamp, bytestream, reinterpret_cast(param))); - break; - case QTI_VIDEO_PERF_MODE: - err = static_cast(android::gralloc4::decodeUint32( - qtigralloc::MetadataType_VideoPerfMode, bytestream, reinterpret_cast(param))); - break; - case QTI_LINEAR_FORMAT: - err = static_cast(android::gralloc4::decodeUint32( - qtigralloc::MetadataType_LinearFormat, bytestream, reinterpret_cast(param))); - break; - case QTI_SINGLE_BUFFER_MODE: - err = static_cast( - android::gralloc4::decodeUint32(qtigralloc::MetadataType_SingleBufferMode, bytestream, - reinterpret_cast(param))); - break; - case QTI_PP_PARAM_INTERLACED: - err = static_cast( - android::gralloc4::decodeInt32(qtigralloc::MetadataType_PPParamInterlaced, bytestream, - reinterpret_cast(param))); - break; - case QTI_MAP_SECURE_BUFFER: - err = static_cast( - android::gralloc4::decodeInt32(qtigralloc::MetadataType_MapSecureBuffer, bytestream, - reinterpret_cast(param))); - break; - case QTI_COLOR_METADATA: - err = decodeColorMetadata(bytestream, reinterpret_cast(param)); - break; - case QTI_GRAPHICS_METADATA: - err = decodeGraphicsMetadataRaw(bytestream, param); - break; - case QTI_UBWC_CR_STATS_INFO: - err = decodeUBWCStats(bytestream, reinterpret_cast(param)); - break; - case QTI_REFRESH_RATE: - err = static_cast(android::gralloc4::decodeFloat( - qtigralloc::MetadataType_RefreshRate, bytestream, reinterpret_cast(param))); - break; - case QTI_CVP_METADATA: - err = decodeCVPMetadata(bytestream, reinterpret_cast(param)); - break; - case QTI_VIDEO_HISTOGRAM_STATS: - err = decodeVideoHistogramMetadata(bytestream, - reinterpret_cast(param)); - break; - case QTI_VIDEO_TRANSCODE_STATS: - err = decodeVideoTranscodeStatsMetadata(bytestream, - reinterpret_cast(param)); - break; - case QTI_VIDEO_TS_INFO: - err = decodeVideoTimestampInfo(bytestream, reinterpret_cast(param)); - break; - case QTI_FD: - err = static_cast(android::gralloc4::decodeInt32( - qtigralloc::MetadataType_FD, bytestream, reinterpret_cast(param))); - break; - case QTI_PRIVATE_FLAGS: - err = static_cast(android::gralloc4::decodeInt32( - qtigralloc::MetadataType_PrivateFlags, bytestream, reinterpret_cast(param))); - break; - case QTI_ALIGNED_WIDTH_IN_PIXELS: - err = static_cast( - android::gralloc4::decodeUint32(qtigralloc::MetadataType_AlignedWidthInPixels, bytestream, - reinterpret_cast(param))); - break; - case QTI_ALIGNED_HEIGHT_IN_PIXELS: - err = static_cast( - android::gralloc4::decodeUint32(qtigralloc::MetadataType_AlignedHeightInPixels, - bytestream, reinterpret_cast(param))); - break; - case QTI_STANDARD_METADATA_STATUS: - case QTI_VENDOR_METADATA_STATUS: - err = decodeMetadataState(bytestream, reinterpret_cast(param)); - break; - case QTI_BUFFER_TYPE: - err = static_cast(android::gralloc4::decodeUint32( - qtigralloc::MetadataType_BufferType, bytestream, reinterpret_cast(param))); - break; - case QTI_CUSTOM_DIMENSIONS_STRIDE: - err = static_cast( - android::gralloc4::decodeUint32(qtigralloc::MetadataType_CustomDimensionsStride, - bytestream, reinterpret_cast(param))); - break; - case QTI_CUSTOM_DIMENSIONS_HEIGHT: - err = static_cast( - android::gralloc4::decodeUint32(qtigralloc::MetadataType_CustomDimensionsHeight, - bytestream, reinterpret_cast(param))); - break; - case QTI_RGB_DATA_ADDRESS: - err = static_cast( - android::gralloc4::decodeUint64(qtigralloc::MetadataType_RgbDataAddress, bytestream, - reinterpret_cast(param))); - break; - case QTI_COLORSPACE: - err = static_cast(android::gralloc4::decodeUint32( - qtigralloc::MetadataType_ColorSpace, bytestream, reinterpret_cast(param))); - break; - case QTI_YUV_PLANE_INFO: - err = decodeYUVPlaneInfoMetadata(bytestream, reinterpret_cast(param)); - break; - case QTI_TIMED_RENDERING: - err = static_cast(android::gralloc4::decodeUint32( - qtigralloc::MetadataType_TimedRendering, bytestream, reinterpret_cast(param))); - break; - case QTI_CUSTOM_CONTENT_METADATA: - err = decodeCustomContentMetadata(bytestream, param); - break; - case QTI_BUFFER_DEQUEUE_DURATION: - err = static_cast(android::gralloc4::decodeInt64( - qtigralloc::MetadataType_BufferDequeueDuration, bytestream, - reinterpret_cast(param))); - break; - default: - param = nullptr; - return Error::UNSUPPORTED; - } - - return err; -} - -Error set(void *buffer, uint32_t type, void *param) { - hidl_vec bytestream; - sp mapper = getInstance(); - - Error err = Error::UNSUPPORTED; - MetadataType metadata_type = getMetadataType(type); - if (metadata_type == MetadataType_Invalid) { - return err; - } - - switch (type) { - case QTI_VT_TIMESTAMP: - err = static_cast(android::gralloc4::encodeUint64( - qtigralloc::MetadataType_VTTimestamp, *reinterpret_cast(param), &bytestream)); - break; - case QTI_VIDEO_PERF_MODE: - err = static_cast( - android::gralloc4::encodeUint32(qtigralloc::MetadataType_VideoPerfMode, - *reinterpret_cast(param), &bytestream)); - break; - case QTI_LINEAR_FORMAT: - err = static_cast( - android::gralloc4::encodeUint32(qtigralloc::MetadataType_LinearFormat, - *reinterpret_cast(param), &bytestream)); - break; - case QTI_SINGLE_BUFFER_MODE: - err = static_cast( - android::gralloc4::encodeUint32(qtigralloc::MetadataType_SingleBufferMode, - *reinterpret_cast(param), &bytestream)); - break; - case QTI_PP_PARAM_INTERLACED: - err = static_cast( - android::gralloc4::encodeInt32(qtigralloc::MetadataType_PPParamInterlaced, - *reinterpret_cast(param), &bytestream)); - break; - case QTI_MAP_SECURE_BUFFER: - err = static_cast( - android::gralloc4::encodeInt32(qtigralloc::MetadataType_MapSecureBuffer, - *reinterpret_cast(param), &bytestream)); - break; - case QTI_COLOR_METADATA: - err = encodeColorMetadata(*reinterpret_cast(param), &bytestream); - break; - case QTI_GRAPHICS_METADATA: - err = encodeGraphicsMetadataRaw(param, &bytestream); - break; - case QTI_UBWC_CR_STATS_INFO: - err = encodeUBWCStats(reinterpret_cast(param), &bytestream); - break; - case QTI_REFRESH_RATE: - err = static_cast(android::gralloc4::encodeFloat( - qtigralloc::MetadataType_RefreshRate, *reinterpret_cast(param), &bytestream)); - break; - case QTI_CVP_METADATA: - err = encodeCVPMetadata(*reinterpret_cast(param), &bytestream); - break; - case QTI_VIDEO_HISTOGRAM_STATS: - err = encodeVideoHistogramMetadata(*reinterpret_cast(param), - &bytestream); - break; - case QTI_VIDEO_TRANSCODE_STATS: - err = encodeVideoTranscodeStatsMetadata( - *reinterpret_cast(param), &bytestream); - break; - case QTI_VIDEO_TS_INFO: - err = encodeVideoTimestampInfo(*reinterpret_cast(param), &bytestream); - break; - case QTI_TIMED_RENDERING: - err = static_cast( - android::gralloc4::encodeUint32(qtigralloc::MetadataType_TimedRendering, - *reinterpret_cast(param), &bytestream)); - break; - case QTI_CUSTOM_CONTENT_METADATA: - err = encodeCustomContentMetadata(param, &bytestream); - break; - case QTI_BUFFER_DEQUEUE_DURATION: - err = static_cast(android::gralloc4::encodeInt64( - qtigralloc::MetadataType_BufferDequeueDuration, - *reinterpret_cast(param), &bytestream)); - break; - default: - param = nullptr; - return Error::UNSUPPORTED; - } - - if (err != Error::NONE) { - return err; - } - - return mapper->set(reinterpret_cast(buffer), metadata_type, bytestream); -} - -int getMetadataState(void *buffer, uint32_t type) { - bool metadata_set[METADATA_SET_SIZE]; - Error err; - if (IS_VENDOR_METADATA_TYPE(type)) { - err = get(buffer, QTI_VENDOR_METADATA_STATUS, &metadata_set); - } else { - err = get(buffer, QTI_STANDARD_METADATA_STATUS, &metadata_set); - } - - if (err != Error::NONE) { - ALOGE("Unable to get metadata state"); - return -1; - } - - if (IS_VENDOR_METADATA_TYPE(type)) { - return metadata_set[GET_VENDOR_METADATA_STATUS_INDEX(type)]; - } else if (GET_STANDARD_METADATA_STATUS_INDEX(type) < METADATA_SET_SIZE) { - return metadata_set[GET_STANDARD_METADATA_STATUS_INDEX(type)]; - } else { - return -1; - } -} - -} // namespace qtigralloc diff --git a/qcom/opensource/commonsys/display/libqdmetadata/Android.bp b/qcom/opensource/commonsys/display/libqdmetadata/Android.bp deleted file mode 100755 index 181eb163..00000000 --- a/qcom/opensource/commonsys/display/libqdmetadata/Android.bp +++ /dev/null @@ -1,21 +0,0 @@ -cc_library_shared { - name: "libqdMetaData.system", - system_ext_specific: true, - cflags: [ - "-Wno-sign-conversion", - "-DLOG_TAG=\"qdmetadata\"", - "-D__QTI_DISPLAY_GRALLOC__", - ], - shared_libs: [ - "liblog", - "libcutils", - "libutils", - "libhidlbase", - "libgralloc.system.qti", - "libgralloctypes", - ], - header_libs: ["libhardware_headers", "display_intf_headers"], - srcs: ["qdMetaData.cpp", "qd_utils.cpp"], - export_header_lib_headers: ["display_intf_headers"], -} - diff --git a/qcom/opensource/commonsys/display/libqdmetadata/Makefile.am b/qcom/opensource/commonsys/display/libqdmetadata/Makefile.am deleted file mode 100755 index 1fa7e644..00000000 --- a/qcom/opensource/commonsys/display/libqdmetadata/Makefile.am +++ /dev/null @@ -1,16 +0,0 @@ -h_sources = qdMetaData.h - -cpp_sources = qdMetaData.cpp - -AM_CPPFLAGS += -D__QTI_NO_GRALLOC4__ - -qdMetaData_includedir = $(pkgincludedir)/display -qdMetaData_include_HEADERS = $(h_sources) - -lib_LTLIBRARIES = libqdMetaData.la -libqdMetaData_la_CC = @CC@ -libqdMetaData_la_SOURCES = $(cpp_sources) -libqdMetaData_la_CFLAGS = $(AM_CFLAGS) -DLOG_TAG=\"DisplayMetaData\" -libqdMetaData_la_CPPFLAGS = $(AM_CPPFLAGS) -libqdMetaData_LDADD = -lcutils -llog -libqdMetaData_la_LDFLAGS = -shared -avoid-version \ No newline at end of file diff --git a/qcom/opensource/commonsys/display/libqdmetadata/qdMetaData.cpp b/qcom/opensource/commonsys/display/libqdmetadata/qdMetaData.cpp deleted file mode 100755 index 228a634c..00000000 --- a/qcom/opensource/commonsys/display/libqdmetadata/qdMetaData.cpp +++ /dev/null @@ -1,642 +0,0 @@ -/* - * Copyright (c) 2012-2021, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "qdMetaData.h" - -#include -#include -#include -#ifndef __QTI_NO_GRALLOC4__ -#include -#endif -#include -#include -#include - -#include - -static int colorMetaDataToColorSpace(ColorMetaData in, ColorSpace_t *out) { - if (in.colorPrimaries == ColorPrimaries_BT601_6_525 || - in.colorPrimaries == ColorPrimaries_BT601_6_625) { - if (in.range == Range_Full) { - *out = ITU_R_601_FR; - } else { - *out = ITU_R_601; - } - } else if (in.colorPrimaries == ColorPrimaries_BT2020) { - if (in.range == Range_Full) { - *out = ITU_R_2020_FR; - } else { - *out = ITU_R_2020; - } - } else if (in.colorPrimaries == ColorPrimaries_BT709_5) { - if (in.range == Range_Full) { - *out = ITU_R_709_FR; - } else { - *out = ITU_R_709; - } - } else { - ALOGE( - "Cannot convert ColorMetaData to ColorSpace_t. " - "Primaries = %d, Range = %d", - in.colorPrimaries, in.range); - return -1; - } - - return 0; -} - -static int colorSpaceToColorMetadata(ColorSpace_t in, ColorMetaData *out) { - out->transfer = Transfer_sRGB; - switch (in) { - case ITU_R_601: - out->colorPrimaries = ColorPrimaries_BT601_6_525; - out->range = Range_Limited; - break; - case ITU_R_601_FR: - out->colorPrimaries = ColorPrimaries_BT601_6_525; - out->range = Range_Full; - break; - case ITU_R_709: - out->colorPrimaries = ColorPrimaries_BT709_5; - out->range = Range_Limited; - break; - case ITU_R_709_FR: - out->colorPrimaries = ColorPrimaries_BT709_5; - out->range = Range_Full; - break; - case ITU_R_2020: - out->colorPrimaries = ColorPrimaries_BT2020; - out->range = Range_Limited; - break; - case ITU_R_2020_FR: - out->colorPrimaries = ColorPrimaries_BT2020; - out->range = Range_Full; - break; - default: - ALOGE("Cannot convert ColorSpace_t %d to ColorMetaData", in); - return -1; - break; - } - - return 0; -} - -#ifndef __QTI_NO_GRALLOC4__ -static bool getGralloc4Array(MetaData_t *metadata, int32_t paramType) { - switch (paramType) { - case SET_VT_TIMESTAMP: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_VT_TIMESTAMP)]; - case COLOR_METADATA: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_COLOR_METADATA)]; - case PP_PARAM_INTERLACED: - return metadata - ->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_PP_PARAM_INTERLACED)]; - case SET_VIDEO_PERF_MODE: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_VIDEO_PERF_MODE)]; - case SET_GRAPHICS_METADATA: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_GRAPHICS_METADATA)]; - case SET_UBWC_CR_STATS_INFO: - return metadata - ->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_UBWC_CR_STATS_INFO)]; - case UPDATE_BUFFER_GEOMETRY: - return metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX( - ::android::gralloc4::MetadataType_Crop.value)]; - case UPDATE_REFRESH_RATE: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_REFRESH_RATE)]; - case UPDATE_COLOR_SPACE: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_COLOR_METADATA)]; - case MAP_SECURE_BUFFER: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_MAP_SECURE_BUFFER)]; - case LINEAR_FORMAT: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_LINEAR_FORMAT)]; - case SET_SINGLE_BUFFER_MODE: - return metadata - ->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_SINGLE_BUFFER_MODE)]; - case SET_CVP_METADATA: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_CVP_METADATA)]; - case SET_VIDEO_HISTOGRAM_STATS: - return metadata - ->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_VIDEO_HISTOGRAM_STATS)]; - case SET_VIDEO_TS_INFO: - return metadata - ->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_VIDEO_TS_INFO)]; - case GET_S3D_FORMAT: - return metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_S3D_FORMAT)]; - default: - ALOGE("paramType %d not supported", paramType); - return false; - } -} - -static void setGralloc4Array(MetaData_t *metadata, int32_t paramType, bool isSet) { - switch (paramType) { - case SET_VT_TIMESTAMP: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_VT_TIMESTAMP)] = isSet; - break; - case COLOR_METADATA: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_COLOR_METADATA)] = isSet; - break; - case PP_PARAM_INTERLACED: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_PP_PARAM_INTERLACED)] = - isSet; - break; - case SET_VIDEO_PERF_MODE: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_VIDEO_PERF_MODE)] = isSet; - break; - case SET_GRAPHICS_METADATA: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_GRAPHICS_METADATA)] = - isSet; - break; - case SET_UBWC_CR_STATS_INFO: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_UBWC_CR_STATS_INFO)] = - isSet; - break; - case UPDATE_BUFFER_GEOMETRY: - metadata->isStandardMetadataSet[GET_STANDARD_METADATA_STATUS_INDEX( - ::android::gralloc4::MetadataType_Crop.value)] = isSet; - break; - case UPDATE_REFRESH_RATE: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_REFRESH_RATE)] = isSet; - break; - case UPDATE_COLOR_SPACE: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_COLOR_METADATA)] = isSet; - break; - case MAP_SECURE_BUFFER: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_MAP_SECURE_BUFFER)] = - isSet; - break; - case LINEAR_FORMAT: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_LINEAR_FORMAT)] = isSet; - break; - case SET_SINGLE_BUFFER_MODE: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_SINGLE_BUFFER_MODE)] = - isSet; - break; - case SET_CVP_METADATA: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_CVP_METADATA)] = isSet; - break; - case SET_VIDEO_HISTOGRAM_STATS: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_VIDEO_HISTOGRAM_STATS)] = - isSet; - break; - case SET_VIDEO_TS_INFO: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_VIDEO_TS_INFO)] = - isSet; - break; - case S3D_FORMAT: - metadata->isVendorMetadataSet[GET_VENDOR_METADATA_STATUS_INDEX(QTI_S3D_FORMAT)] = isSet; - break; - default: - ALOGE("paramType %d not supported in Gralloc4", paramType); - } -} -#else -static bool getGralloc4Array(MetaData_t *metadata, int32_t paramType) { - return true; -} - -static void setGralloc4Array(MetaData_t *metadata, int32_t paramType, bool isSet) { -} -#endif - - -unsigned long getMetaDataSize() { - return static_cast(ROUND_UP_PAGESIZE(sizeof(MetaData_t))); -} - -// Cannot add default argument to existing function -unsigned long getMetaDataSizeWithReservedRegion(uint64_t reserved_size) { - return static_cast(ROUND_UP_PAGESIZE(sizeof(MetaData_t) + reserved_size)); -} - -static int validateAndMap(private_handle_t* handle) { - if (private_handle_t::validate(handle)) { - ALOGE("%s: Private handle is invalid - handle:%p", __func__, handle); - return -1; - } - if (handle->fd_metadata < 0) { - // Metadata cannot be used - return -1; - } - - if (!handle->base_metadata) { - auto size = getMetaDataSize(); - void *base = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, - handle->fd_metadata, 0); - if (base == reinterpret_cast(MAP_FAILED)) { - ALOGE("%s: metadata mmap failed - handle:%p fd: %d err: %s", - __func__, handle, handle->fd_metadata, strerror(errno)); - return -1; - } - handle->base_metadata = (uintptr_t) base; - auto metadata = reinterpret_cast(handle->base_metadata); - if (metadata->reservedSize) { - auto reserved_size = metadata->reservedSize; - munmap(reinterpret_cast(handle->base_metadata), getMetaDataSize()); - handle->base_metadata = 0; - size = getMetaDataSizeWithReservedRegion(reserved_size); - void *new_base = - mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, handle->fd_metadata, 0); - if (new_base == reinterpret_cast(MAP_FAILED)) { - ALOGE("%s: metadata mmap failed - handle:%p fd: %d err: %s", __func__, handle, - handle->fd_metadata, strerror(errno)); - return -1; - } - handle->base_metadata = (uintptr_t)new_base; - } - } - return 0; -} - -static void unmapAndReset(private_handle_t *handle) { - if (private_handle_t::validate(handle) == 0 && handle->base_metadata) { - // If reservedSize is 0, the return value will be the same as getMetaDataSize - auto metadata = reinterpret_cast(handle->base_metadata); - auto size = getMetaDataSizeWithReservedRegion(metadata->reservedSize); - munmap(reinterpret_cast(handle->base_metadata), size); - handle->base_metadata = 0; - } -} - -int setMetaData(private_handle_t *handle, DispParamType paramType, - void *param) { - auto err = validateAndMap(handle); - if (err != 0) - return err; - return setMetaDataVa(reinterpret_cast(handle->base_metadata), - paramType, param); -} - -int setMetaDataVa(MetaData_t *data, DispParamType paramType, - void *param) { - if (data == nullptr) - return -EINVAL; - // If parameter is NULL reset the specific MetaData Key - if (!param) { - setGralloc4Array(data, paramType, false); - switch (paramType) { - case SET_VIDEO_PERF_MODE: - data->isVideoPerfMode = 0; - break; - case SET_CVP_METADATA: - data->cvpMetadata.size = 0; - break; - case SET_VIDEO_HISTOGRAM_STATS: - data->video_histogram_stats.stat_len = 0; - break; - default: - ALOGE("Unknown paramType %d", paramType); - break; - } - // param unset - return 0; - } - - setGralloc4Array(data, paramType, true); - switch (paramType) { - case PP_PARAM_INTERLACED: - data->interlaced = *((int32_t *)param); - break; - case UPDATE_BUFFER_GEOMETRY: { - BufferDim_t in = *((BufferDim_t *)param); - data->crop = {0, 0, in.sliceWidth, in.sliceHeight}; - break; - } - case UPDATE_REFRESH_RATE: - data->refreshrate = *((float *)param); - break; - case UPDATE_COLOR_SPACE: { - ColorMetaData color = {}; - if (!colorSpaceToColorMetadata(*((ColorSpace_t *)param), &color)) { - data->color = color; - break; - } - return -EINVAL; - } - case MAP_SECURE_BUFFER: - data->mapSecureBuffer = *((int32_t *)param); - break; - case S3D_FORMAT: - data->s3dFormat = *((uint32_t *)param); - break; - case LINEAR_FORMAT: - data->linearFormat = *((uint32_t *)param); - break; - case SET_SINGLE_BUFFER_MODE: - data->isSingleBufferMode = *((uint32_t *)param); - break; - case SET_VT_TIMESTAMP: - data->vtTimeStamp = *((uint64_t *)param); - break; - case COLOR_METADATA: - data->color = *((ColorMetaData *)param); - break; - case SET_UBWC_CR_STATS_INFO: { - struct UBWCStats *stats = (struct UBWCStats *)param; - int numelems = sizeof(data->ubwcCRStats) / sizeof(struct UBWCStats); - for (int i = 0; i < numelems; i++) { - data->ubwcCRStats[i] = stats[i]; - } - break; - } - case SET_VIDEO_PERF_MODE: - data->isVideoPerfMode = *((uint32_t *)param); - break; - case SET_GRAPHICS_METADATA: { - GraphicsMetadata payload = *((GraphicsMetadata*)(param)); - data->graphics_metadata.size = payload.size; - memcpy(data->graphics_metadata.data, payload.data, - sizeof(data->graphics_metadata.data)); - break; - } - case SET_CVP_METADATA: { - struct CVPMetadata *cvpMetadata = (struct CVPMetadata *)param; - if (cvpMetadata->size <= CVP_METADATA_SIZE) { - data->cvpMetadata.size = cvpMetadata->size; - memcpy(data->cvpMetadata.payload, cvpMetadata->payload, - cvpMetadata->size); - data->cvpMetadata.capture_frame_rate = cvpMetadata->capture_frame_rate; - data->cvpMetadata.cvp_frame_rate = cvpMetadata->cvp_frame_rate; - data->cvpMetadata.flags = cvpMetadata->flags; - memcpy(data->cvpMetadata.reserved, cvpMetadata->reserved, - (8 * sizeof(uint32_t))); - } else { - setGralloc4Array(data, paramType, false); - ALOGE("%s: cvp metadata length %d is more than max size %d", __func__, - cvpMetadata->size, CVP_METADATA_SIZE); - return -EINVAL; - } - break; - } - case SET_VIDEO_HISTOGRAM_STATS: { - struct VideoHistogramMetadata *vidstats = (struct VideoHistogramMetadata *)param; - if (vidstats->stat_len <= VIDEO_HISTOGRAM_STATS_SIZE) { - memcpy(data->video_histogram_stats.stats_info, - vidstats->stats_info, VIDEO_HISTOGRAM_STATS_SIZE); - data->video_histogram_stats.stat_len = vidstats->stat_len; - data->video_histogram_stats.frame_type = vidstats->frame_type; - data->video_histogram_stats.display_width = vidstats->display_width; - data->video_histogram_stats.display_height = vidstats->display_height; - data->video_histogram_stats.decode_width = vidstats->decode_width; - data->video_histogram_stats.decode_height = vidstats->decode_height; - } else { - setGralloc4Array(data, paramType, false); - ALOGE("%s: video stats length %u is more than max size %u", __func__, - vidstats->stat_len, VIDEO_HISTOGRAM_STATS_SIZE); - return -EINVAL; - } - break; - } - case SET_VIDEO_TS_INFO: - data->videoTsInfo = *((VideoTimestampInfo *)param); - break; - default: - ALOGE("Unknown paramType %d", paramType); - break; - } - return 0; -} - -int clearMetaData(private_handle_t *handle, DispParamType paramType) { - auto err = validateAndMap(handle); - if (err != 0) - return err; - return clearMetaDataVa(reinterpret_cast(handle->base_metadata), - paramType); -} - -int clearMetaDataVa(MetaData_t *data, DispParamType paramType) { - if (data == nullptr) - return -EINVAL; - data->operation &= ~paramType; - switch (paramType) { - case SET_VIDEO_PERF_MODE: - data->isVideoPerfMode = 0; - break; - case SET_CVP_METADATA: - data->cvpMetadata.size = 0; - break; - case SET_VIDEO_HISTOGRAM_STATS: - data->video_histogram_stats.stat_len = 0; - break; - default: - ALOGE("Unknown paramType %d", paramType); - break; - } - return 0; -} - -int getMetaData(private_handle_t *handle, DispFetchParamType paramType, - void *param) { - int ret = validateAndMap(handle); - if (ret != 0) - return ret; - return getMetaDataVa(reinterpret_cast(handle->base_metadata), - paramType, param); -} - -int getMetaDataVa(MetaData_t *data, DispFetchParamType paramType, - void *param) { - // Make sure we send 0 only if the operation queried is present - int ret = -EINVAL; - if (data == nullptr) - return ret; - if (param == nullptr) - return ret; - - if (!getGralloc4Array(data, paramType)) { - return ret; - } - - ret = 0; - - switch (paramType) { - case GET_PP_PARAM_INTERLACED: - *((int32_t *)param) = data->interlaced; - break; - case GET_BUFFER_GEOMETRY: - *((BufferDim_t *)param) = {data->crop.right, data->crop.bottom}; - break; - case GET_REFRESH_RATE: - *((float *)param) = data->refreshrate; - break; - case GET_COLOR_SPACE: { - ColorSpace_t color_space; - if (!colorMetaDataToColorSpace(data->color, &color_space)) { - *((ColorSpace_t *)param) = color_space; - } else { - ret = -EINVAL; - } - break; - } - case GET_MAP_SECURE_BUFFER: - *((int32_t *)param) = data->mapSecureBuffer; - break; - case GET_S3D_FORMAT: - *((uint32_t *)param) = data->s3dFormat; - break; - case GET_LINEAR_FORMAT: - *((uint32_t *)param) = data->linearFormat; - break; - case GET_SINGLE_BUFFER_MODE: - *((uint32_t *)param) = data->isSingleBufferMode; - break; - case GET_VT_TIMESTAMP: - *((uint64_t *)param) = data->vtTimeStamp; - break; - case GET_COLOR_METADATA: - *((ColorMetaData *)param) = data->color; - break; - case GET_UBWC_CR_STATS_INFO: { - struct UBWCStats *stats = (struct UBWCStats *)param; - int numelems = sizeof(data->ubwcCRStats) / sizeof(struct UBWCStats); - for (int i = 0; i < numelems; i++) { - stats[i] = data->ubwcCRStats[i]; - } - break; - } - case GET_VIDEO_PERF_MODE: - *((uint32_t *)param) = data->isVideoPerfMode; - break; - case GET_GRAPHICS_METADATA: - memcpy(param, data->graphics_metadata.data, sizeof(data->graphics_metadata.data)); - break; - case GET_CVP_METADATA: { - struct CVPMetadata *cvpMetadata = (struct CVPMetadata *)param; - cvpMetadata->size = 0; - if (data->cvpMetadata.size <= CVP_METADATA_SIZE) { - cvpMetadata->size = data->cvpMetadata.size; - memcpy(cvpMetadata->payload, data->cvpMetadata.payload, data->cvpMetadata.size); - cvpMetadata->capture_frame_rate = data->cvpMetadata.capture_frame_rate; - cvpMetadata->cvp_frame_rate = data->cvpMetadata.cvp_frame_rate; - cvpMetadata->flags = data->cvpMetadata.flags; - memcpy(cvpMetadata->reserved, data->cvpMetadata.reserved, (8 * sizeof(uint32_t))); - } else { - ret = -EINVAL; - } - break; - } - case GET_VIDEO_HISTOGRAM_STATS: { - struct VideoHistogramMetadata *vidstats = (struct VideoHistogramMetadata *)param; - vidstats->stat_len = 0; - if (data->video_histogram_stats.stat_len <= VIDEO_HISTOGRAM_STATS_SIZE) { - memcpy(vidstats->stats_info, data->video_histogram_stats.stats_info, - VIDEO_HISTOGRAM_STATS_SIZE); - vidstats->stat_len = data->video_histogram_stats.stat_len; - vidstats->frame_type = data->video_histogram_stats.frame_type; - vidstats->display_width = data->video_histogram_stats.display_width; - vidstats->display_height = data->video_histogram_stats.display_height; - vidstats->decode_width = data->video_histogram_stats.decode_width; - vidstats->decode_height = data->video_histogram_stats.decode_height; - } else { - ret = -EINVAL; - } - break; - } - case GET_VIDEO_TS_INFO: - *((VideoTimestampInfo *)param) = data->videoTsInfo; - break; - default: - ALOGE("Unknown paramType %d", paramType); - ret = -EINVAL; - break; - } - return ret; -} - -int copyMetaData(struct private_handle_t *src, struct private_handle_t *dst) { - auto err = validateAndMap(src); - if (err != 0) - return err; - - err = validateAndMap(dst); - if (err != 0) - return err; - - MetaData_t *src_data = reinterpret_cast (src->base_metadata); - MetaData_t *dst_data = reinterpret_cast (dst->base_metadata); - *dst_data = *src_data; - return 0; -} - -int copyMetaDataVaToHandle(MetaData_t *src_data, struct private_handle_t *dst) { - int err = -EINVAL; - if (src_data == nullptr) - return err; - - err = validateAndMap(dst); - if (err != 0) - return err; - - MetaData_t *dst_data = reinterpret_cast (dst->base_metadata); - *dst_data = *src_data; - return 0; -} - -int copyMetaDataHandleToVa(struct private_handle_t *src, MetaData_t *dst_data) { - int err = -EINVAL; - if (dst_data == nullptr) - return err; - - err = validateAndMap(src); - if (err != 0) - return err; - - MetaData_t *src_data = reinterpret_cast (src->base_metadata); - *dst_data = *src_data; - return 0; -} - -int copyMetaDataVaToVa(MetaData_t *src_data, MetaData_t *dst_data) { - int err = -EINVAL; - if (src_data == nullptr) - return err; - - if (dst_data == nullptr) - return err; - - *dst_data = *src_data; - return 0; -} - -int setMetaDataAndUnmap(struct private_handle_t *handle, enum DispParamType paramType, - void *param) { - auto ret = setMetaData(handle, paramType, param); - unmapAndReset(handle); - return ret; -} - -int getMetaDataAndUnmap(struct private_handle_t *handle, - enum DispFetchParamType paramType, - void *param) { - auto ret = getMetaData(handle, paramType, param); - unmapAndReset(handle); - return ret; -} diff --git a/qcom/opensource/commonsys/display/libqdmetadata/qd_utils.cpp b/qcom/opensource/commonsys/display/libqdmetadata/qd_utils.cpp deleted file mode 100755 index ac5d094b..00000000 --- a/qcom/opensource/commonsys/display/libqdmetadata/qd_utils.cpp +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (c) 2013, 2018, 2020 The Linux Foundation. All rights reserved. - - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include "qd_utils.h" - -static const int kFBNodeMax = 4; -namespace qdutils { - -static int parseLine(char *input, char *tokens[], const uint32_t maxToken, uint32_t *count) { - char *tmpToken = NULL; - char *tmpPtr; - uint32_t index = 0; - const char *delim = ", =\n"; - if (!input) { - return -1; - } - tmpToken = strtok_r(input, delim, &tmpPtr); - while (tmpToken && index < maxToken) { - tokens[index++] = tmpToken; - tmpToken = strtok_r(NULL, delim, &tmpPtr); - } - *count = index; - - return 0; -} - -static int getExternalNode(const char *type) { - FILE *displayDeviceFP = NULL; - char fbType[MAX_FRAME_BUFFER_NAME_SIZE]; - char msmFbTypePath[MAX_FRAME_BUFFER_NAME_SIZE]; - int j = 0; - - for(j = 0; j < kFBNodeMax; j++) { - snprintf (msmFbTypePath, sizeof(msmFbTypePath), - "/sys/devices/virtual/graphics/fb%d/msm_fb_type", j); - displayDeviceFP = fopen(msmFbTypePath, "r"); - if(displayDeviceFP) { - fread(fbType, sizeof(char), MAX_FRAME_BUFFER_NAME_SIZE, - displayDeviceFP); - if(strncmp(fbType, type, strlen(type)) == 0) { - ALOGD("%s: %s is at fb%d", __func__, type, j); - fclose(displayDeviceFP); - break; - } - fclose(displayDeviceFP); - } else { - ALOGE("%s: Failed to open fb node %s", __func__, msmFbTypePath); - } - } - - if (j < kFBNodeMax) - return j; - else - ALOGE("%s: Failed to find %s node", __func__, type); - - return -1; -} - -int getHDMINode(void) { - return getExternalNode("dtv panel"); -} - -int getEdidRawData(char *buffer) -{ - int size; - int edidFile; - char msmFbTypePath[MAX_FRAME_BUFFER_NAME_SIZE]; - int node_id = getHDMINode(); - - if (node_id < 0) { - ALOGE("%s no HDMI node found", __func__); - return 0; - } - - snprintf(msmFbTypePath, sizeof(msmFbTypePath), - "/sys/devices/virtual/graphics/fb%d/edid_raw_data", node_id); - - edidFile = open(msmFbTypePath, O_RDONLY, 0); - - if (edidFile < 0) { - ALOGE("%s no edid raw data found %s", __func__,msmFbTypePath); - return 0; - } - - size = (int)read(edidFile, (char*)buffer, EDID_RAW_DATA_SIZE); - close(edidFile); - return size; -} - -bool isDPConnected() { - char connectPath[MAX_FRAME_BUFFER_NAME_SIZE]; - FILE *connectFile = NULL; - size_t len = MAX_STRING_LENGTH; - char stringBuffer[MAX_STRING_LENGTH]; - char *line = stringBuffer; - - int nodeId = getExternalNode("dp panel"); - if (nodeId < 0) { - ALOGE("%s no DP node found", __func__); - return false; - } - - snprintf(connectPath, sizeof(connectPath), - "/sys/devices/virtual/graphics/fb%d/connected", nodeId); - - connectFile = fopen(connectPath, "rb"); - if (!connectFile) { - ALOGW("Failed to open connect node for device node %s", connectPath); - return false; - } - - if (getline(&line, &len, connectFile) < 0) { - fclose(connectFile); - return false; - } - - fclose(connectFile); - - return atoi(line); -} - -int getDPTestConfig(uint32_t *panelBpp, uint32_t *patternType) { - if (!panelBpp || !patternType) { - return -1; - } - - char configPath[MAX_FRAME_BUFFER_NAME_SIZE]; - FILE *configFile = NULL; - uint32_t tokenCount = 0; - const uint32_t maxCount = 10; - char *tokens[maxCount] = { NULL }; - size_t len = MAX_STRING_LENGTH; - char stringBuffer[MAX_STRING_LENGTH]; - char *line = stringBuffer; - - int nodeId = getExternalNode("dp panel"); - if (nodeId < 0) { - ALOGE("%s no DP node found", __func__); - return -EINVAL; - } - - snprintf(configPath, sizeof(configPath), - "/sys/devices/virtual/graphics/fb%d/config", nodeId); - - configFile = fopen(configPath, "rb"); - if (!configFile) { - ALOGW("Failed to open config node for device node %s", configPath); - return -EINVAL; - } - - while (getline(&line, &len, configFile) != -1) { - if (!parseLine(line, tokens, maxCount, &tokenCount)) { - if (tokens[0] != NULL) { - if (!strncmp(tokens[0], "bpp", strlen("bpp"))) { - *panelBpp = static_cast(atoi(tokens[1])); - } else if (!strncmp(tokens[0], "pattern", strlen("pattern"))) { - *patternType = static_cast(atoi(tokens[1])); - } - } - } - } - - fclose(configFile); - - return 0; -} - -DriverType getDriverType() { - const char *fb_caps = "/sys/devices/virtual/graphics/fb0/mdp/caps"; - // 0 - File exists - return access(fb_caps, F_OK) ? DriverType::DRM : DriverType::FB; -} - -const char *GetHALPixelFormatString(int format) { - switch (format) { - case HAL_PIXEL_FORMAT_RGBA_8888: - return "RGBA_8888"; - case HAL_PIXEL_FORMAT_RGBX_8888: - return "RGBX_8888"; - case HAL_PIXEL_FORMAT_RGB_888: - return "RGB_888"; - case HAL_PIXEL_FORMAT_RGB_565: - return "RGB_565"; - case HAL_PIXEL_FORMAT_BGR_565: - return "BGR_565"; - case HAL_PIXEL_FORMAT_BGRA_8888: - return "BGRA_8888"; - case HAL_PIXEL_FORMAT_RGBA_5551: - return "RGBA_5551"; - case HAL_PIXEL_FORMAT_RGBA_4444: - return "RGBA_4444"; - case HAL_PIXEL_FORMAT_YV12: - return "YV12"; - case HAL_PIXEL_FORMAT_YCbCr_422_SP: - return "YCbCr_422_SP_NV16"; - case HAL_PIXEL_FORMAT_YCrCb_420_SP: - return "YCrCb_420_SP_NV21"; - case HAL_PIXEL_FORMAT_YCbCr_422_I: - return "YCbCr_422_I_YUY2"; - case HAL_PIXEL_FORMAT_YCrCb_422_I: - return "YCrCb_422_I_YVYU"; - case HAL_PIXEL_FORMAT_NV12_ENCODEABLE: - return "NV12_ENCODEABLE"; - case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED: - return "YCbCr_420_SP_TILED_TILE_4x2"; - case HAL_PIXEL_FORMAT_YCbCr_420_SP: - return "YCbCr_420_SP"; - case HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO: - return "YCrCb_420_SP_ADRENO"; - case HAL_PIXEL_FORMAT_YCrCb_422_SP: - return "YCrCb_422_SP"; - case HAL_PIXEL_FORMAT_R_8: - return "R_8"; - case HAL_PIXEL_FORMAT_RG_88: - return "RG_88"; - case HAL_PIXEL_FORMAT_INTERLACE: - return "INTERLACE"; - case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS: - return "YCbCr_420_SP_VENUS"; - case HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS: - return "YCrCb_420_SP_VENUS"; - case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC: - return "YCbCr_420_SP_VENUS_UBWC"; - case HAL_PIXEL_FORMAT_RGBA_1010102: - return "RGBA_1010102"; - case HAL_PIXEL_FORMAT_ARGB_2101010: - return "ARGB_2101010"; - case HAL_PIXEL_FORMAT_RGBX_1010102: - return "RGBX_1010102"; - case HAL_PIXEL_FORMAT_XRGB_2101010: - return "XRGB_2101010"; - case HAL_PIXEL_FORMAT_BGRA_1010102: - return "BGRA_1010102"; - case HAL_PIXEL_FORMAT_ABGR_2101010: - return "ABGR_2101010"; - case HAL_PIXEL_FORMAT_BGRX_1010102: - return "BGRX_1010102"; - case HAL_PIXEL_FORMAT_XBGR_2101010: - return "XBGR_2101010"; - case HAL_PIXEL_FORMAT_YCbCr_420_P010: - return "YCbCr_420_P010"; - case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC: - return "YCbCr_420_TP10_UBWC"; - case HAL_PIXEL_FORMAT_YCbCr_420_P010_VENUS: - return "YCbCr_420_P010_VENUS"; - default: - return "Unknown_format"; - } -} - -}; //namespace qdutils diff --git a/qcom/opensource/commonsys/display/services/config/src/Android.bp b/qcom/opensource/commonsys/display/services/config/src/Android.bp deleted file mode 100755 index 307f773e..00000000 --- a/qcom/opensource/commonsys/display/services/config/src/Android.bp +++ /dev/null @@ -1,24 +0,0 @@ -cc_library_shared { - name: "libdisplayconfig.system.qti", - system_ext_specific: true, - cflags: [ - "-Wno-sign-conversion", - "-Wno-unused-parameter", - "-DLOG_TAG=\"libdisplayconfigqti\"", - ], - shared_libs: [ - "liblog", - "libhidlbase", - "libutils", - "vendor.display.config@2.0" - ], - header_libs: ["libhardware_headers", "display_intf_headers"], - srcs: [ - "client_interface.cpp", - "client_impl.cpp", - "device_impl.cpp", - "device_interface.cpp", - ], - export_header_lib_headers: ["display_intf_headers"], -} - diff --git a/qcom/opensource/commonsys/display/services/config/src/client_impl.cpp b/qcom/opensource/commonsys/display/services/config/src/client_impl.cpp deleted file mode 100755 index 197af93b..00000000 --- a/qcom/opensource/commonsys/display/services/config/src/client_impl.cpp +++ /dev/null @@ -1,1216 +0,0 @@ -/* -* Copyright (c) 2020-2021 The Linux Foundation. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following -* disclaimer in the documentation and/or other materials provided -* with the distribution. -* * Neither the name of The Linux Foundation. nor the names of its -* contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the - * disclaimer below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE - * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT - * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include - -#include "client_impl.h" - -namespace DisplayConfig { - -int ClientImpl::Init(std::string client_name, ConfigCallback *callback) { - display_config_ = IDisplayConfig::tryGetService(); - // Unable to find Display Config 2.0 service. Fail Init. - if (!display_config_) { - return -1; - } - int32_t error = 0; - uint64_t handle = 0; - auto hidl_callback = [&error, &handle] (int32_t err, uint64_t client_handle) { - error = err; - handle = client_handle; - }; - int pid = getpid(); - android::sp client_cb(new ClientCallback(callback)); - display_config_->registerClient(client_name + std::to_string(pid), client_cb, - hidl_callback); - client_handle_ = handle; - - return 0; -} - -void ClientImpl::DeInit() { - int32_t error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kDestroy, {}, {}, hidl_cb); - display_config_.clear(); - display_config_ = nullptr; -} - -int ClientImpl::IsDisplayConnected(DisplayType dpy, bool *connected) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&dpy), sizeof(DisplayType)); - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kIsDisplayConnected, input_params, {}, hidl_cb); - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - - if (!error) { - *connected = *output; - } - - return error; -} - -int ClientImpl::SetDisplayStatus(DisplayType dpy, ExternalStatus status) { - struct StatusParams input = {dpy, status}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct StatusParams)); - int error = 0; - - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetDisplayStatus, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::ConfigureDynRefreshRate(DynRefreshRateOp op, uint32_t refresh_rate) { - struct DynRefreshRateParams input = {op, refresh_rate}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(struct DynRefreshRateParams)); - int error = 0; - - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kConfigureDynRefreshRate, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::GetConfigCount(DisplayType dpy, uint32_t *count) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&dpy), sizeof(DisplayType)); - const uint32_t *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetConfigCount, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - *count = *output; - - return error; -} - -int ClientImpl::GetActiveConfig(DisplayType dpy, uint32_t *config) { - if (!config) { - return -EINVAL; - } - - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&dpy), sizeof(DisplayType)); - const uint32_t *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - if (display_config_) { - display_config_->perform(client_handle_, kGetActiveConfig, input_params, {}, hidl_cb); - } - - if (!error) { - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - *config = *output; - } - - return error; -} - -int ClientImpl::SetActiveConfig(DisplayType dpy, uint32_t config) { - struct ConfigParams input = {dpy, config}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct ConfigParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetActiveConfig, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::GetDisplayAttributes(uint32_t config_index, DisplayType dpy, - Attributes *attributes) { - struct AttributesParams input = {config_index, dpy}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct AttributesParams)); - const struct Attributes *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetDisplayAttributes, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - if (!error) { - *attributes = *output; - } - - return error; -} - -int ClientImpl::SetPanelBrightness(uint32_t level) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&level), sizeof(uint32_t)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetPanelBrightness, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::GetPanelBrightness(uint32_t *level) { - const uint32_t *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetPanelBrightness, {}, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - if (!error) { - *level = *output; - } - - return error; -} - -int ClientImpl::MinHdcpEncryptionLevelChanged(DisplayType dpy, uint32_t min_enc_level) { - struct MinHdcpEncLevelChangedParams input = {dpy, min_enc_level}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(struct MinHdcpEncLevelChangedParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kMinHdcpEncryptionLevelChanged, - input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::RefreshScreen() { - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kRefreshScreen, {}, {}, hidl_cb); - - return error; -} - -int ClientImpl::ControlPartialUpdate(DisplayType dpy, bool enable) { - struct PartialUpdateParams input = {dpy, enable}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(struct PartialUpdateParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kControlPartialUpdate, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::ToggleScreenUpdate(bool on) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&on), sizeof(bool)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kToggleScreenUpdate, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::SetIdleTimeout(uint32_t value) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&value), sizeof(uint32_t)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetIdleTimeout, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::GetHDRCapabilities(DisplayType dpy, HDRCapsParams *caps) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&dpy), sizeof(DisplayType)); - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetHdrCapabilities, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - - if (!error) { - const int32_t *hdr_caps; - const float *lum; - size_t size = output_params.size(); - size_t hdr_caps_size = size - 3 * sizeof(float); - hdr_caps_size /= sizeof(int32_t); - hdr_caps = reinterpret_cast(data); - for (size_t i = 0; i < hdr_caps_size; i++) { - caps->supported_hdr_types.push_back(*hdr_caps); - hdr_caps++; - } - lum = reinterpret_cast(hdr_caps); - caps->max_luminance = lum[0]; - caps->max_avg_luminance = lum[1]; - caps->min_luminance = lum[2]; - } - - return error; -} - -int ClientImpl::SetCameraLaunchStatus(uint32_t on) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&on), sizeof(uint32_t)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetCameraLaunchStatus, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::SetCameraSmoothInfo(CameraSmoothOp op, uint32_t fps) { - CameraSmoothInfo input = {op, fps}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(CameraSmoothInfo)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetCameraSmoothInfo, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::DisplayBWTransactionPending(bool *status) { - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kDisplayBwTransactionPending, {}, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - if (!error) { - *status = *output; - } - - return error; -} - -int ClientImpl::SetDisplayAnimating(uint64_t display_id, bool animating) { - struct AnimationParams input = {display_id, animating}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct AnimationParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetDisplayAnimating, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::ControlIdlePowerCollapse(bool enable, bool synchronous) { - struct IdlePcParams input = {enable, synchronous}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct IdlePcParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kControlIdlePowerCollapse, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::GetWriteBackCapabilities(bool *is_wb_ubwc_supported) { - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetWritebackCapabilities, {}, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - if (!error) { - *is_wb_ubwc_supported = *output; - } - - return error; -} - -int ClientImpl::SetDisplayDppsAdROI(uint32_t display_id, uint32_t h_start, - uint32_t h_end, uint32_t v_start, uint32_t v_end, - uint32_t factor_in, uint32_t factor_out) { - struct DppsAdRoiParams input = {display_id, h_start, h_end, v_start, v_end, - factor_in, factor_out}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct DppsAdRoiParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetDisplayDppsAdRoi, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::UpdateVSyncSourceOnPowerModeOff() { - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kUpdateVsyncSourceOnPowerModeOff, {}, {}, hidl_cb); - - return error; -} - -int ClientImpl::UpdateVSyncSourceOnPowerModeDoze() { - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kUpdateVsyncSourceOnPowerModeDoze, {}, {}, hidl_cb); - - return error; -} - -int ClientImpl::SetPowerMode(uint32_t disp_id, PowerMode power_mode) { - struct PowerModeParams input = {disp_id, power_mode}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct PowerModeParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetPowerMode, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::IsPowerModeOverrideSupported(uint32_t disp_id, bool *supported) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&disp_id), sizeof(uint32_t)); - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kIsPowerModeOverrideSupported, - input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - - if (!error) { - *supported = *output; - } - - return error; -} - -int ClientImpl::IsHDRSupported(uint32_t disp_id, bool *supported) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&disp_id), sizeof(uint32_t)); - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kIsHdrSupported, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - - if (!error) { - *supported = *output; - } - - return error; -} - -int ClientImpl::IsWCGSupported(uint32_t disp_id, bool *supported) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&disp_id), sizeof(int32_t)); - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kIsWcgSupported, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - - if (!error) { - *supported = *output; - } - - return error; -} - -int ClientImpl::SetLayerAsMask(uint32_t disp_id, uint64_t layer_id) { - struct LayerMaskParams input = {disp_id, layer_id}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct LayerMaskParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetLayerAsMask, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::GetDebugProperty(const std::string prop_name, std::string *value) { - ByteStream input_params; - std::string prop(prop_name); - prop += '\0'; - uint8_t *data_input = reinterpret_cast(const_cast(prop.data())); - input_params.setToExternal(reinterpret_cast(data_input), - prop.size() * sizeof(char)); - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetDebugProperty, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - const char *name = reinterpret_cast(data); - if (!error) { - std::string output(name); - *value = output; - } - - return error; -} - -int ClientImpl::GetActiveBuiltinDisplayAttributes(Attributes *attr) { - const struct Attributes *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetActiveBuiltinDisplayAttributes, {}, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - if (!error) { - *attr = *output; - } - - return error; -} - -int ClientImpl::SetPanelLuminanceAttributes(uint32_t disp_id, float min_lum, float max_lum) { - struct PanelLumAttrParams input = {disp_id, min_lum, max_lum}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct PanelLumAttrParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetPanelLuminanceAttributes, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::IsBuiltInDisplay(uint32_t disp_id, bool *is_builtin) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&disp_id), sizeof(uint32_t)); - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kIsBuiltinDisplay, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - - if (!error) { - *is_builtin = *output; - } - - return error; -} - -int ClientImpl::SetCWBOutputBuffer(uint32_t disp_id, const Rect rect, bool post_processed, - const native_handle_t *buffer) { - struct CwbBufferParams input = {disp_id, rect, post_processed}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct CwbBufferParams)); - - hidl_handle handle = buffer; - std::vector handle_vector; - handle_vector.push_back(buffer); - HandleStream input_handles = handle_vector; - - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetCwbOutputBuffer, input_params, - input_handles, hidl_cb); - - return error; -} - -int ClientImpl::GetSupportedDSIBitClks(uint32_t disp_id, std::vector *bit_clks) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&disp_id), sizeof(uint32_t)); - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetSupportedDsiBitclks, input_params, {}, hidl_cb); - - if (!error) { - const uint8_t *data = output_params.data(); - const uint64_t *bit_clks_data = reinterpret_cast(data); - int num_bit_clks = static_cast(output_params.size() / sizeof(uint64_t)); - for (int i = 0; i < num_bit_clks; i++) { - bit_clks->push_back(bit_clks_data[i]); - } - } - - return error; -} - -int ClientImpl::GetDSIClk(uint32_t disp_id, uint64_t *bit_clk) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&disp_id), sizeof(uint32_t)); - const uint64_t *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetDsiClk, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - - if (!error) { - *bit_clk = *output; - } - - return error; -} - -int ClientImpl::SetDSIClk(uint32_t disp_id, uint64_t bit_clk) { - struct DsiClkParams input = {disp_id, bit_clk}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct DsiClkParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetDsiClk, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::SetQsyncMode(uint32_t disp_id, QsyncMode mode) { - struct QsyncModeParams input = {disp_id, mode}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct QsyncModeParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetQsyncMode, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::IsSmartPanelConfig(uint32_t disp_id, uint32_t config_id, bool *is_smart) { - struct SmartPanelCfgParams input = {disp_id, config_id}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(struct SmartPanelCfgParams)); - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kIsSmartPanelConfig, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - - if (!error) { - *is_smart = *output; - } - - return error; -} - -int ClientImpl::IsAsyncVDSCreationSupported(bool *supported) { - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kIsAsyncVdsSupported, {}, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - - if (!error) { - *supported = *output; - } - - return error; -} - -int ClientImpl::CreateVirtualDisplay(uint32_t width, uint32_t height, int32_t format) { - struct VdsParams input = {width, height, format}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct VdsParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kCreateVirtualDisplay, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::IsRotatorSupportedFormat(int hal_format, bool ubwc, bool *supported) { - struct RotatorFormatParams input = {hal_format, ubwc}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(struct RotatorFormatParams)); - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kIsRotatorSupportedFormat, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - - if (!error) { - *supported = *output; - } - - return error; -} - -int ClientImpl::ControlQsyncCallback(bool enable) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&enable), sizeof(bool)); - int32_t error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kControlQsyncCallback, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::ControlIdleStatusCallback(bool enable) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&enable), sizeof(bool)); - int32_t error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kControlIdleStatusCallback, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::ControlCameraSmoothCallback(bool enable) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&enable), sizeof(bool)); - int32_t error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kControlCameraSmoothCallback, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::SendTUIEvent(DisplayType dpy, TUIEventType event_type) { - struct TUIEventParams input = {dpy, event_type}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), sizeof(struct TUIEventParams)); - int32_t error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSendTUIEvent, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::DummyDisplayConfigAPI() { - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - display_config_->perform(client_handle_, kDummyOpcode, {}, {}, hidl_cb); - if (error) { - return -EINVAL; - } - return error; -} - -int ClientImpl::GetDisplayHwId(uint32_t disp_id, uint32_t *display_hw_id) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&disp_id), sizeof(uint32_t)); - ByteStream output_params; - - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetDisplayHwId, input_params, {}, hidl_cb); - - const uint8_t *data = output_params.data(); - const uint32_t *output = reinterpret_cast(data); - - if (!error) { - *display_hw_id = *output; - } - - return error; -} - -int ClientImpl::GetSupportedDisplayRefreshRates(DisplayType dpy, - std::vector *supported_refresh_rates) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&dpy), sizeof(DisplayType)); - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params](int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetSupportedDisplayRefreshRates, input_params, {}, - hidl_cb); - - if (!error) { - const uint8_t *data = output_params.data(); - const uint32_t *refresh_rates_data = reinterpret_cast(data); - int num_refresh_rates = static_cast(output_params.size() / sizeof(uint32_t)); - for (int i = 0; i < num_refresh_rates; i++) { - supported_refresh_rates->push_back(refresh_rates_data[i]); - } - } - - return error; -} - -int ClientImpl::IsRCSupported(uint32_t disp_id, bool *supported) { - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&disp_id), sizeof(uint32_t)); - const bool *output; - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kIsRCSupported, input_params, {}, hidl_cb); - - if (!error) { - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - *supported = *output; - } - - return error; -} - -int ClientImpl::IsSupportedConfigSwitch(uint32_t disp_id, uint32_t config, bool *supported) { - struct SupportedModesParams input = {disp_id, config}; - ByteStream input_params; - ByteStream output_params; - const bool *output; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(struct SupportedModesParams)); - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - if (display_config_) { - display_config_->perform(client_handle_, kIsSupportedConfigSwitch, input_params, {}, hidl_cb); - } - - if (!error) { - const uint8_t *data = output_params.data(); - output = reinterpret_cast(data); - *supported = *output; - } - - return error; -} - -int ClientImpl::GetDisplayType(uint64_t physical_disp_id, DisplayType *disp_type) { - if (!disp_type) { - return -EINVAL; - } - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&physical_disp_id), sizeof(uint64_t)); - ByteStream output_params; - int error = 0; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - if (display_config_) { - display_config_->perform(client_handle_, kGetDisplayType, input_params, {}, hidl_cb); - } - - if (!error) { - const uint8_t *data = output_params.data(); - const DisplayType *output = reinterpret_cast(data); - *disp_type = *output; - } - return error; -} - -int ClientImpl::AllowIdleFallback() { - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - if (display_config_) { - display_config_->perform(client_handle_, kAllowIdleFallback, {}, {}, hidl_cb); - } - return error; -} - -void ClientCallback::ParseNotifyCWBBufferDone(const ByteStream &input_params, - const HandleStream &input_handles) { - const int *error; - - if (callback_ == nullptr || input_params.size() == 0 || input_handles.size() == 0) { - return; - } - - const uint8_t *data = input_params.data(); - error = reinterpret_cast(data); - hidl_handle buffer = input_handles[0]; - callback_->NotifyCWBBufferDone(*error, buffer.getNativeHandle()); -} - -void ClientCallback::ParseNotifyQsyncChange(const ByteStream &input_params) { - const struct QsyncCallbackParams *qsync_data; - - if (callback_ == nullptr || input_params.size() == 0) { - return; - } - - const uint8_t *data = input_params.data(); - qsync_data = reinterpret_cast(data); - callback_->NotifyQsyncChange(qsync_data->qsync_enabled, qsync_data->refresh_rate, - qsync_data->qsync_refresh_rate); -} - -void ClientCallback::ParseNotifyCameraSmooth(const ByteStream &input_params) { - if (callback_ == nullptr || input_params.size() == 0) { - return; - } - - const uint8_t *data = input_params.data(); - const CameraSmoothInfo *camera_info = reinterpret_cast(data); - callback_->NotifyCameraSmoothInfo(camera_info->op, camera_info->fps); -} - -void ClientCallback::ParseNotifyIdleStatus(const ByteStream &input_params) { - const bool *is_idle; - if (callback_ == nullptr || input_params.size() == 0) { - return; - } - - const uint8_t *data = input_params.data(); - is_idle = reinterpret_cast(data); - callback_->NotifyIdleStatus(*is_idle); -} - -int ClientImpl::GetDisplayTileCount(uint64_t physical_disp_id, uint32_t *num_h_tiles, - uint32_t *num_v_tiles) { - if (!num_h_tiles || !num_v_tiles) { - return -EINVAL; - } - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&physical_disp_id), sizeof(uint64_t)); - int error = 0; - ByteStream output_params; - auto hidl_cb = [&error, &output_params] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - output_params = params; - }; - - display_config_->perform(client_handle_, kGetDisplayTileCount, input_params, {}, hidl_cb); - - if (!error) { - const uint32_t *data = reinterpret_cast(output_params.data()); - *num_h_tiles = data ? *data : 0; - *num_v_tiles = data ? *(data + 1) : 0; - } - - return error; -} - -int ClientImpl::SetPowerModeTiled(uint64_t physical_disp_id, PowerMode power_mode, - uint32_t tile_h_loc, uint32_t tile_v_loc) { - struct PowerModeTiledParams input = {physical_disp_id, power_mode, tile_h_loc, tile_v_loc}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(struct PowerModeTiledParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetPowerModeTiled, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::SetPanelBrightnessTiled(uint64_t physical_disp_id, uint32_t level, - uint32_t tile_h_loc, uint32_t tile_v_loc) { - struct PanelBrightnessTiledParams input = {physical_disp_id, level, tile_h_loc, tile_v_loc}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(struct PanelBrightnessTiledParams)); - int error = 0; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetPanelBrightnessTiled, input_params, {}, hidl_cb); - - return error; -} - -int ClientImpl::SetWiderModePreference(uint64_t physical_disp_id, WiderModePref mode_pref) { - struct WiderModePrefParams input = {physical_disp_id, mode_pref}; - ByteStream input_params; - input_params.setToExternal(reinterpret_cast(&input), - sizeof(struct WiderModePrefParams)); - int error = 0; - ByteStream output_params; - auto hidl_cb = [&error] (int32_t err, ByteStream params, HandleStream handles) { - error = err; - }; - - display_config_->perform(client_handle_, kSetWiderModePref, input_params, {}, hidl_cb); - - return error; -} - -Return ClientCallback::perform(uint32_t op_code, const ByteStream &input_params, - const HandleStream &input_handles) { - switch (op_code) { - case kSetCwbOutputBuffer: - ParseNotifyCWBBufferDone(input_params, input_handles); - break; - case kControlQsyncCallback: - ParseNotifyQsyncChange(input_params); - break; - case kControlIdleStatusCallback: - ParseNotifyIdleStatus(input_params); - break; - case kSetCameraSmoothInfo: - ParseNotifyCameraSmooth(input_params); - break; - default: - break; - } - - return Void(); -} - -} // namespace DisplayConfig diff --git a/qcom/opensource/commonsys/display/services/config/src/client_impl.h b/qcom/opensource/commonsys/display/services/config/src/client_impl.h deleted file mode 100755 index dc4f0a15..00000000 --- a/qcom/opensource/commonsys/display/services/config/src/client_impl.h +++ /dev/null @@ -1,185 +0,0 @@ -/* -* Copyright (c) 2020-2021 The Linux Foundation. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following -* disclaimer in the documentation and/or other materials provided -* with the distribution. -* * Neither the name of The Linux Foundation. nor the names of its -* contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the - * disclaimer below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE - * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT - * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __CLIENT_IMPL_H__ -#define __CLIENT_IMPL_H__ - -#define VALIDATE_CONFIG_SWITCH 1 - -#include -#include -#include -#include -#include -#include - -#include "opcode_types.h" - -namespace DisplayConfig { - -using vendor::display::config::V2_0::IDisplayConfig; -using vendor::display::config::V2_0::IDisplayConfigCallback; -using ::android::hardware::Return; -using ::android::hardware::Void; -using ::android::hardware::hidl_handle; -using ::android::hardware::hidl_vec; - -typedef hidl_vec ByteStream; -typedef hidl_vec HandleStream; - -class ClientCallback: public IDisplayConfigCallback { - public: - ClientCallback(ConfigCallback *cb) { - callback_ = cb; - } - - private: - virtual Return perform(uint32_t op_code, const ByteStream &input_params, - const HandleStream &input_handles); - void ParseNotifyCWBBufferDone(const ByteStream &input_params, const HandleStream &input_handles); - void ParseNotifyQsyncChange(const ByteStream &input_params); - void ParseNotifyIdleStatus(const ByteStream &input_params); - void ParseNotifyCameraSmooth(const ByteStream &input_params); - ConfigCallback *callback_ = nullptr; -}; - -class ClientImpl : public ClientInterface { - public: - int Init(std::string client_name, ConfigCallback *callback); - void DeInit(); - - virtual int IsDisplayConnected(DisplayType dpy, bool *connected); - virtual int SetDisplayStatus(DisplayType dpy, ExternalStatus status); - virtual int ConfigureDynRefreshRate(DynRefreshRateOp op, uint32_t refresh_rate); - virtual int GetConfigCount(DisplayType dpy, uint32_t *count); - virtual int GetActiveConfig(DisplayType dpy, uint32_t *config); - virtual int SetActiveConfig(DisplayType dpy, uint32_t config); - virtual int GetDisplayAttributes(uint32_t config_index, DisplayType dpy, Attributes *attributes); - virtual int SetPanelBrightness(uint32_t level); - virtual int GetPanelBrightness(uint32_t *level); - virtual int MinHdcpEncryptionLevelChanged(DisplayType dpy, uint32_t min_enc_level); - virtual int RefreshScreen(); - virtual int ControlPartialUpdate(DisplayType dpy, bool enable); - virtual int ToggleScreenUpdate(bool on); - virtual int SetIdleTimeout(uint32_t value); - virtual int GetHDRCapabilities(DisplayType dpy, HDRCapsParams *caps); - virtual int SetCameraLaunchStatus(uint32_t on); - virtual int SetCameraSmoothInfo(CameraSmoothOp op, uint32_t fps); - virtual int DisplayBWTransactionPending(bool *status); - virtual int SetDisplayAnimating(uint64_t display_id, bool animating); - virtual int ControlIdlePowerCollapse(bool enable, bool synchronous); - virtual int GetWriteBackCapabilities(bool *is_wb_ubwc_supported); - virtual int SetDisplayDppsAdROI(uint32_t display_id, uint32_t h_start, uint32_t h_end, - uint32_t v_start, uint32_t v_end, uint32_t factor_in, - uint32_t factor_out); - virtual int UpdateVSyncSourceOnPowerModeOff(); - virtual int UpdateVSyncSourceOnPowerModeDoze(); - virtual int SetPowerMode(uint32_t disp_id, PowerMode power_mode); - virtual int IsPowerModeOverrideSupported(uint32_t disp_id, bool *supported); - virtual int IsHDRSupported(uint32_t disp_id, bool *supported); - virtual int IsWCGSupported(uint32_t disp_id, bool *supported); - virtual int SetLayerAsMask(uint32_t disp_id, uint64_t layer_id); - virtual int GetDebugProperty(const std::string prop_name, std::string *value); - virtual int GetActiveBuiltinDisplayAttributes(Attributes *attr); - virtual int SetPanelLuminanceAttributes(uint32_t disp_id, float min_lum, float max_lum); - virtual int IsBuiltInDisplay(uint32_t disp_id, bool *is_builtin); - virtual int IsAsyncVDSCreationSupported(bool *supported); - virtual int CreateVirtualDisplay(uint32_t width, uint32_t height, int format); - virtual int GetSupportedDSIBitClks(uint32_t disp_id, std::vector *bit_clks); - virtual int GetDSIClk(uint32_t disp_id, uint64_t *bit_clk); - virtual int SetDSIClk(uint32_t disp_id, uint64_t bit_clk); - virtual int SetCWBOutputBuffer(uint32_t disp_id, const Rect rect, bool post_processed, - const native_handle_t *buffer); - virtual int SetQsyncMode(uint32_t disp_id, QsyncMode mode); - virtual int IsSmartPanelConfig(uint32_t disp_id, uint32_t config_id, bool *is_smart); - virtual int IsRotatorSupportedFormat(int hal_format, bool ubwc, bool *supported); - virtual int ControlQsyncCallback(bool enable); - virtual int SendTUIEvent(DisplayType dpy, TUIEventType event_type); - virtual int GetDisplayHwId(uint32_t disp_id, uint32_t *display_hw_id); - virtual int GetSupportedDisplayRefreshRates(DisplayType dpy, - std::vector *supported_refresh_rates); - virtual int IsRCSupported(uint32_t disp_id, bool *supported); - virtual int ControlIdleStatusCallback(bool enable); - virtual int IsSupportedConfigSwitch(uint32_t disp_id, uint32_t config, bool *supported); - virtual int GetDisplayType(uint64_t physical_disp_id, DisplayType *disp_type); - virtual int AllowIdleFallback(); - virtual int GetDisplayTileCount(uint64_t physical_disp_id, uint32_t *num_h_tiles, - uint32_t *num_v_tiles); - virtual int SetPowerModeTiled(uint64_t physical_disp_id, PowerMode power_mode, - uint32_t tile_h_loc, uint32_t tile_v_loc); - virtual int SetPanelBrightnessTiled(uint64_t physical_disp_id, uint32_t level, - uint32_t tile_h_loc, uint32_t tile_v_loc); - virtual int SetWiderModePreference(uint64_t physical_disp_id, WiderModePref mode_pref); - virtual int ControlCameraSmoothCallback(bool enable); - virtual int DummyDisplayConfigAPI(); - - private: - android::sp display_config_ = nullptr; - uint64_t client_handle_ = 0; -}; - -} // namespace DisplayConfig - -#endif // __CLIENT_IMPL_H__ diff --git a/qcom/opensource/commonsys/display/services/config/src/client_interface.cpp b/qcom/opensource/commonsys/display/services/config/src/client_interface.cpp deleted file mode 100755 index 9c9ecd2b..00000000 --- a/qcom/opensource/commonsys/display/services/config/src/client_interface.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* -* Copyright (c) 2020 The Linux Foundation. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following -* disclaimer in the documentation and/or other materials provided -* with the distribution. -* * Neither the name of The Linux Foundation. nor the names of its -* contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include - -#include "client_impl.h" - -namespace DisplayConfig { - -int ClientInterface::Create(std::string client_name, ConfigCallback *callback, - ClientInterface **intf) { - if (!intf) { - return -1; - } - - ClientImpl *impl = new ClientImpl(); - if (!impl) { - return -1; - } - - int ret = impl->Init(client_name, callback); - if (ret) { - delete impl; - return -1; - } - - *intf = impl; - return 0; -} - -void ClientInterface::Destroy(ClientInterface *intf) { - if (intf) { - ClientImpl *impl = static_cast(intf); - impl->DeInit(); - delete impl; - } -} - -} // namespace DisplayConfig diff --git a/qcom/opensource/commonsys/display/services/config/src/device_impl.cpp b/qcom/opensource/commonsys/display/services/config/src/device_impl.cpp deleted file mode 100755 index 4541368e..00000000 --- a/qcom/opensource/commonsys/display/services/config/src/device_impl.cpp +++ /dev/null @@ -1,1189 +0,0 @@ -/* -* Copyright (c) 2020-2021 The Linux Foundation. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following -* disclaimer in the documentation and/or other materials provided -* with the distribution. -* * Neither the name of The Linux Foundation. nor the names of its -* contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the - * disclaimer below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE - * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT - * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include - -#include "device_impl.h" - -namespace DisplayConfig { - -DeviceImpl *DeviceImpl::device_obj_ = nullptr; -std::mutex DeviceImpl::device_lock_; - -int DeviceImpl::CreateInstance(ClientContext *intf) { - std::lock_guard lock(device_lock_); - if (!device_obj_) { - device_obj_ = new DeviceImpl(); - if (!device_obj_) { - return -1; - } - - android::status_t status = device_obj_->IDisplayConfig::registerAsService(); - // Unable to start Display Config 2.0 service. Fail Init. - if (status != android::OK) { - device_obj_ = nullptr; - return -1; - } - device_obj_->intf_ = intf; - } - - return 0; -} - -Return DeviceImpl::registerClient(const hidl_string &client_name, - const sp& callback, - registerClient_cb _hidl_cb) { - int32_t error = 0; - std::string client_name_str = client_name.c_str(); - if (client_name_str.empty()) { - error = -EINVAL; - _hidl_cb(error, 0); - return Void(); - } - - if (!callback) { - ALOGW("IDisplayConfigCallback provided is null"); - } - - uint64_t client_handle = static_cast(client_id_++); - std::shared_ptr device_client(new DeviceClientContext(callback)); - if (callback) { - callback->linkToDeath(this, client_handle); - } - - if (!intf_) { - ALOGW("ConfigInterface is invalid"); - _hidl_cb(error, 0); - return Void(); - } - - if (!device_client) { - ALOGW("Failed to initialize device client:%s", client_name.c_str()); - _hidl_cb(error, 0); - return Void(); - } - - ConfigInterface *intf = nullptr; - error = intf_->RegisterClientContext(device_client, &intf); - - if (error) { - callback->unlinkToDeath(this); - return Void(); - } - - device_client->SetDeviceConfigIntf(intf); - - std::lock_guard lock(death_service_mutex_); - ALOGI("Register client name: %s device client: %p", client_name.c_str(), device_client.get()); - display_config_map_.emplace(std::make_pair(client_handle, device_client)); - _hidl_cb(error, client_handle); - return Void(); -} - -void DeviceImpl::serviceDied(uint64_t client_handle, - const android::wp<::android::hidl::base::V1_0::IBase>& callback) { - std::lock_guard lock(death_service_mutex_); - auto itr = display_config_map_.find(client_handle); - std::shared_ptr client = itr->second; - if (client != NULL) { - ConfigInterface *intf = client->GetDeviceConfigIntf(); - intf_->UnRegisterClientContext(intf); - client.reset(); - ALOGW("Client id:%" PRIu64 " service died", client_handle); - display_config_map_.erase(itr); - } -} - -DeviceImpl::DeviceClientContext::DeviceClientContext( - const sp callback) : callback_(callback) { } - -sp DeviceImpl::DeviceClientContext::GetDeviceConfigCallback() { - return callback_; -} - -void DeviceImpl::DeviceClientContext::SetDeviceConfigIntf(ConfigInterface *intf) { - intf_ = intf; -} - -ConfigInterface* DeviceImpl::DeviceClientContext::GetDeviceConfigIntf() { - return intf_; -} - -void DeviceImpl::DeviceClientContext::NotifyCWBBufferDone(int32_t error, - const native_handle_t *buffer) { - ByteStream output_params; - HandleStream output_handles; - std::vector handles; - - output_params.setToExternal(reinterpret_cast(&error), sizeof(int)); - handles.push_back(buffer); - output_handles = handles; - - auto status = callback_->perform(kSetCwbOutputBuffer, output_params, output_handles); - if (status.isDeadObject()) { - return; - } -} - -void DeviceImpl::DeviceClientContext::NotifyQsyncChange(bool qsync_enabled, int32_t refresh_rate, - int32_t qsync_refresh_rate) { - struct QsyncCallbackParams data = {qsync_enabled, refresh_rate, qsync_refresh_rate}; - ByteStream output_params; - - output_params.setToExternal(reinterpret_cast(&data), sizeof(data)); - - auto status = callback_->perform(kControlQsyncCallback, output_params, {}); - if (status.isDeadObject()) { - return; - } -} - -void DeviceImpl::DeviceClientContext::NotifyIdleStatus(bool is_idle) { - bool data = {is_idle}; - ByteStream output_params; - - output_params.setToExternal(reinterpret_cast(&data), sizeof(data)); - - auto status = callback_->perform(kControlIdleStatusCallback, output_params, {}); - if (status.isDeadObject()) { - return; - } -} - -void DeviceImpl::DeviceClientContext::NotifyCameraSmoothInfo(CameraSmoothOp op, uint32_t fps) { - struct CameraSmoothInfo data = {op, fps}; - ByteStream output_params; - - output_params.setToExternal(reinterpret_cast(&data), sizeof(data)); - - auto status = callback_->perform(kSetCameraSmoothInfo, output_params, {}); - if (status.isDeadObject()) { - return; - } -} - -void DeviceImpl::DeviceClientContext::ParseIsDisplayConnected(const ByteStream &input_params, - perform_cb _hidl_cb) { - const DisplayType *dpy; - bool connected = false; - ByteStream output_params; - - const uint8_t *data = input_params.data(); - dpy = reinterpret_cast(data); - int32_t error = intf_->IsDisplayConnected(*dpy, &connected); - - output_params.setToExternal(reinterpret_cast(&connected), - sizeof(connected)); - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetDisplayStatus(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct StatusParams *display_status; - const uint8_t *data = input_params.data(); - display_status = reinterpret_cast(data); - int32_t error = intf_->SetDisplayStatus(display_status->dpy, - display_status->status); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseConfigureDynRefreshRate(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct DynRefreshRateParams *dyn_refresh_data; - const uint8_t *data = input_params.data(); - dyn_refresh_data = reinterpret_cast(data); - int32_t error = intf_->ConfigureDynRefreshRate(dyn_refresh_data->op, - dyn_refresh_data->refresh_rate); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetConfigCount(const ByteStream &input_params, - perform_cb _hidl_cb) { - const DisplayType *dpy; - uint32_t count = 0; - ByteStream output_params; - - if (input_params.size() == 0) { - _hidl_cb(-ENODATA, {}, {}); - return; - } - - const uint8_t *data = input_params.data(); - dpy = reinterpret_cast(data); - int32_t error = intf_->GetConfigCount(*dpy, &count); - output_params.setToExternal(reinterpret_cast(&count), - sizeof(uint32_t)); - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetActiveConfig(const ByteStream &input_params, - perform_cb _hidl_cb) { - const DisplayType *dpy; - uint32_t config = 0; - ByteStream output_params; - - const uint8_t *data = input_params.data(); - dpy = reinterpret_cast(data); - int32_t error = intf_->GetActiveConfig(*dpy, &config); - output_params.setToExternal(reinterpret_cast(&config), - sizeof(uint32_t)); - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetActiveConfig(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct ConfigParams *set_active_cfg_data; - - const uint8_t *data = input_params.data(); - set_active_cfg_data = reinterpret_cast(data); - int32_t error = intf_->SetActiveConfig(set_active_cfg_data->dpy, - set_active_cfg_data->config); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetDisplayAttributes(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct AttributesParams *get_disp_attr_data; - struct Attributes attributes = {}; - ByteStream output_params; - int32_t error = -EINVAL; - - const uint8_t *data = input_params.data(); - get_disp_attr_data = reinterpret_cast(data); - error = intf_->GetDisplayAttributes(get_disp_attr_data->config_index, get_disp_attr_data->dpy, - &attributes); - output_params.setToExternal(reinterpret_cast(&attributes), - sizeof(struct Attributes)); - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetPanelBrightness(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint32_t *level; - int32_t error = 0; - - const uint8_t *data = input_params.data(); - level = reinterpret_cast(data); - error = intf_->SetPanelBrightness(*level); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetPanelBrightness(perform_cb _hidl_cb) { - uint32_t level = 0; - ByteStream output_params; - int32_t error = -EINVAL; - - error = intf_->GetPanelBrightness(&level); - output_params.setToExternal(reinterpret_cast(&level), - sizeof(uint32_t)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseMinHdcpEncryptionLevelChanged( - const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct MinHdcpEncLevelChangedParams *min_hdcp_enc_level_data; - int32_t error = 0; - - const uint8_t *data = input_params.data(); - min_hdcp_enc_level_data = reinterpret_cast(data); - error = intf_->MinHdcpEncryptionLevelChanged(min_hdcp_enc_level_data->dpy, - min_hdcp_enc_level_data->min_enc_level); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseRefreshScreen(perform_cb _hidl_cb) { - int32_t error = intf_->RefreshScreen(); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseControlPartialUpdate(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct PartialUpdateParams *partial_update_data; - int32_t error = 0; - - const uint8_t *data = input_params.data(); - partial_update_data = reinterpret_cast(data); - error = intf_->ControlPartialUpdate(partial_update_data->dpy, partial_update_data->enable); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseToggleScreenUpdate(const ByteStream &input_params, - perform_cb _hidl_cb) { - const bool *on; - int32_t error = 0; - - const uint8_t *data = input_params.data(); - on = reinterpret_cast(data); - error = intf_->ToggleScreenUpdate(on); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetIdleTimeout(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint32_t *timeout_value; - - const uint8_t *data = input_params.data(); - timeout_value = reinterpret_cast(data); - int32_t error = intf_->SetIdleTimeout(*timeout_value); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetHdrCapabilities(const ByteStream &input_params, - perform_cb _hidl_cb) { - const DisplayType *dpy; - ByteStream output_params; - struct HDRCapsParams hdr_caps; - int32_t *data_output; - int32_t error = -EINVAL; - - const uint8_t *data = input_params.data(); - dpy = reinterpret_cast(data); - error = intf_->GetHDRCapabilities(*dpy, &hdr_caps); - - data_output = reinterpret_cast(malloc(sizeof(int32_t) * - hdr_caps.supported_hdr_types.size() + 3 * sizeof(float))); - if (data_output != NULL) { - for (int i = 0; i < hdr_caps.supported_hdr_types.size(); i++) { - data_output[i] = hdr_caps.supported_hdr_types[i]; - } - float *lum = reinterpret_cast(&data_output[hdr_caps.supported_hdr_types.size()]); - *lum = hdr_caps.max_luminance; - lum++; - *lum = hdr_caps.max_avg_luminance; - lum++; - *lum = hdr_caps.min_luminance; - output_params.setToExternal(reinterpret_cast(data_output), sizeof(int32_t) * - hdr_caps.supported_hdr_types.size() + 3 * sizeof(float)); - _hidl_cb(error, output_params, {}); - } - else { - _hidl_cb(-EINVAL, {}, {}); - } -} - -void DeviceImpl::DeviceClientContext::ParseSetCameraLaunchStatus(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint32_t *launch_status_data; - - const uint8_t *data = input_params.data(); - launch_status_data = reinterpret_cast(data); - - int32_t error = intf_->SetCameraLaunchStatus(*launch_status_data); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetCameraSmoothInfo(const ByteStream &input_params, - perform_cb _hidl_cb) { - const CameraSmoothInfo *camera_info; - - const uint8_t *data = input_params.data(); - camera_info = reinterpret_cast(data); - int32_t error = intf_->SetCameraSmoothInfo(camera_info->op, camera_info->fps); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseControlCameraSmoothCallback(const ByteStream &input_params, - perform_cb _hidl_cb) { - const bool *enable; - - const uint8_t *data = input_params.data(); - enable = reinterpret_cast(data); - - int32_t error = intf_->ControlCameraSmoothCallback(*enable); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseDisplayBwTransactionPending(perform_cb _hidl_cb) { - bool status = true; - ByteStream output_params; - - int32_t error = intf_->DisplayBWTransactionPending(&status); - output_params.setToExternal(reinterpret_cast(&status), - sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetDisplayAnimating(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct AnimationParams *display_animating_data; - - const uint8_t *data = input_params.data(); - display_animating_data = reinterpret_cast(data); - int32_t error = intf_->SetDisplayAnimating(display_animating_data->display_id, - display_animating_data->animating); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseControlIdlePowerCollapse(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct IdlePcParams *idle_pc_data; - - const uint8_t *data = input_params.data(); - idle_pc_data = reinterpret_cast(data); - int32_t error = intf_->ControlIdlePowerCollapse(idle_pc_data->enable, idle_pc_data->synchronous); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetWritebackCapabilities(perform_cb _hidl_cb) { - bool is_wb_ubwc_supported = false; - int32_t error = intf_->GetWriteBackCapabilities(&is_wb_ubwc_supported); - ByteStream output_params; - output_params.setToExternal(reinterpret_cast(&is_wb_ubwc_supported), - sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetDisplayDppsAdRoi(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct DppsAdRoiParams *ad_roi_data; - - const uint8_t *data = input_params.data(); - ad_roi_data = reinterpret_cast(data); - - int32_t error = intf_->SetDisplayDppsAdROI(ad_roi_data->display_id, ad_roi_data->h_start, - ad_roi_data->h_end, ad_roi_data->v_start, - ad_roi_data->v_end, ad_roi_data->factor_in, - ad_roi_data->factor_out); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseUpdateVsyncSourceOnPowerModeOff(perform_cb _hidl_cb) { - int32_t error = intf_->UpdateVSyncSourceOnPowerModeOff(); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseUpdateVsyncSourceOnPowerModeDoze(perform_cb _hidl_cb) { - int32_t error = intf_->UpdateVSyncSourceOnPowerModeDoze(); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetPowerMode(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct PowerModeParams *set_power_mode_data; - - const uint8_t *data = input_params.data(); - set_power_mode_data = reinterpret_cast(data); - int32_t error = intf_->SetPowerMode(set_power_mode_data->disp_id, - set_power_mode_data->power_mode); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseIsPowerModeOverrideSupported( - const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint8_t *data = input_params.data(); - const uint32_t *disp_id = reinterpret_cast(data); - bool supported = false; - int32_t error = intf_->IsPowerModeOverrideSupported(*disp_id, &supported); - ByteStream output_params; - output_params.setToExternal(reinterpret_cast(&supported), - sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseIsHdrSupported(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint8_t *data = input_params.data(); - const uint32_t *disp_id = reinterpret_cast(data); - bool supported = false; - int32_t error = intf_->IsHDRSupported(*disp_id, &supported); - ByteStream output_params; - output_params.setToExternal(reinterpret_cast(&supported), - sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseIsWcgSupported(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint8_t *data = input_params.data(); - const int32_t *disp_id = reinterpret_cast(data); - bool supported = false; - int32_t error = intf_->IsWCGSupported(*disp_id, &supported); - ByteStream output_params; - output_params.setToExternal(reinterpret_cast(&supported), - sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetLayerAsMask(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct LayerMaskParams *layer_mask_data; - - const uint8_t *data = input_params.data(); - layer_mask_data = reinterpret_cast(data); - int32_t error = intf_->SetLayerAsMask(layer_mask_data->disp_id, layer_mask_data->layer_id); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetDebugProperty(const ByteStream &input_params, - perform_cb _hidl_cb) { - std::string value; - ByteStream output_params; - - const uint8_t *data = input_params.data(); - const char *name = reinterpret_cast(data); - std::string prop_name(name); - int32_t error = intf_->GetDebugProperty(prop_name, &value); - value += '\0'; - uint8_t *data_output = reinterpret_cast(value.data()); - output_params.setToExternal(reinterpret_cast(data_output), - value.size() * sizeof(char)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetActiveBuiltinDisplayAttributes(perform_cb _hidl_cb) { - struct Attributes attr; - ByteStream output_params; - - int32_t error = intf_->GetActiveBuiltinDisplayAttributes(&attr); - output_params.setToExternal(reinterpret_cast(&attr), sizeof(Attributes)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetPanelLuminanceAttributes( - const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct PanelLumAttrParams *panel_lum_attr_data; - - const uint8_t *data = input_params.data(); - panel_lum_attr_data = reinterpret_cast(data); - int32_t error = intf_->SetPanelLuminanceAttributes(panel_lum_attr_data->disp_id, - panel_lum_attr_data->min_lum, - panel_lum_attr_data->max_lum); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseIsBuiltinDisplay(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint32_t *disp_id; - bool is_builtin = false; - ByteStream output_params; - - const uint8_t *data = input_params.data(); - disp_id = reinterpret_cast(data); - int32_t error = intf_->IsBuiltInDisplay(*disp_id, &is_builtin); - output_params.setToExternal(reinterpret_cast(&is_builtin), - sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetCwbOutputBuffer(uint64_t clientHandle, - const ByteStream &input_params, - const HandleStream &input_handles, - perform_cb _hidl_cb) { - const struct CwbBufferParams *cwb_buffer_data; - - const uint8_t *data = input_params.data(); - cwb_buffer_data = reinterpret_cast(data); - hidl_handle buffer = input_handles[0]; - - if (!callback_ || !buffer.getNativeHandle()) { - _hidl_cb(-1, {}, {}); - return; - } - - int32_t error = intf_->SetCWBOutputBuffer(cwb_buffer_data->disp_id , cwb_buffer_data->rect, - cwb_buffer_data->post_processed, - buffer.getNativeHandle()); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetSupportedDsiBitclks(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint32_t *disp_id; - ByteStream output_params; - std::vector bit_clks; - uint64_t *bit_clks_data; - - const uint8_t *data = input_params.data(); - disp_id = reinterpret_cast(data); - int32_t error = intf_->GetSupportedDSIBitClks(*disp_id, &bit_clks); - - bit_clks_data = reinterpret_cast(malloc(sizeof(uint64_t) * bit_clks.size())); - if (bit_clks_data == NULL) { - _hidl_cb(-EINVAL, {}, {}); - return; - } - for (int i = 0; i < bit_clks.size(); i++) { - bit_clks_data[i] = bit_clks[i]; - } - output_params.setToExternal(reinterpret_cast(bit_clks_data), - sizeof(uint64_t) * bit_clks.size()); - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetDsiClk(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint32_t *disp_id; - uint64_t bit_clk = 0; - ByteStream output_params; - - const uint8_t *data = input_params.data(); - disp_id = reinterpret_cast(data); - int32_t error = intf_->GetDSIClk(*disp_id, &bit_clk); - output_params.setToExternal(reinterpret_cast(&bit_clk), - sizeof(uint64_t)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetDsiClk(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct DsiClkParams *set_dsi_clk_data; - - const uint8_t *data = input_params.data(); - set_dsi_clk_data = reinterpret_cast(data); - int32_t error = intf_->SetDSIClk(set_dsi_clk_data->disp_id, set_dsi_clk_data->bit_clk); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetQsyncMode(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct QsyncModeParams *set_qsync_mode_data; - - const uint8_t *data = input_params.data(); - set_qsync_mode_data = reinterpret_cast(data); - int32_t error = intf_->SetQsyncMode(set_qsync_mode_data->disp_id, set_qsync_mode_data->mode); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseIsSmartPanelConfig(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct SmartPanelCfgParams *smart_panel_cfg_data; - bool is_smart = false; - ByteStream output_params; - - const uint8_t *data = input_params.data(); - smart_panel_cfg_data = reinterpret_cast(data); - int32_t error = intf_->IsSmartPanelConfig(smart_panel_cfg_data->disp_id, - smart_panel_cfg_data->config_id, &is_smart); - output_params.setToExternal(reinterpret_cast(&is_smart), - sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseIsAsyncVdsSupported(perform_cb _hidl_cb) { - bool is_supported = false; - int32_t error = intf_->IsAsyncVDSCreationSupported(&is_supported); - ByteStream output_params; - output_params.setToExternal(reinterpret_cast(&is_supported), - sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseCreateVirtualDisplay(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct VdsParams *vds_input_data; - - const uint8_t *data = input_params.data(); - vds_input_data = reinterpret_cast(data); - - int32_t error = intf_->CreateVirtualDisplay(vds_input_data->width, vds_input_data->height, - vds_input_data->format); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseIsRotatorSupportedFormat(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct RotatorFormatParams *input_data; - bool supported = false; - ByteStream output_params; - - const uint8_t *data = input_params.data(); - input_data = reinterpret_cast(data); - int32_t error = intf_->IsRotatorSupportedFormat(input_data->hal_format, input_data->ubwc, - &supported); - output_params.setToExternal(reinterpret_cast(&supported), - sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseControlQsyncCallback(uint64_t client_handle, - const ByteStream &input_params, - perform_cb _hidl_cb) { - const bool *enable; - - const uint8_t *data = input_params.data(); - enable = reinterpret_cast(data); - - int32_t error = intf_->ControlQsyncCallback(*enable); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseControlIdleStatusCallback(uint64_t client_handle, - const ByteStream &input_params, - perform_cb _hidl_cb) { - const bool *enable; - - const uint8_t *data = input_params.data(); - enable = reinterpret_cast(data); - - int32_t error = intf_->ControlIdleStatusCallback(*enable); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSendTUIEvent(const ByteStream &input_params, - perform_cb _hidl_cb) { - const struct TUIEventParams *input_data = - reinterpret_cast(input_params.data()); - - int32_t error = intf_->SendTUIEvent(input_data->dpy, input_data->tui_event_type); - - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::ParseDestroy(uint64_t client_handle, perform_cb _hidl_cb) { - std::lock_guard lock(death_service_mutex_); - auto itr = display_config_map_.find(client_handle); - if (itr == display_config_map_.end()) { - _hidl_cb(-EINVAL, {}, {}); - return; - } - - std::shared_ptr client = itr->second; - if (client != NULL) { - sp callback = client->GetDeviceConfigCallback(); - callback->unlinkToDeath(this); - ConfigInterface *intf = client->GetDeviceConfigIntf(); - intf_->UnRegisterClientContext(intf); - client.reset(); - display_config_map_.erase(itr); - } - - _hidl_cb(0, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetDisplayHwId(const ByteStream &input_params, - perform_cb _hidl_cb) { - uint32_t disp_hw_id = 0; - ByteStream output_params; - - const uint8_t *data = input_params.data(); - const uint32_t *disp_id = reinterpret_cast(data); - int32_t error = intf_->GetDisplayHwId(*disp_id, &disp_hw_id); - output_params.setToExternal(reinterpret_cast(&disp_hw_id), sizeof(uint32_t)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetSupportedDisplayRefreshRates( - const ByteStream &input_params, perform_cb _hidl_cb) { - ByteStream output_params; - std::vector refresh_rates; - - const uint8_t *data = input_params.data(); - const DisplayType *dpy = reinterpret_cast(data); - int32_t error = intf_->GetSupportedDisplayRefreshRates(*dpy, &refresh_rates); - - uint32_t *refresh_rates_data = - reinterpret_cast(malloc(sizeof(uint32_t) * refresh_rates.size())); - if (refresh_rates_data) { - for (int i = 0; i < refresh_rates.size(); i++) { - refresh_rates_data[i] = refresh_rates[i]; - } - output_params.setToExternal(reinterpret_cast(refresh_rates_data), - sizeof(uint32_t) * refresh_rates.size()); - _hidl_cb(error, output_params, {}); - } else { - _hidl_cb(-EINVAL, {}, {}); - } -} - -void DeviceImpl::DeviceClientContext::ParseIsRCSupported(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint8_t *data = input_params.data(); - const uint32_t *disp_id = reinterpret_cast(data); - bool supported = false; - int32_t error = intf_->IsRCSupported(*disp_id, &supported); - ByteStream output_params; - output_params.setToExternal(reinterpret_cast(&supported), sizeof(bool)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseIsSupportedConfigSwitch(const ByteStream &input_params, - perform_cb _hidl_cb) { - if (!intf_) { - _hidl_cb(-EINVAL, {}, {}); - return; - } - - const struct SupportedModesParams *supported_modes_data; - const uint8_t *data = input_params.data(); - bool supported = false; - ByteStream output_params; - supported_modes_data = reinterpret_cast(data); - - int32_t error = intf_->IsSupportedConfigSwitch(supported_modes_data->disp_id, - supported_modes_data->mode, &supported); - output_params.setToExternal(reinterpret_cast(&supported), sizeof(bool)); - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetDisplayType(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint8_t *data = input_params.data(); - const uint64_t *physical_disp_id = reinterpret_cast(data); - DisplayType disp_type = DisplayConfig::DisplayType::kInvalid; - int32_t error = intf_->GetDisplayType(*physical_disp_id, &disp_type); - ByteStream output_params; - output_params.setToExternal(reinterpret_cast(&disp_type), sizeof(DisplayType)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseAllowIdleFallback(perform_cb _hidl_cb) { - int32_t error = intf_->AllowIdleFallback(); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseGetDisplayTileCount(const ByteStream &input_params, - perform_cb _hidl_cb) { - const uint64_t *data = reinterpret_cast(input_params.data()); - uint64_t physical_disp_id = data ? *data : 0; - uint32_t num_tiles[2] = {0, 0}; - - int32_t error = intf_->GetDisplayTileCount(physical_disp_id, &num_tiles[0], &num_tiles[1]); - ByteStream output_params; - output_params.setToExternal(reinterpret_cast(&num_tiles), - sizeof(num_tiles) * sizeof(uint32_t)); - - _hidl_cb(error, output_params, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetPowerModeTiled(const ByteStream &input_params, - perform_cb _hidl_cb) { - struct PowerModeTiledParams set_power_mode_tiled_data = {}; - - const uint8_t *data = input_params.data(); - if (data) { - set_power_mode_tiled_data = *reinterpret_cast(data); - } - int32_t error = intf_->SetPowerModeTiled(set_power_mode_tiled_data.physical_disp_id, - set_power_mode_tiled_data.power_mode, - set_power_mode_tiled_data.tile_h_loc, - set_power_mode_tiled_data.tile_v_loc); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetPanelBrightnessTiled(const ByteStream &input_params, - perform_cb _hidl_cb) { - struct PanelBrightnessTiledParams set_panel_brightness_tiled_data = {}; - - const uint8_t *data = input_params.data(); - if (data) { - set_panel_brightness_tiled_data = *reinterpret_cast(data); - } - int32_t error = intf_->SetPanelBrightnessTiled(set_panel_brightness_tiled_data.physical_disp_id, - set_panel_brightness_tiled_data.level, - set_panel_brightness_tiled_data.tile_h_loc, - set_panel_brightness_tiled_data.tile_v_loc); - _hidl_cb(error, {}, {}); -} - -void DeviceImpl::DeviceClientContext::ParseSetWiderModePreference(const ByteStream &input_params, - perform_cb _hidl_cb) { - struct WiderModePrefParams set_wider_mode_pref_data = {}; - - const uint8_t *data = input_params.data(); - if (data) { - set_wider_mode_pref_data = *reinterpret_cast(data); - } - int32_t error = intf_->SetWiderModePreference(set_wider_mode_pref_data.physical_disp_id, - set_wider_mode_pref_data.mode_pref); - _hidl_cb(error, {}, {}); -} - -Return DeviceImpl::perform(uint64_t client_handle, uint32_t op_code, - const ByteStream &input_params, const HandleStream &input_handles, - perform_cb _hidl_cb) { - int32_t error = 0; - std::lock_guard lock(death_service_mutex_); - auto itr = display_config_map_.find(client_handle); - if (itr == display_config_map_.end()) { - error = -EINVAL; - _hidl_cb(error, {}, {}); - return Void(); - } - - std::shared_ptr client = itr->second; - if (!client) { - error = -EINVAL; - _hidl_cb(error, {}, {}); - return Void(); - } - switch (op_code) { - case kIsDisplayConnected: - client->ParseIsDisplayConnected(input_params, _hidl_cb); - break; - case kSetDisplayStatus: - client->ParseSetDisplayStatus(input_params, _hidl_cb); - break; - case kConfigureDynRefreshRate: - client->ParseConfigureDynRefreshRate(input_params, _hidl_cb); - break; - case kGetConfigCount: - client->ParseGetConfigCount(input_params, _hidl_cb); - break; - case kGetActiveConfig: - client->ParseGetActiveConfig(input_params, _hidl_cb); - break; - case kSetActiveConfig: - client->ParseSetActiveConfig(input_params, _hidl_cb); - break; - case kGetDisplayAttributes: - client->ParseGetDisplayAttributes(input_params, _hidl_cb); - break; - case kSetPanelBrightness: - client->ParseSetPanelBrightness(input_params, _hidl_cb); - break; - case kGetPanelBrightness: - client->ParseGetPanelBrightness(_hidl_cb); - break; - case kMinHdcpEncryptionLevelChanged: - client->ParseMinHdcpEncryptionLevelChanged(input_params, _hidl_cb); - break; - case kRefreshScreen: - client->ParseRefreshScreen(_hidl_cb); - break; - case kControlPartialUpdate: - client->ParseControlPartialUpdate(input_params, _hidl_cb); - break; - case kToggleScreenUpdate: - client->ParseToggleScreenUpdate(input_params, _hidl_cb); - break; - case kSetIdleTimeout: - client->ParseSetIdleTimeout(input_params, _hidl_cb); - break; - case kGetHdrCapabilities: - client->ParseGetHdrCapabilities(input_params, _hidl_cb); - break; - case kSetCameraLaunchStatus: - client->ParseSetCameraLaunchStatus(input_params, _hidl_cb); - break; - case kSetCameraSmoothInfo: - client->ParseSetCameraSmoothInfo(input_params, _hidl_cb); - break; - case kControlCameraSmoothCallback: - client->ParseControlCameraSmoothCallback(input_params, _hidl_cb); - break; - case kDisplayBwTransactionPending: - client->ParseDisplayBwTransactionPending(_hidl_cb); - break; - case kSetDisplayAnimating: - client->ParseSetDisplayAnimating(input_params, _hidl_cb); - break; - case kControlIdlePowerCollapse: - client->ParseControlIdlePowerCollapse(input_params, _hidl_cb); - break; - case kGetWritebackCapabilities: - client->ParseGetWritebackCapabilities(_hidl_cb); - break; - case kSetDisplayDppsAdRoi: - client->ParseSetDisplayDppsAdRoi(input_params, _hidl_cb); - break; - case kUpdateVsyncSourceOnPowerModeOff: - client->ParseUpdateVsyncSourceOnPowerModeOff(_hidl_cb); - break; - case kUpdateVsyncSourceOnPowerModeDoze: - client->ParseUpdateVsyncSourceOnPowerModeDoze(_hidl_cb); - break; - case kSetPowerMode: - client->ParseSetPowerMode(input_params, _hidl_cb); - break; - case kIsPowerModeOverrideSupported: - client->ParseIsPowerModeOverrideSupported(input_params, _hidl_cb); - break; - case kIsHdrSupported: - client->ParseIsHdrSupported(input_params, _hidl_cb); - break; - case kIsWcgSupported: - client->ParseIsWcgSupported(input_params, _hidl_cb); - break; - case kSetLayerAsMask: - client->ParseSetLayerAsMask(input_params, _hidl_cb); - break; - case kGetDebugProperty: - client->ParseGetDebugProperty(input_params, _hidl_cb); - break; - case kGetActiveBuiltinDisplayAttributes: - client->ParseGetActiveBuiltinDisplayAttributes(_hidl_cb); - break; - case kSetPanelLuminanceAttributes: - client->ParseSetPanelLuminanceAttributes(input_params, _hidl_cb); - break; - case kIsBuiltinDisplay: - client->ParseIsBuiltinDisplay(input_params, _hidl_cb); - break; - case kSetCwbOutputBuffer: - client->ParseSetCwbOutputBuffer(client_handle, input_params, input_handles, _hidl_cb); - break; - case kGetSupportedDsiBitclks: - client->ParseGetSupportedDsiBitclks(input_params, _hidl_cb); - break; - case kGetDsiClk: - client->ParseGetDsiClk(input_params, _hidl_cb); - break; - case kSetDsiClk: - client->ParseSetDsiClk(input_params, _hidl_cb); - break; - case kSetQsyncMode: - client->ParseSetQsyncMode(input_params, _hidl_cb); - break; - case kIsSmartPanelConfig: - client->ParseIsSmartPanelConfig(input_params, _hidl_cb); - break; - case kIsAsyncVdsSupported: - client->ParseIsAsyncVdsSupported(_hidl_cb); - break; - case kCreateVirtualDisplay: - client->ParseCreateVirtualDisplay(input_params, _hidl_cb); - break; - case kIsRotatorSupportedFormat: - client->ParseIsRotatorSupportedFormat(input_params, _hidl_cb); - break; - case kControlQsyncCallback: - client->ParseControlQsyncCallback(client_handle, input_params, _hidl_cb); - break; - case kControlIdleStatusCallback: - client->ParseControlIdleStatusCallback(client_handle, input_params, _hidl_cb); - break; - case kSendTUIEvent: - client->ParseSendTUIEvent(input_params, _hidl_cb); - break; - case kDestroy: - ParseDestroy(client_handle, _hidl_cb); - break; - case kGetDisplayHwId: - client->ParseGetDisplayHwId(input_params, _hidl_cb); - break; - case kGetSupportedDisplayRefreshRates: - client->ParseGetSupportedDisplayRefreshRates(input_params, _hidl_cb); - break; - case kIsRCSupported: - client->ParseIsRCSupported(input_params, _hidl_cb); - break; - case kIsSupportedConfigSwitch: - client->ParseIsSupportedConfigSwitch(input_params, _hidl_cb); - break; - case kGetDisplayType: - client->ParseGetDisplayType(input_params, _hidl_cb); - break; - case kAllowIdleFallback: - client->ParseAllowIdleFallback(_hidl_cb); - break; - case kGetDisplayTileCount: - client->ParseGetDisplayTileCount(input_params, _hidl_cb); - break; - case kSetPowerModeTiled: - client->ParseSetPowerModeTiled(input_params, _hidl_cb); - break; - case kSetPanelBrightnessTiled: - client->ParseSetPanelBrightnessTiled(input_params, _hidl_cb); - break; - case kSetWiderModePref: - client->ParseSetWiderModePreference(input_params, _hidl_cb); - break; - case kDummyOpcode: - _hidl_cb(-EINVAL, {}, {}); - break; - default: - _hidl_cb(-EINVAL, {}, {}); - break; - } - return Void(); -} - -} // namespace DisplayConfig diff --git a/qcom/opensource/commonsys/display/services/config/src/device_impl.h b/qcom/opensource/commonsys/display/services/config/src/device_impl.h deleted file mode 100755 index cf603667..00000000 --- a/qcom/opensource/commonsys/display/services/config/src/device_impl.h +++ /dev/null @@ -1,196 +0,0 @@ -/* -* Copyright (c) 2021 The Linux Foundation. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following -* disclaimer in the documentation and/or other materials provided -* with the distribution. -* * Neither the name of The Linux Foundation. nor the names of its -* contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the - * disclaimer below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE - * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT - * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __DEVICE_IMPL_H__ -#define __DEVICE_IMPL_H__ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "opcode_types.h" - -namespace DisplayConfig { - -using vendor::display::config::V2_0::IDisplayConfig; -using vendor::display::config::V2_0::IDisplayConfigCallback; -using ::android::hardware::Return; -using ::android::hardware::Void; -using ::android::hardware::hidl_handle; -using ::android::hardware::hidl_string; -using ::android::hardware::hidl_vec; -using ::android::sp; - -typedef hidl_vec ByteStream; -typedef hidl_vec HandleStream; - -class DeviceImpl : public IDisplayConfig, public android::hardware::hidl_death_recipient { - public: - static int CreateInstance(ClientContext *intf); - - private: - class DeviceClientContext : public ConfigCallback { - public: - explicit DeviceClientContext(const sp callback); - - void SetDeviceConfigIntf(ConfigInterface *intf); - ConfigInterface* GetDeviceConfigIntf(); - sp GetDeviceConfigCallback(); - - virtual void NotifyCWBBufferDone(int32_t error, const native_handle_t *buffer); - virtual void NotifyQsyncChange(bool qsync_enabled, int32_t refresh_rate, - int32_t qsync_refresh_rate); - virtual void NotifyIdleStatus(bool is_idle); - virtual void NotifyCameraSmoothInfo(CameraSmoothOp op, uint32_t fps); - - void ParseIsDisplayConnected(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetDisplayStatus(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseConfigureDynRefreshRate(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetConfigCount(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetActiveConfig(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetActiveConfig(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetDisplayAttributes(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetPanelBrightness(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetPanelBrightness(perform_cb _hidl_cb); - void ParseMinHdcpEncryptionLevelChanged(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseRefreshScreen(perform_cb _hidl_cb); - void ParseControlPartialUpdate(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseToggleScreenUpdate(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetIdleTimeout(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetHdrCapabilities(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetCameraLaunchStatus(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetCameraSmoothInfo(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseControlCameraSmoothCallback(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseDisplayBwTransactionPending(perform_cb _hidl_cb); - void ParseSetDisplayAnimating(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseControlIdlePowerCollapse(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetWritebackCapabilities(perform_cb _hidl_cb); - void ParseSetDisplayDppsAdRoi(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseUpdateVsyncSourceOnPowerModeOff(perform_cb _hidl_cb); - void ParseUpdateVsyncSourceOnPowerModeDoze(perform_cb _hidl_cb); - void ParseSetPowerMode(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseIsPowerModeOverrideSupported(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseIsHdrSupported(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseIsWcgSupported(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetLayerAsMask(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetDebugProperty(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetActiveBuiltinDisplayAttributes(perform_cb _hidl_cb); - void ParseSetPanelLuminanceAttributes(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseIsBuiltinDisplay(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetCwbOutputBuffer(uint64_t clientHandle, const ByteStream &input_params, - const HandleStream &inputHandles, perform_cb _hidl_cb); - void ParseGetSupportedDsiBitclks(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetDsiClk(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetDsiClk(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetQsyncMode(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseIsSmartPanelConfig(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseIsAsyncVdsSupported(perform_cb _hidl_cb); - void ParseCreateVirtualDisplay(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseIsRotatorSupportedFormat(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseControlQsyncCallback(uint64_t client_handle, const ByteStream &input_params, - perform_cb _hidl_cb); - void ParseSendTUIEvent(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetDisplayHwId(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetSupportedDisplayRefreshRates(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseIsRCSupported(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseControlIdleStatusCallback(uint64_t client_handle, const ByteStream &input_params, - perform_cb _hidl_cb); - void ParseIsSupportedConfigSwitch(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseGetDisplayType(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseAllowIdleFallback(perform_cb _hidl_cb); - void ParseGetDisplayTileCount(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetPowerModeTiled(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetPanelBrightnessTiled(const ByteStream &input_params, perform_cb _hidl_cb); - void ParseSetWiderModePreference(const ByteStream &input_params, perform_cb _hidl_cb); - - private: - ConfigInterface *intf_ = nullptr; - const sp callback_; - }; - - Return registerClient(const hidl_string &client_name, const sp& cb, - registerClient_cb _hidl_cb) override; - Return perform(uint64_t client_handle, uint32_t op_code, const ByteStream &input_params, - const HandleStream &input_handles, perform_cb _hidl_cb) override; - void serviceDied(uint64_t client_handle, - const android::wp<::android::hidl::base::V1_0::IBase>& callback); - void ParseDestroy(uint64_t client_handle, perform_cb _hidl_cb); - - ClientContext *intf_ = nullptr; - std::map> display_config_map_; - uint64_t client_id_ = 0; - std::recursive_mutex death_service_mutex_; - static DeviceImpl *device_obj_; - static std::mutex device_lock_; -}; - -} // namespace DisplayConfig - -#endif // __DEVICE_IMPL_H__ diff --git a/qcom/opensource/commonsys/display/services/config/src/device_interface.cpp b/qcom/opensource/commonsys/display/services/config/src/device_interface.cpp deleted file mode 100755 index 0c2d6b73..00000000 --- a/qcom/opensource/commonsys/display/services/config/src/device_interface.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright (c) 2020 The Linux Foundation. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following -* disclaimer in the documentation and/or other materials provided -* with the distribution. -* * Neither the name of The Linux Foundation. nor the names of its -* contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include "device_impl.h" - -namespace DisplayConfig { - -int DeviceInterface::RegisterDevice(ClientContext *intf) { - if (!intf) { - return -1; - } - - return DeviceImpl::CreateInstance(intf); -} - -} // namespace DisplayConfig diff --git a/qcom/opensource/commonsys/display/services/config/src/opcode_types.h b/qcom/opensource/commonsys/display/services/config/src/opcode_types.h deleted file mode 100755 index c69e1a8f..00000000 --- a/qcom/opensource/commonsys/display/services/config/src/opcode_types.h +++ /dev/null @@ -1,135 +0,0 @@ -/* -* Copyright (c) 2020-2021 The Linux Foundation. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are -* met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above -* copyright notice, this list of conditions and the following -* disclaimer in the documentation and/or other materials provided -* with the distribution. -* * Neither the name of The Linux Foundation. nor the names of its -* contributors may be used to endorse or promote products derived -* from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - * Changes from Qualcomm Innovation Center are provided under the following license: - * - * Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the - * disclaimer below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of Qualcomm Innovation Center, Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE - * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT - * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __OPCODE_TYPES_H__ -#define __OPCODE_TYPES_H__ - -namespace DisplayConfig { - -enum OpCode { - kIsDisplayConnected = 0, - kSetDisplayStatus = 1, - kConfigureDynRefreshRate = 2, - kGetConfigCount = 3, - kGetActiveConfig = 4, - kSetActiveConfig = 5, - kGetDisplayAttributes = 6, - kSetPanelBrightness = 7, - kGetPanelBrightness = 8, - kMinHdcpEncryptionLevelChanged = 9, - kRefreshScreen = 10, - kControlPartialUpdate = 11, - kToggleScreenUpdate = 12, - kSetIdleTimeout = 13, - kGetHdrCapabilities = 14, - kSetCameraLaunchStatus = 15, - kDisplayBwTransactionPending = 16, - kSetDisplayAnimating = 17, - kControlIdlePowerCollapse = 18, - kGetWritebackCapabilities = 19, - kSetDisplayDppsAdRoi = 20, - kUpdateVsyncSourceOnPowerModeOff = 21, - kUpdateVsyncSourceOnPowerModeDoze = 22, - kSetPowerMode = 23, - kIsPowerModeOverrideSupported = 24, - kIsHdrSupported = 25, - kIsWcgSupported = 26, - kSetLayerAsMask = 27, - kGetDebugProperty = 28, - kGetActiveBuiltinDisplayAttributes = 29, - kSetPanelLuminanceAttributes = 30, - kIsBuiltinDisplay = 31, - kSetCwbOutputBuffer = 32, - kGetSupportedDsiBitclks = 33, - kGetDsiClk = 34, - kSetDsiClk = 35, - kSetQsyncMode = 36, - kIsSmartPanelConfig = 37, - kIsAsyncVdsSupported = 38, - kCreateVirtualDisplay = 39, - kIsRotatorSupportedFormat = 40, - kControlQsyncCallback = 41, - kSendTUIEvent = 42, - kGetDisplayHwId = 43, - kGetSupportedDisplayRefreshRates = 44, - kIsRCSupported = 45, - kControlIdleStatusCallback = 46, - kIsSupportedConfigSwitch = 47, - kGetDisplayType = 48, - kAllowIdleFallback = 49, - kGetDisplayTileCount = 50, - kSetPowerModeTiled = 51, - kSetPanelBrightnessTiled = 52, - kSetWiderModePref = 53, - kSetCameraSmoothInfo = 54, - kControlCameraSmoothCallback = 55, - kDummyOpcode = 56, - - kDestroy = 0xFFFF, // Destroy sequence execution -}; - -} // namespace DisplayConfig - -#endif // __OPCODE_TYPES_H__ diff --git a/qcom/opensource/commonsys/fm/fm_hci/Android.bp b/qcom/opensource/commonsys/fm/fm_hci/Android.bp deleted file mode 100755 index fa86ad03..00000000 --- a/qcom/opensource/commonsys/fm/fm_hci/Android.bp +++ /dev/null @@ -1,30 +0,0 @@ - - -cc_library_shared { - name: "libfm-hci", - - srcs: ["fm_hci.cpp"], - - shared_libs: [ - "libdl", - "libcutils", - "libbase", - "libhidlbase", - "liblog", - "libutils", - "libbinder_ndk", - "libbinder", - "android.hardware.bluetooth.audio-V3-ndk", - //"vendor.qti.hardware.fm-V1-ndk", - //"vendor.qti.hardware.fm@1.0", - ], - - cflags: ["-Wno-unused-parameter"], - - include_dirs: [ - "vendor/qcom/opensource/commonsys/fm/helium", - ], - - system_ext_specific: true, - -} diff --git a/qcom/opensource/commonsys/fm/fm_hci/fm_hci.cpp b/qcom/opensource/commonsys/fm/fm_hci/fm_hci.cpp deleted file mode 100755 index 527ecb4f..00000000 --- a/qcom/opensource/commonsys/fm/fm_hci/fm_hci.cpp +++ /dev/null @@ -1,923 +0,0 @@ -/* - * Copyright (c) 2017, The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/***************************************************************************** - * - * This file contains main functions to support FM HCI interface to send - * commands and recieved events. - * - *****************************************************************************/ - -#define LOG_TAG "fm_hci" - -#include // std::queue -#include // std::mutex, std::unique_lock -#include // std::condition_variable -#include -#include -#include -#include -#include -//#include -#include - -#include -#include - -#include -#include -#include -#include "fm_hci.h" - -#include - -#include -#include -#include - -#define ASSERT_LOG(condition, fmt, args...) \ - do { \ - if (!(condition)) { \ - LOG_ALWAYS_FATAL("assertion '" #condition "' failed - " fmt, ##args); \ - } \ - } while (false) - -using vendor::qti::hardware::fm::V1_0::IFmHci; -using vendor::qti::hardware::fm::V1_0::IFmHciCallbacks; -using vendor::qti::hardware::fm::V1_0::HciPacket; -using vendor::qti::hardware::fm::V1_0::Status; -using android::hardware::ProcessState; -using ::android::hardware::Return; -using ::android::hardware::Void; -using ::android::hardware::hidl_vec; -using ::android::hardware::hidl_death_recipient; - -using ::aidl::vendor::qti::hardware::fm::BnFmHci; -using fm_aidl = ::aidl::vendor::qti::hardware::fm::IFmHci; -//using IBluetoothHci_1_1 = ::android::hardware::bluetooth::V1_1::IBluetoothHci; -using AidlStatus = ::aidl::vendor::qti::hardware::fm::Status; - -static struct fm_hci_t hci; - -typedef std::unique_lock Lock; -static std::recursive_mutex mtx; -android::sp fmHci; -std::shared_ptr<::aidl::vendor::qti::hardware::fm::IFmHci> fmAidlHci; -::ndk::ScopedAIBinder_DeathRecipient aidl_death_recipient_; -std::shared_ptr<::aidl::vendor::qti::hardware::fm::IFmHciCallbacks> aidl_callbacks_; - -static int enqueue_fm_rx_event(struct fm_event_header_t *hdr); -static void dequeue_fm_rx_event(); -static int enqueue_fm_tx_cmd(struct fm_command_header_t *hdr); -static void dequeue_fm_tx_cmd(); -static void hci_tx_thread(); -static void hci_rx_thread(); -static int start_tx_thread(); -static void stop_tx_thread(); -static int start_rx_thread(); -static void stop_rx_thread(); -static void cleanup_threads(); -static bool hci_initialize(); -static void hci_transmit(struct fm_command_header_t *hdr); -static void hci_close(); -static void initialization_complete(bool is_hci_initialize); -#define HCI_EV_HW_ERR_EVENT 0x1A - - -void hal_service_died() { - struct fm_event_header_t *temp = (struct fm_event_header_t *) - malloc(sizeof(struct fm_event_header_t)); - if (temp != nullptr) { - temp->evt_code = HCI_EV_HW_ERR_EVENT; - temp->evt_len = 0; - ALOGI("%s: evt_code: 0x%x", __func__, temp->evt_code); - enqueue_fm_rx_event(temp); - } else { - ALOGE("%s: Memory Allocation failed for event buffer ",__func__); - } -} -class AidlHciCallbacks : public ::aidl::vendor::qti::hardware::fm::BnFmHciCallbacks { - public: - - ::ndk::ScopedAStatus initializationComplete(AidlStatus status) { - if(status == AidlStatus::SUCCESS) - { - initialization_complete(true); - } else { - initialization_complete(false); - } - return ::ndk::ScopedAStatus::ok(); - } - - ::ndk::ScopedAStatus hciEventReceived(const std::vector& event) override { - struct fm_event_header_t *temp = (struct fm_event_header_t *) malloc(event.size()); - if (temp != nullptr) { - memcpy(temp, event.data(), event.size()); - uint8_t evt = temp->evt_code; - ALOGI("%s: evt_code: 0x%x", __func__, evt); - enqueue_fm_rx_event(temp); - ALOGI("%s: evt_code: 0x%x done", __func__, evt); - } else { - ALOGE("%s: Memory Allocation failed for event buffer ",__func__); - } - - return ::ndk::ScopedAStatus::ok(); - } - - private: - IFmHciCallbacks* callback_ = nullptr; -}; - -static constexpr char kFmAidlHalServiceName[] = - "vendor.qti.hardware.fm.IFmHci/default"; - -class FmHciDeathRecipient : public hidl_death_recipient { - public: - virtual void serviceDied(uint64_t /*cookie*/, - const android::wp<::android::hidl::base::V1_0::IBase>& /*who*/) { - ALOGE("Fm HAL service died!"); - hal_service_died(); - } -}; - -android::sp fmHciDeathRecipient = new FmHciDeathRecipient(); - -/******************************************************************************* -** -** Function enqueue_fm_rx_event -** -** Description This function is called in the hal daemon context to queue -** FM events in RX queue. -** -** Parameters: hdr - contains the fm event header pointer -** -** -** Returns int -** -*******************************************************************************/ -static int enqueue_fm_rx_event(struct fm_event_header_t *hdr) -{ - - ALOGV("%s: putting lock before enqueue ", __func__); - /* - * enqueue_fm_rx_event may need to wait for rx_cond_mtx here as - * last event is still under processing, besides current event - * has held internal_mutex_ when OnPacketReady called in data_handler.cpp - * if last event is HCI_EV_CMD_COMPLETE, it will try to hold - * internal_mutex_ again when calling close in data_handler, - * thus, last event will wait for internal_mutex_ while new event - * will wait util last event done, finally dead lock occurs. - * so we try to check hci state here if rx_cond_mtx is still locked - */ - int tryLockCount = 0; - while (1) { - if (!hci.rx_cond_mtx.try_lock()) { - if (hci.state == FM_RADIO_DISABLING || hci.state == FM_RADIO_DISABLED) { - ALOGI("%s: can't lock rx_cond_mtx and hci is not available", __func__); - return FM_HC_STATUS_NULL_POINTER; - } - usleep(1000); - tryLockCount++; - continue; - } else { - break; - } - } - hci.rx_queue_mtx.lock(); - hci.rx_event_queue.push(hdr); - hci.rx_queue_mtx.unlock(); - ALOGV("%s:notify to waiting thred", __func__); - hci.rx_cond.notify_all(); - ALOGI("%s: FM-Event ENQUEUED SUCCESSFULLY tryLockCount = %d", __func__, tryLockCount); - hci.rx_cond_mtx.unlock(); - - return FM_HC_STATUS_SUCCESS; -} - -/******************************************************************************* -** -** Function dequeue_fm_rx_event -** -** Description This function is called in the rx thread context to dequeue -** FM events from RX queue & processing the FM event. -** -** Parameters: void -** -** -** Returns void -** -*******************************************************************************/ -static void dequeue_fm_rx_event() -{ - fm_event_header_t *evt_buf; - - ALOGI("%s", __func__); - while (1) { - hci.rx_queue_mtx.lock(); - if (hci.rx_event_queue.empty()) { - ALOGI("No more FM Events are available in the RX Queue"); - hci.rx_queue_mtx.unlock(); - return; - } else { - } - - evt_buf = hci.rx_event_queue.front(); - hci.rx_event_queue.pop(); - hci.rx_queue_mtx.unlock(); - - if (evt_buf->evt_code == FM_CMD_COMPLETE) { - ALOGI("%s: FM_CMD_COMPLETE: current_credits %d, %d Credits got from the SOC", __func__, hci.command_credits, evt_buf->params[0]); - if (hci.command_credits == 0) { - hci.command_credits += evt_buf->params[0]; - ALOGV(" dequeue_fm_rx_event: wait for tx_cond_lock "); - hci.tx_cond_mtx.lock(); - ALOGV(" dequeue_fm_rx_event: Notifying tx_cond_lock "); - hci.tx_cond.notify_all(); - ALOGV(" dequeue_fm_rx_event: UNLOCKING tx_cond_lock "); - hci.tx_cond_mtx.unlock(); - } else { - hci.command_credits += evt_buf->params[0]; - } - - } else if (evt_buf->evt_code == FM_CMD_STATUS) { - ALOGI("%s: FM_CMD_STATUS: current_credits %d, %d Credits got from the SOC", __func__, hci.command_credits, evt_buf->params[1]); - if (hci.command_credits == 0) { - hci.command_credits += evt_buf->params[1]; - ALOGV(" dequeue_fm_rx_event: wait for tx_cond_lock "); - hci.tx_cond_mtx.lock(); - ALOGV(" dequeue_fm_rx_event: Notifying tx_cond_lock "); - hci.tx_cond.notify_all(); - ALOGV(" dequeue_fm_rx_event: UNLOCKING tx_cond_lock "); - hci.tx_cond_mtx.unlock(); - } else { - hci.command_credits += evt_buf->params[1]; - } - } else if (evt_buf->evt_code == FM_HW_ERR_EVENT) { - ALOGI("%s: FM H/w Err Event Recvd. Event Code: 0x%x", __func__, evt_buf->evt_code); - } else { - ALOGE("%s: Not CS/CC Event: Recvd. Event Code: 0x%x", __func__, evt_buf->evt_code); - } - - if (hci.cb && hci.cb->process_event) { - ALOGI("%s: processing the event", __func__); - hci.cb->process_event((uint8_t *)evt_buf); - } - - free(evt_buf); - evt_buf = NULL; - } - -} - -/******************************************************************************* -** -** Function enqueue_fm_tx_cmd -** -** Description This function is called in the application JNI context to -** queue FM commands in TX queue. -** -** Parameters: hdr - contains the fm command header pointer -** -** -** Returns int -** -*******************************************************************************/ -static int enqueue_fm_tx_cmd(struct fm_command_header_t *hdr) -{ - ALOGI("%s: opcode 0x%x len:%d ", __func__, hdr->opcode, hdr->len); - - hci.tx_queue_mtx.lock(); - hci.tx_cmd_queue.push(hdr); - hci.tx_queue_mtx.unlock(); - - ALOGI("%s: notifying credits %d", __func__, hci.command_credits); - if (hci.command_credits > 0) { - ALOGV(" enqueue_fm_tx_cmd: wait for tx_cond_lock "); - hci.tx_cond_mtx.lock(); - ALOGV(" enqueue_fm_tx_cmd: Notifying tx_cond_lock "); - hci.tx_cond.notify_all(); - ALOGV(" enqueue_fm_tx_cmd: UNLOCK tx_cond_lock "); - hci.tx_cond_mtx.unlock(); - } - - ALOGI("%s: FM-CMD ENQUEUED SUCCESSFULLY credits %d", __func__, hci.command_credits); - - return FM_HC_STATUS_SUCCESS; -} - -/******************************************************************************* -** -** Function dequeue_fm_tx_cmd -** -** Description This function is called in the tx thread context to dequeue -** & transmitting FM command to to HAL daemon. -** -** Parameters: void -** -** -** Returns void -** -*******************************************************************************/ -static void dequeue_fm_tx_cmd() -{ - fm_command_header_t *hdr; - - ALOGI("%s command credits %d ", __func__, hci.command_credits); - - while (1) - { - if (hci.command_credits == 0) { - return; - } - hci.tx_queue_mtx.lock(); - ALOGV("%s is_que_empty %d", __func__,hci.tx_cmd_queue.empty()); - if(hci.tx_cmd_queue.empty()){ - ALOGI(" %s No more FM CMDs are available in the Queue",__func__); - hci.tx_queue_mtx.unlock(); - return; - } - - hdr = hci.tx_cmd_queue.front(); - hci.tx_cmd_queue.pop(); - hci.tx_queue_mtx.unlock(); - ALOGV("%s: packet popped %d credits", __func__,hci.command_credits); - - - hci.command_credits--; - hci_transmit(hdr); - ALOGI("%s: packet transmitted %d credits", __func__,hci.command_credits); - } - ALOGI(" %s outside while(1), credits %d ", __func__, hci.command_credits); -} - - -/******************************************************************************* -** -** Function hci_tx_thread -** -** Description This function is main function of tx worker thread. -** -** Parameters: void -** -** -** Returns void -** -*******************************************************************************/ -static void hci_tx_thread() -{ - ALOGI("%s: ##### starting hci_tx_thread Worker thread!!! #####", __func__); - hci.is_tx_thread_running = true; - - Lock lk(hci.tx_cond_mtx); - while (hci.state != FM_RADIO_DISABLING && hci.state != FM_RADIO_DISABLED) { - //wait for tx cmd - ALOGI("%s: before wait %d credits!!!" , __func__,hci.command_credits); - hci.tx_cond.wait(lk); - ALOGV("%s: after wait dequeueing the tx cmd!!!" , __func__); - dequeue_fm_tx_cmd(); - } - - hci.is_tx_thread_running =false; - ALOGI("%s: ##### Exiting hci_tx_thread Worker thread!!! #####", __func__); -} - -/******************************************************************************* -** -** Function hci_rx_thread -** -** Description This function is main function of tx worker thread. -** -** Parameters: void -** -** -** Returns void -** -*******************************************************************************/ -static void hci_rx_thread() -{ - - ALOGI("%s: ##### starting hci_rx_thread Worker thread!!! #####", __func__); - hci.is_rx_thread_running = true; - - ALOGI("%s: constr unique_lock ", __func__); - Lock lk(hci.rx_cond_mtx); - while (hci.state != FM_RADIO_DISABLING && hci.state != FM_RADIO_DISABLED) { - //wait for rx event - ALOGI("%s:before wait", __func__); - hci.rx_cond.wait(lk); - ALOGI("%s:after wait ", __func__); - dequeue_fm_rx_event(); - } - - hci.is_rx_thread_running = false; - ALOGI("%s: ##### Exiting hci_rx_thread Worker thread!!! #####", __func__); -} - -/******************************************************************************* -** -** Function start_tx_thread -** -** Description This function is called to start tx worker thread. -** -** Parameters: void -** -** -** Returns int -** -*******************************************************************************/ -static int start_tx_thread() -{ - - ALOGI("FM-HCI: Creating the FM-HCI TX TASK..."); - hci.tx_thread_ = std::thread(hci_tx_thread); - if (!hci.tx_thread_.joinable()) { - ALOGE("tx thread is not joinable"); - return FM_HC_STATUS_FAIL; - } - - return FM_HC_STATUS_SUCCESS; -} - -/******************************************************************************* -** -** Function stop_tx_thread -** -** Description This function is called to stop tx worker thread. -** -** Parameters: void -** -** -** Returns int -** -*******************************************************************************/ -static void stop_tx_thread() -{ - ALOGI("%s:stop_tx_thread ++", __func__); - hci.tx_cond_mtx.lock(); - hci.tx_cond.notify_all(); - ALOGI("%s:notify to tx thread", __func__); - hci.tx_cond_mtx.unlock(); - - hci.tx_thread_.join(); - ALOGI("%s:stop_tx_thread --", __func__); -} - -/******************************************************************************* -** -** Function start_rx_thread -** -** Description This function is called to start rx worker thread. -** -** Parameters: void -** -** -** Returns int -** -*******************************************************************************/ -static int start_rx_thread() -{ - int ret = FM_HC_STATUS_SUCCESS; - ALOGI("FM-HCI: Creating the FM-HCI RX TASK..."); - - hci.rx_thread_ = std::thread(hci_rx_thread); - if (!hci.rx_thread_.joinable()) { - ALOGE("rx thread is not joinable"); - return FM_HC_STATUS_FAIL; - } - - return ret; -} - -/******************************************************************************* -** -** Function stop_rx_thread -** -** Description This function is called to stop rx worker thread. -** -** Parameters: void -** -** -** Returns int -** -*******************************************************************************/ -static void stop_rx_thread() -{ - ALOGI("%s:stop_rx_thread ++", __func__); - hci.rx_cond.notify_all(); - - hci.rx_thread_.join(); - ALOGI("%s:stop_rx_thread --", __func__); -} - -/******************************************************************************* -** -** Function cleanup_threads -** -** Description This function is called to cleanup rx & tx worker thread. -** -** Parameters: void -** -** -** Returns int -** -*******************************************************************************/ -static void cleanup_threads() -{ - stop_rx_thread(); - stop_tx_thread(); -} - -/******************************************************************************* -** -** Function initialization_complete -** -** Description This function is called, when initialization complete -** callback is called by hal daemon. -** -** Parameters: hdr - contains the fm event header pointer -** -** -** Returns int -** -*******************************************************************************/ -static void initialization_complete(bool is_hci_initialize) -{ - int ret; - ALOGI("++%s: is_hci_initialize: %d", __func__, is_hci_initialize); - - hci.on_mtx.lock(); - while (is_hci_initialize) { - ret = start_tx_thread(); - if (ret) - { - cleanup_threads(); - hci.state = FM_RADIO_DISABLING; - break; - } - - ret = start_rx_thread(); - if (ret) - { - cleanup_threads(); - hci.state = FM_RADIO_DISABLING; - break; - } - - hci.state = FM_RADIO_ENABLED; - break; - } - - hci.on_cond.notify_all(); - hci.on_mtx.unlock(); - ALOGI("--%s: is_hci_initialize: %d", __func__, is_hci_initialize); - -} - -/******************************************************************************* -** -** Class FmHciCallbacks -** -** Description This is main class, which has the implemention for FM HCI -** callback functions. -** -** Member callback Functions: initializationComplete, hciEventReceived -** -** -** Returns int -** -*******************************************************************************/ -class FmHciCallbacks : public IFmHciCallbacks { - public: - FmHciCallbacks() { - }; - virtual ~FmHciCallbacks() = default; - - Return initializationComplete(Status status) { - if(status == Status::SUCCESS) - { - initialization_complete(true); - } else { - initialization_complete(false); - } - - return Void(); - } - - Return hciEventReceived(const hidl_vec& event) { - struct fm_event_header_t *temp = (struct fm_event_header_t *) malloc(event.size()); - if (temp != nullptr) { - memcpy(temp, event.data(), event.size()); - uint8_t evt = temp->evt_code; - ALOGI("%s: evt_code: 0x%x", __func__, evt); - enqueue_fm_rx_event(temp); - ALOGI("%s: evt_code: 0x%x done", __func__, evt); - } else { - ALOGE("%s: Memory Allocation failed for event buffer ",__func__); - } - return Void(); - } -}; - - bool start_aidl() { - ndk::SpAIBinder binder(AServiceManager_waitForService(kFmAidlHalServiceName)); - fmAidlHci = fm_aidl::fromBinder(binder); - if (fmAidlHci != nullptr) { - ALOGE("Using the AIDL interface"); - aidl_death_recipient_ = - ::ndk::ScopedAIBinder_DeathRecipient(AIBinder_DeathRecipient_new([](void* cookie) { - ALOGE("The Fm HAL service died. Dumping logs and crashing in 1 second."); - LOG_ALWAYS_FATAL("The Bluetooth HAL died."); - })); - - auto death_link = - AIBinder_linkToDeath(fmAidlHci->asBinder().get(), aidl_death_recipient_.get(), NULL); - - ASSERT_LOG( - death_link == STATUS_OK, "Unable to set the death recipient for the Bluetooth HAL"); - - hci.state = FM_RADIO_ENABLING; - aidl_callbacks_ = ::ndk::SharedRefBase::make(); - fmAidlHci->initialize(aidl_callbacks_); - } - return true; - } - - bool start_hidl() { - fmHci = IFmHci::getService(); - if(fmHci == nullptr) { - ALOGE("FM hal service is not running"); - return FM_HC_STATUS_NULL_POINTER; - } - - auto death_link = fmHci->linkToDeath(fmHciDeathRecipient, 0); - if (!death_link.isOk()) { - ALOGE("%s: Unable to set the death recipient for the Fm HAL", __func__); - abort(); - } - if (fmHci != nullptr) { - hci.state = FM_RADIO_ENABLING; - android::sp callbacks = new FmHciCallbacks(); - auto hidl_daemon_status = fmHci->initialize(callbacks); - if(!hidl_daemon_status.isOk()) { - ALOGE("%s: HIDL daemon is dead", __func__); - } - return true; - } else { - return false; - } - } -/******************************************************************************* -** -** Function hci_initialize -** -** Description This function is used to initialize fm hci hidl transport. -** It makes a binder call to hal daemon -** -** Parameters: void -** -** -** Returns bool -** -*******************************************************************************/ -static bool hci_initialize() -{ - ALOGI("%s: acquiring mutex", __func__); - std::lock_guard lk(mtx); - if (AServiceManager_isDeclared(kFmAidlHalServiceName)) { - start_aidl(); - } else { - start_hidl(); - } - return true; - -} - - -/******************************************************************************* -** -** Function hci_transmit -** -** Description This function is used to send fm command to fm hci hidl transport. -** It makes a binder call to hal daemon. -** -** Parameters: void -** -** -** Returns void -** -*******************************************************************************/ -static void hci_transmit(struct fm_command_header_t *hdr) { - HciPacket data; - - ALOGI("%s: opcode 0x%x len:%d, acquiring mutex", __func__, hdr->opcode, hdr->len); - std::lock_guard lk(mtx); - - if (fmHci != nullptr) { - data.setToExternal((uint8_t *)hdr, 3 + hdr->len); - auto hidl_daemon_status = fmHci->sendHciCommand(data); - if(!hidl_daemon_status.isOk()) { - ALOGE("%s: send Command failed, HIDL daemon is dead", __func__); - } - } else if( fmAidlHci != nullptr) { - data.setToExternal((uint8_t *)hdr, 3 + hdr->len); - auto hidl_daemon_status = fmAidlHci->sendHciCommand(data); - } else { - ALOGI("%s: fmHci is NULL", __func__); - } - - free(hdr); -} - -/******************************************************************************* -** -** Function hci_close -** -** Description This function is used to close fm hci hidl transport. -** It makes a binder call to hal daemon -** -** Parameters: void -** -** -** Returns void -** -*******************************************************************************/ -static void hci_close() -{ - ALOGI("%s: acquiring mutex", __func__); - std::lock_guard lk(mtx); - - if (fmHci != nullptr) { - auto death_unlink = fmHci->unlinkToDeath(fmHciDeathRecipient); - if (!death_unlink.isOk()) { - ALOGE( "%s: Error unlinking death recipient from the Fm HAL", __func__); - } - auto hidl_daemon_status = fmHci->close(); - if(!hidl_daemon_status.isOk()) { - ALOGE("%s: HIDL daemon is dead", __func__); - } - fmHci = nullptr; - } else if(fmAidlHci != nullptr) { - auto death_unlink = - AIBinder_unlinkToDeath(fmAidlHci->asBinder().get(), aidl_death_recipient_.get(), NULL); - if (death_unlink != STATUS_OK) { - ALOGE("Error unlinking death recipient from the Bluetooth HAL"); - } - auto close_status = fmAidlHci->close(); - if (!close_status.isOk()) { - ALOGE("Error calling close on the Bluetooth HAL"); - } - fmAidlHci = nullptr; - } -} - -/******************************************************************************* -** -** Function fm_hci_init -** -** Description This function is used to intialize fm hci -** -** Parameters: hci_hal - contains the fm helium hal hci pointer -** -** -** Returns void -** -*******************************************************************************/ -int fm_hci_init(fm_hci_hal_t *hci_hal) -{ - int ret = FM_HC_STATUS_FAIL; - - ALOGD("++%s", __func__); - - if(hci.is_rx_thread_running) - { - ALOGI("%s:previous rx thread running wait until rx thread stops", __func__); - hci.rx_thread_.join(); - ALOGI("%s:stop_rx_thread completed, proceed iniialization", __func__); - } - if (!hci_hal || !hci_hal->hal) { - ALOGE("NULL input argument"); - return FM_HC_STATUS_NULL_POINTER; - } - - memset(&hci, 0, sizeof(struct fm_hci_t)); - - hci.cb = hci_hal->cb; - hci.command_credits = 1; - hci.is_tx_thread_running = false; - hci.is_rx_thread_running = false; - hci.state = FM_RADIO_DISABLED; - hci_hal->hci = &hci; - - if (hci_initialize()) { - //wait for iniialization complete - Lock lk(hci.on_mtx); - if(hci.state == FM_RADIO_ENABLING){ - ALOGD("--%s waiting for iniialization complete hci state: %d ", - __func__, hci.state); - std::cv_status status = std::cv_status::no_timeout; - auto now = std::chrono::system_clock::now(); - status = - hci.on_cond.wait_until(lk, now + std::chrono::seconds(HCI_TIMEOUT)); - if (status == std::cv_status::timeout) { - ALOGE("hci_initialize failed, kill the fm process"); - hci.on_mtx.unlock(); - kill(getpid(), SIGKILL); - } - } - hci.on_mtx.unlock(); - } - - if (hci.state == FM_RADIO_ENABLED) { - while (hci.is_tx_thread_running == false - || hci.is_rx_thread_running == false) - { - /* checking tx & rx thread running status after every - 5ms before notifying on to upper layer */ - usleep(5000); - } - ALOGD("--%s success", __func__); - ret = FM_HC_STATUS_SUCCESS; - } else { - ALOGD("--%s failed", __func__); - hci_close(); - hci.state = FM_RADIO_DISABLED; - } - return ret; -} - -/******************************************************************************* -** -** Function fm_hci_transmit -** -** Description This function is called by helium hal & is used enqueue the -** tx commands in tx queue. -** -** Parameters: p_hci - contains the fm helium hal hci pointer -** hdr - contains the fm command header pointer -** -** Returns void -** -*******************************************************************************/ -int fm_hci_transmit(void *p_hci, struct fm_command_header_t *hdr) -{ - if (!hdr) { - ALOGE("NULL input arguments"); - return FM_HC_STATUS_NULL_POINTER; - } - - return enqueue_fm_tx_cmd(hdr); -} - -/******************************************************************************* -** -** Function fm_hci_close -** -** Description This function is used to close & cleanup hci -** -** Parameters: p_hci - contains the fm hci pointer -** -** -** Returns void -** -*******************************************************************************/ -void fm_hci_close(void *p_hci) -{ - ALOGI("%s", __func__); - hci.state = FM_RADIO_DISABLING; - - hci_close(); - stop_tx_thread(); - - if (hci.cb && hci.cb->fm_hci_close_done) { - ALOGI("%s:Notify FM OFF to hal", __func__); - hci.cb->fm_hci_close_done(); - } - - hci.state = FM_RADIO_DISABLED; -} \ No newline at end of file diff --git a/qcom/opensource/commonsys/fm/fm_hci/fm_hci.h b/qcom/opensource/commonsys/fm/fm_hci/fm_hci.h deleted file mode 100755 index f209aaaf..00000000 --- a/qcom/opensource/commonsys/fm/fm_hci/fm_hci.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2015-2017 The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __FM_HCI__ -#define __FM_HCI__ - -#include "fm_hci_api.h" - -#define FM_CMD_COMPLETE 0x0f -#define FM_CMD_STATUS 0x10 -#define FM_HW_ERR_EVENT 0x1A -#define HCI_TIMEOUT 3 -struct fm_hci_t { - public: - fm_power_state_t state; - std::condition_variable on_cond; - std::mutex on_mtx; - - bool is_tx_thread_running; - bool is_rx_thread_running; - - std::condition_variable tx_cond; - std::mutex tx_cond_mtx; - - std::condition_variable rx_cond; - std::mutex rx_cond_mtx; - - std::mutex tx_queue_mtx; - - std::mutex rx_queue_mtx; - - std::condition_variable cmd_credits_cond; - - std::queue tx_cmd_queue; - std::queue rx_event_queue; - - volatile uint16_t command_credits; - struct fm_hci_callbacks_t *cb; - - std::thread tx_thread_; - std::thread rx_thread_; -}; - -#endif - diff --git a/qcom/opensource/commonsys/fm/fm_hci/fm_hci_api.h b/qcom/opensource/commonsys/fm/fm_hci/fm_hci_api.h deleted file mode 100755 index 1602fbb0..00000000 --- a/qcom/opensource/commonsys/fm/fm_hci/fm_hci_api.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2015-2016 The Linux Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of The Linux Foundation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __FM_HCI_API__ -#define __FM_HCI_API__ - - -/** Host/Controller Library Return Status */ -typedef enum { - FM_HC_STATUS_SUCCESS, - FM_HC_STATUS_FAIL, - FM_HC_STATUS_NOT_READY, - FM_HC_STATUS_NOMEM, - FM_HC_STATUS_BUSY, - FM_HC_STATUS_CORRUPTED_BUFFER, - FM_HC_STATUS_NULL_POINTER, -} fm_hc_status_t; - -static char *status_s[] = { - "Success", - "Failed, generic error", - "Not ready", - "Memory not available", - "Resource busy", - "Buffer is corrupted", - "NULL pointer dereference", -}; - -static inline char *fm_hci_status(int status) { - return status_s[status]; -} - -typedef enum { - FM_RADIO_DISABLED, - FM_RADIO_DISABLING, - FM_RADIO_ENABLED, - FM_RADIO_ENABLING -} fm_power_state_t; - -typedef int (*event_notification_cb_t)(unsigned char *buf); -typedef int (*hci_close_done_cb_t)(void); - - -struct fm_hci_callbacks_t { - event_notification_cb_t process_event; - hci_close_done_cb_t fm_hci_close_done; -}; - -typedef struct { - void *hci; - void *hal; - struct fm_hci_callbacks_t *cb; -}fm_hci_hal_t; - -struct fm_command_header_t { - uint16_t opcode; - uint8_t len; - uint8_t params[]; -}__attribute__((packed)); - -struct fm_event_header_t { - uint8_t evt_code; - uint8_t evt_len; - uint8_t params[]; -}__attribute__((packed)); -#ifdef __cplusplus -extern "C" -{ -#endif - -/******************************************************************************* -** -** Function fm_hci_init -** -** Description This function is used to intialize fm hci -** -** Parameters: hci_hal: contains the fm helium hal hci pointer -** -** -** Returns void -** -*******************************************************************************/ -int fm_hci_init(fm_hci_hal_t *hal_hci); - -/******************************************************************************* -** -** Function fm_hci_transmit -** -** Description This function is called by helium hal & is used enqueue the -** tx commands in tx queue. -** -** Parameters: p_hci - contains the fm helium hal hci pointer -** hdr - contains the fm command header pointer -** -** Returns void -** -*******************************************************************************/ -int fm_hci_transmit(void *p_hci, struct fm_command_header_t *hdr); -/******************************************************************************* -** -** Function fm_hci_close -** -** Description This function is used to close & cleanup hci -** -** Parameters: p_hci: contains the fm hci pointer -** -** -** Returns void -** -*******************************************************************************/ -void fm_hci_close(void *p_hci); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/qcom/opensource/commonsys/fm/fmapp2/Android.bp b/qcom/opensource/commonsys/fm/fmapp2/Android.bp deleted file mode 100755 index a2ef6ab3..00000000 --- a/qcom/opensource/commonsys/fm/fmapp2/Android.bp +++ /dev/null @@ -1,13 +0,0 @@ - - -android_app { - name: "FM2", - - srcs: ["src/com/caf/fmradio/CommaSeparatedFreqFileReader.java"] + ["src/com/caf/fmradio/FMAdapterApp.java"] + ["src/com/caf/fmradio/FMMediaButtonIntentReceiver.java"] + ["src/com/caf/fmradio/FMRadio.java"] + ["src/com/caf/fmradio/FMRadioService.java"] + ["src/com/caf/fmradio/FmSharedPreferences.java"] + ["src/com/caf/fmradio/FMStats.java"] + ["src/com/caf/fmradio/FmTags.java"] + ["src/com/caf/fmradio/GetNextFreqInterface.java"] + ["src/com/caf/fmradio/HorizontalNumberPicker.java"] + ["src/com/caf/fmradio/PresetList.java"] + ["src/com/caf/fmradio/PresetStation.java"] + ["src/com/caf/fmradio/Settings.java"] + ["src/com/caf/fmradio/StationListActivity.java"] + ["src/com/caf/fmradio/IFMRadioService.aidl"] + ["src/com/caf/fmradio/IFMRadioServiceCallbacks.aidl"] + ["src/com/caf/fmradio/IFMTransmitterServiceCallbacks.aidl"] + ["src/com/caf/hc_utils/**/*.java"], - certificate: "platform", - jni_libs: ["libqcomfm_jni"], - libs: ["qcom.fmradio"], - platform_apis: true, - aaptflags: ["--legacy"], - system_ext_specific: true, -} diff --git a/qcom/opensource/commonsys/fm/fmapp2/AndroidManifest.xml b/qcom/opensource/commonsys/fm/fmapp2/AndroidManifest.xml deleted file mode 100755 index 833250c5..00000000 --- a/qcom/opensource/commonsys/fm/fmapp2/AndroidManifest.xml +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qcom/opensource/commonsys/fm/fmapp2/fmtransmitter.xml b/qcom/opensource/commonsys/fm/fmapp2/fmtransmitter.xml deleted file mode 100755 index 5e656205..00000000 --- a/qcom/opensource/commonsys/fm/fmapp2/fmtransmitter.xml +++ /dev/null @@ -1,223 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -