From 36bea37e9781276e7162292ea6933a7f6404c5ee Mon Sep 17 00:00:00 2001 From: fulup Date: Thu, 30 Mar 2017 10:12:31 +0200 Subject: Initial working implementation for Alsa UCM. Cleanup format for Alsa control GET. Status: working in progress --- AlsaSound/CoreBinding/AlsaAfbBinding.c | 74 --- AlsaSound/CoreBinding/AlsaCoreBinding.c | 79 +++ AlsaSound/CoreBinding/AlsaCoreBinding.h | 60 ++ AlsaSound/CoreBinding/AlsaCtlSetGet.c | 1056 +++++++++++++++++++++++++++++++ AlsaSound/CoreBinding/AlsaLibMapping.c | 1036 ------------------------------ AlsaSound/CoreBinding/AlsaLibMapping.h | 37 -- AlsaSound/CoreBinding/AlsaUseCase.c | 430 +++++++++++++ AlsaSound/CoreBinding/CMakeLists.txt | 2 +- 8 files changed, 1626 insertions(+), 1148 deletions(-) delete mode 100644 AlsaSound/CoreBinding/AlsaAfbBinding.c create mode 100644 AlsaSound/CoreBinding/AlsaCoreBinding.c create mode 100644 AlsaSound/CoreBinding/AlsaCoreBinding.h create mode 100644 AlsaSound/CoreBinding/AlsaCtlSetGet.c delete mode 100644 AlsaSound/CoreBinding/AlsaLibMapping.c delete mode 100644 AlsaSound/CoreBinding/AlsaLibMapping.h create mode 100644 AlsaSound/CoreBinding/AlsaUseCase.c (limited to 'AlsaSound') diff --git a/AlsaSound/CoreBinding/AlsaAfbBinding.c b/AlsaSound/CoreBinding/AlsaAfbBinding.c deleted file mode 100644 index c9bdf30..0000000 --- a/AlsaSound/CoreBinding/AlsaAfbBinding.c +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2016 "IoT.bzh" - * Author Fulup Ar Foll - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define _GNU_SOURCE -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AlsaLibMapping.h" - -PUBLIC const struct afb_binding_interface *afbIface; - -/* - * array of the verbs exported to afb-daemon - */ -static const struct afb_verb_desc_v1 binding_verbs[] = { - /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */ - { .name= "ping" , .session= AFB_SESSION_NONE, .callback= pingtest, .info= "Ping Binding" }, - { .name= "getinfo", .session= AFB_SESSION_NONE, .callback= alsaGetInfo, .info= "List All/One Sound Cards Info" }, - { .name= "getctls", .session= AFB_SESSION_NONE,.callback= alsaGetCtls, .info= "List All/One Controls from selected sndcard" }, - { .name= "subscribe", .session= AFB_SESSION_NONE, .callback= alsaSubcribe, .info= "Subscribe to events from selected sndcard" }, - { .name= "getcardid", .session= AFB_SESSION_NONE, .callback= alsaGetCardId, .info= "Get CardId from its short/long name" }, - { .name= "registerHal",.session= AFB_SESSION_NONE,.callback= alsaRegisterHal,.info= "Register Hal CardName/ApiPrefix" }, - { .name= NULL } /* marker for end of the array */ -}; - -/* - * description of the binding for afb-daemon - */ -static const struct afb_binding binding_description = { - /* description conforms to VERSION 1 */ - .type= AFB_BINDING_VERSION_1, - .v1= { - .prefix= "alsacore", - .info= "Low Level Interface to Alsa Sound Lib", - .verbs = binding_verbs - } -}; - -extern int afbBindingV1ServiceInit(struct afb_service service) { - // this is call when after all bindings are loaded - // alsaLibInit (service); // AlsaBinding check for sound card at installation time - return (0); -}; - -/* - * activation function for registering the binding called by afb-daemon - */ -const struct afb_binding *afbBindingV1Register(const struct afb_binding_interface *itf) { - afbIface= itf; - - return &binding_description; /* returns the description of the binding */ -} - diff --git a/AlsaSound/CoreBinding/AlsaCoreBinding.c b/AlsaSound/CoreBinding/AlsaCoreBinding.c new file mode 100644 index 0000000..19a7f3b --- /dev/null +++ b/AlsaSound/CoreBinding/AlsaCoreBinding.c @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2016 "IoT.bzh" + * Author Fulup Ar Foll + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "AlsaCoreBinding.h" + +PUBLIC const struct afb_binding_interface *afbIface; + +/* + * array of the verbs exported to afb-daemon + */ +static const struct afb_verb_desc_v1 binding_verbs[] = { + /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */ + { .name= "ping" , .session= AFB_SESSION_NONE, .callback= pingtest, .info= "Ping Binding" }, + { .name= "getinfo", .session= AFB_SESSION_NONE, .callback= alsaGetInfo, .info= "List All/One Sound Cards Info" }, + { .name= "getctls", .session= AFB_SESSION_NONE,.callback= alsaGetCtls, .info= "List All/One Controls from selected sndcard" }, + { .name= "subscribe", .session= AFB_SESSION_NONE, .callback= alsaSubcribe, .info= "Subscribe to events from selected sndcard" }, + { .name= "getcardid", .session= AFB_SESSION_NONE, .callback= alsaGetCardId, .info= "Get CardId from its short/long name" }, + { .name= "registerHal",.session= AFB_SESSION_NONE,.callback= alsaRegisterHal, .info= "Register Hal CardName/ApiPrefix" }, + { .name= "ucmquery", .session= AFB_SESSION_NONE, .callback= alsaUseCaseQuery,.info= "Use Case Query" }, + { .name= "ucmset", .session= AFB_SESSION_NONE, .callback= alsaUseCaseSet, .info= "Use Case Set" }, + { .name= "ucmget", .session= AFB_SESSION_NONE, .callback= alsaUseCaseGet, .info= "Use Case Get" }, + { .name= "ucmreset", .session= AFB_SESSION_NONE, .callback= alsaUseCaseReset,.info= "Use Case Reset to Default" }, + { .name= "ucmclose", .session= AFB_SESSION_NONE, .callback= alsaUseCaseClose,.info= "Use Case Close Manager" }, + { .name= NULL } /* marker for end of the array */ +}; + +/* + * description of the binding for afb-daemon + */ +static const struct afb_binding binding_description = { + /* description conforms to VERSION 1 */ + .type= AFB_BINDING_VERSION_1, + .v1= { + .prefix= "alsacore", + .info= "Low Level Interface to Alsa Sound Lib", + .verbs = binding_verbs + } +}; + +extern int afbBindingV1ServiceInit(struct afb_service service) { + // this is call when after all bindings are loaded + // alsaLibInit (service); // AlsaBinding check for sound card at installation time + return (0); +}; + +/* + * activation function for registering the binding called by afb-daemon + */ +const struct afb_binding *afbBindingV1Register(const struct afb_binding_interface *itf) { + afbIface= itf; + + return &binding_description; /* returns the description of the binding */ +} + diff --git a/AlsaSound/CoreBinding/AlsaCoreBinding.h b/AlsaSound/CoreBinding/AlsaCoreBinding.h new file mode 100644 index 0000000..0e5f84a --- /dev/null +++ b/AlsaSound/CoreBinding/AlsaCoreBinding.h @@ -0,0 +1,60 @@ +/* + * AlsaLibMapping -- provide low level interface with ALSA lib (extracted from alsa-json-gateway code) + * Copyright (C) 2015,2016,2017, Fulup Ar Foll fulup@iot.bzh + * + * 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 ALSALIBMAPPING_H +#define ALSALIBMAPPING_H + +#include "AudioCommonLib.h" + + +typedef enum { + ACTION_SET, + ACTION_GET +} ActionSetGetT; + +// generic structure to pass parsed query values +typedef struct { + const char *devid; + json_object *jNumIds; + int quiet; + int count; +} queryValuesT; + +// import from AlsaAfbBinding +extern const struct afb_binding_interface *afbIface; +PUBLIC int alsaCheckQuery (struct afb_req request, queryValuesT *queryValues); + +// AlseCoreSetGet exports +PUBLIC void alsaGetInfo (struct afb_req request); +PUBLIC void alsaGetCtls(struct afb_req request); +PUBLIC void alsaSetCtrl(struct afb_req request); +PUBLIC void alsaSubcribe (struct afb_req request); +PUBLIC void alsaGetCardId (struct afb_req request); +PUBLIC void alsaRegisterHal (struct afb_req request); + +// AlsaUseCase exports +PUBLIC void alsaUseCaseQuery(struct afb_req request); +PUBLIC void alsaUseCaseSet(struct afb_req request); +PUBLIC void alsaUseCaseGet(struct afb_req request); +PUBLIC void alsaUseCaseClose(struct afb_req request); +PUBLIC void alsaUseCaseReset(struct afb_req request); + + + +#endif /* ALSALIBMAPPING_H */ + diff --git a/AlsaSound/CoreBinding/AlsaCtlSetGet.c b/AlsaSound/CoreBinding/AlsaCtlSetGet.c new file mode 100644 index 0000000..a6cd45b --- /dev/null +++ b/AlsaSound/CoreBinding/AlsaCtlSetGet.c @@ -0,0 +1,1056 @@ +/* + * AlsaLibMapping -- provide low level interface with ALSA lib (extracted from alsa-json-gateway code) + * Copyright (C) 2015,2016,2017, Fulup Ar Foll fulup@iot.bzh + * + * 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. + + References: + https://github.com/fulup-bzh/AlsaJsonGateway (original code) + http://alsa-lib.sourcearchive.com/documentation/1.0.20/modules.html + http://alsa-lib.sourcearchive.com/documentation/1.0.8/group__Control_gd48d44da8e3bfe150e928267008b8ff5.html + http://alsa.opensrc.org/HowTo_access_a_mixer_control + https://github.com/gch1p/alsa-volume-monitor/blob/master/main.c + https://github.com/DongheonKim/android_hardware_alsa-sound/blob/master/ALSAControl.cpp (ALSA low level API) + +*/ + +#define _GNU_SOURCE // needed for vasprintf + +#include +#include "AlsaCoreBinding.h" +#include + + + +// use to store crl numid user request +typedef struct { + unsigned int numId; + json_object *jToken; + json_object *jValues; + int used; +} ctlRequestT; + +// generic sndctrl event handle hook to event callback when pooling +typedef struct { + struct pollfd pfds; + sd_event_source *src; + snd_ctl_t *ctlDev; + int quiet; + struct afb_event afbevt; +} evtHandleT; + +typedef struct { + int ucount; + int cardId; + evtHandleT *evtHandle; +} sndHandleT; + +typedef struct { + char *apiprefix; + char *shortname; +}cardRegistryT; + +cardRegistryT *cardRegistry[MAX_SND_CARD+1]; + +PUBLIC void NumidsListParse (queryValuesT *queryValues, ctlRequestT *ctlRequest) { + json_object *jValues; + int length; + + for (int idx=0; idx < queryValues->count; idx ++) { + ctlRequest[idx].jToken = json_object_array_get_idx (queryValues->jNumIds, idx); + ctlRequest[idx].jValues = NULL; + ctlRequest[idx].used=0; + + + switch (json_object_get_type(ctlRequest[idx].jToken)) { + + case json_type_int: + // if NUMID is not an array then it should be an integer numid with no value + ctlRequest[idx].numId = json_object_get_int (ctlRequest[idx].jToken); + break; + + case json_type_array: + // NUMID is an array 1st slot should be numid, optionally values may come after + length=json_object_array_length (ctlRequest[idx].jToken); + if (length < 1 || length >2) { + ctlRequest[idx].used=-1; + continue; + } + + ctlRequest[idx].numId =json_object_get_int(json_object_array_get_idx (ctlRequest[idx].jToken, 0)); + + if (length == 2) { + jValues = json_object_array_get_idx (ctlRequest[idx].jToken, 1); + if (jValues == NULL) { + ctlRequest[idx].used=-1; + continue; + } + // Value is an int or an array with potentially multiple subvalues + ctlRequest[idx].jValues = jValues; + } + default: + ctlRequest[idx].used=-1; + } + } +} + +PUBLIC int alsaCheckQuery (struct afb_req request, queryValuesT *queryValues) { + + queryValues->devid = afb_req_value(request, "devid"); + if (queryValues->devid == NULL) goto OnErrorExit; + const char *numids; + json_object *jNumIds; + + const char *rqtQuiet = afb_req_value(request, "quiet"); + if (!rqtQuiet) queryValues->quiet=99; // default super quiet + else if (rqtQuiet && ! sscanf (rqtQuiet, "%d", &queryValues->quiet)) { + json_object *query = afb_req_json(request); + + afb_req_fail_f (request, "quiet-notinteger","Query=%s Quiet not integer &quiet=%s&", json_object_to_json_string(query), rqtQuiet); + goto OnErrorExit; + }; + + // no NumId is interpreted as ALL for get and error for set + numids = afb_req_value(request, "numids"); + if (numids == NULL) { + queryValues->count=0; + goto OnExit; + } + + jNumIds = json_tokener_parse(numids); + if (!jNumIds) { + afb_req_fail_f (request, "numids-notjson","numids=%s not a valid json entry", numids); + goto OnErrorExit; + }; + + enum json_type jtype= json_object_get_type(jNumIds); + switch (jtype) { + case json_type_array: + queryValues->jNumIds = jNumIds; + queryValues->count = json_object_array_length (jNumIds); + break; + + case json_type_int: + queryValues->count = 1; + queryValues->jNumIds = json_object_new_array (); + json_object_array_add (queryValues->jNumIds, jNumIds); + break; + + default: + afb_req_fail_f (request, "numid-notarray","NumId=%s NumId not valid JSON array", numids); + goto OnErrorExit; + } + +OnExit: + return 0; + +OnErrorExit: + return 1; +} + +STATIC json_object *DB2StringJsonOject (long dB) { + char label [20]; + if (dB < 0) { + snprintf(label, sizeof(label), "-%li.%02lidB", -dB / 100, -dB % 100); + } else { + snprintf(label, sizeof(label), "%li.%02lidB", dB / 100, dB % 100); + } + + // json function takes care of string copy + return (json_object_new_string (label)); +} + + +// Direct port from amixer TLV decode routine. This code is too complex for me. +// I hopefully did not break it when porting it. + +STATIC json_object *decodeTlv(unsigned int *tlv, unsigned int tlv_size) { + char label[20]; + unsigned int type = tlv[0]; + unsigned int size; + unsigned int idx = 0; + const char *chmap_type = NULL; + json_object * decodeTlvJson = json_object_new_object(); + + if (tlv_size < (unsigned int) (2 * sizeof (unsigned int))) { + printf("TLV size error!\n"); + return NULL; + } + type = tlv[idx++]; + size = tlv[idx++]; + tlv_size -= (unsigned int) (2 * sizeof (unsigned int)); + if (size > tlv_size) { + fprintf(stderr, "TLV size error (%i, %i, %i)!\n", type, size, tlv_size); + return NULL; + } + switch (type) { + + case SND_CTL_TLVT_CONTAINER: + { + json_object * containerJson = json_object_new_array(); + + size += (unsigned int) (sizeof (unsigned int) - 1); + size /= (unsigned int) (sizeof (unsigned int)); + while (idx < size) { + json_object *embedJson; + + if (tlv[idx + 1] > (size - idx) * sizeof (unsigned int)) { + fprintf(stderr, "TLV size error in compound!\n"); + return NULL; + } + embedJson = decodeTlv(tlv + idx, tlv[idx + 1] + 8); + json_object_array_add(containerJson, embedJson); + idx += (unsigned int) (2 + (tlv[idx + 1] + sizeof (unsigned int) - 1) / sizeof (unsigned int)); + } + json_object_object_add(decodeTlvJson, "container", containerJson); + break; + } + + case SND_CTL_TLVT_DB_SCALE: + { + json_object * dbscaleJson = json_object_new_object(); + + if (size != 2 * sizeof (unsigned int)) { + json_object * arrayJson = json_object_new_array(); + while (size > 0) { + snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); + json_object_array_add(arrayJson, json_object_new_string(label)); + size -= (unsigned int) sizeof (unsigned int); + } + json_object_object_add(dbscaleJson, "array", arrayJson); + } else { + json_object_object_add(dbscaleJson, "min", DB2StringJsonOject((int) tlv[2])); + json_object_object_add(dbscaleJson, "step", DB2StringJsonOject(tlv[3] & 0xffff)); + json_object_object_add(dbscaleJson, "mute", DB2StringJsonOject((tlv[3] >> 16) & 1)); + } + json_object_object_add(decodeTlvJson, "dbscale", dbscaleJson); + break; + } + +#ifdef SND_CTL_TLVT_DB_LINEAR + case SND_CTL_TLVT_DB_LINEAR: + { + json_object * dbLinearJson = json_object_new_object(); + + if (size != 2 * sizeof (unsigned int)) { + json_object * arrayJson = json_object_new_array(); + while (size > 0) { + snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); + json_object_array_add(arrayJson, json_object_new_string(label)); + size -= (unsigned int) sizeof (unsigned int); + } + json_object_object_add(dbLinearJson, "offset", arrayJson); + } else { + json_object_object_add(dbLinearJson, "min", DB2StringJsonOject((int) tlv[2])); + json_object_object_add(dbLinearJson, "max", DB2StringJsonOject((int) tlv[3])); + } + json_object_object_add(decodeTlvJson, "dblinear", dbLinearJson); + break; + } +#endif + +#ifdef SND_CTL_TLVT_DB_RANGE + case SND_CTL_TLVT_DB_RANGE: + { + json_object *dbRangeJson = json_object_new_object(); + + if ((size % (6 * sizeof (unsigned int))) != 0) { + json_object *arrayJson = json_object_new_array(); + while (size > 0) { + snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); + json_object_array_add(arrayJson, json_object_new_string(label)); + size -= (unsigned int) sizeof (unsigned int); + } + json_object_object_add(dbRangeJson, "dbrange", arrayJson); + break; + } + while (size > 0) { + json_object * embedJson = json_object_new_object(); + snprintf(label, sizeof (label), "%i,", tlv[idx++]); + json_object_object_add(embedJson, "rangemin", json_object_new_string(label)); + snprintf(label, sizeof (label), "%i", tlv[idx++]); + json_object_object_add(embedJson, "rangemax", json_object_new_string(label)); + embedJson = decodeTlv(tlv + idx, 4 * sizeof (unsigned int)); + json_object_object_add(embedJson, "tlv", embedJson); + idx += 4; + size -= (unsigned int) (6 * sizeof (unsigned int)); + json_object_array_add(dbRangeJson, embedJson); + } + json_object_object_add(decodeTlvJson, "dbrange", dbRangeJson); + break; + } +#endif +#ifdef SND_CTL_TLVT_DB_MINMAX + case SND_CTL_TLVT_DB_MINMAX: + case SND_CTL_TLVT_DB_MINMAX_MUTE: + { + json_object * dbMinMaxJson = json_object_new_object(); + + if (size != 2 * sizeof (unsigned int)) { + json_object * arrayJson = json_object_new_array(); + while (size > 0) { + snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); + json_object_array_add(arrayJson, json_object_new_string(label)); + size -= (unsigned int) sizeof (unsigned int); + } + json_object_object_add(dbMinMaxJson, "array", arrayJson); + + } else { + json_object_object_add(dbMinMaxJson, "min", DB2StringJsonOject((int) tlv[2])); + json_object_object_add(dbMinMaxJson, "max", DB2StringJsonOject((int) tlv[3])); + } + + if (type == SND_CTL_TLVT_DB_MINMAX_MUTE) { + json_object_object_add(decodeTlvJson, "dbminmaxmute", dbMinMaxJson); + } else { + json_object_object_add(decodeTlvJson, "dbminmax", dbMinMaxJson); + } + break; + } +#endif +#ifdef SND_CTL_TLVT_CHMAP_FIXED + case SND_CTL_TLVT_CHMAP_FIXED: + chmap_type = "fixed"; + /* Fall through */ + case SND_CTL_TLVT_CHMAP_VAR: + if (!chmap_type) + chmap_type = "variable"; + /* Fall through */ + case SND_CTL_TLVT_CHMAP_PAIRED: + if (!chmap_type) + chmap_type = "paired"; + + json_object * chmapJson = json_object_new_object(); + json_object * arrayJson = json_object_new_array(); + + while (size > 0) { + snprintf(label, sizeof (label), "%s", snd_pcm_chmap_name(tlv[idx++])); + size -= (unsigned int) sizeof (unsigned int); + json_object_array_add(arrayJson, json_object_new_string(label)); + } + json_object_object_add(chmapJson, chmap_type, arrayJson); + json_object_object_add(decodeTlvJson, "chmap", chmapJson); + break; +#endif + default: + { + printf("unk-%i-", type); + json_object * arrayJson = json_object_new_array(); + + while (size > 0) { + snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); + size -= (unsigned int) sizeof (unsigned int); + json_object_array_add(arrayJson, json_object_new_string(label)); + } + break; + json_object_object_add(decodeTlvJson, "unknown", arrayJson); + } + } + + return (decodeTlvJson); +} + + +// retreive info for one given card +STATIC json_object* alsaCardProbe (const char *rqtSndId) { + const char *info, *name; + const char *devid, *driver; + json_object *ctlDev; + snd_ctl_t *handle; + snd_ctl_card_info_t *cardinfo; + int err; + + if ((err = snd_ctl_open(&handle, rqtSndId, 0)) < 0) { + INFO (afbIface, "SndCard [%s] Not Found", rqtSndId); + return NULL; + } + + snd_ctl_card_info_alloca(&cardinfo); + if ((err = snd_ctl_card_info(handle, cardinfo)) < 0) { + snd_ctl_close(handle); + WARNING (afbIface, "SndCard [%s] info error: %s", rqtSndId, snd_strerror(err)); + return NULL; + } + + // start a new json object to store card info + ctlDev = json_object_new_object(); + + devid= snd_ctl_card_info_get_id(cardinfo); + json_object_object_add (ctlDev, "devid" , json_object_new_string(devid)); + name = snd_ctl_card_info_get_name(cardinfo); + json_object_object_add (ctlDev, "name", json_object_new_string (name)); + + if (afbIface->verbosity > 1) { + json_object_object_add (ctlDev, "devid", json_object_new_string(rqtSndId)); + driver= snd_ctl_card_info_get_driver(cardinfo); + json_object_object_add (ctlDev, "driver" , json_object_new_string(driver)); + info = strdup(snd_ctl_card_info_get_longname (cardinfo)); + json_object_object_add (ctlDev, "info" , json_object_new_string (info)); + INFO (afbIface, "AJG: Soundcard Devid=%-5s devid=%-7s Name=%s\n", rqtSndId, devid, info); + } + + // free card handle and return info + snd_ctl_close(handle); + return (ctlDev); +} + +// Loop on every potential Sound card and register active one +PUBLIC void alsaGetInfo (struct afb_req request) { + int card; + json_object *ctlDev, *ctlDevs; + char devid[32]; + + const char *rqtSndId = afb_req_value(request, "devid"); + + // if no specific card requested loop on all + + if (rqtSndId != NULL) { + // only one card was requested let's probe it + ctlDev = alsaCardProbe (rqtSndId); + if (ctlDev != NULL) afb_req_success(request, ctlDev, NULL); + else afb_req_fail_f (request, "sndscard-notfound", "SndCard [%s] Not Found", rqtSndId); + + } else { + // return an array of ctlDev + ctlDevs =json_object_new_array(); + + // loop on potential card number + for (card =0; card < MAX_SND_CARD; card++) { + + // build card devid and probe it + snprintf (devid, sizeof(devid), "hw:%i", card); + ctlDev = alsaCardProbe (devid); + + // Alsa has hole within card list [ignore them] + if (ctlDev != NULL) { + // add current ctlDev to ctlDevs object + json_object_array_add (ctlDevs, ctlDev); + } + } + afb_req_success (request, ctlDevs, NULL); + } +} + +// pack Alsa element's ACL into a JSON object +STATIC json_object *getControlAcl (snd_ctl_elem_info_t *info) { + + json_object * jsonAclCtl = json_object_new_object(); + + json_object_object_add (jsonAclCtl, "read" , json_object_new_boolean(snd_ctl_elem_info_is_readable(info))); + json_object_object_add (jsonAclCtl, "write" , json_object_new_boolean(snd_ctl_elem_info_is_writable(info))); + json_object_object_add (jsonAclCtl, "inact" , json_object_new_boolean(snd_ctl_elem_info_is_inactive(info))); + json_object_object_add (jsonAclCtl, "volat" , json_object_new_boolean(snd_ctl_elem_info_is_volatile(info))); + json_object_object_add (jsonAclCtl, "lock" , json_object_new_boolean(snd_ctl_elem_info_is_locked(info))); + + // if TLV is readable we insert its ACL + if (!snd_ctl_elem_info_is_tlv_readable(info)) { + json_object * jsonTlv = json_object_new_object(); + + json_object_object_add (jsonTlv, "read" , json_object_new_boolean(snd_ctl_elem_info_is_tlv_readable(info))); + json_object_object_add (jsonTlv, "write" , json_object_new_boolean(snd_ctl_elem_info_is_tlv_writable(info))); + json_object_object_add (jsonTlv, "command", json_object_new_boolean(snd_ctl_elem_info_is_tlv_commandable(info))); + + json_object_object_add (jsonAclCtl, "tlv", jsonTlv); + } + return (jsonAclCtl); +} + +// process ALSA control and store resulting value into ctlRequest +STATIC int alsaSetSingleCtl (snd_ctl_t *ctlDev, snd_ctl_elem_id_t *elemId, ctlRequestT *ctlRequest) { + snd_ctl_elem_value_t *elemData; + snd_ctl_elem_info_t *elemInfo; + int count, length, err, valueIsArray; + + // let's make sure we are processing the right control + if (ctlRequest->numId != snd_ctl_elem_id_get_numid (elemId)) goto OnErrorExit; + + // set info event ID and get value + snd_ctl_elem_info_alloca(&elemInfo); + snd_ctl_elem_info_set_id(elemInfo, elemId); // map ctlInfo to ctlId elemInfo is updated !!! + if (snd_ctl_elem_info(ctlDev, elemInfo) < 0) { + NOTICE (afbIface, "Fail to load ALSA NUMID=%d Values=[%s]", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues)); + goto OnErrorExit; + } + + snd_ctl_elem_info_get_id(elemInfo, elemId); // map ctlInfo to ctlId elemInfo is updated !!! + if (!snd_ctl_elem_info_is_writable(elemInfo)) { + NOTICE (afbIface, "Not Writable ALSA NUMID=%d Values=[%s]", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues)); + goto OnErrorExit; + } + + count = snd_ctl_elem_info_get_count (elemInfo); + if (!json_object_is_type (ctlRequest->jValues, json_type_array)) { + length=1; + valueIsArray=0; + } else { + length = json_object_array_length (ctlRequest->jValues); + valueIsArray=1; + } + + if (count == 0 || count < length) { + NOTICE (afbIface, "Invalid Values ALSA NUMID=%d Values=[%s] wanted count=%d", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues), count); + goto OnErrorExit; + } + + snd_ctl_elem_value_alloca(&elemData); + snd_ctl_elem_value_set_id(elemData, elemId); // map ctlInfo to ctlId elemInfo is updated !!! + if (snd_ctl_elem_read(ctlDev, elemData) < 0) goto OnErrorExit; + + // Loop on every control value and push to sndcard + for (int index=0; index < count && index < length; index++) { + json_object *element; + int value; + + if (valueIsArray) element= json_object_array_get_idx(ctlRequest->jValues, index); + else element= ctlRequest->jValues; + + value= json_object_get_int (element); + snd_ctl_elem_value_set_integer(elemData, index, value); + } + + if ((err = snd_ctl_elem_write(ctlDev, elemData)) < 0) { + NOTICE (afbIface, "Fail to write ALSA NUMID=%d Values=[%s]", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues)); + goto OnErrorExit; + } + + ctlRequest->used=1; + return 0; + + OnErrorExit: + ctlRequest->used=-1; + return -1; +} + +// process ALSA control and store then into ctlRequest +STATIC int alsaGetSingleCtl (snd_ctl_t *ctlDev, snd_ctl_elem_id_t *elemId, ctlRequestT *ctlRequest, int quiet) { + snd_ctl_elem_type_t elemType; + snd_ctl_elem_value_t *elemData; + snd_ctl_elem_info_t *elemInfo; + int count, idx, err; + + + // set info event ID and get value + + snd_ctl_elem_info_alloca(&elemInfo); + snd_ctl_elem_info_set_id(elemInfo, elemId); // map ctlInfo to ctlId elemInfo is updated !!! + if (snd_ctl_elem_info(ctlDev, elemInfo) < 0) goto OnErrorExit; + count = snd_ctl_elem_info_get_count (elemInfo); + if (count == 0) goto OnErrorExit; + + snd_ctl_elem_info_get_id(elemInfo, elemId); // map ctlInfo to ctlId elemInfo is updated !!! + if (!snd_ctl_elem_info_is_readable(elemInfo)) goto OnErrorExit; + elemType = snd_ctl_elem_info_get_type(elemInfo); + + snd_ctl_elem_value_alloca(&elemData); + snd_ctl_elem_value_set_id(elemData, elemId); // map ctlInfo to ctlId elemInfo is updated !!! + if (snd_ctl_elem_read(ctlDev, elemData) < 0) goto OnErrorExit; + + ctlRequest->jValues= json_object_new_object(); + json_object_object_add (ctlRequest->jValues,"numid" , ctlRequest->jToken); + if (quiet < 2) json_object_object_add (ctlRequest->jValues,"name" , json_object_new_string(snd_ctl_elem_id_get_name (elemId))); + if (quiet < 1) json_object_object_add (ctlRequest->jValues,"iface" , json_object_new_string(snd_ctl_elem_iface_name(snd_ctl_elem_id_get_interface(elemId)))); + if (quiet < 3) json_object_object_add (ctlRequest->jValues,"actif", json_object_new_boolean(!snd_ctl_elem_info_is_inactive(elemInfo))); + + json_object *jsonValuesCtl = json_object_new_array(); + for (idx = 0; idx < count; idx++) { // start from one in amixer.c !!! + switch (elemType) { + case SND_CTL_ELEM_TYPE_BOOLEAN: { + json_object_array_add (jsonValuesCtl, json_object_new_boolean (snd_ctl_elem_value_get_boolean(elemData, idx))); + break; + } + case SND_CTL_ELEM_TYPE_INTEGER: + json_object_array_add (jsonValuesCtl, json_object_new_int ((int)snd_ctl_elem_value_get_integer(elemData, idx))); + break; + case SND_CTL_ELEM_TYPE_INTEGER64: + json_object_array_add (jsonValuesCtl, json_object_new_int64 (snd_ctl_elem_value_get_integer64(elemData, idx))); + break; + case SND_CTL_ELEM_TYPE_ENUMERATED: + json_object_array_add (jsonValuesCtl, json_object_new_int (snd_ctl_elem_value_get_enumerated(elemData, idx))); + break; + case SND_CTL_ELEM_TYPE_BYTES: + json_object_array_add (jsonValuesCtl, json_object_new_int ((int)snd_ctl_elem_value_get_byte(elemData, idx))); + break; + case SND_CTL_ELEM_TYPE_IEC958: { + json_object *jsonIec958Ctl = json_object_new_object(); + snd_aes_iec958_t iec958; + snd_ctl_elem_value_get_iec958(elemData, &iec958); + + json_object_object_add (jsonIec958Ctl,"AES0",json_object_new_int(iec958.status[0])); + json_object_object_add (jsonIec958Ctl,"AES1",json_object_new_int(iec958.status[1])); + json_object_object_add (jsonIec958Ctl,"AES2",json_object_new_int(iec958.status[2])); + json_object_object_add (jsonIec958Ctl,"AES3",json_object_new_int(iec958.status[3])); + json_object_array_add (jsonValuesCtl, jsonIec958Ctl); + break; + } + default: + json_object_array_add (jsonValuesCtl, json_object_new_string ("?unknown?")); + break; + } + } + json_object_object_add (ctlRequest->jValues,"value",jsonValuesCtl); + + if (!quiet) { // in simple mode do not print usable values + json_object *jsonClassCtl = json_object_new_object(); + json_object_object_add (jsonClassCtl,"type" , json_object_new_string(snd_ctl_elem_type_name(elemType))); + json_object_object_add (jsonClassCtl,"count", json_object_new_int(count)); + + switch (elemType) { + case SND_CTL_ELEM_TYPE_INTEGER: + json_object_object_add (jsonClassCtl,"min", json_object_new_int((int)snd_ctl_elem_info_get_min(elemInfo))); + json_object_object_add (jsonClassCtl,"max", json_object_new_int((int)snd_ctl_elem_info_get_max(elemInfo))); + json_object_object_add (jsonClassCtl,"step", json_object_new_int((int)snd_ctl_elem_info_get_step(elemInfo))); + break; + case SND_CTL_ELEM_TYPE_INTEGER64: + json_object_object_add (jsonClassCtl,"min", json_object_new_int64(snd_ctl_elem_info_get_min64(elemInfo))); + json_object_object_add (jsonClassCtl,"max", json_object_new_int64(snd_ctl_elem_info_get_max64(elemInfo))); + json_object_object_add (jsonClassCtl,"step", json_object_new_int64(snd_ctl_elem_info_get_step64(elemInfo))); + break; + case SND_CTL_ELEM_TYPE_ENUMERATED: { + unsigned int item, items = snd_ctl_elem_info_get_items(elemInfo); + json_object *jsonEnum = json_object_new_array(); + + for (item = 0; item < items; item++) { + snd_ctl_elem_info_set_item(elemInfo, item); + if ((err = snd_ctl_elem_info(ctlDev, elemInfo)) >= 0) { + json_object_array_add (jsonEnum, json_object_new_string(snd_ctl_elem_info_get_item_name(elemInfo))); + } + } + json_object_object_add (jsonClassCtl, "enums",jsonEnum); + break; + } + default: break; // ignore any unknown type + } + + // add collected class info with associated ACLs + json_object_object_add (ctlRequest->jValues,"ctrl", jsonClassCtl); + json_object_object_add (ctlRequest->jValues,"acl" , getControlAcl (elemInfo)); + + // check for tlv [direct port from amixer.c] + if (snd_ctl_elem_info_is_tlv_readable(elemInfo)) { + unsigned int *tlv; + tlv = malloc(4096); + if ((err = snd_ctl_elem_info(ctlDev, elemInfo)) < 0) { + fprintf (stderr, "Control %s element TLV read error\n", snd_strerror(err)); + free(tlv); + } else { + json_object_object_add (ctlRequest->jValues,"tlv", decodeTlv (tlv, 4096)); + } + } + } + ctlRequest->used=1; + return 0; + + OnErrorExit: + ctlRequest->used=-1; + return -1; +} + +// assign multiple control to the same value +PUBLIC void alsaSetGetCtls (struct afb_req request, ActionSetGetT action) { + ctlRequestT *ctlRequest; + const char *warmsg=NULL; + int err=0, status=0; + unsigned int ctlCount; + snd_ctl_t *ctlDev; + snd_ctl_elem_list_t *ctlList; + json_object *sndctls=json_object_new_array();; + queryValuesT queryValues; + + err = alsaCheckQuery (request, &queryValues); + if (err) goto OnErrorExit; + + + if ((err = snd_ctl_open(&ctlDev, queryValues.devid, 0)) < 0) { + afb_req_fail_f (request, "sndcrl-notfound","devid=[%s] load fail error=%s\n", queryValues.devid, snd_strerror(err)); + goto OnErrorExit; + } + + snd_ctl_elem_list_alloca(&ctlList); + if ((err = snd_ctl_elem_list (ctlDev, ctlList)) < 0) { + afb_req_fail_f (request, "listInit-failed","devid=[%s] load fail error=%s\n", queryValues.devid, snd_strerror(err)); + goto OnErrorExit; + } + + if ((err = snd_ctl_elem_list_alloc_space(ctlList, snd_ctl_elem_list_get_count(ctlList))) < 0) { + afb_req_fail_f (request, "listAlloc-failed","devid=[%s] load fail error=%s\n", queryValues.devid, snd_strerror(err)); + goto OnErrorExit; + } + + if ((err = snd_ctl_elem_list (ctlDev, ctlList)) < 0) { + afb_req_fail_f (request, "listOpen-failed","devid=[%s] load fail error=%s\n", queryValues.devid, snd_strerror(err)); + goto OnErrorExit; + } + + // Parse numids string (empty == all) + ctlCount= snd_ctl_elem_list_get_used(ctlList); + if (queryValues.count==0) { + ctlRequest= alloca (sizeof(ctlRequestT)*(ctlCount)); + } else { + ctlRequest= alloca (sizeof(ctlRequestT)*(queryValues.count)); + NumidsListParse (&queryValues, ctlRequest); + } + + // Loop on all ctlDev controls + for (int ctlIndex=0; ctlIndex < ctlCount; ctlIndex++) { + unsigned int selected=0; + int jdx; + + if (queryValues.count == 0) { + selected=1; // check is this numid is selected within query + jdx = ctlIndex; // map all existing ctl as requested + } else { + int numid = snd_ctl_elem_list_get_numid(ctlList, ctlIndex); + if (numid < 0) { + NOTICE (afbIface,"snd_ctl_elem_list_get_numid index=%d fail", ctlIndex); + continue; + } + // check if current control was requested in query numids list + for (jdx=0; jdx < queryValues.count; jdx++) { + if (numid == ctlRequest[jdx].numId) { + selected = 1; + break; + } + } + } + + // control is selected open ctlid and get value + if (selected) { + snd_ctl_elem_id_t *elemId; + snd_ctl_elem_id_alloca(&elemId); + + snd_ctl_elem_list_get_id (ctlList, ctlIndex, elemId); + switch (action) { + case ACTION_GET: + err = alsaGetSingleCtl (ctlDev, elemId, &ctlRequest[jdx], queryValues.quiet); + break; + + case ACTION_SET: + err = alsaSetSingleCtl (ctlDev, elemId, &ctlRequest[jdx]); + + default: + err = 1; + } + if (err) status++; + else { + json_object_array_add (sndctls, ctlRequest[jdx].jValues); + } + } + } + + // if we had error let's add them into response message info + json_object *warnings = json_object_new_array(); + for (int jdx=0; jdx < queryValues.count; jdx++) { + if (ctlRequest[jdx].used <= 0) { + json_object *failctl = json_object_new_object(); + json_object_object_add (failctl, "numid", ctlRequest[jdx].jToken); + if (ctlRequest[jdx].jValues) + json_object_object_add(failctl, "values", ctlRequest[jdx].jValues); + + if (ctlRequest[jdx].numId == -1) json_object_object_add (failctl, "info", json_object_new_string ("Invalid NumID")); + else { + if (ctlRequest[jdx].used == 0) json_object_object_add (failctl, "info", json_object_new_string ("Does Not Exist")); + if (ctlRequest[jdx].used == -1) json_object_object_add (failctl, "info", json_object_new_string ("Invalid Value")); + } + json_object_array_add (warnings, failctl); + } + /* WARNING!!!! Check with Jose why following put free jValues + if (ctlRequest[jdx].jToken) json_object_put(ctlRequest[jdx].jToken); + if (ctlRequest[jdx].jValues) json_object_put(ctlRequest[jdx].jValues); + */ + } + + if (json_object_array_length(warnings)) warmsg=json_object_to_json_string_ext(warnings, JSON_C_TO_STRING_PLAIN); + + // send response+warning if any + afb_req_success (request, sndctls, warmsg); + snd_ctl_elem_list_clear(ctlList); + + OnErrorExit: + return; +} + +PUBLIC void alsaGetCtls (struct afb_req request) { + alsaSetGetCtls (request, ACTION_GET); +} + +PUBLIC void alsaSetCtls (struct afb_req request) { + alsaSetGetCtls (request, ACTION_SET); +} + + +// This routine is called when ALSA event are fired +STATIC int sndCtlEventCB (sd_event_source* src, int fd, uint32_t revents, void* userData) { + int err; + evtHandleT *evtHandle = (evtHandleT*)userData; + snd_ctl_event_t *eventId; + json_object *ctlEventJ; + unsigned int mask; + int iface; + int device; + int subdev; + const char*devname; + ctlRequestT ctlRequest; + snd_ctl_elem_id_t *elemId; + + if ((revents & EPOLLHUP) != 0) { + NOTICE (afbIface, "SndCtl hanghup [car disconnected]"); + goto ExitOnSucess; + } + + if ((revents & EPOLLIN) != 0) { + + // initialise event structure on stack + snd_ctl_event_alloca(&eventId); + snd_ctl_elem_id_alloca(&elemId); + + err = snd_ctl_read(evtHandle->ctlDev, eventId); + if (err < 0) goto OnErrorExit; + + // we only process sndctrl element + if (snd_ctl_event_get_type(eventId) != SND_CTL_EVENT_ELEM) goto ExitOnSucess; + + // we only process value changed events + mask = snd_ctl_event_elem_get_mask(eventId); + if (!(mask & SND_CTL_EVENT_MASK_VALUE)) goto ExitOnSucess; + + snd_ctl_event_elem_get_id (eventId, elemId); + + err = alsaGetSingleCtl (evtHandle->ctlDev, elemId, &ctlRequest, evtHandle->quiet); + if (err) goto OnErrorExit; + + iface = snd_ctl_event_elem_get_interface(eventId); + device = snd_ctl_event_elem_get_device(eventId); + subdev = snd_ctl_event_elem_get_subdevice(eventId); + devname= snd_ctl_event_elem_get_name(eventId); + + // proxy ctlevent as a binder event + ctlEventJ = json_object_new_object(); + json_object_object_add(ctlEventJ, "device" ,json_object_new_int (device)); + json_object_object_add(ctlEventJ, "subdev" ,json_object_new_int (subdev)); + if (evtHandle->quiet < 2) { + json_object_object_add(ctlEventJ, "iface" ,json_object_new_int (iface)); + json_object_object_add(ctlEventJ, "devname",json_object_new_string (devname)); + } + if (ctlRequest.jValues) (json_object_object_add(ctlEventJ, "values" ,ctlRequest.jValues)); + DEBUG(afbIface, "sndCtlEventCB=%s", json_object_get_string(ctlEventJ)); + afb_event_push(evtHandle->afbevt, ctlEventJ); + + } + + ExitOnSucess: + return 0; + + OnErrorExit: + WARNING (afbIface, "sndCtlEventCB: ignored unsupported event type"); + return (0); +} + +// Subscribe to every Alsa CtlEvent send by a given board +PUBLIC void alsaSubcribe (struct afb_req request) { + static sndHandleT sndHandles[MAX_SND_CARD]; + evtHandleT *evtHandle; + snd_ctl_t *ctlDev; + int err, idx, cardId, idxFree=-1; + snd_ctl_card_info_t *cardinfo; + queryValuesT queryValues; + + + err = alsaCheckQuery (request, &queryValues); + if (err) goto OnErrorExit; + + + // open control interface for devid + err = snd_ctl_open(&ctlDev, queryValues.devid, SND_CTL_READONLY); + if (err < 0) { + ctlDev=NULL; + afb_req_fail_f (request, "devid-unknown", "SndCard devid=%s Not Found err=%s", queryValues.devid, snd_strerror(err)); + goto OnErrorExit; + } + + snd_ctl_card_info_alloca(&cardinfo); + if ((err = snd_ctl_card_info(ctlDev, cardinfo)) < 0) { + afb_req_fail_f (request, "devid-invalid", "SndCard devid=%s Not Found err=%s", queryValues.devid, snd_strerror(err)); + goto OnErrorExit; + } + + cardId=snd_ctl_card_info_get_card(cardinfo); + + // search for an existing subscription and mark 1st free slot + for (idx= 0; idx < MAX_SND_CARD; idx ++) { + if (sndHandles[idx].ucount > 0 && cardId == sndHandles[idx].cardId) { + evtHandle= sndHandles[idx].evtHandle; + break; + } else if (idxFree == -1) idxFree= idx; + }; + + // if not subscription exist for the event let's create one + if (idx == MAX_SND_CARD) { + + // reach MAX_SND_CARD event registration + if (idxFree == -1) { + afb_req_fail_f (request, "register-toomany", "Cannot register new event Maxcard==%devent name=%s", idx); + goto OnErrorExit; + } + + evtHandle = malloc (sizeof(evtHandleT)); + evtHandle->ctlDev = ctlDev; + evtHandle->quiet = queryValues.quiet; + sndHandles[idxFree].ucount = 0; + sndHandles[idxFree].cardId = cardId; + sndHandles[idxFree].evtHandle = evtHandle; + + // subscribe for sndctl events attached to devid + err = snd_ctl_subscribe_events(evtHandle->ctlDev, 1); + if (err < 0) { + afb_req_fail_f (request, "subscribe-fail", "Cannot subscribe events from devid=%s err=%d", queryValues.devid, err); + goto OnErrorExit; + } + + // get pollfd attach to this sound board + snd_ctl_poll_descriptors(evtHandle->ctlDev, &evtHandle->pfds, 1); + + // register sound event to binder main loop + err = sd_event_add_io(afb_daemon_get_event_loop(afbIface->daemon), &evtHandle->src, evtHandle->pfds.fd, EPOLLIN, sndCtlEventCB, evtHandle); + if (err < 0) { + afb_req_fail_f (request, "register-mainloop", "Cannot hook events to mainloop devid=%s err=%d", queryValues.devid, err); + goto OnErrorExit; + } + + // create binder event attached to devid name + evtHandle->afbevt = afb_daemon_make_event (afbIface->daemon, queryValues.devid); + if (!afb_event_is_valid (evtHandle->afbevt)) { + afb_req_fail_f (request, "register-event", "Cannot register new binder event name=%s", queryValues.devid); + goto OnErrorExit; + } + + // everything looks OK let's move forward + idx=idxFree; + } + + // subscribe to binder event + err = afb_req_subscribe(request, evtHandle->afbevt); + if (err != 0) { + afb_req_fail_f (request, "register-eventname", "Cannot subscribe binder event name=%s [invalid channel]", queryValues.devid, err); + goto OnErrorExit; + } + + // increase usage count and return success + sndHandles[idx].ucount ++; + afb_req_success(request, NULL, NULL); + return; + + OnErrorExit: + if (ctlDev) snd_ctl_close(ctlDev); + return; +} + +// Subscribe to every Alsa CtlEvent send by a given board +PUBLIC void alsaGetCardId (struct afb_req request) { + char devid [10]; + const char *devname, *shortname, *longname; + int card, err, index, idx; + json_object *respJson; + snd_ctl_t *ctlDev; + snd_ctl_card_info_t *cardinfo; + + const char *sndname = afb_req_value(request, "sndname"); + if (sndname == NULL) { + afb_req_fail_f (request, "argument-missing", "sndname=SndCardName missing"); + goto OnErrorExit; + } + + // loop on potential card number + snd_ctl_card_info_alloca(&cardinfo); + for (card =0; card < MAX_SND_CARD; card++) { + + // build card devid and probe it + snprintf (devid, sizeof(devid), "hw:%i", card); + + // open control interface for devid + err = snd_ctl_open(&ctlDev, devid, SND_CTL_READONLY); + if (err < 0) continue; + + // extract sound card information + snd_ctl_card_info(ctlDev, cardinfo); + index = snd_ctl_card_info_get_card(cardinfo); + devname = snd_ctl_card_info_get_id(cardinfo); + shortname= snd_ctl_card_info_get_name(cardinfo); + longname = snd_ctl_card_info_get_longname(cardinfo); + + // check if short|long name match + if (!strcmp (sndname, devname)) break; + if (!strcmp (sndname, shortname)) break; + if (!strcmp (sndname, longname)) break; + } + + if (card == MAX_SND_CARD) { + afb_req_fail_f (request, "ctlDev-notfound", "Fail to find card with name=%s", sndname); + goto OnErrorExit; + } + + // proxy ctlevent as a binder event + respJson = json_object_new_object(); + json_object_object_add(respJson, "index" ,json_object_new_int (index)); + json_object_object_add(respJson, "devid" ,json_object_new_string (devid)); + json_object_object_add(respJson, "shortname" ,json_object_new_string (shortname)); + json_object_object_add(respJson, "longname" ,json_object_new_string (longname)); + + // search for a HAL binder card mapping name to api prefix + for (idx=0; idx < MAX_SND_CARD; idx++) { + if (!strcmp (cardRegistry[idx]->shortname, shortname)) break; + } + // if a match if found, then we have an HAL for this board let's return its value + if (idx < MAX_SND_CARD) json_object_object_add(respJson, "halapi",json_object_new_string (cardRegistry[idx]->apiprefix)); + + afb_req_success(request, respJson, NULL); + return; + + OnErrorExit: + return; +} + +// Register loaded HAL with board Name and API prefix +PUBLIC void alsaRegisterHal (struct afb_req request) { + static int index=0; + const char *shortname, *apiPrefix; + + apiPrefix = afb_req_value(request, "prefix"); + if (apiPrefix == NULL) { + afb_req_fail_f (request, "argument-missing", "prefix=BindingApiPrefix missing"); + goto OnErrorExit; + } + + shortname = afb_req_value(request, "name"); + if (shortname == NULL) { + afb_req_fail_f (request, "argument-missing", "sndname=SndCardName missing"); + goto OnErrorExit; + } + + if (index == MAX_SND_CARD) { + afb_req_fail_f (request, "alsahal-toomany", "Fail to register sndname=[%s]", shortname); + goto OnErrorExit; + } + + cardRegistry[index]= malloc (sizeof(cardRegistry)); + cardRegistry[index]->apiprefix=strdup(apiPrefix); + cardRegistry[index]->shortname=strdup(shortname); + index++;cardRegistry[index]=NULL; + + // when OK nothing to return + afb_req_success(request, NULL, NULL); + return; + + OnErrorExit: + return; +} + diff --git a/AlsaSound/CoreBinding/AlsaLibMapping.c b/AlsaSound/CoreBinding/AlsaLibMapping.c deleted file mode 100644 index 375d501..0000000 --- a/AlsaSound/CoreBinding/AlsaLibMapping.c +++ /dev/null @@ -1,1036 +0,0 @@ -/* - * AlsaLibMapping -- provide low level interface with ALSA lib (extracted from alsa-json-gateway code) - * Copyright (C) 2015,2016,2017, Fulup Ar Foll fulup@iot.bzh - * - * 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. - - References: - https://github.com/fulup-bzh/AlsaJsonGateway (original code) - http://alsa-lib.sourcearchive.com/documentation/1.0.20/modules.html - http://alsa-lib.sourcearchive.com/documentation/1.0.8/group__Control_gd48d44da8e3bfe150e928267008b8ff5.html - http://alsa.opensrc.org/HowTo_access_a_mixer_control - https://github.com/gch1p/alsa-volume-monitor/blob/master/main.c - https://github.com/DongheonKim/android_hardware_alsa-sound/blob/master/ALSAControl.cpp (ALSA low level API) - -*/ - -#define _GNU_SOURCE // needed for vasprintf - -#include -#include "AlsaLibMapping.h" -#include - - -typedef enum { - ACTION_SET, - ACTION_GET -} ActionSetGetT; - -// generic structure to pass parsed query values -typedef struct { - const char *devid; - json_object *jNumIds; - int quiet; - int count; -} queryValuesT; - -// generic sndctrl event handle hook to event callback when pooling -typedef struct { - struct pollfd pfds; - sd_event_source *src; - snd_ctl_t *ctl; - struct afb_event afbevt; -} evtHandleT; - -typedef struct { - int cardid; - int ucount; - evtHandleT *evtHandle; -} sndHandleT; - -typedef struct { - char *apiprefix; - char *shortname; -}cardRegistryT; - -// use to store crl numid user request -typedef struct { - unsigned int numId; - json_object *jToken; - json_object *jValues; - int used; -} ctlRequestT; - - -cardRegistryT *cardRegistry[MAX_SND_CARD+1]; - -STATIC void NumidsListParse (queryValuesT *queryValues, ctlRequestT *ctlRequest) { - json_object *jValues; - int length; - - for (int idx=0; queryValues->count; idx ++) { - ctlRequest[idx].jToken = json_object_array_get_idx (queryValues->jNumIds, idx); - - switch (json_object_get_type(ctlRequest[idx].jToken)) { - - case json_type_int: - // if NUMID is not an array then it should be an integer numid with no value - ctlRequest[idx].numId = json_object_get_int (ctlRequest[idx].jToken); - break; - - case json_type_array: - // NUMID is an array 1st slot should be numid, optionally values may come after - length=json_object_array_length (ctlRequest[idx].jToken); - if (length < 1 || length >2) { - ctlRequest[idx].used=-1; - continue; - } - - ctlRequest[idx].numId =json_object_get_int(json_object_array_get_idx (ctlRequest[idx].jToken, 0)); - ctlRequest[idx].used=0; - - if (length == 2) { - jValues = json_object_array_get_idx (ctlRequest[idx].jToken, 1); - if (jValues == NULL) { - ctlRequest[idx].used=-1; - continue; - } - // Value is an int or an array with potentially multiple subvalues - ctlRequest[idx].jValues = jValues; - } - default: - ctlRequest[idx].used=-1; - } - } -} - -STATIC int alsaCheckQuery (struct afb_req request, queryValuesT *queryValues) { - - queryValues->devid = afb_req_value(request, "devid"); - if (queryValues->devid == NULL) goto OnErrorExit; - const char *numids; - - const char *rqtQuiet = afb_req_value(request, "quiet"); - if (!rqtQuiet) queryValues->quiet=99; // default super quiet - else if (rqtQuiet && ! sscanf (rqtQuiet, "%d", &queryValues->quiet)) { - json_object *query = afb_req_json(request); - - afb_req_fail_f (request, "quiet-notinteger","Query=%s NumID not integer &numid=%s&", json_object_to_json_string(query), rqtQuiet); - goto OnErrorExit; - }; - - // no NumId is interpreted as ALL for get and error for set - numids = afb_req_value(request, "numids"); - if (numids != NULL) { - queryValues->count=0; - goto OnExit; - } - - queryValues->jNumIds = json_tokener_parse(numids); - queryValues->count = json_object_array_length (queryValues->jNumIds); - if (queryValues->count <= 0) { - afb_req_fail_f (request, "numid-notarray","NumId=%s NumId not valid JSON array", numids); - goto OnErrorExit; - } - -OnExit: - return 0; - -OnErrorExit: - return 1; -} - -STATIC json_object *DB2StringJsonOject (long dB) { - char label [20]; - if (dB < 0) { - snprintf(label, sizeof(label), "-%li.%02lidB", -dB / 100, -dB % 100); - } else { - snprintf(label, sizeof(label), "%li.%02lidB", dB / 100, dB % 100); - } - - // json function takes care of string copy - return (json_object_new_string (label)); -} - - -// Direct port from amixer TLV decode routine. This code is too complex for me. -// I hopefully did not break it when porting it. - -STATIC json_object *decodeTlv(unsigned int *tlv, unsigned int tlv_size) { - char label[20]; - unsigned int type = tlv[0]; - unsigned int size; - unsigned int idx = 0; - const char *chmap_type = NULL; - json_object * decodeTlvJson = json_object_new_object(); - - if (tlv_size < (unsigned int) (2 * sizeof (unsigned int))) { - printf("TLV size error!\n"); - return NULL; - } - type = tlv[idx++]; - size = tlv[idx++]; - tlv_size -= (unsigned int) (2 * sizeof (unsigned int)); - if (size > tlv_size) { - fprintf(stderr, "TLV size error (%i, %i, %i)!\n", type, size, tlv_size); - return NULL; - } - switch (type) { - - case SND_CTL_TLVT_CONTAINER: - { - json_object * containerJson = json_object_new_array(); - - size += (unsigned int) (sizeof (unsigned int) - 1); - size /= (unsigned int) (sizeof (unsigned int)); - while (idx < size) { - json_object *embedJson; - - if (tlv[idx + 1] > (size - idx) * sizeof (unsigned int)) { - fprintf(stderr, "TLV size error in compound!\n"); - return NULL; - } - embedJson = decodeTlv(tlv + idx, tlv[idx + 1] + 8); - json_object_array_add(containerJson, embedJson); - idx += (unsigned int) (2 + (tlv[idx + 1] + sizeof (unsigned int) - 1) / sizeof (unsigned int)); - } - json_object_object_add(decodeTlvJson, "container", containerJson); - break; - } - - case SND_CTL_TLVT_DB_SCALE: - { - json_object * dbscaleJson = json_object_new_object(); - - if (size != 2 * sizeof (unsigned int)) { - json_object * arrayJson = json_object_new_array(); - while (size > 0) { - snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); - json_object_array_add(arrayJson, json_object_new_string(label)); - size -= (unsigned int) sizeof (unsigned int); - } - json_object_object_add(dbscaleJson, "array", arrayJson); - } else { - json_object_object_add(dbscaleJson, "min", DB2StringJsonOject((int) tlv[2])); - json_object_object_add(dbscaleJson, "step", DB2StringJsonOject(tlv[3] & 0xffff)); - json_object_object_add(dbscaleJson, "mute", DB2StringJsonOject((tlv[3] >> 16) & 1)); - } - json_object_object_add(decodeTlvJson, "dbscale", dbscaleJson); - break; - } - -#ifdef SND_CTL_TLVT_DB_LINEAR - case SND_CTL_TLVT_DB_LINEAR: - { - json_object * dbLinearJson = json_object_new_object(); - - if (size != 2 * sizeof (unsigned int)) { - json_object * arrayJson = json_object_new_array(); - while (size > 0) { - snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); - json_object_array_add(arrayJson, json_object_new_string(label)); - size -= (unsigned int) sizeof (unsigned int); - } - json_object_object_add(dbLinearJson, "offset", arrayJson); - } else { - json_object_object_add(dbLinearJson, "min", DB2StringJsonOject((int) tlv[2])); - json_object_object_add(dbLinearJson, "max", DB2StringJsonOject((int) tlv[3])); - } - json_object_object_add(decodeTlvJson, "dblinear", dbLinearJson); - break; - } -#endif - -#ifdef SND_CTL_TLVT_DB_RANGE - case SND_CTL_TLVT_DB_RANGE: - { - json_object *dbRangeJson = json_object_new_object(); - - if ((size % (6 * sizeof (unsigned int))) != 0) { - json_object *arrayJson = json_object_new_array(); - while (size > 0) { - snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); - json_object_array_add(arrayJson, json_object_new_string(label)); - size -= (unsigned int) sizeof (unsigned int); - } - json_object_object_add(dbRangeJson, "dbrange", arrayJson); - break; - } - while (size > 0) { - json_object * embedJson = json_object_new_object(); - snprintf(label, sizeof (label), "%i,", tlv[idx++]); - json_object_object_add(embedJson, "rangemin", json_object_new_string(label)); - snprintf(label, sizeof (label), "%i", tlv[idx++]); - json_object_object_add(embedJson, "rangemax", json_object_new_string(label)); - embedJson = decodeTlv(tlv + idx, 4 * sizeof (unsigned int)); - json_object_object_add(embedJson, "tlv", embedJson); - idx += 4; - size -= (unsigned int) (6 * sizeof (unsigned int)); - json_object_array_add(dbRangeJson, embedJson); - } - json_object_object_add(decodeTlvJson, "dbrange", dbRangeJson); - break; - } -#endif -#ifdef SND_CTL_TLVT_DB_MINMAX - case SND_CTL_TLVT_DB_MINMAX: - case SND_CTL_TLVT_DB_MINMAX_MUTE: - { - json_object * dbMinMaxJson = json_object_new_object(); - - if (size != 2 * sizeof (unsigned int)) { - json_object * arrayJson = json_object_new_array(); - while (size > 0) { - snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); - json_object_array_add(arrayJson, json_object_new_string(label)); - size -= (unsigned int) sizeof (unsigned int); - } - json_object_object_add(dbMinMaxJson, "array", arrayJson); - - } else { - json_object_object_add(dbMinMaxJson, "min", DB2StringJsonOject((int) tlv[2])); - json_object_object_add(dbMinMaxJson, "max", DB2StringJsonOject((int) tlv[3])); - } - - if (type == SND_CTL_TLVT_DB_MINMAX_MUTE) { - json_object_object_add(decodeTlvJson, "dbminmaxmute", dbMinMaxJson); - } else { - json_object_object_add(decodeTlvJson, "dbminmax", dbMinMaxJson); - } - break; - } -#endif -#ifdef SND_CTL_TLVT_CHMAP_FIXED - case SND_CTL_TLVT_CHMAP_FIXED: - chmap_type = "fixed"; - /* Fall through */ - case SND_CTL_TLVT_CHMAP_VAR: - if (!chmap_type) - chmap_type = "variable"; - /* Fall through */ - case SND_CTL_TLVT_CHMAP_PAIRED: - if (!chmap_type) - chmap_type = "paired"; - - json_object * chmapJson = json_object_new_object(); - json_object * arrayJson = json_object_new_array(); - - while (size > 0) { - snprintf(label, sizeof (label), "%s", snd_pcm_chmap_name(tlv[idx++])); - size -= (unsigned int) sizeof (unsigned int); - json_object_array_add(arrayJson, json_object_new_string(label)); - } - json_object_object_add(chmapJson, chmap_type, arrayJson); - json_object_object_add(decodeTlvJson, "chmap", chmapJson); - break; -#endif - default: - { - printf("unk-%i-", type); - json_object * arrayJson = json_object_new_array(); - - while (size > 0) { - snprintf(label, sizeof (label), "0x%08x,", tlv[idx++]); - size -= (unsigned int) sizeof (unsigned int); - json_object_array_add(arrayJson, json_object_new_string(label)); - } - break; - json_object_object_add(decodeTlvJson, "unknown", arrayJson); - } - } - - return (decodeTlvJson); -} - - -// retreive info for one given card -STATIC json_object* alsaCardProbe (const char *rqtSndId) { - const char *info, *name; - const char *devid, *driver; - json_object *ctlDev; - snd_ctl_t *handle; - snd_ctl_card_info_t *cardinfo; - int err; - - - snd_ctl_card_info_alloca(&cardinfo); - - if ((err = snd_ctl_open(&handle, rqtSndId, 0)) < 0) { - INFO (afbIface, "SndCard [%s] Not Found", rqtSndId); - return NULL; - } - - if ((err = snd_ctl_card_info(handle, cardinfo)) < 0) { - snd_ctl_close(handle); - WARNING (afbIface, "SndCard [%s] info error: %s", rqtSndId, snd_strerror(err)); - return NULL; - } - - // start a new json object to store card info - ctlDev = json_object_new_object(); - - devid= snd_ctl_card_info_get_id(cardinfo); - json_object_object_add (ctlDev, "devid" , json_object_new_string(devid)); - name = snd_ctl_card_info_get_name(cardinfo); - json_object_object_add (ctlDev, "name", json_object_new_string (name)); - - if (afbIface->verbosity > 1) { - json_object_object_add (ctlDev, "devid", json_object_new_string(rqtSndId)); - driver= snd_ctl_card_info_get_driver(cardinfo); - json_object_object_add (ctlDev, "driver" , json_object_new_string(driver)); - info = strdup(snd_ctl_card_info_get_longname (cardinfo)); - json_object_object_add (ctlDev, "info" , json_object_new_string (info)); - INFO (afbIface, "AJG: Soundcard Devid=%-5s Cardid=%-7s Name=%s\n", rqtSndId, devid, info); - } - - // free card handle and return info - snd_ctl_close(handle); - return (ctlDev); -} - -// Loop on every potential Sound card and register active one -PUBLIC void alsaGetInfo (struct afb_req request) { - int card; - json_object *ctlDev, *ctlDevs; - char devid[32]; - - const char *rqtSndId = afb_req_value(request, "devid"); - - // if no specific card requested loop on all - - if (rqtSndId != NULL) { - // only one card was requested let's probe it - ctlDev = alsaCardProbe (rqtSndId); - if (ctlDev != NULL) afb_req_success(request, ctlDev, NULL); - else afb_req_fail_f (request, "sndscard-notfound", "SndCard [%s] Not Found", rqtSndId); - - } else { - // return an array of ctlDev - ctlDevs =json_object_new_array(); - - // loop on potential card number - for (card =0; card < MAX_SND_CARD; card++) { - - // build card devid and probe it - snprintf (devid, sizeof(devid), "hw:%i", card); - ctlDev = alsaCardProbe (devid); - - // Alsa has hole within card list [ignore them] - if (ctlDev != NULL) { - // add current ctlDev to ctlDevs object - json_object_array_add (ctlDevs, ctlDev); - } - } - afb_req_success (request, ctlDevs, NULL); - } -} - -// pack Alsa element's ACL into a JSON object -STATIC json_object *getControlAcl (snd_ctl_elem_info_t *info) { - - json_object * jsonAclCtl = json_object_new_object(); - - json_object_object_add (jsonAclCtl, "read" , json_object_new_boolean(snd_ctl_elem_info_is_readable(info))); - json_object_object_add (jsonAclCtl, "write" , json_object_new_boolean(snd_ctl_elem_info_is_writable(info))); - json_object_object_add (jsonAclCtl, "inact" , json_object_new_boolean(snd_ctl_elem_info_is_inactive(info))); - json_object_object_add (jsonAclCtl, "volat" , json_object_new_boolean(snd_ctl_elem_info_is_volatile(info))); - json_object_object_add (jsonAclCtl, "lock" , json_object_new_boolean(snd_ctl_elem_info_is_locked(info))); - - // if TLV is readable we insert its ACL - if (!snd_ctl_elem_info_is_tlv_readable(info)) { - json_object * jsonTlv = json_object_new_object(); - - json_object_object_add (jsonTlv, "read" , json_object_new_boolean(snd_ctl_elem_info_is_tlv_readable(info))); - json_object_object_add (jsonTlv, "write" , json_object_new_boolean(snd_ctl_elem_info_is_tlv_writable(info))); - json_object_object_add (jsonTlv, "command", json_object_new_boolean(snd_ctl_elem_info_is_tlv_commandable(info))); - - json_object_object_add (jsonAclCtl, "tlv", jsonTlv); - } - return (jsonAclCtl); -} - -// process ALSA control and store resulting value into ctlRequest -STATIC int alsaSetSingleCtl (snd_ctl_t *ctlDev, snd_ctl_elem_id_t *elemId, ctlRequestT *ctlRequest) { - snd_ctl_elem_value_t *elemData; - snd_ctl_elem_info_t *elemInfo; - int count, length, err, valueIsArray; - - // let's make sure we are processing the right control - if (ctlRequest->numId != snd_ctl_elem_id_get_numid (elemId)) goto OnErrorExit; - - // set info event ID and get value - snd_ctl_elem_info_alloca(&elemInfo); - snd_ctl_elem_info_set_id(elemInfo, elemId); // map ctlInfo to ctlId elemInfo is updated !!! - if (snd_ctl_elem_info(ctlDev, elemInfo) < 0) { - NOTICE (afbIface, "Fail to load ALSA NUMID=%d Values=[%s]", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues)); - goto OnErrorExit; - } - - snd_ctl_elem_info_get_id(elemInfo, elemId); // map ctlInfo to ctlId elemInfo is updated !!! - if (!snd_ctl_elem_info_is_writable(elemInfo)) { - NOTICE (afbIface, "Not Writable ALSA NUMID=%d Values=[%s]", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues)); - goto OnErrorExit; - } - - count = snd_ctl_elem_info_get_count (elemInfo); - if (!json_object_is_type (ctlRequest->jValues, json_type_array)) { - length=1; - valueIsArray=0; - } else { - length = json_object_array_length (ctlRequest->jValues); - valueIsArray=1; - } - - if (count == 0 || count < length) { - NOTICE (afbIface, "Invalid Values ALSA NUMID=%d Values=[%s] wanted count=%d", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues), count); - goto OnErrorExit; - } - - snd_ctl_elem_value_alloca(&elemData); - snd_ctl_elem_value_set_id(elemData, elemId); // map ctlInfo to ctlId elemInfo is updated !!! - if (snd_ctl_elem_read(ctlDev, elemData) < 0) goto OnErrorExit; - - // Loop on every control value and push to sndcard - for (int index=0; index < count && index < length; index++) { - json_object *element; - int value; - - if (valueIsArray) element= json_object_array_get_idx(ctlRequest->jValues, index); - else element= ctlRequest->jValues; - - value= json_object_get_int (element); - snd_ctl_elem_value_set_integer(elemData, index, value); - } - - if ((err = snd_ctl_elem_write(ctlDev, elemData)) < 0) { - NOTICE (afbIface, "Fail to write ALSA NUMID=%d Values=[%s]", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues)); - goto OnErrorExit; - } - - ctlRequest->used=1; - return 0; - - OnErrorExit: - ctlRequest->used=-1; - return -1; -} - -// process ALSA control and store then into ctlRequest -STATIC int alsaGetSingleCtl (snd_ctl_t *ctlDev, snd_ctl_elem_id_t *elemId, ctlRequestT *ctlRequest, int quiet) { - snd_ctl_elem_type_t elemType; - snd_ctl_elem_value_t *elemData; - snd_ctl_elem_info_t *elemInfo; - int count, idx, err; - - // let's make sure we are processing the right control - if (ctlRequest->numId != snd_ctl_elem_id_get_numid (elemId)) goto OnErrorExit; - - // set info event ID and get value - - snd_ctl_elem_info_alloca(&elemInfo); - snd_ctl_elem_info_set_id(elemInfo, elemId); // map ctlInfo to ctlId elemInfo is updated !!! - if (snd_ctl_elem_info(ctlDev, elemInfo) < 0) goto OnErrorExit; - count = snd_ctl_elem_info_get_count (elemInfo); - if (count == 0) goto OnErrorExit; - - snd_ctl_elem_info_get_id(elemInfo, elemId); // map ctlInfo to ctlId elemInfo is updated !!! - if (!snd_ctl_elem_info_is_readable(elemInfo)) goto OnErrorExit; - elemType = snd_ctl_elem_info_get_type(elemInfo); - - snd_ctl_elem_value_alloca(&elemData); - snd_ctl_elem_value_set_id(elemData, elemId); // map ctlInfo to ctlId elemInfo is updated !!! - if (snd_ctl_elem_read(ctlDev, elemData) < 0) goto OnErrorExit; - - ctlRequest->jValues= json_object_new_object(); - if (quiet < 2) json_object_object_add (ctlRequest->jValues,"name" , json_object_new_string(snd_ctl_elem_id_get_name (elemId))); - if (quiet < 1) json_object_object_add (ctlRequest->jValues,"iface" , json_object_new_string(snd_ctl_elem_iface_name(snd_ctl_elem_id_get_interface(elemId)))); - if (quiet < 3) json_object_object_add (ctlRequest->jValues,"actif", json_object_new_boolean(!snd_ctl_elem_info_is_inactive(elemInfo))); - - json_object *jsonValuesCtl = json_object_new_array(); - for (idx = 0; idx < count; idx++) { // start from one in amixer.c !!! - switch (elemType) { - case SND_CTL_ELEM_TYPE_BOOLEAN: { - json_object_array_add (jsonValuesCtl, json_object_new_boolean (snd_ctl_elem_value_get_boolean(elemData, idx))); - break; - } - case SND_CTL_ELEM_TYPE_INTEGER: - json_object_array_add (jsonValuesCtl, json_object_new_int ((int)snd_ctl_elem_value_get_integer(elemData, idx))); - break; - case SND_CTL_ELEM_TYPE_INTEGER64: - json_object_array_add (jsonValuesCtl, json_object_new_int64 (snd_ctl_elem_value_get_integer64(elemData, idx))); - break; - case SND_CTL_ELEM_TYPE_ENUMERATED: - json_object_array_add (jsonValuesCtl, json_object_new_int (snd_ctl_elem_value_get_enumerated(elemData, idx))); - break; - case SND_CTL_ELEM_TYPE_BYTES: - json_object_array_add (jsonValuesCtl, json_object_new_int ((int)snd_ctl_elem_value_get_byte(elemData, idx))); - break; - case SND_CTL_ELEM_TYPE_IEC958: { - json_object *jsonIec958Ctl = json_object_new_object(); - snd_aes_iec958_t iec958; - snd_ctl_elem_value_get_iec958(elemData, &iec958); - - json_object_object_add (jsonIec958Ctl,"AES0",json_object_new_int(iec958.status[0])); - json_object_object_add (jsonIec958Ctl,"AES1",json_object_new_int(iec958.status[1])); - json_object_object_add (jsonIec958Ctl,"AES2",json_object_new_int(iec958.status[2])); - json_object_object_add (jsonIec958Ctl,"AES3",json_object_new_int(iec958.status[3])); - json_object_array_add (jsonValuesCtl, jsonIec958Ctl); - break; - } - default: - json_object_array_add (jsonValuesCtl, json_object_new_string ("?unknown?")); - break; - } - } - json_object_object_add (ctlRequest->jValues,"value",jsonValuesCtl); - - if (!quiet) { // in simple mode do not print usable values - json_object *jsonClassCtl = json_object_new_object(); - json_object_object_add (jsonClassCtl,"type" , json_object_new_string(snd_ctl_elem_type_name(elemType))); - json_object_object_add (jsonClassCtl,"count", json_object_new_int(count)); - - switch (elemType) { - case SND_CTL_ELEM_TYPE_INTEGER: - json_object_object_add (jsonClassCtl,"min", json_object_new_int((int)snd_ctl_elem_info_get_min(elemInfo))); - json_object_object_add (jsonClassCtl,"max", json_object_new_int((int)snd_ctl_elem_info_get_max(elemInfo))); - json_object_object_add (jsonClassCtl,"step", json_object_new_int((int)snd_ctl_elem_info_get_step(elemInfo))); - break; - case SND_CTL_ELEM_TYPE_INTEGER64: - json_object_object_add (jsonClassCtl,"min", json_object_new_int64(snd_ctl_elem_info_get_min64(elemInfo))); - json_object_object_add (jsonClassCtl,"max", json_object_new_int64(snd_ctl_elem_info_get_max64(elemInfo))); - json_object_object_add (jsonClassCtl,"step", json_object_new_int64(snd_ctl_elem_info_get_step64(elemInfo))); - break; - case SND_CTL_ELEM_TYPE_ENUMERATED: { - unsigned int item, items = snd_ctl_elem_info_get_items(elemInfo); - json_object *jsonEnum = json_object_new_array(); - - for (item = 0; item < items; item++) { - snd_ctl_elem_info_set_item(elemInfo, item); - if ((err = snd_ctl_elem_info(ctlDev, elemInfo)) >= 0) { - json_object_array_add (jsonEnum, json_object_new_string(snd_ctl_elem_info_get_item_name(elemInfo))); - } - } - json_object_object_add (jsonClassCtl, "enums",jsonEnum); - break; - } - default: break; // ignore any unknown type - } - - // add collected class info with associated ACLs - json_object_object_add (ctlRequest->jValues,"ctrl", jsonClassCtl); - json_object_object_add (ctlRequest->jValues,"acl" , getControlAcl (elemInfo)); - - // check for tlv [direct port from amixer.c] - if (snd_ctl_elem_info_is_tlv_readable(elemInfo)) { - unsigned int *tlv; - tlv = malloc(4096); - if ((err = snd_ctl_elem_info(ctlDev, elemInfo)) < 0) { - fprintf (stderr, "Control %s element TLV read error\n", snd_strerror(err)); - free(tlv); - } else { - json_object_object_add (ctlRequest->jValues,"tlv", decodeTlv (tlv, 4096)); - } - } - } - ctlRequest->used=1; - return 0; - - OnErrorExit: - ctlRequest->used=-1; - return -1; -} - -// assign multiple control to the same value -PUBLIC void alsaSetGetCtls (struct afb_req request, ActionSetGetT action) { - ctlRequestT *ctlRequest; - const char *warmsg=NULL; - int err=0, status=0; - unsigned int ctlCount; - snd_ctl_t *ctlDev; - snd_ctl_elem_list_t *ctlList; - - json_object *sndctrls=json_object_new_object();; - queryValuesT queryValues; - - err = alsaCheckQuery (request, &queryValues); - if (err) goto OnErrorExit; - - - if ((err = snd_ctl_open(&ctlDev, queryValues.devid, 0)) < 0) { - afb_req_fail_f (request, "sndcrl-notfound","devid=[%s] load fail error=%s\n", queryValues.devid, snd_strerror(err)); - goto OnErrorExit; - } - - snd_ctl_elem_list_alloca(&ctlList); - if ((err = snd_ctl_elem_list (ctlDev, ctlList)) < 0) { - afb_req_fail_f (request, "listInit-failed","devid=[%s] load fail error=%s\n", queryValues.devid, snd_strerror(err)); - goto OnErrorExit; - } - - if ((err = snd_ctl_elem_list_alloc_space(ctlList, snd_ctl_elem_list_get_count(ctlList))) < 0) { - afb_req_fail_f (request, "listAlloc-failed","devid=[%s] load fail error=%s\n", queryValues.devid, snd_strerror(err)); - goto OnErrorExit; - } - - if ((err = snd_ctl_elem_list (ctlDev, ctlList)) < 0) { - afb_req_fail_f (request, "listOpen-failed","devid=[%s] load fail error=%s\n", queryValues.devid, snd_strerror(err)); - goto OnErrorExit; - } - - // Parse numids string (empty == all) - ctlCount= snd_ctl_elem_list_get_used(ctlList); - if (queryValues.count==0) { - ctlRequest= alloca (sizeof(ctlRequestT)*(ctlCount)); - } else { - ctlRequest= alloca (sizeof(ctlRequestT)*(queryValues.count)); - NumidsListParse (&queryValues, ctlRequest); - } - - // Loop on all ctlDev controls - for (int ctlIndex=0; ctlIndex < ctlCount; ctlIndex++) { - unsigned int selected=0; - int jdx; - - if (queryValues.count == 0) { - selected=1; // check is this numid is selected within query - jdx = ctlIndex; // map all existing ctl as requested - } else { - int numid = snd_ctl_elem_list_get_numid(ctlList, ctlIndex); - if (numid < 0) { - NOTICE (afbIface,"snd_ctl_elem_list_get_numid index=%d fail", ctlIndex); - continue; - } - // check if current control was requested in query numids list - for (jdx=0; jdx < queryValues.count; jdx++) { - if (numid == ctlRequest[jdx].numId) { - selected = 1; - break; - } - } - } - - // control is selected open ctlid and get value - if (selected) { - snd_ctl_elem_id_t *elemId; - snd_ctl_elem_id_alloca(&elemId); - - snd_ctl_elem_list_get_id (ctlList, ctlIndex, elemId); - switch (action) { - case ACTION_GET: - err = alsaGetSingleCtl (ctlDev, elemId, &ctlRequest[jdx], queryValues.quiet); - break; - - case ACTION_SET: - err = alsaSetSingleCtl (ctlDev, elemId, &ctlRequest[jdx]); - - default: - err = 1; - } - if (err) status++; - else json_object_object_add (sndctrls, json_object_to_json_string(ctlRequest[jdx].jToken), ctlRequest[jdx].jValues); - } - } - - // if we had error let's add them into response message info - json_object *warnings = json_object_new_object(); - for (int jdx=0; jdx < queryValues.count; jdx++) { - if (ctlRequest[jdx].used <= 0) { - if (ctlRequest[jdx].used == 0) json_object_object_add (warnings, json_object_to_json_string(ctlRequest[jdx].jToken), json_object_new_string ("Does Not Exist")); - else json_object_object_add (warnings, json_object_to_json_string(ctlRequest[jdx].jToken), json_object_new_string ("Invalid Value")); - } - if (ctlRequest[jdx].numId == -1) { - json_object_object_add (warnings, json_object_to_json_string(ctlRequest[jdx].jToken), json_object_new_string ("Invalid NumID")); - } - // free intermediary object - if (ctlRequest[jdx].jToken) json_object_put(ctlRequest[jdx].jToken); - if (ctlRequest[jdx].jValues) json_object_put(ctlRequest[jdx].jValues); - } - if (json_object_object_length(warnings)) warmsg=json_object_to_json_string(warnings); - else json_object_put(warnings); - - // send response warning if any are passed into info element - afb_req_success (request, sndctrls, warmsg); - snd_ctl_elem_list_clear(ctlList); - - OnErrorExit: - return; -} - -PUBLIC void alsaGetCtls (struct afb_req request) { - alsaSetGetCtls (request, ACTION_GET); -} - -PUBLIC void alsaSetCtls (struct afb_req request) { - alsaSetGetCtls (request, ACTION_SET); -} - - -// This routine is called when ALSA event are fired -STATIC int sndCtlEventCB (sd_event_source* src, int fd, uint32_t revents, void* userData) { - int err; - evtHandleT *evtHandle = (evtHandleT*)userData; - snd_ctl_event_t *ctlEvent; - json_object *ctlEventJson; - unsigned int mask; - int numid; - int iface; - int device; - int subdev; - const char*devname; - int index; - - if ((revents & EPOLLHUP) != 0) { - NOTICE (afbIface, "SndCtl hanghup [car disconnected]"); - goto ExitOnSucess; - } - - if ((revents & EPOLLIN) != 0) { - - snd_ctl_event_alloca(&ctlEvent); // initialise event structure on stack - - err = snd_ctl_read(evtHandle->ctl, ctlEvent); - if (err < 0) goto OnErrorExit; - - // we only process sndctrl element - if (snd_ctl_event_get_type(ctlEvent) != SND_CTL_EVENT_ELEM) goto ExitOnSucess; - - // we only process value changed events - mask = snd_ctl_event_elem_get_mask(ctlEvent); - if (!(mask & SND_CTL_EVENT_MASK_VALUE)) goto ExitOnSucess; - - numid = snd_ctl_event_elem_get_numid(ctlEvent); - iface = snd_ctl_event_elem_get_interface(ctlEvent); - device = snd_ctl_event_elem_get_device(ctlEvent); - subdev = snd_ctl_event_elem_get_subdevice(ctlEvent); - devname= snd_ctl_event_elem_get_name(ctlEvent); - index = snd_ctl_event_elem_get_index(ctlEvent); - - DEBUG(afbIface, "sndCtlEventCB: (%i,%i,%i,%i,%s,%i)", numid, iface, device, subdev, devname, index); - - // proxy ctlevent as a binder event - ctlEventJson = json_object_new_object(); - json_object_object_add(ctlEventJson, "numid" ,json_object_new_int (numid)); - json_object_object_add(ctlEventJson, "iface" ,json_object_new_int (iface)); - json_object_object_add(ctlEventJson, "device" ,json_object_new_int (device)); - json_object_object_add(ctlEventJson, "subdev" ,json_object_new_int (subdev)); - json_object_object_add(ctlEventJson, "devname",json_object_new_string (devname)); - json_object_object_add(ctlEventJson, "index" ,json_object_new_int (index)); - afb_event_push(evtHandle->afbevt, ctlEventJson); - } - - ExitOnSucess: - return 0; - - OnErrorExit: - WARNING (afbIface, "sndCtlEventCB: ignored unsupported event type"); - return (0); -} - -// Subscribe to every Alsa CtlEvent send by a given board -PUBLIC void alsaSubcribe (struct afb_req request) { - static sndHandleT sndHandles[MAX_SND_CARD]; - evtHandleT *evtHandle; - snd_ctl_t *ctlDev; - snd_ctl_card_info_t *card_info; - int err, idx, cardid; - int idxFree=-1; - - const char *devid = afb_req_value(request, "devid"); - if (devid == NULL) { - afb_req_fail_f (request, "devid-missing", "devid=hw:xxx missing"); - goto OnErrorExit; - } - - // open control interface for devid - err = snd_ctl_open(&ctlDev, devid, SND_CTL_READONLY); - if (err < 0) { - afb_req_fail_f (request, "devid-unknown", "SndCard devid=%s Not Found err=%d", devid, err); - goto OnErrorExit; - } - - // get sound card index use to search existing subscription - snd_ctl_card_info_alloca(&card_info); - snd_ctl_card_info(ctlDev, card_info); - cardid = snd_ctl_card_info_get_card(card_info); - - // search for an existing subscription and mark 1st free slot - for (idx= 0; idx < MAX_SND_CARD; idx ++) { - if (sndHandles[idx].ucount > 0 && sndHandles[idx].cardid == cardid) { - evtHandle= sndHandles[idx].evtHandle; - break; - } else if (idxFree == -1) idxFree= idx; - }; - - // if not subscription exist for the event let's create one - if (idx == MAX_SND_CARD) { - - // reach MAX_SND_CARD event registration - if (idxFree == -1) { - afb_req_fail_f (request, "register-toomany", "Cannot register new event Maxcard==%devent name=%s", idx); - snd_ctl_close(ctlDev); - goto OnErrorExit; - } - - evtHandle = malloc (sizeof(evtHandleT)); - evtHandle->ctl = ctlDev; - sndHandles[idxFree].ucount = 0; - sndHandles[idxFree].cardid = cardid; - sndHandles[idxFree].evtHandle = evtHandle; - - // subscribe for sndctl events attached to devid - err = snd_ctl_subscribe_events(evtHandle->ctl, 1); - if (err < 0) { - afb_req_fail_f (request, "subscribe-fail", "Cannot subscribe events from devid=%s err=%d", devid, err); - snd_ctl_close(ctlDev); - goto OnErrorExit; - } - - // get pollfd attach to this sound board - snd_ctl_poll_descriptors(evtHandle->ctl, &evtHandle->pfds, 1); - - // register sound event to binder main loop - err = sd_event_add_io(afb_daemon_get_event_loop(afbIface->daemon), &evtHandle->src, evtHandle->pfds.fd, EPOLLIN, sndCtlEventCB, evtHandle); - if (err < 0) { - afb_req_fail_f (request, "register-mainloop", "Cannot hook events to mainloop devid=%s err=%d", devid, err); - snd_ctl_close(ctlDev); - goto OnErrorExit; - } - - // create binder event attached to devid name - evtHandle->afbevt = afb_daemon_make_event (afbIface->daemon, devid); - if (!afb_event_is_valid (evtHandle->afbevt)) { - afb_req_fail_f (request, "register-event", "Cannot register new binder event name=%s", devid); - snd_ctl_close(ctlDev); - goto OnErrorExit; - } - - // everything looks OK let's move forward - idx=idxFree; - } - - // subscribe to binder event - err = afb_req_subscribe(request, evtHandle->afbevt); - if (err != 0) { - afb_req_fail_f (request, "register-eventname", "Cannot subscribe binder event name=%s [invalid channel]", devid, err); - goto OnErrorExit; - } - - // increase usage count and return success - sndHandles[idx].ucount ++; - afb_req_success(request, NULL, NULL); - return; - - OnErrorExit: - return; -} - -// Subscribe to every Alsa CtlEvent send by a given board -PUBLIC void alsaGetCardId (struct afb_req request) { - char devid [10]; - const char *devname, *shortname, *longname; - int card, err, index, idx; - json_object *respJson; - snd_ctl_t *ctlDev; - snd_ctl_card_info_t *cardinfo; - - const char *sndname = afb_req_value(request, "sndname"); - if (sndname == NULL) { - afb_req_fail_f (request, "argument-missing", "sndname=SndCardName missing"); - goto OnErrorExit; - } - - // loop on potential card number - snd_ctl_card_info_alloca(&cardinfo); - for (card =0; card < MAX_SND_CARD; card++) { - - // build card devid and probe it - snprintf (devid, sizeof(devid), "hw:%i", card); - - // open control interface for devid - err = snd_ctl_open(&ctlDev, devid, SND_CTL_READONLY); - if (err < 0) continue; - - // extract sound card information - snd_ctl_card_info(ctlDev, cardinfo); - index = snd_ctl_card_info_get_card(cardinfo); - devname = snd_ctl_card_info_get_id(cardinfo); - shortname= snd_ctl_card_info_get_name(cardinfo); - longname = snd_ctl_card_info_get_longname(cardinfo); - - // check if short|long name match - if (!strcmp (sndname, devname)) break; - if (!strcmp (sndname, shortname)) break; - if (!strcmp (sndname, longname)) break; - } - - if (card == MAX_SND_CARD) { - afb_req_fail_f (request, "ctlDev-notfound", "Fail to find card with name=%s", sndname); - goto OnErrorExit; - } - - // proxy ctlevent as a binder event - respJson = json_object_new_object(); - json_object_object_add(respJson, "index" ,json_object_new_int (index)); - json_object_object_add(respJson, "devid" ,json_object_new_string (devid)); - json_object_object_add(respJson, "shortname" ,json_object_new_string (shortname)); - json_object_object_add(respJson, "longname" ,json_object_new_string (longname)); - - // search for a HAL binder card mapping name to api prefix - for (idx=0; idx < MAX_SND_CARD; idx++) { - if (!strcmp (cardRegistry[idx]->shortname, shortname)) break; - } - // if a match if found, then we have an HAL for this board let's return its value - if (idx < MAX_SND_CARD) json_object_object_add(respJson, "halapi",json_object_new_string (cardRegistry[idx]->apiprefix)); - - afb_req_success(request, respJson, NULL); - return; - - OnErrorExit: - return; -} - -// Register loaded HAL with board Name and API prefix -PUBLIC void alsaRegisterHal (struct afb_req request) { - static int index=0; - const char *shortname, *apiPrefix; - - apiPrefix = afb_req_value(request, "prefix"); - if (apiPrefix == NULL) { - afb_req_fail_f (request, "argument-missing", "prefix=BindingApiPrefix missing"); - goto OnErrorExit; - } - - shortname = afb_req_value(request, "name"); - if (shortname == NULL) { - afb_req_fail_f (request, "argument-missing", "sndname=SndCardName missing"); - goto OnErrorExit; - } - - if (index == MAX_SND_CARD) { - afb_req_fail_f (request, "alsahal-toomany", "Fail to register sndname=[%s]", shortname); - goto OnErrorExit; - } - - cardRegistry[index]= malloc (sizeof(cardRegistry)); - cardRegistry[index]->apiprefix=strdup(apiPrefix); - cardRegistry[index]->shortname=strdup(shortname); - index++;cardRegistry[index]=NULL; - - // when OK nothing to return - afb_req_success(request, NULL, NULL); - return; - - OnErrorExit: - return; -} - diff --git a/AlsaSound/CoreBinding/AlsaLibMapping.h b/AlsaSound/CoreBinding/AlsaLibMapping.h deleted file mode 100644 index a6edd1d..0000000 --- a/AlsaSound/CoreBinding/AlsaLibMapping.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * AlsaLibMapping -- provide low level interface with ALSA lib (extracted from alsa-json-gateway code) - * Copyright (C) 2015,2016,2017, Fulup Ar Foll fulup@iot.bzh - * - * 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 ALSALIBMAPPING_H -#define ALSALIBMAPPING_H - -#include "AudioCommonLib.h" - -// import from AlsaAfbBinding -extern const struct afb_binding_interface *afbIface; - -// import from AlsaAfbMapping -PUBLIC void alsaGetInfo (struct afb_req request); -PUBLIC void alsaGetCtls(struct afb_req request); -PUBLIC void alsaSetCtrl(struct afb_req request); -PUBLIC void alsaSubcribe (struct afb_req request); -PUBLIC void alsaGetCardId (struct afb_req request); -PUBLIC void alsaRegisterHal (struct afb_req request); - - -#endif /* ALSALIBMAPPING_H */ - diff --git a/AlsaSound/CoreBinding/AlsaUseCase.c b/AlsaSound/CoreBinding/AlsaUseCase.c new file mode 100644 index 0000000..ccea4fa --- /dev/null +++ b/AlsaSound/CoreBinding/AlsaUseCase.c @@ -0,0 +1,430 @@ +/* + * AlsaUseCase -- provide low level interface with ALSA lib (extracted from alsa-json-gateway code) + * Copyright (C) 2015,2016,2017, Fulup Ar Foll fulup@iot.bzh + * + * 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. + + References: + http://www.alsa-project.org/alsa-doc/alsa-lib/group__ucm.html + https://www.alsa-project.org/main/index.php/DAPM + http://alsa-lib.sourcearchive.com/documentation/1.0.24.1-2/group__Use_ga4332c6bb50481bbdaf21be11551fb930.html + https://android.googlesource.com/platform/hardware/qcom/audio/+/jb-mr1-dev/libalsa-intf/alsa_ucm.h + + Sample alsaucm commands using /usr/share/alsa/ucm/PandaBoard + - alsaucm -c PandaBoard list _verbs + - alsaucm -c PandaBoard list _devices/HiFi + - alsaucm -c PandaBoard list _modifiers/HiFi #need to uncomment modifiers section + - alsaucm -c PandaBoard list TQ/HiFi + - alsaucm -c PandaBoard get TQ/HiFi/Voice + - alsaucm -c PandaBoard get PlaybackPCM//HiFi + - alsaucm -c PandaBoard set _verb HiFi + - alsaucm -c PandaBoard set _verb HiFi _enadev Headset + - alsaucm -c 'HDA Intel PCH' set _verb HiFi set _enadev Headphone set _enamod RecordMedia + - alsaucm -c 'HDA Intel PCH' set _verb HiFi get OutputDspName// + +*/ +#define _GNU_SOURCE // needed for vasprintf + +#include +#include "AlsaCoreBinding.h" +#include +#include + +typedef struct { + snd_use_case_mgr_t *ucm; + int cardId; + char *cardName; +} ucmHandleT; + +static ucmHandleT ucmHandles[MAX_SND_CARD]; + +// Cache opened UCM handles +STATIC int alsaUseCaseOpen (struct afb_req request, queryValuesT *queryValues, int allowNewMgr) { + snd_ctl_t *ctlDev; + snd_ctl_card_info_t *cardinfo; + snd_use_case_mgr_t *ucmHandle; + const char *cardName; + int cardId, idx, idxFree=-1, err; + + // open control interface for devid + err = snd_ctl_open(&ctlDev, queryValues->devid, SND_CTL_READONLY); + if (err < 0) { + ctlDev=NULL; + afb_req_fail_f (request, "devid-unknown", "SndCard devid=[%s] Not Found err=%d", queryValues->devid, err); + goto OnErrorExit; + } + + snd_ctl_card_info_alloca(&cardinfo); + if ((err = snd_ctl_card_info(ctlDev, cardinfo)) < 0) { + afb_req_fail_f (request, "devid-invalid", "SndCard devid=[%s] Not Found err=%s", queryValues->devid, snd_strerror(err)); + goto OnErrorExit; + } + + // search for an existing subscription and mark 1st free slot + cardId = snd_ctl_card_info_get_card(cardinfo); + for (idx= 0; idx < MAX_SND_CARD; idx ++) { + if (ucmHandles[idx].ucm != NULL) { + if (ucmHandles[idx].cardId == cardId) goto OnSuccessExit; + } else if (idxFree == -1) idxFree= idx; + }; + + if (!allowNewMgr) { + afb_req_fail_f (request, "ucm-nomgr", "SndCard devid=[%s] no exiting UCM manager session", queryValues->devid); + goto OnErrorExit; + } + + if (idxFree < 0 && idx == MAX_SND_CARD) { + afb_req_fail_f (request, "ucm-toomany", "SndCard devid=[%s] too many open UCM Max=%d", queryValues->devid, MAX_SND_CARD); + goto OnErrorExit; + } + + idx = idxFree; + cardName = snd_ctl_card_info_get_name(cardinfo); + err = snd_use_case_mgr_open(&ucmHandle, cardName); + if (err) { + afb_req_fail_f (request, "ucm-open", "SndCard devid=[%s] name=[%s] No UCM Profile err=%s", queryValues->devid, cardName, snd_strerror(err)); + goto OnErrorExit; + } + ucmHandles[idx].ucm = ucmHandle; + ucmHandles[idx].cardId = cardId; + ucmHandles[idx].cardName = strdup(cardName); + + OnSuccessExit: + if (ctlDev) snd_ctl_close(ctlDev); + return idx; + + OnErrorExit: + if (ctlDev) snd_ctl_close(ctlDev); + return -1; +} + + +PUBLIC void alsaUseCaseQuery(struct afb_req request) { + int err, verbCount, ucmIdx; + const char **verbList; + snd_use_case_mgr_t *ucmHandle; + queryValuesT queryValues; + json_object *ucmJs; + const char *cardName; + + + err = alsaCheckQuery (request, &queryValues); + if (err) goto OnErrorExit; + + ucmIdx = alsaUseCaseOpen (request, &queryValues, TRUE); + if (ucmIdx < 0) goto OnErrorExit; + ucmHandle = ucmHandles [ucmIdx].ucm; + cardName = ucmHandles [ucmIdx].cardName; + + verbCount = snd_use_case_get_list (ucmHandle, "_verbs", &verbList); + if (verbCount < 0) { + afb_req_fail_f (request, "ucm-list", "SndCard devid=[%s] name=[%s] No UCM Verbs", queryValues.devid, cardName); + goto OnErrorExit; + } + + ucmJs = json_object_new_array(); + for (int idx=0; idx < verbCount; idx +=2) { + int devCount, modCount, tqCount; + const char **devList, **modList, **tqList; + json_object *ucmJ = json_object_new_object(); + char identifier[32]; + + json_object_object_add (ucmJ, "verb", json_object_new_string(verbList[idx])); + if (verbList[idx+1]) json_object_object_add (ucmJ, "info", json_object_new_string(verbList[idx+1])); + + DEBUG (afbIface, "Verb[%d] Action=%s Info=%s", idx, verbList[idx], verbList[idx+1]); + + snprintf (identifier, sizeof(identifier), "_devices/%s", verbList[idx]); + devCount = snd_use_case_get_list (ucmHandle, identifier, &devList); + if (devCount > 0) { + json_object *devsJ = json_object_new_array(); + + for (int jdx=0; jdx < devCount; jdx+=2) { + json_object *devJ = json_object_new_object(); + DEBUG (afbIface, "device[%d] Action=%s Info=%s", jdx, devList[jdx], devList[jdx+1]); + json_object_object_add (devJ, "dev", json_object_new_string(devList[jdx])); + if (devList[jdx+1]) json_object_object_add (devJ, "info", json_object_new_string(devList[jdx+1])); + json_object_array_add (devsJ, devJ); + } + json_object_object_add(ucmJ,"devices", devsJ); + snd_use_case_free_list(devList, err); + } + + snprintf (identifier, sizeof(identifier), "_modifiers/%s", verbList[idx]); + modCount = snd_use_case_get_list (ucmHandle, identifier, &modList); + if (modCount > 0) { + json_object *modsJ = json_object_new_array(); + + for (int jdx=0; jdx < modCount; jdx+=2) { + json_object *modJ = json_object_new_object(); + DEBUG (afbIface, "modifier[%d] Action=%s Info=%s", jdx, modList[jdx], modList[jdx+1]); + json_object_object_add (modJ, "mod", json_object_new_string(modList[jdx])); + if (modList[jdx+1]) json_object_object_add (modJ, "info", json_object_new_string(modList[jdx+1])); + json_object_array_add (modsJ, modJ); + } + json_object_object_add(ucmJ,"modifiers", modsJ); + snd_use_case_free_list(modList, err); + } + + snprintf (identifier, sizeof(identifier), "TQ/%s", verbList[idx]); + tqCount = snd_use_case_get_list (ucmHandle, identifier, &tqList); + if (tqCount > 0) { + json_object *tqsJ = json_object_new_array(); + + for (int jdx=0; jdx < tqCount; jdx+=2) { + json_object *tqJ = json_object_new_object(); + DEBUG (afbIface, "toneqa[%d] Action=%s Info=%s", jdx, tqList[jdx], tqList[jdx+1]); + json_object_object_add (tqJ, "tq", json_object_new_string(tqList[jdx])); + if (tqList[jdx+1]) json_object_object_add (tqJ, "info", json_object_new_string(tqList[jdx+1])); + json_object_array_add (tqsJ, tqJ); + } + json_object_object_add(ucmJ,"tqs", tqsJ); + snd_use_case_free_list(tqList, err); + } + + json_object_array_add (ucmJs, ucmJ); + } + + afb_req_success (request, ucmJs, NULL); + snd_use_case_free_list(verbList, err); + + OnErrorExit: + return; +} + +STATIC json_object *ucmGetValue (ucmHandleT *ucmHandle, const char *verb, const char *mod, const char *label) { + char identifier[80]; + char *value; + int err; + json_object *jValue; + + // handle optional parameters + if (!mod) mod=""; + if (!verb) verb=""; + + if (!label) { + NOTICE (afbIface, "ucmGetValue cardname=[%s] value label missing", ucmHandle->cardName); + goto OnErrorExit; + } + + snprintf (identifier, sizeof(identifier), "%s/%s/%s", label, mod, verb); + err = snd_use_case_get (ucmHandle->ucm, identifier, (const char**)&value); // Note: value casting is a known "FEATURE" of AlsaUCM API + if (err) { + DEBUG (afbIface, "ucmGetValue cardname=[%s] identifier=[%s] error=%s", ucmHandle->cardName, identifier, snd_strerror (err)); + goto OnErrorExit; + } + + // copy value into json object and free string + jValue = json_object_new_string (value); + free (value); + return (jValue); + + OnErrorExit: + return (NULL); +} + +PUBLIC void alsaUseCaseSet(struct afb_req request) { + int err, ucmIdx; + queryValuesT queryValues; + json_object *jResponse = json_object_new_object(); + + err = alsaCheckQuery (request, &queryValues); + if (err) goto OnErrorExit; + + ucmIdx = alsaUseCaseOpen (request, &queryValues, TRUE); + if (ucmIdx < 0) goto OnErrorExit; + + snd_use_case_mgr_t *ucmMgr= ucmHandles[ucmIdx].ucm; + const char *cardName= ucmHandles[ucmIdx].cardName; + + const char *verb = afb_req_value(request, "verb"); + const char *mod = afb_req_value(request, "mod"); + const char *dev = afb_req_value(request, "dev"); + // Known identifiers: _verb - set current verb = value _enadev - enable given device = value _disdev - disable given device = value _swdev/{old_device} - new_device = value + + if (verb) { + err = snd_use_case_set (ucmMgr, "_verb", verb); + if (err) { + afb_req_fail_f (request, "ucmset-verb", "SndCard devid=[%s] name=[%s] Invalid UCM verb=[%s] err=%s", queryValues.devid, cardName, verb, snd_strerror(err)); + goto OnErrorExit; + } + } + + if (dev) { + err = snd_use_case_set (ucmMgr, "_enadev", dev); + if (err) { + afb_req_fail_f (request, "ucmset-dev", "SndCard devid=[%s] name=[%s] Invalid UCMverb=[%s] dev=%s err=%s", queryValues.devid, cardName, verb, dev, snd_strerror(err)); + goto OnErrorExit; + } + } + + if (mod) { + err = snd_use_case_set (ucmMgr, "_enamod", mod); + if (err) { + afb_req_fail_f (request, "ucmset-mod", "SndCard devid=[%s] name=[%s] Invalid UCM verb=[%s] mod=[%s] err=%s", queryValues.devid, cardName, verb, mod, snd_strerror(err)); + goto OnErrorExit; + } + } + + if (queryValues.quiet <= 3) { + json_object *jValue; + + jValue = ucmGetValue (&ucmHandles[ucmIdx], verb, dev, "OutputDspName"); + if (jValue) json_object_object_add (jResponse, "OutputDspName", jValue); + + jValue = ucmGetValue (&ucmHandles[ucmIdx], verb, dev, "PlaybackPCM"); + if (jValue) json_object_object_add (jResponse, "PlaybackPCM", jValue); + + jValue = ucmGetValue (&ucmHandles[ucmIdx], verb, mod, "CapturePCM"); + if (jValue) json_object_object_add (jResponse, "CapturePCM", jValue); + } + afb_req_success (request, jResponse, NULL); + + OnErrorExit: + return; +} + + +PUBLIC void alsaUseCaseGet (struct afb_req request) { + int err, ucmIdx, labelCount; + queryValuesT queryValues; + json_object *jResponse = json_object_new_object(); + json_object *jWarnings = json_object_new_array(); + const char *warnings=NULL; + + err = alsaCheckQuery (request, &queryValues); + if (err) goto OnErrorExit; + + ucmIdx = alsaUseCaseOpen (request, &queryValues, TRUE); + if (ucmIdx < 0) goto OnErrorExit; + + const char *cardName= ucmHandles[ucmIdx].cardName; + + const char *verb = afb_req_value(request, "verb"); + const char *mod = afb_req_value(request, "mod"); + const char *dev = afb_req_value(request, "dev"); + + if (dev && mod) { + afb_req_fail_f (request, "ucmget-labels", "SndCard devid=[%s] name=[%s] UCM mod+dev incompatible", queryValues.devid, cardName); + goto OnErrorExit; + } + + // device selection is handle as a modifier + if (dev) mod=dev; + + const char *labels = afb_req_value(request, "values"); + if (!labels) { + afb_req_fail_f (request, "ucmget-labels", "SndCard devid=[%s] name=[%s] UCM values name missing", queryValues.devid, cardName); + goto OnErrorExit; + } + + json_object *jLabels = json_tokener_parse(labels); + if (!jLabels) { + afb_req_fail_f (request, "ucmget-notjson","labels=%s not a valid json entry", labels); + goto OnErrorExit; + }; + + enum json_type jtype= json_object_get_type(jLabels); + switch (jtype) { + json_object *jTmp; + + case json_type_array: + labelCount = json_object_array_length (jLabels); + break; + + case json_type_string: + jTmp = json_object_new_array (); + labelCount = 1; + json_object_array_add (jTmp, jLabels); + jLabels=jTmp; + break; + + default: + afb_req_fail_f (request, "ucmget-notarray","labels=%s not valid JSON array", labels); + goto OnErrorExit; + } + + for (int idx=0; idx < labelCount; idx++) { + json_object *jValue, *jLabel; + const char *label ; + + jLabel= json_object_array_get_idx (jLabels, idx); + label= json_object_get_string (jLabel); + jValue = ucmGetValue (&ucmHandles[ucmIdx], verb, mod, label); + if (jValue) json_object_object_add (jResponse, label, jValue); + else { + json_object_array_add (jWarnings, jLabel); + } + } + + // use info section to notified not found values label + if (json_object_array_length (jWarnings) > 0) { + json_object *jTmp = json_object_new_object (); + json_object_object_add (jTmp, "no-context", jWarnings); + warnings= json_object_to_json_string (jTmp); + } + afb_req_success (request, jResponse, warnings); + + OnErrorExit: + return; +} + + +PUBLIC void alsaUseCaseReset (struct afb_req request) { + int err, ucmIdx; + queryValuesT queryValues; + + err = alsaCheckQuery (request, &queryValues); + if (err) goto OnErrorExit; + + ucmIdx = alsaUseCaseOpen (request, &queryValues, FALSE); + if (ucmIdx < 0) goto OnErrorExit; + + err= snd_use_case_mgr_reset (ucmHandles[ucmIdx].ucm); + if (err) { + afb_req_fail_f (request, "ucmreset-fail","devid=%s Card Name=%s", queryValues.devid, ucmHandles[ucmIdx].cardName); + goto OnErrorExit; + } + + afb_req_success (request, NULL, NULL); + + OnErrorExit: + return; +} + +PUBLIC void alsaUseCaseClose (struct afb_req request) { + int err, ucmIdx; + queryValuesT queryValues; + + err = alsaCheckQuery (request, &queryValues); + if (err) goto OnErrorExit; + + ucmIdx = alsaUseCaseOpen (request, &queryValues, FALSE); + if (ucmIdx < 0) goto OnErrorExit; + + err= snd_use_case_mgr_close (ucmHandles[ucmIdx].ucm); + if (err) { + afb_req_fail_f (request, "ucmreset-close","devid=%s Card Name=%s", queryValues.devid, ucmHandles[ucmIdx].cardName); + goto OnErrorExit; + } + + // do not forget to release sound card name string + free (ucmHandles[ucmIdx].cardName); + + afb_req_success (request, NULL, NULL); + + OnErrorExit: + return; +} + + diff --git a/AlsaSound/CoreBinding/CMakeLists.txt b/AlsaSound/CoreBinding/CMakeLists.txt index 0475e72..e14432e 100644 --- a/AlsaSound/CoreBinding/CMakeLists.txt +++ b/AlsaSound/CoreBinding/CMakeLists.txt @@ -22,7 +22,7 @@ INCLUDE_DIRECTORIES(${include_dirs}) ################################################## # AlsaBinding ################################################## -ADD_LIBRARY(alsacore-afb MODULE AlsaAfbBinding.c AlsaLibMapping.c) +ADD_LIBRARY(alsacore-afb MODULE AlsaCoreBinding.c AlsaCtlSetGet.c AlsaUseCase.c) SET_TARGET_PROPERTIES(alsacore-afb PROPERTIES PREFIX "" -- cgit 1.2.3-korg