From 6e70aac6c9f02496978d3d02efb355d66fb36ceb Mon Sep 17 00:00:00 2001 From: fulup Date: Sun, 9 Apr 2017 14:35:00 +0200 Subject: Clean CMAKE structure and rename files/directories --- ALSA-afb/AlsaCoreBinding.c | 80 ++ ALSA-afb/AlsaCoreBinding.h | 60 ++ ALSA-afb/AlsaCtlSetGet.c | 1084 ++++++++++++++++++++++++++++ ALSA-afb/AlsaUseCase.c | 433 +++++++++++ ALSA-afb/CMakeLists.txt | 41 ++ ALSA-afb/README.md | 33 + AlsaSound/CMakeLists.txt | 32 - AlsaSound/CoreBinding/AlsaCoreBinding.c | 80 -- AlsaSound/CoreBinding/AlsaCoreBinding.h | 60 -- AlsaSound/CoreBinding/AlsaCtlSetGet.c | 1084 ---------------------------- AlsaSound/CoreBinding/AlsaUseCase.c | 433 ----------- AlsaSound/CoreBinding/CMakeLists.txt | 36 - AlsaSound/CoreBinding/README.md | 33 - AlsaSound/HALayer/CMakeLists.txt | 31 - AlsaSound/HALayer/IntelHda/CMakeLists.txt | 36 - AlsaSound/HALayer/IntelHda/IntelHdaHAL.c | 68 -- AlsaSound/HALayer/SharedHal/CMakeLists.txt | 29 - AlsaSound/HALayer/SharedHal/SharedHalLib.c | 341 --------- AlsaSound/HALayer/SharedHal/SharedHalLib.h | 62 -- Audio-Interface/CMakeLists.txt | 37 + Audio-Interface/audio-interface.c | 102 +++ Audio-Interface/audio-interface.h | 68 ++ AudioLogic/AudioLogicBinding.c | 98 --- AudioLogic/AudioLogicLib.c | 316 -------- AudioLogic/AudioLogicLib.h | 57 -- AudioLogic/CMakeLists.txt | 36 - AudioLogic/README.md | 35 - CMakeLists.txt | 157 ++-- Common/AudioCommonLib.c | 102 --- Common/AudioCommonLib.h | 68 -- Common/CMakeLists.txt | 31 - HAL-afb/CMakeLists.txt | 28 + HAL-afb/HAL-interface/CMakeLists.txt | 37 + HAL-afb/HAL-interface/hal-interface.c | 341 +++++++++ HAL-afb/HAL-interface/hal-interface.h | 62 ++ HAL-afb/HDA-intel/CMakeLists.txt | 41 ++ HAL-afb/HDA-intel/IntelHdaHAL.c | 68 ++ HighLevel-afb/CMakeLists.txt | 40 + HighLevel-afb/HighLevelApiConf.c | 98 +++ HighLevel-afb/HighLevelBinding.c | 316 ++++++++ HighLevel-afb/HighLevelBinding.h | 58 ++ HighLevel-afb/README.md | 35 + README.md | 27 +- cd | 0 etc/config.cmake | 64 ++ htdocs/CMakeLists.txt | 1 - nbproject/configurations.xml | 18 - nbproject/project.xml | 2 +- 48 files changed, 3235 insertions(+), 3164 deletions(-) create mode 100644 ALSA-afb/AlsaCoreBinding.c create mode 100644 ALSA-afb/AlsaCoreBinding.h create mode 100644 ALSA-afb/AlsaCtlSetGet.c create mode 100644 ALSA-afb/AlsaUseCase.c create mode 100644 ALSA-afb/CMakeLists.txt create mode 100644 ALSA-afb/README.md delete mode 100644 AlsaSound/CMakeLists.txt delete mode 100644 AlsaSound/CoreBinding/AlsaCoreBinding.c delete mode 100644 AlsaSound/CoreBinding/AlsaCoreBinding.h delete mode 100644 AlsaSound/CoreBinding/AlsaCtlSetGet.c delete mode 100644 AlsaSound/CoreBinding/AlsaUseCase.c delete mode 100644 AlsaSound/CoreBinding/CMakeLists.txt delete mode 100644 AlsaSound/CoreBinding/README.md delete mode 100644 AlsaSound/HALayer/CMakeLists.txt delete mode 100644 AlsaSound/HALayer/IntelHda/CMakeLists.txt delete mode 100644 AlsaSound/HALayer/IntelHda/IntelHdaHAL.c delete mode 100644 AlsaSound/HALayer/SharedHal/CMakeLists.txt delete mode 100644 AlsaSound/HALayer/SharedHal/SharedHalLib.c delete mode 100644 AlsaSound/HALayer/SharedHal/SharedHalLib.h create mode 100644 Audio-Interface/CMakeLists.txt create mode 100644 Audio-Interface/audio-interface.c create mode 100644 Audio-Interface/audio-interface.h delete mode 100644 AudioLogic/AudioLogicBinding.c delete mode 100644 AudioLogic/AudioLogicLib.c delete mode 100644 AudioLogic/AudioLogicLib.h delete mode 100644 AudioLogic/CMakeLists.txt delete mode 100644 AudioLogic/README.md delete mode 100644 Common/AudioCommonLib.c delete mode 100644 Common/AudioCommonLib.h delete mode 100644 Common/CMakeLists.txt create mode 100644 HAL-afb/CMakeLists.txt create mode 100644 HAL-afb/HAL-interface/CMakeLists.txt create mode 100644 HAL-afb/HAL-interface/hal-interface.c create mode 100644 HAL-afb/HAL-interface/hal-interface.h create mode 100644 HAL-afb/HDA-intel/CMakeLists.txt create mode 100644 HAL-afb/HDA-intel/IntelHdaHAL.c create mode 100644 HighLevel-afb/CMakeLists.txt create mode 100644 HighLevel-afb/HighLevelApiConf.c create mode 100644 HighLevel-afb/HighLevelBinding.c create mode 100644 HighLevel-afb/HighLevelBinding.h create mode 100644 HighLevel-afb/README.md delete mode 100644 cd create mode 100644 etc/config.cmake diff --git a/ALSA-afb/AlsaCoreBinding.c b/ALSA-afb/AlsaCoreBinding.c new file mode 100644 index 0000000..d866daf --- /dev/null +++ b/ALSA-afb/AlsaCoreBinding.c @@ -0,0 +1,80 @@ +/* + * 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= "Get Controls from selected sndcard" }, + { .name= "setctls", .session= AFB_SESSION_NONE, .callback= alsaSetCtls, .info= "Set 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/ALSA-afb/AlsaCoreBinding.h b/ALSA-afb/AlsaCoreBinding.h new file mode 100644 index 0000000..c0fd51f --- /dev/null +++ b/ALSA-afb/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 "audio-interface.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 alsaSetCtls(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/ALSA-afb/AlsaCtlSetGet.c b/ALSA-afb/AlsaCtlSetGet.c new file mode 100644 index 0000000..a41e390 --- /dev/null +++ b/ALSA-afb/AlsaCtlSetGet.c @@ -0,0 +1,1084 @@ +/* + * 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; + + enum json_type jtype=json_object_get_type(ctlRequest[idx].jToken); + switch (jtype) { + json_object *jId, *jVal; + + 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; + } + break; + + case json_type_object: + // numid+values formated as {id:xxx, val:[aa,bb...,nn]} + if (!json_object_object_get_ex (ctlRequest[idx].jToken,"id", &jId) || !json_object_object_get_ex (ctlRequest[idx].jToken,"val",&jVal)) { + NOTICE (afbIface,"Invalid Json=%s missing 'id'|'val'", json_object_get_string(ctlRequest[idx].jToken)); + ctlRequest[idx].used=-1; + } else { + ctlRequest[idx].numId =json_object_get_int(jId); + ctlRequest[idx].jValues =jVal; + } + + + 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 (count == 0) goto OnErrorExit; + + enum json_type jtype= json_object_get_type(ctlRequest->jValues); + switch (jtype) { + case json_type_array: + length = json_object_array_length (ctlRequest->jValues); + valueIsArray=1; + break; + case json_type_int: + length=1; + valueIsArray=0; + break; + default: + count =0; + break; + } + + + if (count == 0 || count < length) { + NOTICE (afbIface, "Invalid values NUMID='%d' Values='%s' count='%d' wanted='%d'", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues), length, 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); + } + + err = snd_ctl_elem_write(ctlDev, elemData); + if (err < 0) { + NOTICE (afbIface, "Fail to write ALSA NUMID=%d Values=[%s] Error=%s", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues), snd_strerror(err)); + 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; + + int numid= snd_ctl_elem_info_get_numid(elemInfo); + + ctlRequest->jValues= json_object_new_object(); + json_object_object_add (ctlRequest->jValues,"id" , json_object_new_int(numid)); + 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,"val",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 && action == ACTION_GET) { + 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); + else json_object_put(warnings); + + // 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/ALSA-afb/AlsaUseCase.c b/ALSA-afb/AlsaUseCase.c new file mode 100644 index 0000000..8e23e3c --- /dev/null +++ b/ALSA-afb/AlsaUseCase.c @@ -0,0 +1,433 @@ +/* + * 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 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 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; + } + } + + // label are requested transfert request to get + if (afb_req_value(request, "values")) return alsaUseCaseGet(request); + + 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 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/ALSA-afb/CMakeLists.txt b/ALSA-afb/CMakeLists.txt new file mode 100644 index 0000000..d7ace36 --- /dev/null +++ b/ALSA-afb/CMakeLists.txt @@ -0,0 +1,41 @@ +########################################################################### +# Copyright 2015, 2016, 2017 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. +########################################################################### + +# Add target to project dependency list +PROJECT_TARGET_ADD(alsa-afb) + + # Define project Targets + ADD_LIBRARY(alsa-afb MODULE AlsaCoreBinding.c AlsaCtlSetGet.c AlsaUseCase.c) + + # Binder exposes a unique public entry point + SET_TARGET_PROPERTIES(alsa-afb PROPERTIES + PREFIX "" + LINK_FLAGS "-Wl,--version-script=${CMAKE_SOURCE_DIR}/export.map" + OUTPUT_NAME alsabinding + ) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(alsa-afb + audio-interface + ${link_libraries} + ) + + # installation directory + INSTALL(TARGETS alsa-afb + LIBRARY DESTINATION ${binding_install_dir}) + diff --git a/ALSA-afb/README.md b/ALSA-afb/README.md new file mode 100644 index 0000000..a4b0395 --- /dev/null +++ b/ALSA-afb/README.md @@ -0,0 +1,33 @@ +------------------------------------------------------------------------ + AlsaCore Low level binding maps AlsaLib APIs +------------------------------------------------------------------------ + +Testing: (from project directory bindings) + * start binder: ~/opt/bin/afb-daemon --ldpaths=./build --token=mysecret --roothttp=htdocs + * connect browser on http://localhost:1234?devid=hw:0 + + # List Avaliable Sound cards + http://localhost:1234/api/alsacore/getinfo + + # Get Info on a given Sound Card + http://localhost:1234/api/alsacore/getinfo?devid=hw:0 + + # Get shortname/longname for a given card + http://localhost:1234/api/alsacore/getcardid?devid=hw:0 + + # Get all controls from a given sound card + http://localhost:1234/api/alsacore/getctl?devid=hw:0 + + # Get detail on a given control (optional quiet=0=verbose,1,2) + http://localhost:1234/api/alsacore/getctl?devid=hw:0&numid=1&quiet=0 + +# Debug event with afb-client-demo +``` + ~/opt/bin/afb-client-demo localhost:1234/api?token=mysecret + alsacore subscribe {"devid":"hw:0"} +``` + +# Open AlsaMixer and play with Volume +``` + alsamixer -D hw:0 +``` diff --git a/AlsaSound/CMakeLists.txt b/AlsaSound/CMakeLists.txt deleted file mode 100644 index 7356ca4..0000000 --- a/AlsaSound/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -########################################################################### -# Copyright 2015, 2016, 2017 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. -########################################################################### - -PROJECT(alsa-bindings C) -PKG_CHECK_MODULES(alsa REQUIRED alsa) - -# Max Sound Card Number eligible to ctlevent subscription -defstr(MAX_SND_CARD 16) - -SET(link_libraries - ${alsa_LIBRARIES} - ${link_libraries} - ) - -ADD_SUBDIRECTORY(CoreBinding) -ADD_SUBDIRECTORY(HALayer) - diff --git a/AlsaSound/CoreBinding/AlsaCoreBinding.c b/AlsaSound/CoreBinding/AlsaCoreBinding.c deleted file mode 100644 index d866daf..0000000 --- a/AlsaSound/CoreBinding/AlsaCoreBinding.c +++ /dev/null @@ -1,80 +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 "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= "Get Controls from selected sndcard" }, - { .name= "setctls", .session= AFB_SESSION_NONE, .callback= alsaSetCtls, .info= "Set 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 deleted file mode 100644 index 2852384..0000000 --- a/AlsaSound/CoreBinding/AlsaCoreBinding.h +++ /dev/null @@ -1,60 +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" - - -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 alsaSetCtls(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 deleted file mode 100644 index a41e390..0000000 --- a/AlsaSound/CoreBinding/AlsaCtlSetGet.c +++ /dev/null @@ -1,1084 +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 "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; - - enum json_type jtype=json_object_get_type(ctlRequest[idx].jToken); - switch (jtype) { - json_object *jId, *jVal; - - 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; - } - break; - - case json_type_object: - // numid+values formated as {id:xxx, val:[aa,bb...,nn]} - if (!json_object_object_get_ex (ctlRequest[idx].jToken,"id", &jId) || !json_object_object_get_ex (ctlRequest[idx].jToken,"val",&jVal)) { - NOTICE (afbIface,"Invalid Json=%s missing 'id'|'val'", json_object_get_string(ctlRequest[idx].jToken)); - ctlRequest[idx].used=-1; - } else { - ctlRequest[idx].numId =json_object_get_int(jId); - ctlRequest[idx].jValues =jVal; - } - - - 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 (count == 0) goto OnErrorExit; - - enum json_type jtype= json_object_get_type(ctlRequest->jValues); - switch (jtype) { - case json_type_array: - length = json_object_array_length (ctlRequest->jValues); - valueIsArray=1; - break; - case json_type_int: - length=1; - valueIsArray=0; - break; - default: - count =0; - break; - } - - - if (count == 0 || count < length) { - NOTICE (afbIface, "Invalid values NUMID='%d' Values='%s' count='%d' wanted='%d'", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues), length, 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); - } - - err = snd_ctl_elem_write(ctlDev, elemData); - if (err < 0) { - NOTICE (afbIface, "Fail to write ALSA NUMID=%d Values=[%s] Error=%s", ctlRequest->numId, json_object_to_json_string(ctlRequest->jValues), snd_strerror(err)); - 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; - - int numid= snd_ctl_elem_info_get_numid(elemInfo); - - ctlRequest->jValues= json_object_new_object(); - json_object_object_add (ctlRequest->jValues,"id" , json_object_new_int(numid)); - 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,"val",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 && action == ACTION_GET) { - 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); - else json_object_put(warnings); - - // 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/AlsaUseCase.c b/AlsaSound/CoreBinding/AlsaUseCase.c deleted file mode 100644 index 8e23e3c..0000000 --- a/AlsaSound/CoreBinding/AlsaUseCase.c +++ /dev/null @@ -1,433 +0,0 @@ -/* - * 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 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 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; - } - } - - // label are requested transfert request to get - if (afb_req_value(request, "values")) return alsaUseCaseGet(request); - - 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 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 deleted file mode 100644 index e14432e..0000000 --- a/AlsaSound/CoreBinding/CMakeLists.txt +++ /dev/null @@ -1,36 +0,0 @@ -########################################################################### -# Copyright 2015, 2016, 2017 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. -########################################################################### - - -INCLUDE_DIRECTORIES(${include_dirs}) - -################################################## -# AlsaBinding -################################################## -ADD_LIBRARY(alsacore-afb MODULE AlsaCoreBinding.c AlsaCtlSetGet.c AlsaUseCase.c) - -SET_TARGET_PROPERTIES(alsacore-afb PROPERTIES - PREFIX "" - LINK_FLAGS "-Wl,--version-script=${CMAKE_SOURCE_DIR}/export.map" -) - -TARGET_LINK_LIBRARIES(alsacore-afb ${link_libraries}) -INSTALL(TARGETS alsacore-afb - LIBRARY DESTINATION ${binding_install_dir}) - - diff --git a/AlsaSound/CoreBinding/README.md b/AlsaSound/CoreBinding/README.md deleted file mode 100644 index a4b0395..0000000 --- a/AlsaSound/CoreBinding/README.md +++ /dev/null @@ -1,33 +0,0 @@ ------------------------------------------------------------------------- - AlsaCore Low level binding maps AlsaLib APIs ------------------------------------------------------------------------- - -Testing: (from project directory bindings) - * start binder: ~/opt/bin/afb-daemon --ldpaths=./build --token=mysecret --roothttp=htdocs - * connect browser on http://localhost:1234?devid=hw:0 - - # List Avaliable Sound cards - http://localhost:1234/api/alsacore/getinfo - - # Get Info on a given Sound Card - http://localhost:1234/api/alsacore/getinfo?devid=hw:0 - - # Get shortname/longname for a given card - http://localhost:1234/api/alsacore/getcardid?devid=hw:0 - - # Get all controls from a given sound card - http://localhost:1234/api/alsacore/getctl?devid=hw:0 - - # Get detail on a given control (optional quiet=0=verbose,1,2) - http://localhost:1234/api/alsacore/getctl?devid=hw:0&numid=1&quiet=0 - -# Debug event with afb-client-demo -``` - ~/opt/bin/afb-client-demo localhost:1234/api?token=mysecret - alsacore subscribe {"devid":"hw:0"} -``` - -# Open AlsaMixer and play with Volume -``` - alsamixer -D hw:0 -``` diff --git a/AlsaSound/HALayer/CMakeLists.txt b/AlsaSound/HALayer/CMakeLists.txt deleted file mode 100644 index 4601c79..0000000 --- a/AlsaSound/HALayer/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -########################################################################### -# Copyright 2015, 2016, 2017 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. -########################################################################### - -PROJECT(hadware-abstraction-layer C) - -SET(include_dirs ${CMAKE_CURRENT_SOURCE_DIR}/SharedHal ${include_dirs}) - -# Add ShareHalLib statically within each HAL bindings -SET(link_libraries - ${CMAKE_BINARY_DIR}/AlsaSound/HALayer/SharedHal/libsharedhal.a - ${link_libraries} -) - -ADD_SUBDIRECTORY(SharedHal) -ADD_SUBDIRECTORY(IntelHda) - diff --git a/AlsaSound/HALayer/IntelHda/CMakeLists.txt b/AlsaSound/HALayer/IntelHda/CMakeLists.txt deleted file mode 100644 index 89665e4..0000000 --- a/AlsaSound/HALayer/IntelHda/CMakeLists.txt +++ /dev/null @@ -1,36 +0,0 @@ -########################################################################### -# Copyright 2015, 2016, 2017 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. -########################################################################### - - -INCLUDE_DIRECTORIES(${include_dirs}) - -################################################## -# Inte-HDA sound card Hardware Abstraction Layer -################################################## -ADD_LIBRARY(intel-hda-hal MODULE IntelHdaHAL.c ) - -SET_TARGET_PROPERTIES(intel-hda-hal PROPERTIES - PREFIX "" - LINK_FLAGS "-Wl,--version-script=${CMAKE_SOURCE_DIR}/export.map" -) - -TARGET_LINK_LIBRARIES(intel-hda-hal ${link_libraries}) -INSTALL(TARGETS intel-hda-hal - LIBRARY DESTINATION ${binding_install_dir}) - - diff --git a/AlsaSound/HALayer/IntelHda/IntelHdaHAL.c b/AlsaSound/HALayer/IntelHda/IntelHdaHAL.c deleted file mode 100644 index 5d668ba..0000000 --- a/AlsaSound/HALayer/IntelHda/IntelHdaHAL.c +++ /dev/null @@ -1,68 +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 "AudioCommonLib.h" -#include "SharedHalLib.h" // Include Share Interface to Alsa Sound Card HAL - -// Force a hard dependency to ShareHallLib -PUBLIC char* SharedHalLibVersion; - -// Init is call after all binding are loaded -STATIC int IntelHalInit (const struct afb_binding_interface *itf, struct afb_service service) { - DEBUG (itf, "IntelHalBinding Initialised"); - - return 0; // 0=OK -} - -/****************************************************************************************** - * alsaCtlsMap link hight level sound control with low level Alsa numid ctls. - * - * To find out which control your sound card uses - * aplay -l - * amixer -D hw:xx controls - * amixer -D hw:xx contents - * amixer -D "hw:3" cget numid=xx - * - * When automatic mapping to Alsa numid is not enough a custom callback might be used - * .cb={.handle=xxxx, .callback=(json_object)MyCtlFunction(struct afb_service service, int controle, int value, const struct alsaHalCtlMapS *map)}; - ********************************************************************************************/ -STATIC alsaHalMapT alsaHalMap[]= { - { .alsa={.control=Master_Playback_Volume,.numid=16,.group=OUTVOL,.values=1,.minval=0,.maxval= 87 ,.step=0,.acl=RW}, .info= "Master Playback Volume" }, - { .alsa={.control=PCM_Playback_Volume ,.numid=27,.group=PCMVOL,.values=2,.minval=0,.maxval= 255,.step=0,.acl=RW}, .info= "PCM Playback Volume" }, - { .alsa={.control=PCM_Playback_Switch ,.numid=17,.group=SWITCH,.values=1,.minval=0,.maxval= 1 ,.step=0,.acl=RW}, .info= "Master Playback Switch" }, - { .alsa={.control=Capture_Volume ,.numid=12,.group=INVOL ,.values=2,.minval=0,.maxval= 31 ,.step=0,.acl=RW}, .info= "Capture Volume" }, - { .alsa={.numid=0}, .cb={.callback=NULL, .handle=NULL}} /* marker for end of the array */ -} ; - -/*********************************************************************************** - * AlsaHalSndT provides - * - cardname used to map a given card to its HAL - * - ctls previously defined AlsaHalMapT control maps - * - info free text - * - * WARNING: name should fit with 'aplay -l' as it used to map from devid to HAL - * you may also retreive shortname when AudioBinder is running from a browser - * http://localhost:1234/api/alsacore/getcardid?devid=hw:xxx - * - ***********************************************************************************/ -PUBLIC alsaHalSndCardT alsaHalSndCard = { - .name = "HDA Intel PCH", - .info = "Hardware Abstraction Layer for IntelHDA sound card", - .ctls = alsaHalMap, - .prefix="intel-hda", - .initCB=IntelHalInit, // if NULL no initcallback -}; diff --git a/AlsaSound/HALayer/SharedHal/CMakeLists.txt b/AlsaSound/HALayer/SharedHal/CMakeLists.txt deleted file mode 100644 index d789367..0000000 --- a/AlsaSound/HALayer/SharedHal/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -########################################################################### -# Copyright 2015, 2016, 2017 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. -########################################################################### - -INCLUDE_DIRECTORIES(${include_dirs}) - -################################################## -# Shared HAL(Hardware Abstraction Layer) -################################################## -ADD_LIBRARY(sharedhal STATIC SharedHalLib.c) -SET_TARGET_PROPERTIES(sharedhal PROPERTIES OUTPUT_NAME sharedhal) -SET(link_libraries ${libefence_LIBRARIES} ${json-c_LIBRARIES}) -TARGET_LINK_LIBRARIES(sharedhal ${link_libraries}) - - diff --git a/AlsaSound/HALayer/SharedHal/SharedHalLib.c b/AlsaSound/HALayer/SharedHal/SharedHalLib.c deleted file mode 100644 index 43d0cfe..0000000 --- a/AlsaSound/HALayer/SharedHal/SharedHalLib.c +++ /dev/null @@ -1,341 +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. - * - * reference: - * amixer contents; amixer controls; - * http://www.tldp.org/HOWTO/Alsa-sound-6.html - */ -#define _GNU_SOURCE // needed for vasprintf -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "SharedHalLib.h" - -typedef struct { - int index; - int numid; -} shareHallMap_T; - -static struct afb_service srvitf; -static const struct afb_binding_interface *afbIface; -static shareHallMap_T *shareHallMap; - -// Force specific HAL to depend on ShareHalLib -PUBLIC char* SharedHalLibVersion="1.0"; - -// This callback when api/alsacore/subscribe returns -STATIC void alsaSubcribeCB(void *handle, int iserror, struct json_object *result) { - struct afb_req request = afb_req_unstore(handle); - struct json_object *x, *resp = NULL; - const char *info = NULL; - - if (result) { - INFO(afbIface, "result=[%s]\n", json_object_to_json_string(result)); - if (json_object_object_get_ex(result, "request", &x) && json_object_object_get_ex(x, "info", &x)) - info = json_object_get_string(x); - if (!json_object_object_get_ex(result, "response", &resp)) resp = NULL; - } - - // push message respond - if (iserror) afb_req_fail_f(request, "Fail", info); - else afb_req_success(request, resp, info); - - // free calling request - afb_req_unref(request); -} - -// Create and subscribe to alsacore ctl events - -STATIC void halMonitor(struct afb_req request) { - - // save request in session as it might be used after return by callback - struct afb_req *handle = afb_req_store(request); - - // push request to low level binding - if (!handle) afb_req_fail(request, "error", "out of memory"); - else afb_service_call(srvitf, "alsacore", "subctl", json_object_get(afb_req_json(request)), alsaSubcribeCB, handle); - - // success/failure messages return from callback -} - -// Subscribe to AudioBinding events - -STATIC void halSubscribe(struct afb_req request) { - const char *devid = afb_req_value(request, "devid"); - if (devid == NULL) { - afb_req_fail_f(request, "devid-missing", "devid=hw:xxx missing"); - } -} - -// Call when all bindings are loaded and ready to accept request - -STATIC void halGetVol(struct afb_req request) { - - // Should call here Hardware Alsa Abstraction Layer for corresponding Sound Card - afb_req_success(request, NULL, NULL); - return; - -} - -STATIC void halSetVol(struct afb_req request) { - const char *arg; - const char *pcm; - - arg = afb_req_value(request, "vol"); - if (arg == NULL) { - afb_req_fail_f(request, "argument-missing", "vol=[0,100] missing"); - goto OnErrorExit; - } - - pcm = afb_req_value(request, "pcm"); - if (pcm == NULL) pcm = "Master"; - - // Should call here Hardware Alsa Abstraction Layer for corresponding Sound Card - afb_req_success(request, NULL, NULL); - return; - -OnErrorExit: - return; - -} - -// AudioLogic expect volume values to be 0-100% - -STATIC int NormaliseValue(const alsaHalCtlMapT *halCtls, int valuein) { - int valueout; - - if (valuein > halCtls->maxval) valuein= halCtls->maxval; - if (valuein < halCtls->minval) valuein= halCtls->minval; - - // volume are ajusted to 100% any else is ignored - switch (halCtls->group) { - case OUTVOL: - case PCMVOL: - case INVOL: - valueout = (valuein * 100) / (halCtls->maxval - halCtls->minval); - break; - default: - valueout = valuein; - } - return (valueout); -} - -// receive controls for LowLevel remap them to hight level before returning them - -STATIC void halGetControlCB(void *handle, int iserror, struct json_object *result) { - alsaHalMapT *halCtls = alsaHalSndCard.ctls; - struct json_object *response; - - // retrieve request and check for errors - struct afb_req request = afb_req_unstore(handle); - if (!cbCheckResponse(request, iserror, result)) goto OnExit; - - // Get response from object - json_object_object_get_ex(result, "response", &response); - if (!response) { - afb_req_fail_f(request, "response-notfound", "No Controls return from alsa/getcontrol result=[%s]", json_object_get_string(result)); - goto OnExit; - } - - // extract sounds controls information from received Object - struct json_object *ctls; - json_object_object_get_ex(result, "ctls", &ctls); - if (!ctls) { - afb_req_fail_f(request, "ctls-notfound", "No Controls return from alsa/getcontrol response=[%s]", json_object_get_string(response)); - goto OnExit; - } - - // make sure return controls have a valid type - if (json_object_get_type(ctls) != json_type_array) { - afb_req_fail_f(request, "ctls-notarray", "Invalid Controls return from alsa/getcontrol response=[%s]", json_object_get_string(response)); - goto OnExit; - } - - // loop on array and store values into client context - for (int idx = 0; idx < json_object_array_length(ctls); idx++) { - struct json_object *ctl; - int rawvalue, numid; - - ctl = json_object_array_get_idx(ctls, idx); - if (json_object_array_length(ctl) != 2) { - afb_req_fail_f(request, "ctl-invalid", "Invalid Control return from alsa/getcontrol ctl=[%s]", json_object_get_string(ctl)); - goto OnExit; - } - - // As HAL and Business logic use the same AlsaMixerHal.h direct conversion is not an issue - numid = (halCtlsEnumT) json_object_get_int(json_object_array_get_idx(ctl, 0)); - rawvalue = json_object_get_int(json_object_array_get_idx(ctl, 1)); - - for (int idx = 0; halCtls[idx].alsa.numid != 0; idx++) { - if (halCtls[idx].alsa.numid == numid) { - struct json_object *ctlAndValue = json_object_new_array(); - json_object_array_add(ctlAndValue, json_object_new_int(idx)); // idx == high level control - json_object_array_add(ctlAndValue, json_object_new_int(NormaliseValue(&halCtls[idx].alsa, rawvalue))); - break; - } - } - if (shareHallMap[idx].numid == 0) { - - afb_req_fail_f(request, "ctl-invalid", "Invalid Control numid from alsa/getcontrol ctl=[%s]", json_object_get_string(ctl)); - goto OnExit; - } - } - - OnExit: - return; -} - - -// Translate high level control to low level and call lower layer -STATIC void halGetCtls(struct afb_req request) { - - struct json_object *queryin, *queryout, *ctlsin, *devid; - struct json_object *ctlsout = json_object_new_array(); - - // get query from request - queryin = afb_req_json(request); - - // check devid was given - if (!json_object_object_get_ex (queryin, "devid", &devid)) { - afb_req_fail_f(request, "devid-notfound", "No DevID given query=[%s]", json_object_get_string(queryin)); - goto OnExit; - } - - // loop on requested controls - if (!json_object_object_get_ex(queryin, "ctls", &ctlsin) || json_object_array_length(ctlsin) <= 0) { - afb_req_fail_f(request, "ctlsin-notfound", "No Controls given query=[%s]", json_object_get_string(queryin)); - goto OnExit; - } - - // loop on controls - for (int idx = 0; idx < json_object_array_length(ctlsin); idx++) { - struct json_object *ctl; - halCtlsEnumT control; - - // each control should be halCtlsEnumT - ctl = json_object_array_get_idx(ctlsin, idx); - control = (halCtlsEnumT) json_object_get_int(ctl); - if (control >= EndHalCrlTag || control <= StartHalCrlTag) { - afb_req_fail_f(request, "ctl-invalid", "Invalid Control devid=%s sndcard=%s ctl=[%s] should be [%d-%d]" - , json_object_get_string(devid), alsaHalSndCard.name, json_object_get_string(ctl), StartHalCrlTag, EndHalCrlTag); - goto OnExit; - } - - // add corresponding lowlevel numid to querylist - json_object_array_add(ctlsout, json_object_new_int(shareHallMap[control].numid)); - } - - // register HAL with Alsa Low Level Binder devid=hw:0&numid=1&quiet=0 - queryout = json_object_new_object(); - json_object_object_add(queryout, "devid", devid); - json_object_object_add(queryout, "ctls", ctlsout); - - // save request context dans call lowlevel API - struct afb_req *handle = afb_req_store(request); - afb_service_call(srvitf, "alsacore", "getctl", queryout, halGetControlCB, handle); - -OnExit: - // Under normal situation success/failure is set from callback - return; -}; - -STATIC void halInitCB(void *handle, int iserror, struct json_object *result) { - struct json_object *queryurl = (json_object*) handle; - - if (iserror) NOTICE(afbIface, "halInitCB: registration alsaHAL query=[%s] Fail", json_object_to_json_string(queryurl)); - else DEBUG(afbIface, "halInitCB: registration alsaHAL card=[%s] Success", json_object_to_json_string(queryurl)); -} - -// This receive all event this binding subscribe to -PUBLIC void afbBindingV1ServiceEvent(const char *evtname, struct json_object *object) { - - NOTICE(afbIface, "afbBindingV1ServiceEvent evtname=%s [msg=%s]", evtname, json_object_to_json_string(object)); -} - -// this is call when after all bindings are loaded -PUBLIC int afbBindingV1ServiceInit(struct afb_service service) { - int rc=0; - srvitf = service; - struct json_object *queryurl; - - if (alsaHalSndCard.initCB) { - rc= (alsaHalSndCard.initCB) (afbIface, service); - if (rc != 0) goto OnExit; - } - - // register HAL with Alsa Low Level Binder - queryurl = json_object_new_object(); - json_object_object_add(queryurl, "prefix", json_object_new_string(alsaHalSndCard.prefix)); - json_object_object_add(queryurl, "name", json_object_new_string(alsaHalSndCard.name)); - afb_service_call(srvitf, "alsacore", "registerHal", queryurl, halInitCB, queryurl); - - OnExit: - return (rc); -}; - -// Every HAL export the same API & Interface Mapping from SndCard to AudioLogic is done through alsaHalSndCardT -static const struct afb_verb_desc_v1 halSharedApi[] = { - /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */ - { .name = "ping", .session = AFB_SESSION_NONE, .callback = pingtest, .info = "Ping Binding"}, - { .name = "getctls", .session = AFB_SESSION_NONE, .callback = halGetCtls, .info = "Get Control"}, - { .name = "setvol", .session = AFB_SESSION_NONE, .callback = halSetVol, .info = "Set Volume"}, - { .name = "getvol", .session = AFB_SESSION_NONE, .callback = halGetVol, .info = "Get Volume"}, - { .name = "subscribe", .session = AFB_SESSION_NONE, .callback = halSubscribe,.info = "Subscribe Alsa Events"}, - { .name = "monitor", .session = AFB_SESSION_NONE, .callback = halMonitor ,.info = "Monitor Alsa Events"}, - { .name = NULL} /* marker for end of the array */ -}; - - -static struct afb_binding alsaHalBinding = { - /* description conforms to VERSION 1 */ - .type= AFB_BINDING_VERSION_1, - .v1= { - .prefix= NULL, - .info = NULL, - .verbs = halSharedApi, - } -}; - -// Process HAL mapping from alsaHalSndCardT before registering HAL binder -PUBLIC const struct afb_binding *afbBindingV1Register(const struct afb_binding_interface *itf) { - - afbIface = itf; // need to keep a static trace of binder interface for avances functions - // alsaHalBinding.v1.verbs = halSharedApi; // complete sndcard specific alsaHalBinding with standard HAL APIs - alsaHalMapT *halCtls = alsaHalSndCard.ctls; // Get sndcard specific HAL control mapping - - if (halCtls == NULL) { - ERROR(afbIface, "afbBindingV1Register Fail alsaHalCtlsMap==NULL"); - return NULL; - } - - // Create a zone to store HAL high/low level mapping - shareHallMap = malloc(EndHalCrlTag * sizeof (shareHallMap_T)); - for (int idx = 0; (halCtls[idx].alsa.numid != 0 || halCtls[idx].cb.callback != NULL); idx++) { - if (halCtls[idx].alsa.numid == 0) halCtls[idx].alsa.numid =-1; - shareHallMap[halCtls[idx].alsa.control].numid = halCtls[idx].alsa.numid; - } - - alsaHalBinding.v1.prefix= alsaHalSndCard.prefix; - alsaHalBinding.v1.info = alsaHalSndCard.info; - return &alsaHalBinding; /* returns the description of the binding */ -}; diff --git a/AlsaSound/HALayer/SharedHal/SharedHalLib.h b/AlsaSound/HALayer/SharedHal/SharedHalLib.h deleted file mode 100644 index 7cf4489..0000000 --- a/AlsaSound/HALayer/SharedHal/SharedHalLib.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * AlsaLibMapping -- provide low level interface with AUDIO 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 SHAREHALLIB_H -#define SHAREHALLIB_H - -#include -#include "AudioCommonLib.h" - -typedef struct { - halCtlsEnumT control; - int numid; - halGroupEnumT group; - int values; - int minval; - int maxval; - int step; - halAclEnumT acl; -} alsaHalCtlMapT; - -// avoid compiler warning [Jose does not like typedef :) ] -typedef struct afb_service alsaHalServiceT; - -typedef struct { - struct json_object* (*callback)(alsaHalServiceT service, int control, int value, alsaHalCtlMapT *map, void* handle); - void* handle; -} alsaHalCbMapT; - -typedef struct { - alsaHalCtlMapT alsa; - alsaHalCbMapT cb; - char* info; -} alsaHalMapT; - -typedef struct { - const char *prefix; - const char *name; - const char *info; - alsaHalMapT *ctls; - int (*initCB) (const struct afb_binding_interface *itf, struct afb_service service); - -} alsaHalSndCardT; - -PUBLIC alsaHalSndCardT alsaHalSndCard; -PUBLIC char* SharedHalLibVersion; - -#endif /* SHAREHALLIB_H */ - diff --git a/Audio-Interface/CMakeLists.txt b/Audio-Interface/CMakeLists.txt new file mode 100644 index 0000000..665007f --- /dev/null +++ b/Audio-Interface/CMakeLists.txt @@ -0,0 +1,37 @@ +########################################################################### +# Copyright 2015, 2016, 2017 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. +########################################################################### + +# Add target to project dependency list +PROJECT_TARGET_ADD(audio-interface) + + # Define targets + ADD_LIBRARY(audio-interface STATIC audio-interface.c) + + # Library properties + SET_TARGET_PROPERTIES(audio-interface PROPERTIES OUTPUT_NAME audiointerface) + + # Library dependencies + #TARGET_LINK_LIBRARIES(audio-interface + # empty + #) + + # Define target includes + TARGET_INCLUDE_DIRECTORIES(audio-interface + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} + ) + diff --git a/Audio-Interface/audio-interface.c b/Audio-Interface/audio-interface.c new file mode 100644 index 0000000..c1c4054 --- /dev/null +++ b/Audio-Interface/audio-interface.c @@ -0,0 +1,102 @@ +/* + * 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 // needed for vasprintf + +#include +#include +#include +#include +#include + +#include "audio-interface.h" + +typedef struct { + int index; + int numid; +} shareHallMap_T; + + +PUBLIC int cbCheckResponse(struct afb_req request, int iserror, struct json_object *result) { + struct json_object *response, *status, *info; + + if (iserror) { // on error proxy information we got from lower layer + if (result) { + if (json_object_object_get_ex(result, "request", &response)) { + json_object_object_get_ex(response, "info", &info); + json_object_object_get_ex(response, "status", &status); + afb_req_fail(request, json_object_get_string(status), json_object_get_string(info)); + goto OnErrorExit; + } + } else { + afb_req_fail(request, "cbCheckFail", "No Result inside API response"); + } + goto OnErrorExit; + } + return (0); + +OnErrorExit: + return (-1); +} + + +// This function should be part of Generic AGL Framework +PUBLIC json_object* afb_service_call_sync(struct afb_service srvitf, struct afb_req request, char* api, char* verb, struct json_object* queryurl) { + json_object* response = NULL; + int status = 0; + sem_t semid; + + // Nested procedure are allow in GNU and allow us to keep caller stack valid + + void callback(void *handle, int iserror, struct json_object *result) { + + // Process Basic Error + if (!cbCheckResponse(request, iserror, result)) { + status = -1; + goto OnExitCB; + } + + // Get response from object + json_object_object_get_ex(result, "response", &response); + if (!response) { + afb_req_fail_f(request, "response-notfound", "No Controls return from alsa/getcontrol result=[%s]", json_object_get_string(result)); + goto OnExitCB; + } + +OnExitCB: + sem_post(&semid); + } + + // Create an exclusive semaphore + status = sem_init(&semid, 0, 0); + if (status < 0) { + afb_req_fail_f(request, "error:seminit", "Fail to allocate semaphore err=[%s]", strerror(status)); + goto OnExit; + } + + // Call service and wait for call back to finish before moving any further + afb_service_call(srvitf, api, verb, queryurl, callback, NULL); + sem_wait(&semid); + +OnExit: + return (response); +} + +PUBLIC void pingtest(struct afb_req request) { + json_object *query = afb_req_json(request); + afb_req_success(request, query, NULL); +} diff --git a/Audio-Interface/audio-interface.h b/Audio-Interface/audio-interface.h new file mode 100644 index 0000000..ffefbfc --- /dev/null +++ b/Audio-Interface/audio-interface.h @@ -0,0 +1,68 @@ +/* + * 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. + * + * reference: + * amixer contents; amixer controls; + * http://www.tldp.org/HOWTO/Alsa-sound-6.html + */ + +#ifndef AUDIOCOMMON_H +#define AUDIOCOMMON_H + +#include +#include +#include + +#ifndef PUBLIC + #define PUBLIC +#endif +#define STATIC static + +// Most controls are MIXER but some vendor specific are possible +typedef enum { + OUTVOL, + PCMVOL, + INVOL, + SWITCH, + ROUTE, + CARD, + ENUM, +} halGroupEnumT; + +typedef enum { + READ, + WRITE, + RW, +} halAclEnumT; + +typedef enum { + StartHalCrlTag=0, + + // HighLevel Audio Control List + Master_Playback_Volume, + PCM_Playback_Volume, + PCM_Playback_Switch, + Capture_Volume, + + EndHalCrlTag // used to compute number of ctls +} halCtlsEnumT; + +PUBLIC int cbCheckResponse(struct afb_req request, int iserror, struct json_object *result) ; +PUBLIC json_object* afb_service_call_sync(struct afb_service srvitf, struct afb_req request, char* api, char* verb, struct json_object* queryurl); +PUBLIC void pingtest(struct afb_req request); + +#endif /* AUDIOCOMMON_H */ + diff --git a/AudioLogic/AudioLogicBinding.c b/AudioLogic/AudioLogicBinding.c deleted file mode 100644 index 002ff42..0000000 --- a/AudioLogic/AudioLogicBinding.c +++ /dev/null @@ -1,98 +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 "AudioLogicLib.h" - -PUBLIC const struct afb_binding_interface *afbIface; - -// Map HAL Enum to Labels -typedef const struct { - halCtlsEnumT control; - char *label; -} LogicControlT; - -// High Level Control Mapping to String for JSON & HTML5 -STATIC LogicControlT LogicControl[] = { - {.control= Master_Playback_Volume,.label= "Master_Volume"}, - {.control= PCM_Playback_Volume, .label= "Playback_Volume"}, - {.control= PCM_Playback_Switch, .label= "Playback_Switch"}, - {.control= Capture_Volume, .label= "Capture_Volume"}, - - {.control= 0,.label= NULL} // closing convention -}; - - -/* - * 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= "setvolume", .session= AFB_SESSION_CHECK, .callback= audioLogicSetVol, .info= "Set Volume" }, - { .name= "getvolume", .session= AFB_SESSION_CHECK, .callback= audioLogicGetVol, .info= "Get Volume" }, - { .name= "subscribe", .session= AFB_SESSION_CHECK, .callback= audioLogicSubscribe, .info= "Subscribe AudioBinding Events" }, - { .name= "monitor", .session= AFB_SESSION_CHECK, .callback= audioLogicMonitor, .info= "Activate AlsaCtl Monitoring" }, - { .name= "open", .session= AFB_SESSION_CREATE,.callback= audioLogicOpen, .info= "Open a Dedicated SoundCard" }, - { .name= "close", .session= AFB_SESSION_CLOSE, .callback= audioLogicClose, .info= "Close previously open SoundCard" }, - { .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= "audio", - .info= "High Level Interface to Audio bindings", - .verbs = binding_verbs - } -}; - -// This receive all event this binding subscribe to -PUBLIC void afbBindingV1ServiceEvent(const char *evtname, struct json_object *object) { - - NOTICE (afbIface, "afbBindingV1ServiceEvent evtname=%s [msg=%s]", evtname, json_object_to_json_string(object)); -} - -// this is call when after all bindings are loaded -PUBLIC int afbBindingV1ServiceInit(struct afb_service service) { - - return (audioLogicInit(service)); -}; - -/* - * activation function for registering the binding called by afb-daemon - */ -PUBLIC 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/AudioLogic/AudioLogicLib.c b/AudioLogic/AudioLogicLib.c deleted file mode 100644 index e9d7104..0000000 --- a/AudioLogic/AudioLogicLib.c +++ /dev/null @@ -1,316 +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 "AudioLogicLib.h" - -static struct afb_service srvitf; - - -// This callback is fired when afb_service_call for api/alsacore/subctl returns -STATIC void audioLogicSetVolCB(void *handle, int iserror, struct json_object *result) { - struct afb_req request = afb_req_unstore(handle); - - if (!cbCheckResponse(request, iserror, result)) goto OnExit; - -OnExit: - return; -} - -PUBLIC void audioLogicSetVol(struct afb_req request) { - struct json_object *queryurl; - int volume=0; // FULUP TBD !!!!!!!!!!!! - - // keep request for callback to respond - struct afb_req *handle = afb_req_store(request); - - // get client context - AudioLogicCtxT *ctx = afb_req_context_get(request); - - const char *vol = afb_req_value(request, "vol"); - if (vol == NULL) { - afb_req_fail_f(request, "argument-missing", "vol=+-%[0,100] missing"); - goto OnExit; - } - - switch (vol[0]) { - case '+': - break; - case '-': - break; - case '%': - break; - - default: - afb_req_fail_f(request, "value-invalid", "volume should be (+-%[0-100]xxx) vol=%s", vol); - goto OnExit; - } - - if (!ctx->halapi) { - afb_req_fail_f(request, "context-invalid", "No valid halapi in client context"); - goto OnExit; - } - - // ********** Caluler le volume en % de manière intelligente - queryurl = json_object_new_object(); - json_object_object_add(ctx->queryurl, "pcm", json_object_new_int(Master_Playback_Volume)); - json_object_object_add(ctx->queryurl, "value", json_object_new_int(volume)); - - // subcontract HAL API to process volume - afb_service_call(srvitf, ctx->halapi, "volume", queryurl, audioLogicSetVolCB, handle); - - // final success/failure messages handle from callback -OnExit: - return; -} - -// This callback is fired when afb_service_call for api/alsacore/subctl returns - -STATIC void alsaSubcribeCB(void *handle, int iserror, struct json_object *result) { - struct afb_req request = afb_req_unstore(handle); - - if (!cbCheckResponse(request, iserror, result)) goto OnExit; - -OnExit: - return; -} - -// Create and subscribe to alsacore ctl events -PUBLIC void audioLogicMonitor(struct afb_req request) { - - - // get client context - AudioLogicCtxT *ctx = afb_req_context_get(request); - if (!ctx) { - afb_req_fail_f(request, "ctx-notfound", "No Client Context HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); - goto OnExit; - } - - // push request to low level binding - NOTICE(afbIface, "audioLogicMonitor ctx->devid=%s [ctx->queryurl=%s]", ctx->devid, json_object_to_json_string(ctx->queryurl)); - - if (ctx->queryurl) { - json_object_get(ctx->queryurl); // Make sure usage count does not fall to zero - struct afb_req *handle = afb_req_store(request); - afb_service_call(srvitf, "alsacore", "subscribe", ctx->queryurl, alsaSubcribeCB, handle); - } - else afb_req_fail_f(request, "context-invalid", "No valid queryurl in client context"); - - // success/failure messages return from callback -OnExit: - return; -} - -// Subscribe to AudioBinding events - -PUBLIC void audioLogicSubscribe(struct afb_req request) { - - return; -} - - -// Call when all bindings are loaded and ready to accept request -PUBLIC void audioLogicGetVol(struct afb_req request) { - - // Should call here Hardware Alsa Abstraction Layer for corresponding Sound Card - afb_req_success(request, NULL, NULL); - return; - -} - -// This callback is fired when afb_service_call for api/alsacore/subctl returns - -STATIC void audioLogicOpenCB2(void *handle, int iserror, struct json_object *result) { - struct json_object *response; - - // Make sure we got a response from API - struct afb_req request = afb_req_unstore(handle); - if (!cbCheckResponse(request, iserror, result)) goto OnExit; - - // get client context - AudioLogicCtxT *ctx = afb_req_context_get(request); - if (!ctx) { - afb_req_fail_f(request, "ctx-notfound", "No Client Context HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); - goto OnExit; - } - - // Get response from object - json_object_object_get_ex(result, "response", &response); - if (!response) { - afb_req_fail_f(request, "response-notfound", "No Controls return from HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); - goto OnExit; - } - - // extract sounds controls information from received Object - struct json_object *ctls; - json_object_object_get_ex(response, "ctls", &ctls); - if (!ctls) { - afb_req_fail_f(request, "ctls-notfound", "No Controls return from HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); - goto OnExit; - } - - // make sure return controls have a valid type - if (json_object_get_type(ctls) != json_type_array) { - afb_req_fail_f(request, "ctls-notarray", "Invalid Controls return from HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); - goto OnExit; - } - - // loop on array and store values into client context - for (int idx = 0; idx < json_object_array_length(ctls); idx++) { - struct json_object *ctl; - halCtlsEnumT control; - int value; - - ctl = json_object_array_get_idx(ctls, idx); - if (json_object_array_length(ctl) != 2) { - afb_req_fail_f(request, "ctl-invalid", "Invalid Control return from HAL/getcontrol devid=[%] name=[%s] ctl=%s" - , ctx->devid, ctx->shortname, json_object_get_string(ctl)); - goto OnExit; - } - - // As HAL and Business logic use the same AlsaMixerHal.h direct conversion is not an issue - control = (halCtlsEnumT) json_object_get_int(json_object_array_get_idx(ctl, 0)); - value = json_object_get_int(json_object_array_get_idx(ctl, 1)); - - switch (control) { - case Master_Playback_Volume: - ctx->volumes.masterPlaybackVolume = value; - break; - - case PCM_Playback_Volume: - ctx->volumes.pcmPlaybackVolume = value; - break; - - case PCM_Playback_Switch: - ctx->volumes.pcmPlaybackSwitch = value; - break; - - case Capture_Volume: - ctx->volumes.captureVolume = value; - break; - - default: - NOTICE(afbIface, "audioLogicOpenCB2 unknown HAL control=[%s]", json_object_get_string(ctl)); - } - } - -OnExit: - afb_req_context_set(request, ctx, free); - return; -} - -// This callback is fired when afb_service_call for api/alsacore/subctl returns -STATIC void audioLogicOpenCB1(void *handle, int iserror, struct json_object *result) { - struct json_object *response, *subobj; - - // Make sure we got a valid API response - struct afb_req request = afb_req_unstore(handle); - if (!cbCheckResponse(request, iserror, result)) goto OnExit; - - // Get response from object - json_object_object_get_ex(result, "response", &response); - if (!response) { - afb_req_fail_f(request, "response-notfound", "No Controls return from HAL/getcontrol"); - goto OnExit; - } - - // attach client context to session - AudioLogicCtxT *ctx = malloc(sizeof (AudioLogicCtxT)); - - // extract information from Json Alsa Object - json_object_object_get_ex(response, "cardid", &subobj); - if (subobj) ctx->cardid = json_object_get_int(subobj); - - // store devid as an object for further alsa request - json_object_object_get_ex(response, "devid", &subobj); - if (subobj) ctx->devid = strdup(json_object_get_string(subobj)); - - json_object_object_get_ex(response, "halapi", &subobj); - if (subobj) ctx->halapi = strdup(json_object_get_string(subobj)); - - json_object_object_get_ex(response, "shortname", &subobj); - if (subobj)ctx->shortname = strdup(json_object_get_string(subobj)); - - json_object_object_get_ex(response, "longname", &subobj); - if (subobj)ctx->longname = strdup(json_object_get_string(subobj)); - - // save queryurl with devid only for further ALSA request - ctx->queryurl = json_object_new_object(); - json_object_object_add(ctx->queryurl, "devid", json_object_new_string(ctx->devid)); - - afb_req_context_set(request, ctx, free); - - // sound card was find let's store keycontrols into client session - if (!ctx->halapi) { - afb_req_fail_f(request, "hal-notfound", "No HAL found devid=[%] name=[%s]", ctx->devid, ctx->shortname); - goto OnExit; - } - - struct json_object *queryurl = json_object_new_object(); - struct json_object *ctls = json_object_new_array(); - - // add sound controls we want to keep track of into client session context - json_object_array_add(ctls, json_object_new_int((int) Master_Playback_Volume)); - json_object_array_add(ctls, json_object_new_int((int) PCM_Playback_Volume)); - json_object_array_add(ctls, json_object_new_int((int) PCM_Playback_Switch)); - json_object_array_add(ctls, json_object_new_int((int) Capture_Volume)); - - // send request to soundcard HAL binding - json_object_object_add(queryurl, "ctls", ctls); - handle = afb_req_store(request); // FULUP ???? Needed for 2nd Callback ???? - afb_service_call(srvitf, ctx->halapi, "getControl", queryurl, audioLogicOpenCB2, handle); - - afb_req_success(request, response, NULL); - -OnExit: - // release original calling request - afb_req_unref(request); - return; -} - -// Delegate to lowerlevel the mapping of soundcard name with soundcard ID -PUBLIC void audioLogicOpen(struct afb_req request) { - - // Delegate query to lower level - struct afb_req *handle = afb_req_store(request); - afb_service_call(srvitf, "alsacore", "getCardId", json_object_get(afb_req_json(request)), audioLogicOpenCB1, handle); -} - -// Free client context create from audioLogicOpenCB -PUBLIC void audioLogicClose(struct afb_req request) { - - // retrieve current client context to print debug info - AudioLogicCtxT *ctx = (AudioLogicCtxT*) afb_req_context_get(request); - DEBUG(afbIface, "audioLogicClose cardid=%d devid=%s shortname=%s longname=%s", ctx->cardid, ctx->devid, ctx->shortname, ctx->longname); -} - - -// this function is call after all binder are loaded and initialised -PUBLIC int audioLogicInit(struct afb_service service) { - srvitf = service; - return 0; -} diff --git a/AudioLogic/AudioLogicLib.h b/AudioLogic/AudioLogicLib.h deleted file mode 100644 index 77b8b7b..0000000 --- a/AudioLogic/AudioLogicLib.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * AlsaLibMapping -- provide low level interface with AUDIO 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 AUDIOLOGIC_H -#define AUDIOLOGIC_H - -#include "AudioCommonLib.h" -#include -#include -#include - -// import from AlsaAfbBinding -extern const struct afb_binding_interface *afbIface; - - -// This structure hold private data for a given client of binding -typedef struct { - - int cardid; - const char *devid; - const char *shortname; - const char *longname; - const char *halapi; - struct { // volume in % [0-100] - int masterPlaybackVolume; - int pcmPlaybackVolume; - int pcmPlaybackSwitch; - int captureVolume; - } volumes; - json_object *queryurl; -} AudioLogicCtxT; - -// import from AlsaAfbMapping -PUBLIC void audioLogicSetVol (struct afb_req request); -PUBLIC void audioLogicGetVol(struct afb_req request); -PUBLIC void audioLogicMonitor(struct afb_req request); -PUBLIC void audioLogicOpen(struct afb_req request); -PUBLIC void audioLogicClose(struct afb_req request); -PUBLIC void audioLogicSubscribe(struct afb_req request); -PUBLIC int audioLogicInit (struct afb_service service); - -#endif /* AUDIOLOGIC_H */ - diff --git a/AudioLogic/CMakeLists.txt b/AudioLogic/CMakeLists.txt deleted file mode 100644 index 0b72b5c..0000000 --- a/AudioLogic/CMakeLists.txt +++ /dev/null @@ -1,36 +0,0 @@ -########################################################################### -# Copyright 2015, 2016, 2017 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. -########################################################################### - - -INCLUDE_DIRECTORIES(${include_dirs}) - -################################################## -# AudioLogicBinding -################################################## -ADD_LIBRARY(audiologic-afb MODULE AudioLogicBinding.c AudioLogicLib.c) - -SET_TARGET_PROPERTIES(audiologic-afb PROPERTIES - PREFIX "" - LINK_FLAGS "-Wl,--version-script=${CMAKE_SOURCE_DIR}/export.map" -) - -TARGET_LINK_LIBRARIES(audiologic-afb ${link_libraries}) -INSTALL(TARGETS audiologic-afb - LIBRARY DESTINATION ${binding_install_dir}) - - diff --git a/AudioLogic/README.md b/AudioLogic/README.md deleted file mode 100644 index fa50173..0000000 --- a/AudioLogic/README.md +++ /dev/null @@ -1,35 +0,0 @@ ------------------------------------------------------------------------- - AudioLogic High Level APIs ------------------------------------------------------------------------- - -Testing: (from project directory bindings) - * start binder: ~/opt/bin/afb-daemon --ldpaths=./build --token=mysecret --roothttp=htdocs - * connect browser on http://localhost:1234?devid=hw:0 - - # Open Sound Card from its name - http://localhost:1234/api/audio/open?token=mysecret&sndname=H650e - - # Subscribe event for a given board - http://localhost:1234/api/audio/subscribe?token=mysecret&devid=hw:0 - - # Increase Volume - http://localhost:1234/api/audio/setvol?token=mysecret&devid=hw:0&pcm=master&vol=50% - - # Get Volume - http://localhost:1234/api/audio/getvol?token=mysecret&devid=hw:0&pcm=master - - # Close Session - http://localhost:1234/api/audio/close?token=mysecret - - -Testing with afb-client-demo - -``` -~/opt/bin/afb-client-demo localhost:1234/api?token=mysecret -alsacore subctl {"devid":"hw:0"} -``` - -Start AlsaMixer and change volume -``` -alsamixer -D hw:0 -``` \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 0bd639d..90ecf5c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,48 +17,63 @@ ########################################################################### -# Select GCC5 is avaliable -########################################################################### -execute_process(COMMAND gcc-5 -dumpversion RESULT_VARIABLE GCC5RC OUTPUT_QUIET ERROR_QUIET) -if(GCC5RC EQUAL 0) -message(STATUS "GCC version-5 selected") -set(CMAKE_C_COMPILER "gcc-5") -set(CMAKE_CXX_COMPILER "g++-5") -endif(GCC5RC EQUAL 0) - - -# Compiler should be selected before projet() -project(audio-binding) -SET(PROJECT_NAME "AFB Audio Binding") -SET(PROJECT_PRETTY_NAME "Audio Binding") -SET(PROJECT_DESCRIPTION "Expose Audio API through AGL Framework") -SET(PROJECT_VERSION "1.0") -SET(PROJECT_URL "https://github.com/iotbzh/afb-audio") - -CMAKE_MINIMUM_REQUIRED(VERSION 3.3) -SET(CMAKE_BUILD_TYPE Debug) -SET(CMAKE_POSITION_INDEPENDENT_CODE ON) - -INCLUDE(FindPkgConfig) -INCLUDE(CheckIncludeFiles) -INCLUDE(CheckLibraryExists) -INCLUDE(GNUInstallDirs) +#-------------------------------------------------------------------------- +# WARNING: +# Do not change this cmake template +# Customise your preferences in "./etc/config.cmake" +#-------------------------------------------------------------------------- -SET(binding_install_dir ${CMAKE_INSTALL_FULL_LIBDIR}/audio) - # Generic useful macro -########################################################### +# ----------------------- +macro(PROJECT_TARGET_ADD TARGET_NAME) + set(PROJECT_TARGETS ${PROJECT_TARGETS} ${TARGET_NAME} CACHE INTERNAL PROJECT_TARGETS) +endmacro(PROJECT_TARGET_ADD) + macro(defstr name value) - add_definitions(-D${name}=${value}) + add_definitions(-D${name}=${value}) endmacro(defstr) macro(setc name value) - if(NOT DEFINED ${name}) - set(${name} ${value}) - endif(NOT DEFINED ${name}) + if(NOT DEFINED ${name}) + set(${name} ${value}) + endif(NOT DEFINED ${name}) endmacro(setc) +CMAKE_MINIMUM_REQUIRED(VERSION 3.3) +setc(CMAKE_BUILD_TYPE Debug) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +set(CMP0048 1) + + +# Compiler selection should append before project definition +# ----------------------------------------------------------- +foreach (GCC_VERSION "6" "5") + execute_process(COMMAND gcc-${GCC_VERSION} -dumpversion RESULT_VARIABLE GCCRC OUTPUT_QUIET ERROR_QUIET) + if(GCCRC EQUAL 0) + set(CMAKE_C_COMPILER "gcc-${GCC_VERSION}") + set(CMAKE_CXX_COMPILER "g++-${GCC_VERSION}") + set(CMAKE_C_VERSION ${GCC_VERSION}) + break() + endif(GCCRC EQUAL 0) +endforeach(GCC_VERSION) + +# Include project configuration +# ------------------------------ +include(${CMAKE_CURRENT_SOURCE_DIR}/etc/config.cmake) +project(${NAME} VERSION ${VERSION}) +setc (PROJECT_PRETTY_NAME ${PRETTY_NAME}) +setc (PROJECT_DESCRIPTION ${DESCRIPTION}) +message(STATUS "") +message(STATUS "Project=${PROJECT_NAME}/${VERSION}[${PRETTY_NAME} ${DESCRIPTION}]") +message(STATUS "") +message(STATUS "gcc/g++ version-${CMAKE_C_VERSION}.x selected") + +INCLUDE(FindPkgConfig) +INCLUDE(CheckIncludeFiles) +INCLUDE(CheckLibraryExists) +INCLUDE(GNUInstallDirs) + # Default compilation options ############################################################################ link_libraries(-Wl,--as-needed -Wl,--gc-sections) @@ -73,46 +88,66 @@ add_compile_options(-g) setc(CMAKE_C_FLAGS_PROFILING "-g -O2 -pg -Wp,-U_FORTIFY_SOURCE") setc(CMAKE_C_FLAGS_DEBUG "-g -O2 -ggdb -Wp,-U_FORTIFY_SOURCE") -setc(CMAKE_C_FLAGS_RELEASE "-g -O2") +setc(CMAKE_C_FLAGS_RELEASE "-O2") setc(CMAKE_C_FLAGS_CCOV "-g -O2 --coverage") setc(CMAKE_INSTALL_PREFIX "${CMAKE_SOURCE_DIR}/Install") -# Warning as PKG_CONFIG_PATH does not work [should be en env variable] -set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH 1) -set(CMAKE_PREFIX_PATH ${HOME}/opt/lib64/pkgconfig) +# (BUG!!!) as PKG_CONFIG_PATH does not work [should be en env variable] +setc(PKG_CONFIG_USE_CMAKE_PREFIX_PATH 1) +# Loop on required package and add options +foreach (PKG_CONFIG ${PKG_REQUIRED_LIST}) + PKG_CHECK_MODULES(${PKG_CONFIG} REQUIRED ${PKG_CONFIG}) -# Generic Package dependencies -############################################################################ -PKG_CHECK_MODULES(json-c REQUIRED json-c) -PKG_CHECK_MODULES(afb-daemon REQUIRED afb-daemon) + INCLUDE_DIRECTORIES(${${PKG_CONFIG}_INCLUDE_DIRS}) + list (APPEND link_libraries ${${PKG_CONFIG}_LIBRARIES}) + add_compile_options (${${PKG_CONFIG}_CFLAGS}) +endforeach(PKG_CONFIG) -IF(CMAKE_BUILD_TYPE MATCHES Debug) +# Optional LibEfence Malloc debug library +IF(CMAKE_BUILD_TYPE MATCHES DEBUG) CHECK_LIBRARY_EXISTS(efence malloc "" HAVE_LIBEFENCE) IF(HAVE_LIBEFENCE) MESSAGE(STATUS "Linking with ElectricFence for debugging purposes...") SET(libefence_LIBRARIES "-lefence") + list (APPEND link_libraries libefence_LIBRARIES}) ENDIF(HAVE_LIBEFENCE) -ENDIF(CMAKE_BUILD_TYPE MATCHES Debug) - - -SET(include_dirs - ${INCLUDE_DIRS} - ${CMAKE_CURRENT_SOURCE_DIR}/Common - ${json-c_INCLUDE_DIRS} - ${afb-daemon_INCLUDE_DIRS} - ) +ENDIF(CMAKE_BUILD_TYPE MATCHES DEBUG) -# AudioCommon is linked statically with each audiobindings -SET(link_libraries - ${CMAKE_BINARY_DIR}/Common/libaudiocommon.a - ${libefence_LIBRARIES} - ${json-c_LIBRARIES} - ) +# set default include directories +INCLUDE_DIRECTORIES(${EXTRA_INCLUDE_DIRS}) # Bindings to compile # -------------------- -add_subdirectory(Common) -add_subdirectory(AlsaSound) -add_subdirectory(AudioLogic) -add_subdirectory(htdocs) +file(GLOB filelist "[A-z]*") +foreach(filename ${filelist}) + if(EXISTS "${filename}/CMakeLists.txt") + add_subdirectory(${filename}) + endif(EXISTS "${filename}/CMakeLists.txt") +endforeach() + +# Add a dummy target to enable global dependency order +# ----------------------------------------------------- +if(EXTRA_DEPENDENCIES_ORDER) + set(DEPENDENCIES_TARGET ${PROJECT_NAME}_extra_dependencies) + add_custom_target(${DEPENDENCIES_TARGET} ALL + DEPENDS ${EXTRA_DEPENDENCY_ORDER} + ) +endif() + +# Cmake does not maintain targets list before 3.7 +# ------------------------------------------------- +if(${CMAKE_VERSION} VERSION_LESS 3.7) + set(GLOBAL_TARGET_LIST ${PROJECT_TARGETS}) +else() + get_property(GLOBAL_TARGET_LIST GLOBAL PROPERTY GlobalTargetList) +endif() + +# Print developer helper message when everything is done +# ------------------------------------------------------- +if(CLOSING_MESSAGE AND GLOBAL_TARGET_LIST) + add_custom_target(${PROJECT_NAME}_done ALL + DEPENDS ${DEPENDENCIES_TARGET} ${GLOBAL_TARGET_LIST} + COMMAND ${CMAKE_COMMAND} -E cmake_echo_color --cyan "++ ${CLOSING_MESSAGE}" + ) +endif() diff --git a/Common/AudioCommonLib.c b/Common/AudioCommonLib.c deleted file mode 100644 index 0055896..0000000 --- a/Common/AudioCommonLib.c +++ /dev/null @@ -1,102 +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 // needed for vasprintf - -#include -#include -#include -#include -#include - -#include "AudioCommonLib.h" - -typedef struct { - int index; - int numid; -} shareHallMap_T; - - -PUBLIC int cbCheckResponse(struct afb_req request, int iserror, struct json_object *result) { - struct json_object *response, *status, *info; - - if (iserror) { // on error proxy information we got from lower layer - if (result) { - if (json_object_object_get_ex(result, "request", &response)) { - json_object_object_get_ex(response, "info", &info); - json_object_object_get_ex(response, "status", &status); - afb_req_fail(request, json_object_get_string(status), json_object_get_string(info)); - goto OnErrorExit; - } - } else { - afb_req_fail(request, "cbCheckFail", "No Result inside API response"); - } - goto OnErrorExit; - } - return (0); - -OnErrorExit: - return (-1); -} - - -// This function should be part of Generic AGL Framework -PUBLIC json_object* afb_service_call_sync(struct afb_service srvitf, struct afb_req request, char* api, char* verb, struct json_object* queryurl) { - json_object* response = NULL; - int status = 0; - sem_t semid; - - // Nested procedure are allow in GNU and allow us to keep caller stack valid - - void callback(void *handle, int iserror, struct json_object *result) { - - // Process Basic Error - if (!cbCheckResponse(request, iserror, result)) { - status = -1; - goto OnExitCB; - } - - // Get response from object - json_object_object_get_ex(result, "response", &response); - if (!response) { - afb_req_fail_f(request, "response-notfound", "No Controls return from alsa/getcontrol result=[%s]", json_object_get_string(result)); - goto OnExitCB; - } - -OnExitCB: - sem_post(&semid); - } - - // Create an exclusive semaphore - status = sem_init(&semid, 0, 0); - if (status < 0) { - afb_req_fail_f(request, "error:seminit", "Fail to allocate semaphore err=[%s]", strerror(status)); - goto OnExit; - } - - // Call service and wait for call back to finish before moving any further - afb_service_call(srvitf, api, verb, queryurl, callback, NULL); - sem_wait(&semid); - -OnExit: - return (response); -} - -PUBLIC void pingtest(struct afb_req request) { - json_object *query = afb_req_json(request); - afb_req_success(request, query, NULL); -} diff --git a/Common/AudioCommonLib.h b/Common/AudioCommonLib.h deleted file mode 100644 index ffefbfc..0000000 --- a/Common/AudioCommonLib.h +++ /dev/null @@ -1,68 +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. - * - * reference: - * amixer contents; amixer controls; - * http://www.tldp.org/HOWTO/Alsa-sound-6.html - */ - -#ifndef AUDIOCOMMON_H -#define AUDIOCOMMON_H - -#include -#include -#include - -#ifndef PUBLIC - #define PUBLIC -#endif -#define STATIC static - -// Most controls are MIXER but some vendor specific are possible -typedef enum { - OUTVOL, - PCMVOL, - INVOL, - SWITCH, - ROUTE, - CARD, - ENUM, -} halGroupEnumT; - -typedef enum { - READ, - WRITE, - RW, -} halAclEnumT; - -typedef enum { - StartHalCrlTag=0, - - // HighLevel Audio Control List - Master_Playback_Volume, - PCM_Playback_Volume, - PCM_Playback_Switch, - Capture_Volume, - - EndHalCrlTag // used to compute number of ctls -} halCtlsEnumT; - -PUBLIC int cbCheckResponse(struct afb_req request, int iserror, struct json_object *result) ; -PUBLIC json_object* afb_service_call_sync(struct afb_service srvitf, struct afb_req request, char* api, char* verb, struct json_object* queryurl); -PUBLIC void pingtest(struct afb_req request); - -#endif /* AUDIOCOMMON_H */ - diff --git a/Common/CMakeLists.txt b/Common/CMakeLists.txt deleted file mode 100644 index 79ee8ac..0000000 --- a/Common/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -########################################################################### -# Copyright 2015, 2016, 2017 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. -########################################################################### - -PROJECT(audio-common C) - -INCLUDE_DIRECTORIES(${include_dirs}) - -################################################## -# AudioCommon is a local static Library -################################################## -ADD_LIBRARY(audiocommon STATIC AudioCommonLib.c) -SET_TARGET_PROPERTIES(audiocommon PROPERTIES OUTPUT_NAME audiocommon) -SET(link_libraries ${libefence_LIBRARIES} ${json-c_LIBRARIES}) -TARGET_LINK_LIBRARIES(audiocommon ${link_libraries}) - - diff --git a/HAL-afb/CMakeLists.txt b/HAL-afb/CMakeLists.txt new file mode 100644 index 0000000..c36f530 --- /dev/null +++ b/HAL-afb/CMakeLists.txt @@ -0,0 +1,28 @@ +########################################################################### +# Copyright 2015, 2016, 2017 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. +########################################################################### + + +# Include any directory starting with a Capital letter +# ----------------------------------------------------- +file(GLOB filelist "[A-Z]*") +foreach(filename ${filelist}) + if(EXISTS "${filename}/CMakeLists.txt") + add_subdirectory(${filename}) + endif(EXISTS "${filename}/CMakeLists.txt") +endforeach() + diff --git a/HAL-afb/HAL-interface/CMakeLists.txt b/HAL-afb/HAL-interface/CMakeLists.txt new file mode 100644 index 0000000..0ea298f --- /dev/null +++ b/HAL-afb/HAL-interface/CMakeLists.txt @@ -0,0 +1,37 @@ +########################################################################### +# Copyright 2015, 2016, 2017 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. +########################################################################### + + +# Add target to project dependency list +PROJECT_TARGET_ADD(hal-interface) + + # Define targets + ADD_LIBRARY(hal-interface STATIC hal-interface.c) + + # Library properties + SET_TARGET_PROPERTIES(hal-interface PROPERTIES OUTPUT_NAME halinterface) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(hal-interface + audio-interface + ) + + # Define target includes + TARGET_INCLUDE_DIRECTORIES(hal-interface + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} + ) diff --git a/HAL-afb/HAL-interface/hal-interface.c b/HAL-afb/HAL-interface/hal-interface.c new file mode 100644 index 0000000..7876715 --- /dev/null +++ b/HAL-afb/HAL-interface/hal-interface.c @@ -0,0 +1,341 @@ +/* + * 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. + * + * reference: + * amixer contents; amixer controls; + * http://www.tldp.org/HOWTO/Alsa-sound-6.html + */ +#define _GNU_SOURCE // needed for vasprintf +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "hal-interface.h" + +typedef struct { + int index; + int numid; +} shareHallMap_T; + +static struct afb_service srvitf; +static const struct afb_binding_interface *afbIface; +static shareHallMap_T *shareHallMap; + +// Force specific HAL to depend on ShareHalLib +PUBLIC char* SharedHalLibVersion="1.0"; + +// This callback when api/alsacore/subscribe returns +STATIC void alsaSubcribeCB(void *handle, int iserror, struct json_object *result) { + struct afb_req request = afb_req_unstore(handle); + struct json_object *x, *resp = NULL; + const char *info = NULL; + + if (result) { + INFO(afbIface, "result=[%s]\n", json_object_to_json_string(result)); + if (json_object_object_get_ex(result, "request", &x) && json_object_object_get_ex(x, "info", &x)) + info = json_object_get_string(x); + if (!json_object_object_get_ex(result, "response", &resp)) resp = NULL; + } + + // push message respond + if (iserror) afb_req_fail_f(request, "Fail", info); + else afb_req_success(request, resp, info); + + // free calling request + afb_req_unref(request); +} + +// Create and subscribe to alsacore ctl events + +STATIC void halMonitor(struct afb_req request) { + + // save request in session as it might be used after return by callback + struct afb_req *handle = afb_req_store(request); + + // push request to low level binding + if (!handle) afb_req_fail(request, "error", "out of memory"); + else afb_service_call(srvitf, "alsacore", "subctl", json_object_get(afb_req_json(request)), alsaSubcribeCB, handle); + + // success/failure messages return from callback +} + +// Subscribe to AudioBinding events + +STATIC void halSubscribe(struct afb_req request) { + const char *devid = afb_req_value(request, "devid"); + if (devid == NULL) { + afb_req_fail_f(request, "devid-missing", "devid=hw:xxx missing"); + } +} + +// Call when all bindings are loaded and ready to accept request + +STATIC void halGetVol(struct afb_req request) { + + // Should call here Hardware Alsa Abstraction Layer for corresponding Sound Card + afb_req_success(request, NULL, NULL); + return; + +} + +STATIC void halSetVol(struct afb_req request) { + const char *arg; + const char *pcm; + + arg = afb_req_value(request, "vol"); + if (arg == NULL) { + afb_req_fail_f(request, "argument-missing", "vol=[0,100] missing"); + goto OnErrorExit; + } + + pcm = afb_req_value(request, "pcm"); + if (pcm == NULL) pcm = "Master"; + + // Should call here Hardware Alsa Abstraction Layer for corresponding Sound Card + afb_req_success(request, NULL, NULL); + return; + +OnErrorExit: + return; + +} + +// AudioLogic expect volume values to be 0-100% + +STATIC int NormaliseValue(const alsaHalCtlMapT *halCtls, int valuein) { + int valueout; + + if (valuein > halCtls->maxval) valuein= halCtls->maxval; + if (valuein < halCtls->minval) valuein= halCtls->minval; + + // volume are ajusted to 100% any else is ignored + switch (halCtls->group) { + case OUTVOL: + case PCMVOL: + case INVOL: + valueout = (valuein * 100) / (halCtls->maxval - halCtls->minval); + break; + default: + valueout = valuein; + } + return (valueout); +} + +// receive controls for LowLevel remap them to hight level before returning them + +STATIC void halGetControlCB(void *handle, int iserror, struct json_object *result) { + alsaHalMapT *halCtls = alsaHalSndCard.ctls; + struct json_object *response; + + // retrieve request and check for errors + struct afb_req request = afb_req_unstore(handle); + if (!cbCheckResponse(request, iserror, result)) goto OnExit; + + // Get response from object + json_object_object_get_ex(result, "response", &response); + if (!response) { + afb_req_fail_f(request, "response-notfound", "No Controls return from alsa/getcontrol result=[%s]", json_object_get_string(result)); + goto OnExit; + } + + // extract sounds controls information from received Object + struct json_object *ctls; + json_object_object_get_ex(result, "ctls", &ctls); + if (!ctls) { + afb_req_fail_f(request, "ctls-notfound", "No Controls return from alsa/getcontrol response=[%s]", json_object_get_string(response)); + goto OnExit; + } + + // make sure return controls have a valid type + if (json_object_get_type(ctls) != json_type_array) { + afb_req_fail_f(request, "ctls-notarray", "Invalid Controls return from alsa/getcontrol response=[%s]", json_object_get_string(response)); + goto OnExit; + } + + // loop on array and store values into client context + for (int idx = 0; idx < json_object_array_length(ctls); idx++) { + struct json_object *ctl; + int rawvalue, numid; + + ctl = json_object_array_get_idx(ctls, idx); + if (json_object_array_length(ctl) != 2) { + afb_req_fail_f(request, "ctl-invalid", "Invalid Control return from alsa/getcontrol ctl=[%s]", json_object_get_string(ctl)); + goto OnExit; + } + + // As HAL and Business logic use the same AlsaMixerHal.h direct conversion is not an issue + numid = (halCtlsEnumT) json_object_get_int(json_object_array_get_idx(ctl, 0)); + rawvalue = json_object_get_int(json_object_array_get_idx(ctl, 1)); + + for (int idx = 0; halCtls[idx].alsa.numid != 0; idx++) { + if (halCtls[idx].alsa.numid == numid) { + struct json_object *ctlAndValue = json_object_new_array(); + json_object_array_add(ctlAndValue, json_object_new_int(idx)); // idx == high level control + json_object_array_add(ctlAndValue, json_object_new_int(NormaliseValue(&halCtls[idx].alsa, rawvalue))); + break; + } + } + if (shareHallMap[idx].numid == 0) { + + afb_req_fail_f(request, "ctl-invalid", "Invalid Control numid from alsa/getcontrol ctl=[%s]", json_object_get_string(ctl)); + goto OnExit; + } + } + + OnExit: + return; +} + + +// Translate high level control to low level and call lower layer +STATIC void halGetCtls(struct afb_req request) { + + struct json_object *queryin, *queryout, *ctlsin, *devid; + struct json_object *ctlsout = json_object_new_array(); + + // get query from request + queryin = afb_req_json(request); + + // check devid was given + if (!json_object_object_get_ex (queryin, "devid", &devid)) { + afb_req_fail_f(request, "devid-notfound", "No DevID given query=[%s]", json_object_get_string(queryin)); + goto OnExit; + } + + // loop on requested controls + if (!json_object_object_get_ex(queryin, "ctls", &ctlsin) || json_object_array_length(ctlsin) <= 0) { + afb_req_fail_f(request, "ctlsin-notfound", "No Controls given query=[%s]", json_object_get_string(queryin)); + goto OnExit; + } + + // loop on controls + for (int idx = 0; idx < json_object_array_length(ctlsin); idx++) { + struct json_object *ctl; + halCtlsEnumT control; + + // each control should be halCtlsEnumT + ctl = json_object_array_get_idx(ctlsin, idx); + control = (halCtlsEnumT) json_object_get_int(ctl); + if (control >= EndHalCrlTag || control <= StartHalCrlTag) { + afb_req_fail_f(request, "ctl-invalid", "Invalid Control devid=%s sndcard=%s ctl=[%s] should be [%d-%d]" + , json_object_get_string(devid), alsaHalSndCard.name, json_object_get_string(ctl), StartHalCrlTag, EndHalCrlTag); + goto OnExit; + } + + // add corresponding lowlevel numid to querylist + json_object_array_add(ctlsout, json_object_new_int(shareHallMap[control].numid)); + } + + // register HAL with Alsa Low Level Binder devid=hw:0&numid=1&quiet=0 + queryout = json_object_new_object(); + json_object_object_add(queryout, "devid", devid); + json_object_object_add(queryout, "ctls", ctlsout); + + // save request context dans call lowlevel API + struct afb_req *handle = afb_req_store(request); + afb_service_call(srvitf, "alsacore", "getctl", queryout, halGetControlCB, handle); + +OnExit: + // Under normal situation success/failure is set from callback + return; +}; + +STATIC void halInitCB(void *handle, int iserror, struct json_object *result) { + struct json_object *queryurl = (json_object*) handle; + + if (iserror) NOTICE(afbIface, "halInitCB: registration alsaHAL query=[%s] Fail", json_object_to_json_string(queryurl)); + else DEBUG(afbIface, "halInitCB: registration alsaHAL card=[%s] Success", json_object_to_json_string(queryurl)); +} + +// This receive all event this binding subscribe to +PUBLIC void afbBindingV1ServiceEvent(const char *evtname, struct json_object *object) { + + NOTICE(afbIface, "afbBindingV1ServiceEvent evtname=%s [msg=%s]", evtname, json_object_to_json_string(object)); +} + +// this is call when after all bindings are loaded +PUBLIC int afbBindingV1ServiceInit(struct afb_service service) { + int rc=0; + srvitf = service; + struct json_object *queryurl; + + if (alsaHalSndCard.initCB) { + rc= (alsaHalSndCard.initCB) (afbIface, service); + if (rc != 0) goto OnExit; + } + + // register HAL with Alsa Low Level Binder + queryurl = json_object_new_object(); + json_object_object_add(queryurl, "prefix", json_object_new_string(alsaHalSndCard.prefix)); + json_object_object_add(queryurl, "name", json_object_new_string(alsaHalSndCard.name)); + afb_service_call(srvitf, "alsacore", "registerHal", queryurl, halInitCB, queryurl); + + OnExit: + return (rc); +}; + +// Every HAL export the same API & Interface Mapping from SndCard to AudioLogic is done through alsaHalSndCardT +static const struct afb_verb_desc_v1 halSharedApi[] = { + /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */ + { .name = "ping", .session = AFB_SESSION_NONE, .callback = pingtest, .info = "Ping Binding"}, + { .name = "getctls", .session = AFB_SESSION_NONE, .callback = halGetCtls, .info = "Get Control"}, + { .name = "setvol", .session = AFB_SESSION_NONE, .callback = halSetVol, .info = "Set Volume"}, + { .name = "getvol", .session = AFB_SESSION_NONE, .callback = halGetVol, .info = "Get Volume"}, + { .name = "subscribe", .session = AFB_SESSION_NONE, .callback = halSubscribe,.info = "Subscribe Alsa Events"}, + { .name = "monitor", .session = AFB_SESSION_NONE, .callback = halMonitor ,.info = "Monitor Alsa Events"}, + { .name = NULL} /* marker for end of the array */ +}; + + +static struct afb_binding alsaHalBinding = { + /* description conforms to VERSION 1 */ + .type= AFB_BINDING_VERSION_1, + .v1= { + .prefix= NULL, + .info = NULL, + .verbs = halSharedApi, + } +}; + +// Process HAL mapping from alsaHalSndCardT before registering HAL binder +PUBLIC const struct afb_binding *afbBindingV1Register(const struct afb_binding_interface *itf) { + + afbIface = itf; // need to keep a static trace of binder interface for avances functions + // alsaHalBinding.v1.verbs = halSharedApi; // complete sndcard specific alsaHalBinding with standard HAL APIs + alsaHalMapT *halCtls = alsaHalSndCard.ctls; // Get sndcard specific HAL control mapping + + if (halCtls == NULL) { + ERROR(afbIface, "afbBindingV1Register Fail alsaHalCtlsMap==NULL"); + return NULL; + } + + // Create a zone to store HAL high/low level mapping + shareHallMap = malloc(EndHalCrlTag * sizeof (shareHallMap_T)); + for (int idx = 0; (halCtls[idx].alsa.numid != 0 || halCtls[idx].cb.callback != NULL); idx++) { + if (halCtls[idx].alsa.numid == 0) halCtls[idx].alsa.numid =-1; + shareHallMap[halCtls[idx].alsa.control].numid = halCtls[idx].alsa.numid; + } + + alsaHalBinding.v1.prefix= alsaHalSndCard.prefix; + alsaHalBinding.v1.info = alsaHalSndCard.info; + return &alsaHalBinding; /* returns the description of the binding */ +}; diff --git a/HAL-afb/HAL-interface/hal-interface.h b/HAL-afb/HAL-interface/hal-interface.h new file mode 100644 index 0000000..cebbd21 --- /dev/null +++ b/HAL-afb/HAL-interface/hal-interface.h @@ -0,0 +1,62 @@ +/* + * AlsaLibMapping -- provide low level interface with AUDIO 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 SHAREHALLIB_H +#define SHAREHALLIB_H + +#include +#include "audio-interface.h" + +typedef struct { + halCtlsEnumT control; + int numid; + halGroupEnumT group; + int values; + int minval; + int maxval; + int step; + halAclEnumT acl; +} alsaHalCtlMapT; + +// avoid compiler warning [Jose does not like typedef :) ] +typedef struct afb_service alsaHalServiceT; + +typedef struct { + struct json_object* (*callback)(alsaHalServiceT service, int control, int value, alsaHalCtlMapT *map, void* handle); + void* handle; +} alsaHalCbMapT; + +typedef struct { + alsaHalCtlMapT alsa; + alsaHalCbMapT cb; + char* info; +} alsaHalMapT; + +typedef struct { + const char *prefix; + const char *name; + const char *info; + alsaHalMapT *ctls; + int (*initCB) (const struct afb_binding_interface *itf, struct afb_service service); + +} alsaHalSndCardT; + +PUBLIC alsaHalSndCardT alsaHalSndCard; +PUBLIC char* SharedHalLibVersion; + +#endif /* SHAREHALLIB_H */ + diff --git a/HAL-afb/HDA-intel/CMakeLists.txt b/HAL-afb/HDA-intel/CMakeLists.txt new file mode 100644 index 0000000..26be621 --- /dev/null +++ b/HAL-afb/HDA-intel/CMakeLists.txt @@ -0,0 +1,41 @@ +########################################################################### +# Copyright 2015, 2016, 2017 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. +########################################################################### + + +# Add target to project dependency list +PROJECT_TARGET_ADD(hal-intel-hda) + + # Define project Targets + ADD_LIBRARY(hal-intel-hda MODULE IntelHdaHAL.c) + + # Binder exposes a unique public entry point + SET_TARGET_PROPERTIES(hal-intel-hda PROPERTIES + PREFIX "" + LINK_FLAGS "-Wl,--version-script=${CMAKE_SOURCE_DIR}/export.map" + OUTPUT_NAME intel-hda-binding + ) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(hal-intel-hda + hal-interface + audio-interface + ) + + # installation directory + INSTALL(TARGETS hal-intel-hda + LIBRARY DESTINATION ${binding_install_dir}) diff --git a/HAL-afb/HDA-intel/IntelHdaHAL.c b/HAL-afb/HDA-intel/IntelHdaHAL.c new file mode 100644 index 0000000..bc8fc43 --- /dev/null +++ b/HAL-afb/HDA-intel/IntelHdaHAL.c @@ -0,0 +1,68 @@ +/* + * 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 "hal-interface.h" +#include "audio-interface.h" + +// Force a hard dependency to ShareHallLib +PUBLIC char* SharedHalLibVersion; + +// Init is call after all binding are loaded +STATIC int IntelHalInit (const struct afb_binding_interface *itf, struct afb_service service) { + DEBUG (itf, "IntelHalBinding Initialised"); + + return 0; // 0=OK +} + +/****************************************************************************************** + * alsaCtlsMap link hight level sound control with low level Alsa numid ctls. + * + * To find out which control your sound card uses + * aplay -l + * amixer -D hw:xx controls + * amixer -D hw:xx contents + * amixer -D "hw:3" cget numid=xx + * + * When automatic mapping to Alsa numid is not enough a custom callback might be used + * .cb={.handle=xxxx, .callback=(json_object)MyCtlFunction(struct afb_service service, int controle, int value, const struct alsaHalCtlMapS *map)}; + ********************************************************************************************/ +STATIC alsaHalMapT alsaHalMap[]= { + { .alsa={.control=Master_Playback_Volume,.numid=16,.group=OUTVOL,.values=1,.minval=0,.maxval= 87 ,.step=0,.acl=RW}, .info= "Master Playback Volume" }, + { .alsa={.control=PCM_Playback_Volume ,.numid=27,.group=PCMVOL,.values=2,.minval=0,.maxval= 255,.step=0,.acl=RW}, .info= "PCM Playback Volume" }, + { .alsa={.control=PCM_Playback_Switch ,.numid=17,.group=SWITCH,.values=1,.minval=0,.maxval= 1 ,.step=0,.acl=RW}, .info= "Master Playback Switch" }, + { .alsa={.control=Capture_Volume ,.numid=12,.group=INVOL ,.values=2,.minval=0,.maxval= 31 ,.step=0,.acl=RW}, .info= "Capture Volume" }, + { .alsa={.numid=0}, .cb={.callback=NULL, .handle=NULL}} /* marker for end of the array */ +} ; + +/*********************************************************************************** + * AlsaHalSndT provides + * - cardname used to map a given card to its HAL + * - ctls previously defined AlsaHalMapT control maps + * - info free text + * + * WARNING: name should fit with 'aplay -l' as it used to map from devid to HAL + * you may also retreive shortname when AudioBinder is running from a browser + * http://localhost:1234/api/alsacore/getcardid?devid=hw:xxx + * + ***********************************************************************************/ +PUBLIC alsaHalSndCardT alsaHalSndCard = { + .name = "HDA Intel PCH", + .info = "Hardware Abstraction Layer for IntelHDA sound card", + .ctls = alsaHalMap, + .prefix="intel-hda", + .initCB=IntelHalInit, // if NULL no initcallback +}; diff --git a/HighLevel-afb/CMakeLists.txt b/HighLevel-afb/CMakeLists.txt new file mode 100644 index 0000000..de59686 --- /dev/null +++ b/HighLevel-afb/CMakeLists.txt @@ -0,0 +1,40 @@ +########################################################################### +# Copyright 2015, 2016, 2017 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. +########################################################################### + +# Add target to project dependency list +PROJECT_TARGET_ADD(audio-afb) + + # Define project Targets + ADD_LIBRARY(audio-afb MODULE HighLevelApiConf.c HighLevelBinding.c) + + # Binder exposes a unique public entry point + SET_TARGET_PROPERTIES(audio-afb PROPERTIES + PREFIX "" + LINK_FLAGS "-Wl,--version-script=${CMAKE_SOURCE_DIR}/export.map" + OUTPUT_NAME audio-highlevel-binding + ) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(audio-afb + audio-interface + ${link_libraries} + ) + + # installation directory + INSTALL(TARGETS audio-afb + LIBRARY DESTINATION ${binding_install_dir}) diff --git a/HighLevel-afb/HighLevelApiConf.c b/HighLevel-afb/HighLevelApiConf.c new file mode 100644 index 0000000..75e4a2f --- /dev/null +++ b/HighLevel-afb/HighLevelApiConf.c @@ -0,0 +1,98 @@ +/* + * 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 "HighLevelBinding.h" + +PUBLIC const struct afb_binding_interface *afbIface; + +// Map HAL Enum to Labels +typedef const struct { + halCtlsEnumT control; + char *label; +} LogicControlT; + +// High Level Control Mapping to String for JSON & HTML5 +STATIC LogicControlT LogicControl[] = { + {.control= Master_Playback_Volume,.label= "Master_Volume"}, + {.control= PCM_Playback_Volume, .label= "Playback_Volume"}, + {.control= PCM_Playback_Switch, .label= "Playback_Switch"}, + {.control= Capture_Volume, .label= "Capture_Volume"}, + + {.control= 0,.label= NULL} // closing convention +}; + + +/* + * 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= "setvolume", .session= AFB_SESSION_CHECK, .callback= audioLogicSetVol, .info= "Set Volume" }, + { .name= "getvolume", .session= AFB_SESSION_CHECK, .callback= audioLogicGetVol, .info= "Get Volume" }, + { .name= "subscribe", .session= AFB_SESSION_CHECK, .callback= audioLogicSubscribe, .info= "Subscribe AudioBinding Events" }, + { .name= "monitor", .session= AFB_SESSION_CHECK, .callback= audioLogicMonitor, .info= "Activate AlsaCtl Monitoring" }, + { .name= "open", .session= AFB_SESSION_CREATE,.callback= audioLogicOpen, .info= "Open a Dedicated SoundCard" }, + { .name= "close", .session= AFB_SESSION_CLOSE, .callback= audioLogicClose, .info= "Close previously open SoundCard" }, + { .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= "audio", + .info= "High Level Interface to Audio bindings", + .verbs = binding_verbs + } +}; + +// This receive all event this binding subscribe to +PUBLIC void afbBindingV1ServiceEvent(const char *evtname, struct json_object *object) { + + NOTICE (afbIface, "afbBindingV1ServiceEvent evtname=%s [msg=%s]", evtname, json_object_to_json_string(object)); +} + +// this is call when after all bindings are loaded +PUBLIC int afbBindingV1ServiceInit(struct afb_service service) { + + return (audioLogicInit(service)); +}; + +/* + * activation function for registering the binding called by afb-daemon + */ +PUBLIC 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/HighLevel-afb/HighLevelBinding.c b/HighLevel-afb/HighLevelBinding.c new file mode 100644 index 0000000..df5f2c3 --- /dev/null +++ b/HighLevel-afb/HighLevelBinding.c @@ -0,0 +1,316 @@ +/* + * 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 "HighLevelBinding.h" + +static struct afb_service srvitf; + + +// This callback is fired when afb_service_call for api/alsacore/subctl returns +STATIC void audioLogicSetVolCB(void *handle, int iserror, struct json_object *result) { + struct afb_req request = afb_req_unstore(handle); + + if (!cbCheckResponse(request, iserror, result)) goto OnExit; + +OnExit: + return; +} + +PUBLIC void audioLogicSetVol(struct afb_req request) { + struct json_object *queryurl; + int volume=0; // FULUP TBD !!!!!!!!!!!! + + // keep request for callback to respond + struct afb_req *handle = afb_req_store(request); + + // get client context + AudioLogicCtxT *ctx = afb_req_context_get(request); + + const char *vol = afb_req_value(request, "vol"); + if (vol == NULL) { + afb_req_fail_f(request, "argument-missing", "vol=+-%[0,100] missing"); + goto OnExit; + } + + switch (vol[0]) { + case '+': + break; + case '-': + break; + case '%': + break; + + default: + afb_req_fail_f(request, "value-invalid", "volume should be (+-%[0-100]xxx) vol=%s", vol); + goto OnExit; + } + + if (!ctx->halapi) { + afb_req_fail_f(request, "context-invalid", "No valid halapi in client context"); + goto OnExit; + } + + // ********** Caluler le volume en % de manière intelligente + queryurl = json_object_new_object(); + json_object_object_add(ctx->queryurl, "pcm", json_object_new_int(Master_Playback_Volume)); + json_object_object_add(ctx->queryurl, "value", json_object_new_int(volume)); + + // subcontract HAL API to process volume + afb_service_call(srvitf, ctx->halapi, "volume", queryurl, audioLogicSetVolCB, handle); + + // final success/failure messages handle from callback +OnExit: + return; +} + +// This callback is fired when afb_service_call for api/alsacore/subctl returns + +STATIC void alsaSubcribeCB(void *handle, int iserror, struct json_object *result) { + struct afb_req request = afb_req_unstore(handle); + + if (!cbCheckResponse(request, iserror, result)) goto OnExit; + +OnExit: + return; +} + +// Create and subscribe to alsacore ctl events +PUBLIC void audioLogicMonitor(struct afb_req request) { + + + // get client context + AudioLogicCtxT *ctx = afb_req_context_get(request); + if (!ctx) { + afb_req_fail_f(request, "ctx-notfound", "No Client Context HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); + goto OnExit; + } + + // push request to low level binding + NOTICE(afbIface, "audioLogicMonitor ctx->devid=%s [ctx->queryurl=%s]", ctx->devid, json_object_to_json_string(ctx->queryurl)); + + if (ctx->queryurl) { + json_object_get(ctx->queryurl); // Make sure usage count does not fall to zero + struct afb_req *handle = afb_req_store(request); + afb_service_call(srvitf, "alsacore", "subscribe", ctx->queryurl, alsaSubcribeCB, handle); + } + else afb_req_fail_f(request, "context-invalid", "No valid queryurl in client context"); + + // success/failure messages return from callback +OnExit: + return; +} + +// Subscribe to AudioBinding events + +PUBLIC void audioLogicSubscribe(struct afb_req request) { + + return; +} + + +// Call when all bindings are loaded and ready to accept request +PUBLIC void audioLogicGetVol(struct afb_req request) { + + // Should call here Hardware Alsa Abstraction Layer for corresponding Sound Card + afb_req_success(request, NULL, NULL); + return; + +} + +// This callback is fired when afb_service_call for api/alsacore/subctl returns + +STATIC void audioLogicOpenCB2(void *handle, int iserror, struct json_object *result) { + struct json_object *response; + + // Make sure we got a response from API + struct afb_req request = afb_req_unstore(handle); + if (!cbCheckResponse(request, iserror, result)) goto OnExit; + + // get client context + AudioLogicCtxT *ctx = afb_req_context_get(request); + if (!ctx) { + afb_req_fail_f(request, "ctx-notfound", "No Client Context HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); + goto OnExit; + } + + // Get response from object + json_object_object_get_ex(result, "response", &response); + if (!response) { + afb_req_fail_f(request, "response-notfound", "No Controls return from HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); + goto OnExit; + } + + // extract sounds controls information from received Object + struct json_object *ctls; + json_object_object_get_ex(response, "ctls", &ctls); + if (!ctls) { + afb_req_fail_f(request, "ctls-notfound", "No Controls return from HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); + goto OnExit; + } + + // make sure return controls have a valid type + if (json_object_get_type(ctls) != json_type_array) { + afb_req_fail_f(request, "ctls-notarray", "Invalid Controls return from HAL/getcontrol devid=[%] name=[%s]", ctx->devid, ctx->shortname); + goto OnExit; + } + + // loop on array and store values into client context + for (int idx = 0; idx < json_object_array_length(ctls); idx++) { + struct json_object *ctl; + halCtlsEnumT control; + int value; + + ctl = json_object_array_get_idx(ctls, idx); + if (json_object_array_length(ctl) != 2) { + afb_req_fail_f(request, "ctl-invalid", "Invalid Control return from HAL/getcontrol devid=[%] name=[%s] ctl=%s" + , ctx->devid, ctx->shortname, json_object_get_string(ctl)); + goto OnExit; + } + + // As HAL and Business logic use the same AlsaMixerHal.h direct conversion is not an issue + control = (halCtlsEnumT) json_object_get_int(json_object_array_get_idx(ctl, 0)); + value = json_object_get_int(json_object_array_get_idx(ctl, 1)); + + switch (control) { + case Master_Playback_Volume: + ctx->volumes.masterPlaybackVolume = value; + break; + + case PCM_Playback_Volume: + ctx->volumes.pcmPlaybackVolume = value; + break; + + case PCM_Playback_Switch: + ctx->volumes.pcmPlaybackSwitch = value; + break; + + case Capture_Volume: + ctx->volumes.captureVolume = value; + break; + + default: + NOTICE(afbIface, "audioLogicOpenCB2 unknown HAL control=[%s]", json_object_get_string(ctl)); + } + } + +OnExit: + afb_req_context_set(request, ctx, free); + return; +} + +// This callback is fired when afb_service_call for api/alsacore/subctl returns +STATIC void audioLogicOpenCB1(void *handle, int iserror, struct json_object *result) { + struct json_object *response, *subobj; + + // Make sure we got a valid API response + struct afb_req request = afb_req_unstore(handle); + if (!cbCheckResponse(request, iserror, result)) goto OnExit; + + // Get response from object + json_object_object_get_ex(result, "response", &response); + if (!response) { + afb_req_fail_f(request, "response-notfound", "No Controls return from HAL/getcontrol"); + goto OnExit; + } + + // attach client context to session + AudioLogicCtxT *ctx = malloc(sizeof (AudioLogicCtxT)); + + // extract information from Json Alsa Object + json_object_object_get_ex(response, "cardid", &subobj); + if (subobj) ctx->cardid = json_object_get_int(subobj); + + // store devid as an object for further alsa request + json_object_object_get_ex(response, "devid", &subobj); + if (subobj) ctx->devid = strdup(json_object_get_string(subobj)); + + json_object_object_get_ex(response, "halapi", &subobj); + if (subobj) ctx->halapi = strdup(json_object_get_string(subobj)); + + json_object_object_get_ex(response, "shortname", &subobj); + if (subobj)ctx->shortname = strdup(json_object_get_string(subobj)); + + json_object_object_get_ex(response, "longname", &subobj); + if (subobj)ctx->longname = strdup(json_object_get_string(subobj)); + + // save queryurl with devid only for further ALSA request + ctx->queryurl = json_object_new_object(); + json_object_object_add(ctx->queryurl, "devid", json_object_new_string(ctx->devid)); + + afb_req_context_set(request, ctx, free); + + // sound card was find let's store keycontrols into client session + if (!ctx->halapi) { + afb_req_fail_f(request, "hal-notfound", "No HAL found devid=[%] name=[%s]", ctx->devid, ctx->shortname); + goto OnExit; + } + + struct json_object *queryurl = json_object_new_object(); + struct json_object *ctls = json_object_new_array(); + + // add sound controls we want to keep track of into client session context + json_object_array_add(ctls, json_object_new_int((int) Master_Playback_Volume)); + json_object_array_add(ctls, json_object_new_int((int) PCM_Playback_Volume)); + json_object_array_add(ctls, json_object_new_int((int) PCM_Playback_Switch)); + json_object_array_add(ctls, json_object_new_int((int) Capture_Volume)); + + // send request to soundcard HAL binding + json_object_object_add(queryurl, "ctls", ctls); + handle = afb_req_store(request); // FULUP ???? Needed for 2nd Callback ???? + afb_service_call(srvitf, ctx->halapi, "getControl", queryurl, audioLogicOpenCB2, handle); + + afb_req_success(request, response, NULL); + +OnExit: + // release original calling request + afb_req_unref(request); + return; +} + +// Delegate to lowerlevel the mapping of soundcard name with soundcard ID +PUBLIC void audioLogicOpen(struct afb_req request) { + + // Delegate query to lower level + struct afb_req *handle = afb_req_store(request); + afb_service_call(srvitf, "alsacore", "getCardId", json_object_get(afb_req_json(request)), audioLogicOpenCB1, handle); +} + +// Free client context create from audioLogicOpenCB +PUBLIC void audioLogicClose(struct afb_req request) { + + // retrieve current client context to print debug info + AudioLogicCtxT *ctx = (AudioLogicCtxT*) afb_req_context_get(request); + DEBUG(afbIface, "audioLogicClose cardid=%d devid=%s shortname=%s longname=%s", ctx->cardid, ctx->devid, ctx->shortname, ctx->longname); +} + + +// this function is call after all binder are loaded and initialised +PUBLIC int audioLogicInit(struct afb_service service) { + srvitf = service; + return 0; +} diff --git a/HighLevel-afb/HighLevelBinding.h b/HighLevel-afb/HighLevelBinding.h new file mode 100644 index 0000000..a2ca61c --- /dev/null +++ b/HighLevel-afb/HighLevelBinding.h @@ -0,0 +1,58 @@ +/* + * AlsaLibMapping -- provide low level interface with AUDIO 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 AUDIOLOGIC_H +#define AUDIOLOGIC_H + +#include +#include +#include + +#include "audio-interface.h" + +// import from AlsaAfbBinding +extern const struct afb_binding_interface *afbIface; + + +// This structure hold private data for a given client of binding +typedef struct { + + int cardid; + const char *devid; + const char *shortname; + const char *longname; + const char *halapi; + struct { // volume in % [0-100] + int masterPlaybackVolume; + int pcmPlaybackVolume; + int pcmPlaybackSwitch; + int captureVolume; + } volumes; + json_object *queryurl; +} AudioLogicCtxT; + +// import from AlsaAfbMapping +PUBLIC void audioLogicSetVol (struct afb_req request); +PUBLIC void audioLogicGetVol(struct afb_req request); +PUBLIC void audioLogicMonitor(struct afb_req request); +PUBLIC void audioLogicOpen(struct afb_req request); +PUBLIC void audioLogicClose(struct afb_req request); +PUBLIC void audioLogicSubscribe(struct afb_req request); +PUBLIC int audioLogicInit (struct afb_service service); + +#endif /* AUDIOLOGIC_H */ + diff --git a/HighLevel-afb/README.md b/HighLevel-afb/README.md new file mode 100644 index 0000000..fa50173 --- /dev/null +++ b/HighLevel-afb/README.md @@ -0,0 +1,35 @@ +------------------------------------------------------------------------ + AudioLogic High Level APIs +------------------------------------------------------------------------ + +Testing: (from project directory bindings) + * start binder: ~/opt/bin/afb-daemon --ldpaths=./build --token=mysecret --roothttp=htdocs + * connect browser on http://localhost:1234?devid=hw:0 + + # Open Sound Card from its name + http://localhost:1234/api/audio/open?token=mysecret&sndname=H650e + + # Subscribe event for a given board + http://localhost:1234/api/audio/subscribe?token=mysecret&devid=hw:0 + + # Increase Volume + http://localhost:1234/api/audio/setvol?token=mysecret&devid=hw:0&pcm=master&vol=50% + + # Get Volume + http://localhost:1234/api/audio/getvol?token=mysecret&devid=hw:0&pcm=master + + # Close Session + http://localhost:1234/api/audio/close?token=mysecret + + +Testing with afb-client-demo + +``` +~/opt/bin/afb-client-demo localhost:1234/api?token=mysecret +alsacore subctl {"devid":"hw:0"} +``` + +Start AlsaMixer and change volume +``` +alsamixer -D hw:0 +``` \ No newline at end of file diff --git a/README.md b/README.md index 2e54890..ce0790c 100644 --- a/README.md +++ b/README.md @@ -19,31 +19,29 @@ AFB_daemon dependency on Standard Linux Distributions libopenssl-devel libgcrypt-devel libgnutls-devel (optional but requested by libmicrohttpd for https) OpenSuse >=42.2 - zypper in gcc5 gdb gcc5-c++ cmake ElectricFence systemd-devel libopenssl-devel libuuid-devel alsa-devel libgcrypt-devel libgnutls-devel libjson-c-devel file-devel + zypper in gcc5 gdb gcc5-c++ cit make ElectricFence systemd-devel libopenssl-devel libuuid-devel alsa-devel libgcrypt-devel libgnutls-devel libjson-c-devel file-devel Ubuntu >= 16.4libuuid-devel - apt-get install cmake electric-fence libsystemd-dev libssl-dev uuid-dev libasound2-dev libgcrypt20-dev libgnutls-dev libgnutls-dev libjson-c-dev libmagic-dev + apt-get install cmake git electric-fence libsystemd-dev libssl-dev uuid-dev libasound2-dev libgcrypt20-dev libgnutls-dev libgnutls-dev libjson-c-dev libmagic-dev libmicrohttpd with AGL patches http://iot.bzh/download/public/2016/appfw/libmicrohttpd-0.9.49-agl.tgz afb-daemon from AGL Gerrit git clone https://gerrit.automotivelinux.org/gerrit/src/app-framework-binder ``` # Might want to add following variables into ~/.bashrc - # export CC=gcc-5; export CXX=g++-5 # if using gcc5 - - echo 'export LIBPOSTFIX=64'>>~/.bashrc + export CC=gcc-5; export CXX=g++-5 # if using gcc5 echo 'export DEST=$HOME/opt' >>~/.bashrc - echo 'export LD_LIBRARY_PATH=$DEST/lib${LIBPOSTFIX}' >>~/.bashrc - echo 'export LIBRARY_PATH=$DEST/lib${LIBPOSTFIX}' >>~/.bashrc - echo 'export PKG_CONFIG_PATH=$DEST/lib${LIBPOSTFIX}/pkgconfig' >>~/.bashrc - echo 'export PATH=$DEST/bin:$PATH' >>~/.bashrc + echo 'export LD_LIBRARY_PATH=$INSTALL_DIR/lib64:$INSTALL_DIR/lib' >>~/.bashrc + echo 'export LIBRARY_PATH=$INSTALL_DIR/lib64:$INSTALL_DIR/lib' >>~/.bashrc + echo 'export PKG_CONFIG_PATH=$INSTALL_DIR/lib64/pkgconfig:$INSTALL_DIR/lib/pkgconfig' >>~/.bashrc + echo 'export PATH=$INSTALL_DIR/bin:$PATH' >>~/.bashrc source ~/.bashrc # install AGL pached version of LibMicroHttpd wget http://iot.bzh/download/public/2016/appfw/libmicrohttpd-0.9.49-agl.tgz tar -xzf libmicrohttpd-0.9.49-agl.tgz cd libmicrohttpd-0.9.49-agl - ./configure --prefix=$DEST + ./configure --prefix=$INSTALL_DIR make make install-strip @@ -52,7 +50,7 @@ AFB_daemon dependency on Standard Linux Distributions # Warning: previous GCC options should be set before initial cmake (clean Build/*) cd app-framework-binder; mkdir build; cd build - cmake -DCMAKE_INSTALL_PREFIX=$DEST .. + cmake -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR .. make make install ``` @@ -66,17 +64,16 @@ cd build cmake -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR .. make make install -ls # Start the binder # From Development Tree - mkdir $DEST/share/wssocks - afb-daemon --verbose --token="" --ldpaths=./build --port=1234 --roothttp=./htdoc --ws-server=unix:$DEST/share/wssocks/alsacore + mkdir $INSTALL_DIR/share/wssocks + afb-daemon --verbose --token="" --ldpaths=./build --port=1234 --roothttp=./htdocs # From $INSTALL_DIR mkdir $INSTALL_DIR/share/wssocks - afb-daemon --verbose --token="" --ldpaths=$INSTALL_DIR/lib/audio --port=1234 --roothttp=$INSTALL_DIR/htdocs/audio-bindings --ws-server=unix:$INSTALL_DIR/share/wssocks/alsacore + afb-daemon --verbose --token="" --ldpaths=$INSTALL_DIR/lib/audio --port=1234 --roothttp=$INSTALL_DIR/htdocs/audio-bindings ``` # replace hd:XX with your own sound card ID ex: "hw:0", "hw:PCH", ... Start a browser on http://localhost:1234?devid=hw:XX diff --git a/cd b/cd deleted file mode 100644 index e69de29..0000000 diff --git a/etc/config.cmake b/etc/config.cmake new file mode 100644 index 0000000..f8d11dc --- /dev/null +++ b/etc/config.cmake @@ -0,0 +1,64 @@ +########################################################################### +# Copyright 2015, 2016, 2017 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. +########################################################################### + +# Project Info +# ------------------ + set(NAME audio-bindings) + set(VERSION "1.0") + set(PRETTY_NAME "Audio Bindings") + set(DESCRIPTION "Expose ALSA Sound Low+High Level APIs through AGL Framework") + set(URL "https://github.com/iotbzh/auto-bindings") + +# Compilation Mode (DEBUG, RELEASE) +# ---------------------------------- + setc(CMAKE_BUILD_TYPE "DEBUG") + +# PKG_CONFIG required packages +# ----------------------------- + set (PKG_REQUIRED_LIST + alsa + json-c + afb-daemon + ) + +# Static constante definition +# ----------------------------- + add_compile_options(-DMAX_SND_CARD=16) + add_compile_options(-DCONTROL_CDEV_RX="/dev/inic-usb-crx") + +# Optional dependencies order +# --------------------------- + #set(EXTRA_DEPENDENCY_ORDER target1 target2 ...) + +# Optional Extra global include path +# ------------------------------------ + #set(EXTRA_INCLUDE_DIRS incdir1 incdir2 ...) + +# Optional extra libraries +# ------------------------- + # set(EXTRA_LINK_LIBRARIES lib1 lib2 ... ) + +# Install default destination +# -------------------------------- + set(binding_install_dir ${CMAKE_INSTALL_FULL_LIBDIR}/${PROJECT_NAME}) + +# Print a helper message when every thing is finished +# ---------------------------------------------------- + setc(CLOSING_MESSAGE "Test with: afb-daemon --ldpaths=. --port=1234 --roothttp=../htdocs --tracereq=common --token="" --verbose") + + diff --git a/htdocs/CMakeLists.txt b/htdocs/CMakeLists.txt index 22a4d63..1266d70 100644 --- a/htdocs/CMakeLists.txt +++ b/htdocs/CMakeLists.txt @@ -18,7 +18,6 @@ - ################################################## # HTML Testing Files ################################################## diff --git a/nbproject/configurations.xml b/nbproject/configurations.xml index dbdc7fc..370176d 100644 --- a/nbproject/configurations.xml +++ b/nbproject/configurations.xml @@ -2,14 +2,6 @@ - - - - AlsaHalIface.h - AudioCommonLib.h - - - ConnectionInfo.cpp @@ -65,16 +57,6 @@ true - - - - diff --git a/nbproject/project.xml b/nbproject/project.xml index be8b144..144cd73 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -3,7 +3,7 @@ org.netbeans.modules.cnd.makeproject - AGL-AudioBindings + Audio-Bindings c cpp,cxx h -- cgit 1.2.3-korg