From 39a6570c92b25dd127a546829f8224e84805d297 Mon Sep 17 00:00:00 2001 From: w30042960 Date: Mon, 29 Jan 2024 20:50:22 +0800 Subject: [PATCH] modify json to cjson Signed-off-by: w30042960 --- audiohandler/BUILD.gn | 6 +- audiohandler/include/daudio_handler.h | 3 + audiohandler/src/daudio_handler.cpp | 70 ++++-- bundle.json | 1 - common/include/daudio_util.h | 10 +- common/src/daudio_util.cpp | 63 +++-- .../managersink/include/daudio_sink_dev.h | 8 +- .../managersink/src/daudio_sink_dev.cpp | 141 +++++++---- .../managersink/src/daudio_sink_manager.cpp | 8 +- .../managersource/include/daudio_source_dev.h | 8 +- .../managersource/include/dmic_dev.h | 4 +- .../managersource/include/dspeaker_dev.h | 4 +- .../managersource/src/daudio_source_dev.cpp | 232 +++++++++++++----- .../src/daudio_source_manager.cpp | 38 ++- .../managersource/src/dmic_dev.cpp | 32 ++- .../managersource/src/dspeaker_dev.cpp | 30 ++- 16 files changed, 446 insertions(+), 212 deletions(-) diff --git a/audiohandler/BUILD.gn b/audiohandler/BUILD.gn index ef27e252..3c7d387e 100644 --- a/audiohandler/BUILD.gn +++ b/audiohandler/BUILD.gn @@ -25,6 +25,7 @@ ohos_shared_library("distributed_audio_handler") { stack_protector_ret = true include_dirs = [ "//third_party/json/include", + "//third_party/cJSON", "${fwk_common_path}/utils/include", "${fwk_utils_path}/include", "${mediastandardfwk_path}/audiomanager/include", @@ -40,7 +41,10 @@ ohos_shared_library("distributed_audio_handler") { sources = [ "src/daudio_handler.cpp" ] - deps = [ "${services_path}/common:distributed_audio_utils" ] + deps = [ + "${services_path}/common:distributed_audio_utils", + "//third_party/cJSON:cjson", + ] external_deps = [ "audio_framework:audio_capturer", diff --git a/audiohandler/include/daudio_handler.h b/audiohandler/include/daudio_handler.h index 4b79ea82..483a44f8 100644 --- a/audiohandler/include/daudio_handler.h +++ b/audiohandler/include/daudio_handler.h @@ -18,6 +18,8 @@ #include +#include "cJSON.h" + #include "ihardware_handler.h" #include "single_instance.h" #include "audio_param.h" @@ -57,6 +59,7 @@ private: ~DAudioHandler(); int32_t QueryCodecInfo(); int32_t QueryAudioInfo(); + void AddItemsToObject(DHItem &dhItem, cJSON *infoJson, const int32_t &dhId); void GetSupportAudioInfo(AudioInfo &audioInfos, CoderInfo &encoderInfos, CoderInfo &decoderInfos); private: diff --git a/audiohandler/src/daudio_handler.cpp b/audiohandler/src/daudio_handler.cpp index b12f08c7..3cbcbeb1 100644 --- a/audiohandler/src/daudio_handler.cpp +++ b/audiohandler/src/daudio_handler.cpp @@ -19,7 +19,6 @@ #include "audio_system_manager.h" #include "avcodec_list.h" -#include "nlohmann/json.hpp" #include "string_ex.h" #include "histreamer_query_tool.h" @@ -31,8 +30,6 @@ #undef DH_LOG_TAG #define DH_LOG_TAG "DAudioHandler" -using json = nlohmann::json; - namespace OHOS { namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(DAudioHandler); @@ -68,6 +65,29 @@ int32_t DAudioHandler::Initialize() return ret; } +void DAudioHandler::AddItemsToObject(DHItem &dhItem, cJSON* infoJson, const int32_t &dhId) +{ + DHLOGD("Get dhId and then add other items into cjson object"); + int32_t deviceType = GetDevTypeByDHId(dhId); + if (deviceType == AUDIO_DEVICE_TYPE_MIC) { + dhItem.subtype = "mic"; + cJSON_AddItemToObject(infoJson, "SampleRates", + cJSON_CreateIntArray(micInfos_.sampleRates.data(), micInfos_.sampleRates.size())); + cJSON_AddItemToObject(infoJson, "ChannelMasks", + cJSON_CreateIntArray(micInfos_.channels.data(), micInfos_.channels.size())); + cJSON_AddItemToObject(infoJson, "Formats", + cJSON_CreateIntArray(micInfos_.formats.data(), micInfos_.formats.size())); + } else if (deviceType == AUDIO_DEVICE_TYPE_SPEAKER) { + dhItem.subtype = "speaker"; + cJSON_AddItemToObject(infoJson, "SampleRates", + cJSON_CreateIntArray(spkInfos_.sampleRates.data(), spkInfos_.sampleRates.size())); + cJSON_AddItemToObject(infoJson, "ChannelMasks", + cJSON_CreateIntArray(spkInfos_.channels.data(), spkInfos_.channels.size())); + cJSON_AddItemToObject(infoJson, "Formats", + cJSON_CreateIntArray(spkInfos_.formats.data(), spkInfos_.formats.size())); + } +} + std::vector DAudioHandler::Query() { DHLOGI("Query distributed hardware information."); @@ -82,43 +102,41 @@ std::vector DAudioHandler::Query() for (auto dev : audioDevices) { auto dhId = audioSrv->GetPinValueFromType(dev->deviceType_, dev->deviceRole_); - json infoJson; - DHItem dhItem; - int32_t deviceType = GetDevTypeByDHId(dhId); - if (deviceType == AUDIO_DEVICE_TYPE_MIC) { - dhItem.subtype = "mic"; - infoJson["SampleRates"] = micInfos_.sampleRates; - infoJson["ChannelMasks"] = micInfos_.channels; - infoJson["Formats"] = micInfos_.formats; - } else if (deviceType == AUDIO_DEVICE_TYPE_SPEAKER) { - dhItem.subtype = "speaker"; - infoJson["SampleRates"] = spkInfos_.sampleRates; - infoJson["ChannelMasks"] = spkInfos_.channels; - infoJson["Formats"] = spkInfos_.formats; + cJSON* infoJson = cJSON_CreateObject(); + if (infoJson == nullptr) { + DHLOGE("Failed to create cJSON object."); + return dhItemVec; } - infoJson["INTERRUPT_GROUP_ID"] = dev->interruptGroupId_; - infoJson["VOLUME_GROUP_ID"] = dev->volumeGroupId_; - + DHItem dhItem; + AddItemsToObject(dhItem, infoJson, dhId); + cJSON_AddNumberToObject(infoJson, "INTERRUPT_GROUP_ID", dev->interruptGroupId_); + cJSON_AddNumberToObject(infoJson, "VOLUME_GROUP_ID", dev->volumeGroupId_); std::string audioEncoders = HiStreamerQueryTool::GetInstance().QueryHiStreamerPluginInfo(HISTREAM_PLUGIN_TYPE::AUDIO_ENCODER); DHLOGI("DAudio QueryAudioEncoderAbility info: %s", audioEncoders.c_str()); - infoJson[KEY_HISTREAMER_AUDIO_ENCODER] = audioEncoders; + cJSON_AddStringToObject(infoJson, KEY_HISTREAMER_AUDIO_ENCODER.c_str(), audioEncoders.c_str()); std::string audioDecoders = HiStreamerQueryTool::GetInstance().QueryHiStreamerPluginInfo(HISTREAM_PLUGIN_TYPE::AUDIO_DECODER); DHLOGI("DAudio QueryAudioDecoderAbility info: %s", audioDecoders.c_str()); - infoJson[KEY_HISTREAMER_AUDIO_DECODER] = audioDecoders; - + cJSON_AddStringToObject(infoJson, KEY_HISTREAMER_AUDIO_DECODER.c_str(), audioDecoders.c_str()); dhItem.dhId = std::to_string(dhId); - dhItem.attrs = infoJson.dump(); + char *jsonInfo = cJSON_Print(infoJson); + if (jsonInfo == NULL) { + DHLOGE("Failed to create JSON data."); + cJSON_Delete(infoJson); + return dhItemVec; + } + dhItem.attrs = jsonInfo; dhItemVec.push_back(dhItem); - DHLOGD("Query result: dhId: %d, subtype: %s, attrs: %s.", dhId, dhItem.subtype.c_str(), - infoJson.dump().c_str()); + DHLOGD("Query result: dhId: %d, subtype: %s, attrs: %s.", dhId, dhItem.subtype.c_str(), jsonInfo); if (dhId == DEFAULT_RENDER_ID) { dhItem.dhId = std::to_string(LOW_LATENCY_RENDER_ID); dhItemVec.push_back(dhItem); - DHLOGD("Query result: dhId: %d, attrs: %s.", LOW_LATENCY_RENDER_ID, infoJson.dump().c_str()); + DHLOGD("Query result: dhId: %d, attrs: %s.", LOW_LATENCY_RENDER_ID, jsonInfo); } + cJSON_Delete(infoJson); + cJSON_free(jsonInfo); } ablityForDumpVec_ = dhItemVec; return dhItemVec; diff --git a/bundle.json b/bundle.json index 4d74f225..de77d2c6 100755 --- a/bundle.json +++ b/bundle.json @@ -51,7 +51,6 @@ "samgr" ], "third_party": [ - "json", "cJSON" ] }, diff --git a/common/include/daudio_util.h b/common/include/daudio_util.h index e7c3a577..63dad1b1 100644 --- a/common/include/daudio_util.h +++ b/common/include/daudio_util.h @@ -19,11 +19,8 @@ #include #include #include -#include "nlohmann/json.hpp" #include "cJSON.h" -using json = nlohmann::json; - #define AUDIO_MS_PER_SECOND 1000 #define AUDIO_US_PER_SECOND 1000000 #define AUDIO_NS_PER_SECOND ((int64_t)1000000000) @@ -37,11 +34,10 @@ int64_t GetNowTimeUs(); int32_t GetAudioParamStr(const std::string ¶ms, const std::string &key, std::string &value); int32_t GetAudioParamBool(const std::string ¶ms, const std::string &key, bool &value); int32_t GetAudioParamInt(const std::string ¶ms, const std::string &key, int32_t &value); -bool JsonParamCheck(const json &jsonObj, const std::initializer_list &key); bool CJsonParamCheck(const cJSON *jsonObj, const std::initializer_list &keys); -bool IsString(const json &jsonObj, const std::string &key); -bool IsInt32(const json &jsonObj, const std::string &key); -bool IsAudioParam(const json &jsonObj, const std::string &key); +bool IsString(const cJSON *jsonObj, const std::string &key); +bool IsInt32(const cJSON *jsonObj, const std::string &key); +bool IsAudioParam(const cJSON *jsonObj, const std::string &key); int32_t CalculateSampleNum(uint32_t sampleRate, uint32_t timems); int64_t GetCurNano(); int32_t AbsoluteSleep(int64_t nanoTime); diff --git a/common/src/daudio_util.cpp b/common/src/daudio_util.cpp index 78f50ed5..4ee5e277 100644 --- a/common/src/daudio_util.cpp +++ b/common/src/daudio_util.cpp @@ -36,7 +36,7 @@ namespace OHOS { namespace DistributedHardware { -using JsonTypeCheckFunc = bool (*)(const json &jsonObj, const std::string &key); +using JsonTypeCheckFunc = bool (*)(const cJSON *jsonObj, const std::string &key); constexpr int32_t WORD_WIDTH_8 = 8; constexpr int32_t WORD_WIDTH_4 = 4; constexpr size_t INT32_SHORT_ID_LENGTH = 20; @@ -261,19 +261,19 @@ int32_t GetAudioParamInt(const std::string ¶ms, const std::string &key, int3 return DH_SUCCESS; } -bool JsonParamCheck(const json &jsonObj, const std::initializer_list &keys) +bool CJsonParamCheck(const cJSON *jsonObj, const std::initializer_list &keys) { - if (jsonObj.is_discarded()) { - DHLOGE("Json parameter is invalid."); + if (jsonObj == nullptr || !cJSON_IsObject(jsonObj)) { + DHLOGE("JSON parameter is invalid."); return false; } for (auto it = keys.begin(); it != keys.end(); it++) { - if (!jsonObj.contains(*it)) { - DHLOGE("Json parameter not contain param(%s).", (*it).c_str()); + cJSON *paramValue = cJSON_GetObjectItemCaseSensitive(jsonObj, (*it).c_str()); + if (paramValue == nullptr) { + DHLOGE("JSON parameter does not contain key: %s", (*it).c_str()); return false; } - auto iter = typeCheckMap.find(*it); if (iter == typeCheckMap.end()) { DHLOGE("Check is not supported yet, key %s.", (*it).c_str()); @@ -282,14 +282,14 @@ bool JsonParamCheck(const json &jsonObj, const std::initializer_listsecond; bool res = (*func)(jsonObj, *it); if (!res) { - DHLOGE("The key %s value format in json is illegal.", (*it).c_str()); + DHLOGE("The key %s value format in JSON is illegal.", (*it).c_str()); return false; } } return true; } -static bool IsString(const cJSON *jsonObj, const std::string &key) +bool IsString(const cJSON *jsonObj, const std::string &key) { if (jsonObj == nullptr || !cJSON_IsObject(jsonObj)) { DHLOGE("JSON parameter is invalid."); @@ -307,41 +307,40 @@ static bool IsString(const cJSON *jsonObj, const std::string &key) return false; } -bool CJsonParamCheck(const cJSON *jsonObj, const std::initializer_list &keys) +bool IsInt32(const cJSON *jsonObj, const std::string &key) { if (jsonObj == nullptr || !cJSON_IsObject(jsonObj)) { DHLOGE("JSON parameter is invalid."); return false; } + cJSON *paramValue = cJSON_GetObjectItemCaseSensitive(jsonObj, key.c_str()); + if (paramValue == nullptr) { + DHLOGE("paramValue is null"); + return false; + } - for (auto it = keys.begin(); it != keys.end(); it++) { - cJSON *paramValue = cJSON_GetObjectItemCaseSensitive(jsonObj, (*it).c_str()); - if (paramValue == nullptr) { - DHLOGE("JSON parameter does not contain key: %s", (*it).c_str()); - return false; - } - bool res = IsString(jsonObj, *it); - if (!res) { - DHLOGE("The key %s value format in JSON is illegal.", (*it).c_str()); - return false; + if (cJSON_IsNumber(paramValue)) { + int value = paramValue->valueint; + if (INT32_MIN <= value && value <= INT32_MAX) { + return true; } } - return true; -} - -bool IsString(const json &jsonObj, const std::string &key) -{ - return jsonObj[key].is_string(); + return false; } -bool IsInt32(const json &jsonObj, const std::string &key) +bool IsAudioParam(const cJSON *jsonObj, const std::string &key) { - return jsonObj[key].is_number_integer() && INT32_MIN <= jsonObj[key] && jsonObj[key] <= INT32_MAX; -} + if (jsonObj == nullptr || !cJSON_IsObject(jsonObj)) { + DHLOGE("JSON parameter is invalid."); + return false; + } + cJSON *paramValue = cJSON_GetObjectItemCaseSensitive(jsonObj, key.c_str()); + if (paramValue == nullptr || !cJSON_IsObject(paramValue)) { + DHLOGE("paramValue is null or is not object"); + return false; + } -bool IsAudioParam(const json &jsonObj, const std::string &key) -{ - return JsonParamCheck(jsonObj[key], + return CJsonParamCheck(paramValue, { KEY_SAMPLING_RATE, KEY_CHANNELS, KEY_FORMAT, KEY_SOURCE_TYPE, KEY_CONTENT_TYPE, KEY_STREAM_USAGE }); } diff --git a/services/audiomanager/managersink/include/daudio_sink_dev.h b/services/audiomanager/managersink/include/daudio_sink_dev.h index 87841dfd..052412ea 100644 --- a/services/audiomanager/managersink/include/daudio_sink_dev.h +++ b/services/audiomanager/managersink/include/daudio_sink_dev.h @@ -20,9 +20,9 @@ #include #include #include +#include "cJSON.h" #include "event_handler.h" -#include "nlohmann/json.hpp" #include "daudio_sink_dev_ctrl_mgr.h" #include "dmic_client.h" @@ -34,8 +34,6 @@ #include "i_av_receiver_engine_callback.h" #include "idaudio_sink_ipc_callback.h" -using json = nlohmann::json; - namespace OHOS { namespace DistributedHardware { enum class ChannelState { @@ -74,11 +72,13 @@ private: int32_t TaskDisableDevice(const std::string &args); void NotifySourceDev(const AudioEventType type, const std::string dhId, const int32_t result); - int32_t from_json(const json &j, AudioParam &audioParam); + int32_t from_json(const cJSON *j, AudioParam &audioParam); int32_t HandleEngineMessage(uint32_t type, std::string content, std::string devId); int32_t SendAudioEventToRemote(const AudioEvent &event); void PullUpPage(); + int32_t GetParamValue(const cJSON *j, const char* key, int32_t &value); + int32_t GetCJsonObjectItems(const cJSON *j, AudioParam &audioParam); int32_t ParseDhidFromEvent(std::string args); int32_t ConvertString2Int(std::string val); diff --git a/services/audiomanager/managersink/src/daudio_sink_dev.cpp b/services/audiomanager/managersink/src/daudio_sink_dev.cpp index 5a621858..956afa41 100644 --- a/services/audiomanager/managersink/src/daudio_sink_dev.cpp +++ b/services/audiomanager/managersink/src/daudio_sink_dev.cpp @@ -18,8 +18,6 @@ #include -#include "cJSON.h" - #include "daudio_constants.h" #include "daudio_errorcode.h" #include "daudio_log.h" @@ -122,11 +120,14 @@ int32_t DAudioSinkDev::TaskOpenDSpeaker(const std::string &args) if (args.length() > DAUDIO_MAX_JSON_LEN || args.empty()) { return ERR_DH_AUDIO_SA_PARAM_INVALID; } - json jParam = json::parse(args, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DH_ID, KEY_AUDIO_PARAM })) { + cJSON *jParam = cJSON_Parse(args.c_str()); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + if (!CJsonParamCheck(jParam, { KEY_DH_ID, KEY_AUDIO_PARAM })) { + cJSON_Delete(jParam); + DHLOGE("Not found the keys."); return ERR_DH_AUDIO_FAILED; } - int32_t dhId = ConvertString2Int(std::string(jParam[KEY_DH_ID])); + int32_t dhId = ConvertString2Int(std::string(cJSON_GetObjectItem(jParam, KEY_DH_ID)->valuestring)); CHECK_AND_RETURN_RET_LOG(dhId == -1, ERR_DH_AUDIO_NULLPTR, "%s", "Parse dhId error."); std::shared_ptr speakerClient = nullptr; @@ -134,15 +135,20 @@ int32_t DAudioSinkDev::TaskOpenDSpeaker(const std::string &args) std::lock_guard devLck(spkClientMutex_); speakerClient = spkClientMap_[dhId]; } + cJSON *audioParamJson = cJSON_GetObjectItem(jParam, KEY_AUDIO_PARAM); AudioParam audioParam; - int32_t ret = from_json(jParam[KEY_AUDIO_PARAM], audioParam); - CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, - "Get audio param from json failed, error code %d.", ret); + int32_t ret = from_json(audioParamJson, audioParam); + if (ret != DH_SUCCESS) { + DHLOGE("Get audio param from cjson failed, error code %d.", ret); + cJSON_Delete(jParam); + return ret; + } CHECK_NULL_RETURN(speakerClient, ERR_DH_AUDIO_NULLPTR); ret = speakerClient->SetUp(audioParam); CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "Setup speaker failed, ret: %d.", ret); isSpkInUse_.store(true); + cJSON_Delete(jParam); return ret; } @@ -221,18 +227,27 @@ int32_t DAudioSinkDev::TaskOpenDMic(const std::string &args) if (args.length() > DAUDIO_MAX_JSON_LEN || args.empty()) { return ERR_DH_AUDIO_SA_PARAM_INVALID; } - json jParam = json::parse(args, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DH_ID, KEY_AUDIO_PARAM })) { + cJSON *jParam = cJSON_Parse(args.c_str()); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + if (!CJsonParamCheck(jParam, { KEY_DH_ID, KEY_AUDIO_PARAM })) { + DHLOGE("Not found the keys."); + cJSON_Delete(jParam); return ERR_DH_AUDIO_FAILED; } AudioParam audioParam; - int32_t ret = from_json(jParam[KEY_AUDIO_PARAM], audioParam); + cJSON *audioParamJson = cJSON_GetObjectItem(jParam, KEY_AUDIO_PARAM); + int32_t ret = from_json(audioParamJson, audioParam); + if (ret != DH_SUCCESS) { + DHLOGE("Get audio param from json failed, error code %d.", ret); + cJSON_Delete(jParam); + return ret; + } CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, - "Get audio param from json failed, error code %d.", ret); - micDhId_ = std::string(jParam[KEY_DH_ID]); - int32_t dhId = ConvertString2Int(std::string(jParam[KEY_DH_ID])); + "Get audio param from cjson failed, error code %d.", ret); + int32_t dhId = ParseDhidFromEvent(args); CHECK_AND_RETURN_RET_LOG(dhId == -1, ERR_DH_AUDIO_NULLPTR, "%s", "Parse dhId error."); + micDhId_ = std::to_string(dhId); std::shared_ptr micClient = nullptr; { std::lock_guard devLck(micClientMutex_); @@ -247,6 +262,7 @@ int32_t DAudioSinkDev::TaskOpenDMic(const std::string &args) "Start capture failed, ret: %d.", ret); PullUpPage(); isMicInUse_.store(true); + cJSON_Delete(jParam); return ret; } @@ -438,29 +454,40 @@ void DAudioSinkDev::NotifySourceDev(const AudioEventType type, const std::string { std::random_device rd; const uint32_t randomTaskCode = rd(); - json jEvent; - jEvent[KEY_DH_ID] = dhId; - jEvent[KEY_RESULT] = result; - jEvent[KEY_EVENT_TYPE] = type; - jEvent[KEY_RANDOM_TASK_CODE] = std::to_string(randomTaskCode); + cJSON *jEvent = cJSON_CreateObject(); + CHECK_NULL_VOID(jEvent); + cJSON_AddStringToObject(jEvent, KEY_DH_ID, dhId.c_str()); + cJSON_AddNumberToObject(jEvent, KEY_RESULT, result); + cJSON_AddNumberToObject(jEvent, KEY_EVENT_TYPE, static_cast(type)); + cJSON_AddNumberToObject(jEvent, KEY_RANDOM_TASK_CODE, randomTaskCode); DHLOGD("Notify source dev, new engine, random task code:%s", std::to_string(randomTaskCode).c_str()); if (type == NOTIFY_OPEN_CTRL_RESULT || type == NOTIFY_CLOSE_CTRL_RESULT) { DHLOGE("In new engine mode, ctrl is not allowed."); + cJSON_Delete(jEvent); return; } int32_t dhIdInt = ConvertString2Int(dhId); if (dhIdInt == -1) { DHLOGE("Parse dhId error."); + cJSON_Delete(jEvent); + return; + } + char *data = cJSON_PrintUnformatted(jEvent); + if (data == nullptr) { + DHLOGE("Failed to create JSON data."); + cJSON_Delete(jEvent); return; } + std::string message(data); + std::shared_ptr speakerClient = nullptr; { std::lock_guard devLck(spkClientMutex_); speakerClient = spkClientMap_[dhIdInt]; } if (speakerClient != nullptr) { - speakerClient->SendMessage(static_cast(type), jEvent.dump(), devId_); + speakerClient->SendMessage(static_cast(type), message, devId_); } std::shared_ptr micClient = nullptr; { @@ -468,25 +495,58 @@ void DAudioSinkDev::NotifySourceDev(const AudioEventType type, const std::string micClient = micClientMap_[dhIdInt]; } if (micClient != nullptr) { - micClient->SendMessage(static_cast(type), jEvent.dump(), devId_); + micClient->SendMessage(static_cast(type), message, devId_); + } + cJSON_Delete(jEvent); + cJSON_free(data); +} + +int32_t DAudioSinkDev::GetParamValue(const cJSON *j, const char* key, int32_t &value) +{ + cJSON *paramValue = cJSON_GetObjectItemCaseSensitive(j, key); + if (paramValue == nullptr || !cJSON_IsNumber(paramValue)) { + return ERR_DH_AUDIO_FAILED; } + value = paramValue->valueint; + return DH_SUCCESS; } -int32_t DAudioSinkDev::from_json(const json &j, AudioParam &audioParam) +int32_t DAudioSinkDev::GetCJsonObjectItems(const cJSON *j, AudioParam &audioParam) +{ + int32_t ret = 0; + ret = GetParamValue(j, KEY_SAMPLING_RATE, reinterpret_cast(audioParam.comParam.sampleRate)); + CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "%s", "Get param value error."); + ret = GetParamValue(j, KEY_CHANNELS, reinterpret_cast(audioParam.comParam.channelMask)); + CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "%s", "Get param value error."); + ret = GetParamValue(j, KEY_FORMAT, reinterpret_cast(audioParam.comParam.bitFormat)); + CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "%s", "Get param value error."); + ret = GetParamValue(j, KEY_FRAMESIZE, reinterpret_cast(audioParam.comParam.frameSize)); + CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "%s", "Get param value error."); + ret = GetParamValue(j, KEY_SOURCE_TYPE, reinterpret_cast(audioParam.captureOpts.sourceType)); + CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "%s", "Get param value error."); + ret = GetParamValue(j, KEY_CONTENT_TYPE, reinterpret_cast(audioParam.renderOpts.contentType)); + CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "%s", "Get param value error."); + ret = GetParamValue(j, KEY_STREAM_USAGE, reinterpret_cast(audioParam.renderOpts.streamUsage)); + CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "%s", "Get param value error."); + ret = GetParamValue(j, KEY_RENDER_FLAGS, reinterpret_cast(audioParam.renderOpts.renderFlags)); + CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "%s", "Get param value error."); + ret = GetParamValue(j, KEY_CAPTURE_FLAGS, + reinterpret_cast(audioParam.captureOpts.capturerFlags)); + CHECK_AND_RETURN_RET_LOG(ret != DH_SUCCESS, ret, "%s", "Get param value error."); + return ret; +} + +int32_t DAudioSinkDev::from_json(const cJSON *j, AudioParam &audioParam) { - if (!JsonParamCheck(j, { KEY_SAMPLING_RATE, KEY_CHANNELS, KEY_FORMAT, + if (!CJsonParamCheck(j, { KEY_SAMPLING_RATE, KEY_CHANNELS, KEY_FORMAT, KEY_SOURCE_TYPE, KEY_CONTENT_TYPE, KEY_STREAM_USAGE })) { + DHLOGE("Not found the keys of dhId"); + return ERR_DH_AUDIO_FAILED; + } + if (!GetCJsonObjectItems(j, audioParam)) { + DHLOGE("Get Cjson Object Items failed."); return ERR_DH_AUDIO_FAILED; } - j.at(KEY_SAMPLING_RATE).get_to(audioParam.comParam.sampleRate); - j.at(KEY_CHANNELS).get_to(audioParam.comParam.channelMask); - j.at(KEY_FORMAT).get_to(audioParam.comParam.bitFormat); - j.at(KEY_FRAMESIZE).get_to(audioParam.comParam.frameSize); - j.at(KEY_SOURCE_TYPE).get_to(audioParam.captureOpts.sourceType); - j.at(KEY_CONTENT_TYPE).get_to(audioParam.renderOpts.contentType); - j.at(KEY_STREAM_USAGE).get_to(audioParam.renderOpts.streamUsage); - j.at(KEY_RENDER_FLAGS).get_to(audioParam.renderOpts.renderFlags); - j.at(KEY_CAPTURE_FLAGS).get_to(audioParam.captureOpts.capturerFlags); return DH_SUCCESS; } @@ -571,13 +631,10 @@ void DAudioSinkDev::SinkEventHandler::NotifyOpenSpeaker(const AppExecFwk::InnerE auto sinkDevObj = sinkDev_.lock(); CHECK_NULL_VOID(sinkDevObj); - json jParam = json::parse(eventParam, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DH_ID, KEY_AUDIO_PARAM })) { - DHLOGE("Json param check failed."); - return; - } + int32_t dhId = sinkDevObj->ParseDhidFromEvent(eventParam); + CHECK_AND_RETURN_LOG(dhId == -1, "%s", "Parse dhId error."); int32_t ret = sinkDevObj->TaskOpenDSpeaker(eventParam); - sinkDevObj->NotifySourceDev(NOTIFY_OPEN_SPEAKER_RESULT, jParam[KEY_DH_ID], ret); + sinkDevObj->NotifySourceDev(NOTIFY_OPEN_SPEAKER_RESULT, std::to_string(dhId), ret); DHLOGI("Open speaker device task end, notify source ret %d.", ret); CHECK_AND_RETURN_LOG(ret != DH_SUCCESS, "%s", "Open speaker failed."); } @@ -634,13 +691,15 @@ void DAudioSinkDev::SinkEventHandler::NotifyOpenMic(const AppExecFwk::InnerEvent auto sinkDevObj = sinkDev_.lock(); CHECK_NULL_VOID(sinkDevObj); - json jParam = json::parse(eventParam, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DH_ID, KEY_AUDIO_PARAM })) { + cJSON *jParam = cJSON_Parse(eventParam.c_str()); + CHECK_NULL_VOID(jParam); + if (!CJsonParamCheck(jParam, { KEY_DH_ID, KEY_AUDIO_PARAM })) { DHLOGE("Json param check failed."); return; } int32_t ret = sinkDevObj->TaskOpenDMic(eventParam); - sinkDevObj->NotifySourceDev(NOTIFY_OPEN_MIC_RESULT, jParam[KEY_DH_ID], ret); + sinkDevObj->NotifySourceDev(NOTIFY_OPEN_MIC_RESULT, + std::string(cJSON_GetObjectItem(jParam, KEY_DH_ID)->valuestring), ret); DHLOGI("Open mic device task end, notify source ret %d.", ret); CHECK_AND_RETURN_LOG(ret != DH_SUCCESS, "%s", "Open mic failed."); } diff --git a/services/audiomanager/managersink/src/daudio_sink_manager.cpp b/services/audiomanager/managersink/src/daudio_sink_manager.cpp index 5d172c50..b180b0f2 100644 --- a/services/audiomanager/managersink/src/daudio_sink_manager.cpp +++ b/services/audiomanager/managersink/src/daudio_sink_manager.cpp @@ -141,10 +141,10 @@ int32_t DAudioSinkManager::HandleDAudioNotify(const std::string &devId, const st } // now ctrl channel is also goto here, please sure here not crash. - json jParam = json::parse(eventContent, nullptr, false); - if (JsonParamCheck(jParam, { KEY_RANDOM_TASK_CODE })) { + cJSON *jParam = cJSON_Parse(eventContent.c_str()); + if (CJsonParamCheck(jParam, { KEY_RANDOM_TASK_CODE })) { DHLOGD("Receive audio notify from source, random task code: %s", - ((std::string)jParam[KEY_RANDOM_TASK_CODE]).c_str()); + cJSON_GetObjectItemCaseSensitive(jParam, KEY_RANDOM_TASK_CODE)->valuestring); } bool isDevExisted = false; { @@ -154,9 +154,11 @@ int32_t DAudioSinkManager::HandleDAudioNotify(const std::string &devId, const st if (!isDevExisted) { DHLOGE("Device is not exist, devId: %s, dhId: %s.", GetAnonyString(devId).c_str(), GetAnonyString(dhId).c_str()); + cJSON_Delete(jParam); return ERR_DH_AUDIO_FAILED; } NotifyEvent(devId, eventType, eventContent); + cJSON_Delete(jParam); return DH_SUCCESS; } diff --git a/services/audiomanager/managersource/include/daudio_source_dev.h b/services/audiomanager/managersource/include/daudio_source_dev.h index 79e24d1b..1ffcc97a 100644 --- a/services/audiomanager/managersource/include/daudio_source_dev.h +++ b/services/audiomanager/managersource/include/daudio_source_dev.h @@ -19,7 +19,7 @@ #include #include #include -#include "nlohmann/json.hpp" +#include "cJSON.h" #include "event_handler.h" @@ -35,8 +35,6 @@ #include "idaudio_ipc_callback.h" #include "idaudio_hdi_callback.h" -using json = nlohmann::json; - namespace OHOS { namespace DistributedHardware { class DAudioSourceDev : public IAudioEventCallback, public std::enable_shared_from_this { @@ -103,10 +101,10 @@ private: int32_t HandleMicMmapStart(const AudioEvent &event); int32_t HandleMicMmapStop(const AudioEvent &event); - int32_t NotifySinkDev(const AudioEventType type, const json Param, const std::string dhId); + int32_t NotifySinkDev(const AudioEventType type, const cJSON *Param, const std::string dhId); int32_t NotifyHDF(const AudioEventType type, const std::string result, const int32_t dhId); AudioEventType getEventTypeFromArgs(const std::string &args); - void to_json(json &j, const AudioParam ¶m); + void to_json(cJSON **j, const AudioParam ¶m); int32_t SendAudioEventToRemote(const AudioEvent &event); int32_t CloseSpkNew(const std::string &args); int32_t CloseMicNew(const std::string &args); diff --git a/services/audiomanager/managersource/include/dmic_dev.h b/services/audiomanager/managersource/include/dmic_dev.h index 68d98681..41786ab5 100644 --- a/services/audiomanager/managersource/include/dmic_dev.h +++ b/services/audiomanager/managersource/include/dmic_dev.h @@ -19,7 +19,7 @@ #include #include #include -#include "nlohmann/json.hpp" +#include "cJSON.h" #include "audio_param.h" #include "audio_status.h" @@ -33,8 +33,6 @@ #include "iaudio_event_callback.h" #include "idaudio_hdi_callback.h" -using json = nlohmann::json; - namespace OHOS { namespace DistributedHardware { class DMicDev : public DAudioIoDev, diff --git a/services/audiomanager/managersource/include/dspeaker_dev.h b/services/audiomanager/managersource/include/dspeaker_dev.h index bbe11354..c6c836a6 100644 --- a/services/audiomanager/managersource/include/dspeaker_dev.h +++ b/services/audiomanager/managersource/include/dspeaker_dev.h @@ -19,7 +19,7 @@ #include #include #include -#include "nlohmann/json.hpp" +#include "cJSON.h" #include "audio_param.h" #include "ashmem.h" @@ -32,8 +32,6 @@ #include "iaudio_datatrans_callback.h" #include "idaudio_hdi_callback.h" -using json = nlohmann::json; - namespace OHOS { namespace DistributedHardware { class DSpeakerDev : public DAudioIoDev, diff --git a/services/audiomanager/managersource/src/daudio_source_dev.cpp b/services/audiomanager/managersource/src/daudio_source_dev.cpp index ceb0c6b2..269e6b5d 100644 --- a/services/audiomanager/managersource/src/daudio_source_dev.cpp +++ b/services/audiomanager/managersource/src/daudio_source_dev.cpp @@ -113,8 +113,12 @@ int32_t DAudioSourceDev::EnableDAudio(const std::string &dhId, const std::string isRpcOpen_.store(true); CHECK_NULL_RETURN(handler_, ERR_DH_AUDIO_NULLPTR); - json jParam = { { KEY_DEV_ID, devId_ }, { KEY_DH_ID, dhId }, { KEY_ATTRS, attrs } }; - auto eventParam = std::make_shared(jParam); + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParam, KEY_DEV_ID, devId_.c_str()); + cJSON_AddStringToObject(jParam, KEY_DH_ID, dhId.c_str()); + cJSON_AddStringToObject(jParam, KEY_ATTRS, attrs.c_str()); + auto eventParam = std::shared_ptr(jParam, cJSON_Delete); auto msgEvent = AppExecFwk::InnerEvent::Get(EVENT_DAUDIO_ENABLE, eventParam, 0); if (!handler_->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE)) { DHLOGE("Send event failed."); @@ -130,13 +134,18 @@ int32_t DAudioSourceDev::DisableDAudio(const std::string &dhId) isRpcOpen_.store(false); CHECK_NULL_RETURN(handler_, ERR_DH_AUDIO_NULLPTR); - json jParamClose = { { KEY_DH_ID, dhId } }; - AudioEvent event(AudioEventType::EVENT_UNKNOWN, jParamClose.dump()); - int32_t dhIdNum = ConvertString2Int(dhId); - if (dhIdNum == -1) { - DHLOGE("Parse dhId error."); - return ERR_DH_AUDIO_NOT_SUPPORT; + cJSON *jParamClose = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParamClose, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParamClose, KEY_DH_ID, dhId.c_str()); + char *data = cJSON_PrintUnformatted(jParamClose); + if (data == nullptr) { + DHLOGE("Failed to create JSON data."); + cJSON_Delete(jParamClose); + return ERR_DH_AUDIO_NULLPTR; } + AudioEvent event(AudioEventType::EVENT_UNKNOWN, std::string(data)); + int32_t dhIdNum = ConvertString2Int(dhId); + CHECK_AND_RETURN_RET_LOG(dhIdNum == -1, ERR_DH_AUDIO_NOT_SUPPORT, "%s", "Parse dhId error."); switch (GetDevTypeByDHId(dhIdNum)) { case AUDIO_DEVICE_TYPE_SPEAKER: event.type = CLOSE_SPEAKER; @@ -147,26 +156,34 @@ int32_t DAudioSourceDev::DisableDAudio(const std::string &dhId) HandleCloseDMic(event); break; default: + cJSON_Delete(jParamClose); + cJSON_free(data); DHLOGE("Unknown audio device. dhId: %d.", dhIdNum); return ERR_DH_AUDIO_NOT_SUPPORT; } - json jParam = { { KEY_DEV_ID, devId_ }, { KEY_DH_ID, dhId } }; - auto eventParam = std::make_shared(jParam); + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParam, KEY_DEV_ID, devId_.c_str()); ++ cJSON_AddStringToObject(jParam, KEY_DH_ID, dhId.c_str()); + auto eventParam = std::shared_ptr(jParam, cJSON_Delete); auto msgEvent = AppExecFwk::InnerEvent::Get(EVENT_DAUDIO_DISABLE, eventParam, 0); if (!handler_->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE)) { DHLOGE("Send event failed."); return ERR_DH_AUDIO_FAILED; } DHLOGI("Disable audio task generate successfully."); + cJSON_Delete(jParamClose); + cJSON_free(data); return DH_SUCCESS; } int32_t DAudioSourceDev::RestoreThreadStatus() { CHECK_NULL_RETURN(handler_, ERR_DH_AUDIO_NULLPTR); - json jParam; - auto eventParam = std::make_shared(jParam); + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + auto eventParam = std::shared_ptr(jParam, cJSON_Delete); auto msgEvent = AppExecFwk::InnerEvent::Get(EVENT_SET_THREAD_STATUS, eventParam, 0); if (!handler_->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE)) { DHLOGE("Send event failed."); @@ -323,20 +340,25 @@ int32_t DAudioSourceDev::HandleNotifyRPC(const AudioEvent &event) if (event.content.length() > DAUDIO_MAX_JSON_LEN || event.content.empty()) { return ERR_DH_AUDIO_SA_PARAM_INVALID; } - json jParam = json::parse(event.content, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_RESULT })) { + cJSON *jParam = cJSON_Parse(event.content.c_str()); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + if (!CJsonParamCheck(jParam, { KEY_RESULT })) { + DHLOGE("Not found the keys of result."); + cJSON_Delete(jParam); return ERR_DH_AUDIO_FAILED; } - rpcResult_ = jParam[KEY_RESULT]; + rpcResult_ = cJSON_GetObjectItem(jParam, KEY_DH_ID)->valueint; DHLOGD("Notify RPC event: %d, result: %d.", event.type, rpcResult_); std::map::iterator iter = eventNotifyMap_.find(event.type); if (iter == eventNotifyMap_.end()) { DHLOGE("Invalid eventType."); + cJSON_Delete(jParam); return ERR_DH_AUDIO_NOT_FOUND_KEY; } rpcNotify_ = iter->second; rpcWaitCond_.notify_all(); + cJSON_Delete(jParam); return DH_SUCCESS; } @@ -508,25 +530,36 @@ int32_t DAudioSourceDev::TaskEnableDAudio(const std::string &args) if (args.length() > DAUDIO_MAX_JSON_LEN || args.empty()) { return ERR_DH_AUDIO_SA_PARAM_INVALID; } - json jParam = json::parse(args, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DH_ID, KEY_ATTRS }) || !CheckIsNum((std::string)jParam[KEY_DH_ID])) { + cJSON *jParam = cJSON_Parse(args.c_str()); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + if (!CJsonParamCheck(jParam, { KEY_DH_ID, KEY_ATTRS })) { DHLOGE("The keys or values is invalid."); + cJSON_Delete(jParam); return ERR_DH_AUDIO_SA_PARAM_INVALID; } - int32_t dhId = ConvertString2Int(std::string(jParam[KEY_DH_ID])); + int32_t dhId = ParseDhidFromEvent(args); if (dhId == -1) { DHLOGE("Parse dhId error."); + cJSON_Delete(jParam); return ERR_DH_AUDIO_NOT_SUPPORT; } + char *attrs = cJSON_PrintUnformatted(cJSON_GetObjectItem(jParam, KEY_ATTRS)); + std::string attrsStr(attrs); + int32_t result = 0; switch (GetDevTypeByDHId(dhId)) { case AUDIO_DEVICE_TYPE_SPEAKER: - return EnableDSpeaker(dhId, jParam[KEY_ATTRS]); + result = EnableDSpeaker(dhId, attrsStr); + break; case AUDIO_DEVICE_TYPE_MIC: - return EnableDMic(dhId, jParam[KEY_ATTRS]); + result = EnableDMic(dhId, attrsStr); + break; default: DHLOGE("Unknown audio device. dhId: %d.", dhId); - return ERR_DH_AUDIO_NOT_SUPPORT; + result = ERR_DH_AUDIO_NOT_SUPPORT; } + cJSON_Delete(jParam); + cJSON_free(attrs); + return result; } int32_t DAudioSourceDev::EnableDSpeaker(const int32_t dhId, const std::string &attrs) @@ -569,12 +602,16 @@ void DAudioSourceDev::OnEnableTaskResult(int32_t resultCode, const std::string & if (result.length() > DAUDIO_MAX_JSON_LEN || result.empty()) { return; } - json jParam = json::parse(result, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DEV_ID, KEY_DH_ID })) { + cJSON *jParam = cJSON_Parse(result.c_str()); + CHECK_NULL_VOID(jParam); + if (!CJsonParamCheck(jParam, { KEY_DEV_ID, KEY_DH_ID })) { DHLOGE("Not found the keys."); + cJSON_Delete(jParam); return; } - mgrCallback_->OnEnableAudioResult(jParam[KEY_DEV_ID], jParam[KEY_DH_ID], resultCode); + mgrCallback_->OnEnableAudioResult(std::string(cJSON_GetObjectItem(jParam, KEY_DEV_ID)->valuestring), + std::string(cJSON_GetObjectItem(jParam, KEY_DH_ID)->valuestring), resultCode); + cJSON_Delete(jParam); } int32_t DAudioSourceDev::TaskDisableDAudio(const std::string &args) @@ -583,23 +620,23 @@ int32_t DAudioSourceDev::TaskDisableDAudio(const std::string &args) if (args.length() > DAUDIO_MAX_JSON_LEN || args.empty()) { return ERR_DH_AUDIO_SA_PARAM_INVALID; } - json jParam = json::parse(args, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DH_ID }) || !CheckIsNum((std::string)jParam[KEY_DH_ID])) { - return ERR_DH_AUDIO_SA_PARAM_INVALID; - } - int32_t dhId = ConvertString2Int(std::string(jParam[KEY_DH_ID])); - if (dhId == -1) { - DHLOGE("Parse dhId error."); - return ERR_DH_AUDIO_NOT_SUPPORT; - } + cJSON *jParam = cJSON_Parse(args.c_str()); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + int32_t dhId = ParseDhidFromEvent(args); + CHECK_AND_RETURN_RET_LOG(dhId == -1, ERR_DH_AUDIO_NULLPTR, + "%s", "Parse dhId error."); + DHLOGI("Parsed dhId = %d", dhId); switch (GetDevTypeByDHId(dhId)) { case AUDIO_DEVICE_TYPE_SPEAKER: + cJSON_Delete(jParam); return DisableDSpeaker(dhId); case AUDIO_DEVICE_TYPE_MIC: + cJSON_Delete(jParam); return DisableDMic(dhId); default: DHLOGE("Unknown audio device. hdId: %d.", dhId); + cJSON_Delete(jParam); return ERR_DH_AUDIO_NOT_SUPPORT; } } @@ -636,12 +673,16 @@ void DAudioSourceDev::OnDisableTaskResult(int32_t resultCode, const std::string if (result.length() > DAUDIO_MAX_JSON_LEN || result.empty()) { return; } - json jParam = json::parse(result, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DEV_ID, KEY_DH_ID })) { + cJSON *jParam = cJSON_Parse(result.c_str()); + CHECK_NULL_VOID(jParam); + if (!CJsonParamCheck(jParam, { KEY_DEV_ID, KEY_DH_ID })) { DHLOGE("Not found the keys."); + cJSON_Delete(jParam); return; } - mgrCallback_->OnDisableAudioResult(jParam[KEY_DEV_ID], jParam[KEY_DH_ID], resultCode); + mgrCallback_->OnDisableAudioResult(std::string(cJSON_GetObjectItem(jParam, KEY_DEV_ID)->valuestring), + std::string(cJSON_GetObjectItem(jParam, KEY_DH_ID)->valuestring), resultCode); + cJSON_Delete(jParam); } int32_t DAudioSourceDev::TaskOpenDSpeaker(const std::string &args) @@ -670,20 +711,24 @@ int32_t DAudioSourceDev::TaskOpenDSpeaker(const std::string &args) return ret; } - json jAudioParam; - to_json(jAudioParam, speaker->GetAudioParam()); + cJSON *jAudioParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jAudioParam, ERR_DH_AUDIO_NULLPTR); + to_json(&jAudioParam, speaker->GetAudioParam()); std::string dhIdString = std::to_string(dhId); ret = NotifySinkDev(OPEN_SPEAKER, jAudioParam, dhIdString); if (ret != DH_SUCCESS) { DHLOGE("Notify sink open speaker failed, error code %d.", ret); + cJSON_Delete(jAudioParam); NotifyHDF(NOTIFY_OPEN_SPEAKER_RESULT, HDF_EVENT_NOTIFY_SINK_FAILED, dhId); return ret; } ret = OpenDSpeakerInner(speaker, dhId); if (ret != DH_SUCCESS) { + cJSON_Delete(jAudioParam); DHLOGE("Task Open DSpeaker Execute failed, error code %d.", ret); return ret; } + cJSON_Delete(jAudioParam); return DH_SUCCESS; } @@ -741,13 +786,16 @@ int32_t DAudioSourceDev::OpenDSpeakerInner(std::shared_ptr &speaker int32_t DAudioSourceDev::CloseSpkNew(const std::string &args) { DHLOGI("Close speaker new"); - json jAudioParam; - json jParam = json::parse(args, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DH_ID })) { - DHLOGE("Task close speaker, json param check failed."); + cJSON *jAudioParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jAudioParam, ERR_DH_AUDIO_NULLPTR); + cJSON *jParam = cJSON_Parse(args.c_str()); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + if (!CJsonParamCheck(jParam, { KEY_DH_ID })) { + DHLOGE("Task close speaker, cjson param check failed."); + cJSON_Delete(jParam); return ERR_DH_AUDIO_FAILED; } - NotifySinkDev(CLOSE_SPEAKER, jAudioParam, jParam[KEY_DH_ID]); + NotifySinkDev(CLOSE_SPEAKER, jAudioParam, std::string(cJSON_GetObjectItem(jParam, KEY_DH_ID)->valuestring)); bool closeStatus = true; auto speaker = FindIoDevImpl(args); CHECK_NULL_RETURN(speaker, ERR_DH_AUDIO_NULLPTR); @@ -760,8 +808,10 @@ int32_t DAudioSourceDev::CloseSpkNew(const std::string &args) closeStatus = false; } if (!closeStatus) { + cJSON_Delete(jParam); return ERR_DH_AUDIO_FAILED; } + cJSON_Delete(jParam); return DH_SUCCESS; } @@ -824,14 +874,16 @@ int32_t DAudioSourceDev::TaskOpenDMic(const std::string &args) return ret; } - json jAudioParam; - to_json(jAudioParam, mic->GetAudioParam()); + cJSON *jAudioParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jAudioParam, ERR_DH_AUDIO_NULLPTR); + to_json(&jAudioParam, mic->GetAudioParam()); std::string dhIdString = std::to_string(dhId); ret = NotifySinkDev(OPEN_MIC, jAudioParam, dhIdString); if (ret != DH_SUCCESS) { DHLOGE("Notify sink open mic failed, error code %d.", ret); mic->Release(); NotifyHDF(NOTIFY_OPEN_MIC_RESULT, HDF_EVENT_NOTIFY_SINK_FAILED, dhId); + cJSON_Delete(jAudioParam); return ret; } @@ -841,28 +893,38 @@ int32_t DAudioSourceDev::TaskOpenDMic(const std::string &args) mic->Stop(); mic->Release(); NotifyHDF(NOTIFY_OPEN_MIC_RESULT, HDF_EVENT_TRANS_START_FAILED, dhId); + cJSON_Delete(jAudioParam); return ret; } NotifyHDF(NOTIFY_OPEN_MIC_RESULT, HDF_EVENT_RESULT_SUCCESS, dhId); + cJSON_Delete(jAudioParam); return DH_SUCCESS; } int32_t DAudioSourceDev::CloseMicNew(const std::string &args) { DHLOGI("Close mic new."); - json jAudioParam; - json jParam = json::parse(args, nullptr, false); - if (!JsonParamCheck(jParam, { KEY_DH_ID })) { - DHLOGE("Task close mic, json param check failed."); + cJSON *jAudioParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jAudioParam, ERR_DH_AUDIO_NULLPTR); + cJSON *jParam = cJSON_Parse(args.c_str()); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + if (!CJsonParamCheck(jParam, { KEY_DH_ID })) { + DHLOGE("Task close mic, cjson param check failed."); + cJSON_Delete(jParam); + cJSON_Delete(jAudioParam); return ERR_DH_AUDIO_FAILED; } - NotifySinkDev(CLOSE_MIC, jAudioParam, jParam[KEY_DH_ID]); + NotifySinkDev(CLOSE_MIC, jAudioParam, std::string(cJSON_GetObjectItem(jParam, KEY_DH_ID)->valuestring)); auto mic = FindIoDevImpl(args); CHECK_NULL_RETURN(mic, DH_SUCCESS); if (mic->Stop() != DH_SUCCESS || mic->Release() != DH_SUCCESS) { + cJSON_Delete(jParam); + cJSON_Delete(jAudioParam); return ERR_DH_AUDIO_FAILED; } + cJSON_Delete(jParam); + cJSON_Delete(jAudioParam); return DH_SUCCESS; } @@ -1078,7 +1140,7 @@ void DAudioSourceDev::OnTaskResult(int32_t resultCode, const std::string &result funcName.c_str()); } -int32_t DAudioSourceDev::NotifySinkDev(const AudioEventType type, const json Param, const std::string dhId) +int32_t DAudioSourceDev::NotifySinkDev(const AudioEventType type, const cJSON *Param, const std::string dhId) { if (!isRpcOpen_.load()) { DHLOGE("Network connection failure, rpc is not open!"); @@ -1088,28 +1150,42 @@ int32_t DAudioSourceDev::NotifySinkDev(const AudioEventType type, const json Par std::random_device rd; const uint32_t randomTaskCode = rd(); constexpr uint32_t eventOffset = 4; - json jParam = { { KEY_DH_ID, dhId }, - { KEY_EVENT_TYPE, type }, - { KEY_AUDIO_PARAM, Param }, - { KEY_RANDOM_TASK_CODE, std::to_string(randomTaskCode) } }; + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParam, KEY_DH_ID, dhId.c_str()); + cJSON_AddNumberToObject(jParam, KEY_EVENT_TYPE, static_cast(type)); + cJSON *jParamCopy = cJSON_Duplicate(Param, 1); + cJSON_AddItemToObject(jParam, KEY_AUDIO_PARAM, jParamCopy); + cJSON_AddStringToObject(jParam, KEY_RANDOM_TASK_CODE, std::to_string(randomTaskCode).c_str()); DHLOGD("Notify sink dev, new engine, random task code:%s", std::to_string(randomTaskCode).c_str()); std::lock_guard devLck(ioDevMtx_); int32_t dhIdInt = ConvertString2Int(dhId); if (deviceMap_.find(dhIdInt) == deviceMap_.end()) { DHLOGE("speaker or mic dev is null. find index: %d.", dhIdInt); + cJSON_Delete(jParamCopy); + cJSON_Delete(jParam); return ERR_DH_AUDIO_NULLPTR; } auto ioDev = deviceMap_[dhIdInt]; if (type == OPEN_CTRL || type == CLOSE_CTRL) { DHLOGE("In new engine mode, ctrl is not allowed."); + cJSON_Delete(jParamCopy); + cJSON_Delete(jParam); return ERR_DH_AUDIO_NULLPTR; } - ioDev->SendMessage(static_cast(type), jParam.dump(), devId_); + char *content = cJSON_PrintUnformatted(jParam); + ioDev->SendMessage(static_cast(type), std::string(content), devId_); if (type == CLOSE_SPEAKER || type == CLOSE_MIC) { // Close spk || Close mic do not need to wait RPC + cJSON_Delete(jParamCopy); + cJSON_Delete(jParam); + cJSON_free(content); return DH_SUCCESS; } + cJSON_Delete(jParamCopy); + cJSON_Delete(jParam); + cJSON_free(content); return WaitForRPC(static_cast(static_cast(type) + eventOffset)); } @@ -1149,15 +1225,19 @@ AudioEventType DAudioSourceDev::getEventTypeFromArgs(const std::string &args) return AudioEventType::VOLUME_SET; } -void DAudioSourceDev::to_json(json &j, const AudioParam ¶m) +void DAudioSourceDev::to_json(cJSON **j, const AudioParam ¶m) { - j = json { - { KEY_SAMPLING_RATE, param.comParam.sampleRate }, { KEY_FORMAT, param.comParam.bitFormat }, - { KEY_CHANNELS, param.comParam.channelMask }, { KEY_FRAMESIZE, param.comParam.frameSize }, - { KEY_CONTENT_TYPE, param.renderOpts.contentType }, { KEY_STREAM_USAGE, param.renderOpts.streamUsage }, - { KEY_RENDER_FLAGS, param.renderOpts.renderFlags }, { KEY_CAPTURE_FLAGS, param.captureOpts.capturerFlags }, - { KEY_SOURCE_TYPE, param.captureOpts.sourceType }, - }; + *j = cJSON_CreateObject(); + CHECK_NULL_VOID(*j); + cJSON_AddNumberToObject(*j, KEY_SAMPLING_RATE, param.comParam.sampleRate); + cJSON_AddNumberToObject(*j, KEY_FORMAT, param.comParam.bitFormat); + cJSON_AddNumberToObject(*j, KEY_CHANNELS, param.comParam.channelMask); + cJSON_AddNumberToObject(*j, KEY_FRAMESIZE, param.comParam.frameSize); + cJSON_AddNumberToObject(*j, KEY_CONTENT_TYPE, param.renderOpts.contentType); + cJSON_AddNumberToObject(*j, KEY_STREAM_USAGE, param.renderOpts.streamUsage); + cJSON_AddNumberToObject(*j, KEY_RENDER_FLAGS, param.renderOpts.renderFlags); + cJSON_AddNumberToObject(*j, KEY_CAPTURE_FLAGS, param.captureOpts.capturerFlags); + cJSON_AddNumberToObject(*j, KEY_SOURCE_TYPE, param.captureOpts.sourceType); } DAudioSourceDev::SourceEventHandler::SourceEventHandler(const std::shared_ptr &runner, @@ -1199,25 +1279,41 @@ void DAudioSourceDev::SourceEventHandler::ProcessEvent(const AppExecFwk::InnerEv void DAudioSourceDev::SourceEventHandler::EnableDAudioCallback(const AppExecFwk::InnerEvent::Pointer &event) { CHECK_NULL_VOID(event); - std::shared_ptr jParam = event->GetSharedObject(); + cJSON *jParam = event->GetSharedObject().get(); CHECK_NULL_VOID(jParam); + char* jsonString = cJSON_PrintUnformatted(jParam); + if (jsonString == nullptr) { + DHLOGE("Failed to create JSON data."); + cJSON_Delete(jParam); + return; + } auto sourceDevObj = sourceDev_.lock(); CHECK_NULL_VOID(sourceDevObj); - if (sourceDevObj->TaskEnableDAudio(jParam->dump()) != DH_SUCCESS) { + if (sourceDevObj->TaskEnableDAudio(std::string(jsonString)) != DH_SUCCESS) { DHLOGE("Open ctrl channel failed."); } + cJSON_Delete(jParam); + cJSON_free(jsonString); } void DAudioSourceDev::SourceEventHandler::DisableDAudioCallback(const AppExecFwk::InnerEvent::Pointer &event) { CHECK_NULL_VOID(event); - std::shared_ptr jParam = event->GetSharedObject(); + cJSON *jParam = event->GetSharedObject().get(); CHECK_NULL_VOID(jParam); + char* jsonString = cJSON_PrintUnformatted(jParam); + if (jsonString == nullptr) { + DHLOGE("Failed to create JSON data."); + cJSON_Delete(jParam); + return; + } auto sourceDevObj = sourceDev_.lock(); CHECK_NULL_VOID(sourceDevObj); - if (sourceDevObj->TaskDisableDAudio(jParam->dump()) != DH_SUCCESS) { + if (sourceDevObj->TaskDisableDAudio(std::string(jsonString)) != DH_SUCCESS) { DHLOGE("Disable distributed audio failed."); } + cJSON_Delete(jParam); + cJSON_free(jsonString); } void DAudioSourceDev::SourceEventHandler::OpenDSpeakerCallback(const AppExecFwk::InnerEvent::Pointer &event) diff --git a/services/audiomanager/managersource/src/daudio_source_manager.cpp b/services/audiomanager/managersource/src/daudio_source_manager.cpp index 3ee148a9..fa13ce1f 100644 --- a/services/audiomanager/managersource/src/daudio_source_manager.cpp +++ b/services/audiomanager/managersource/src/daudio_source_manager.cpp @@ -165,9 +165,14 @@ int32_t DAudioSourceManager::EnableDAudio(const std::string &devId, const std::s dhId.c_str(), version.c_str(), reqId.c_str()); CHECK_NULL_RETURN(handler_, ERR_DH_AUDIO_NULLPTR); - json jParam = { { KEY_DEV_ID, devId }, { KEY_DH_ID, dhId }, { KEY_VERSION, version }, - { KEY_ATTRS, attrs }, { KEY_REQID, reqId } }; - auto eventParam = std::make_shared(jParam); + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParam, KEY_DEV_ID, devId.c_str()); + cJSON_AddStringToObject(jParam, KEY_DH_ID, dhId.c_str()); + cJSON_AddStringToObject(jParam, KEY_VERSION, version.c_str()); + cJSON_AddStringToObject(jParam, KEY_ATTRS, attrs.c_str()); + cJSON_AddStringToObject(jParam, KEY_REQID, reqId.c_str()); + auto eventParam = std::shared_ptr(jParam, cJSON_Delete); auto msgEvent = AppExecFwk::InnerEvent::Get(EVENT_MANAGER_ENABLE_DAUDIO, eventParam, 0); if (!handler_->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE)) { DHLOGE("Send event failed."); @@ -212,8 +217,12 @@ int32_t DAudioSourceManager::DisableDAudio(const std::string &devId, const std:: DHLOGI("Disable distributed audio, devId: %s, dhId: %s, reqId: %s.", GetAnonyString(devId).c_str(), dhId.c_str(), reqId.c_str()); CHECK_NULL_RETURN(handler_, ERR_DH_AUDIO_NULLPTR); - json jParam = { { KEY_DEV_ID, devId }, { KEY_DH_ID, dhId }, { KEY_REQID, reqId } }; - auto eventParam = std::make_shared(jParam); + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParam, KEY_DEV_ID, devId.c_str()); + cJSON_AddStringToObject(jParam, KEY_DH_ID, dhId.c_str()); + cJSON_AddStringToObject(jParam, KEY_REQID, reqId.c_str()); + auto eventParam = std::shared_ptr(jParam, cJSON_Delete); auto msgEvent = AppExecFwk::InnerEvent::Get(EVENT_MANAGER_DISABLE_DAUDIO, eventParam, 0); if (!handler_->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE)) { DHLOGE("Send event failed."); @@ -261,10 +270,10 @@ int32_t DAudioSourceManager::HandleDAudioNotify(const std::string &devId, const } // now ctrl channel is also goto here, please sure here not crash. - json jParam = json::parse(eventContent, nullptr, false); - if (JsonParamCheck(jParam, { KEY_RANDOM_TASK_CODE })) { + cJSON *jParam = cJSON_Parse(eventContent.c_str()); + if (CJsonParamCheck(jParam, { KEY_RANDOM_TASK_CODE })) { DHLOGD("Receive audio notify from sink, random task code: %s", - ((std::string)jParam[KEY_RANDOM_TASK_CODE]).c_str()); + cJSON_GetObjectItemCaseSensitive(jParam, KEY_RANDOM_TASK_CODE)->valuestring); } std::shared_ptr sourceDev = nullptr; @@ -280,6 +289,7 @@ int32_t DAudioSourceManager::HandleDAudioNotify(const std::string &devId, const AudioEvent audioEvent(eventType, eventContent); sourceDev->NotifyEvent(audioEvent); + cJSON_Delete(jParam); return DH_SUCCESS; } @@ -571,9 +581,17 @@ int32_t DAudioSourceManager::SourceManagerHandler::GetEventParam(const AppExecFw std::string &eventParam) { CHECK_NULL_RETURN(event, ERR_DH_AUDIO_NULLPTR); - std::shared_ptr paramObj = event->GetSharedObject(); + cJSON *paramObj = event->GetSharedObject().get(); CHECK_NULL_RETURN(paramObj, ERR_DH_AUDIO_NULLPTR); - eventParam = paramObj->dump(); + char* jsonString = cJSON_PrintUnformatted(paramObj); + if (jsonString == nullptr) { + DHLOGE("Failed to create JSON data."); + cJSON_Delete(paramObj); + return ERR_DH_AUDIO_NULLPTR; + } + eventParam = std::string(jsonString); + cJSON_Delete(paramObj); + cJSON_free(jsonString); return DH_SUCCESS; } } // DistributedHardware diff --git a/services/audiomanager/managersource/src/dmic_dev.cpp b/services/audiomanager/managersource/src/dmic_dev.cpp index 537aafad..f68a857c 100644 --- a/services/audiomanager/managersource/src/dmic_dev.cpp +++ b/services/audiomanager/managersource/src/dmic_dev.cpp @@ -117,11 +117,23 @@ int32_t DMicDev::OpenDevice(const std::string &devId, const int32_t dhId) DHLOGI("Open mic device devId: %s, dhId: %d.", GetAnonyString(devId).c_str(), dhId); std::shared_ptr cbObj = audioEventCallback_.lock(); CHECK_NULL_RETURN(cbObj, ERR_DH_AUDIO_NULLPTR); - json jParam = { { KEY_DH_ID, std::to_string(dhId) } }; - AudioEvent event(AudioEventType::OPEN_MIC, jParam.dump()); + + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParam, KEY_DH_ID, std::to_string(dhId).c_str()); + char *jsonData = cJSON_PrintUnformatted(jParam); + if (jsonData == nullptr) { + cJSON_Delete(jParam); + DHLOGE("Failed to create JSON data."); + return ERR_DH_AUDIO_NULLPTR; + } + std::string jsonDataStr(jsonData); + AudioEvent event(AudioEventType::OPEN_MIC, jsonDataStr); cbObj->NotifyEvent(event); DAudioHisysevent::GetInstance().SysEventWriteBehavior(DAUDIO_OPEN, devId, std::to_string(dhId), "daudio mic device open success."); + cJSON_Delete(jParam); + cJSON_free(jsonData); return DH_SUCCESS; } @@ -130,11 +142,23 @@ int32_t DMicDev::CloseDevice(const std::string &devId, const int32_t dhId) DHLOGI("Close mic device devId: %s, dhId: %d.", GetAnonyString(devId).c_str(), dhId); std::shared_ptr cbObj = audioEventCallback_.lock(); CHECK_NULL_RETURN(cbObj, ERR_DH_AUDIO_NULLPTR); - json jParam = { { KEY_DH_ID, std::to_string(dhId) } }; - AudioEvent event(AudioEventType::CLOSE_MIC, jParam.dump()); + + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParam, KEY_DH_ID, std::to_string(dhId).c_str()); + char *jsonData = cJSON_PrintUnformatted(jParam); + if (jsonData == nullptr) { + cJSON_Delete(jParam); + DHLOGE("Failed to create JSON data."); + return ERR_DH_AUDIO_NULLPTR; + } + std::string jsonDataStr(jsonData); + AudioEvent event(AudioEventType::CLOSE_MIC, jsonDataStr); cbObj->NotifyEvent(event); DAudioHisysevent::GetInstance().SysEventWriteBehavior(DAUDIO_CLOSE, devId, std::to_string(dhId), "daudio mic device close success."); + cJSON_Delete(jParam); + cJSON_free(jsonData); curPort_ = 0; return DH_SUCCESS; } diff --git a/services/audiomanager/managersource/src/dspeaker_dev.cpp b/services/audiomanager/managersource/src/dspeaker_dev.cpp index 9a982961..2e250310 100644 --- a/services/audiomanager/managersource/src/dspeaker_dev.cpp +++ b/services/audiomanager/managersource/src/dspeaker_dev.cpp @@ -112,11 +112,22 @@ int32_t DSpeakerDev::OpenDevice(const std::string &devId, const int32_t dhId) std::shared_ptr cbObj = audioEventCallback_.lock(); CHECK_NULL_RETURN(cbObj, ERR_DH_AUDIO_NULLPTR); - json jParam = { { KEY_DH_ID, std::to_string(dhId) } }; - AudioEvent event(AudioEventType::OPEN_SPEAKER, jParam.dump()); + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParam, KEY_DH_ID, std::to_string(dhId).c_str()); + char *jsonData = cJSON_PrintUnformatted(jParam); + if (jsonData == nullptr) { + DHLOGE("Failed to create JSON data."); + cJSON_Delete(jParam); + return ERR_DH_AUDIO_NULLPTR; + } + std::string jsonDataStr(jsonData); + AudioEvent event(AudioEventType::OPEN_SPEAKER, jsonDataStr); cbObj->NotifyEvent(event); DAudioHisysevent::GetInstance().SysEventWriteBehavior(DAUDIO_OPEN, devId, std::to_string(dhId), "daudio spk device open success."); + cJSON_Delete(jParam); + cJSON_free(jsonData); return DH_SUCCESS; } @@ -126,12 +137,23 @@ int32_t DSpeakerDev::CloseDevice(const std::string &devId, const int32_t dhId) std::shared_ptr cbObj = audioEventCallback_.lock(); CHECK_NULL_RETURN(cbObj, ERR_DH_AUDIO_NULLPTR); - json jParam = { { KEY_DH_ID, std::to_string(dhId) } }; - AudioEvent event(AudioEventType::CLOSE_SPEAKER, jParam.dump()); + cJSON *jParam = cJSON_CreateObject(); + CHECK_NULL_RETURN(jParam, ERR_DH_AUDIO_NULLPTR); + cJSON_AddStringToObject(jParam, KEY_DH_ID, std::to_string(dhId).c_str()); + char *jsonData = cJSON_PrintUnformatted(jParam); + if (jsonData == nullptr) { + DHLOGE("Failed to create JSON data."); + cJSON_Delete(jParam); + return ERR_DH_AUDIO_NULLPTR; + } + std::string jsonDataStr(jsonData); + AudioEvent event(AudioEventType::OPEN_SPEAKER, jsonDataStr); cbObj->NotifyEvent(event); DAudioHisysevent::GetInstance().SysEventWriteBehavior(DAUDIO_CLOSE, devId, std::to_string(dhId), "daudio spk device close success."); curPort_ = 0; + cJSON_Delete(jParam); + cJSON_free(jsonData); return DH_SUCCESS; } -- Gitee