• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <cstdio>
17 #include <cstring>
18 #include <cstdlib>
19 #include <unistd.h>
20 #include <cerrno>
21 #include <fcntl.h>
22 #include <csignal>
23 #include <sys/stat.h>
24 #include <iostream>
25 #include <string>
26 #include <securec.h>
27 #include "unistd.h"
28 #include "distributedaudiotest.h"
29 #include "accesstoken_kit.h"
30 #include "nativetoken_kit.h"
31 
32 using namespace OHOS::DistributedHardware;
33 using namespace OHOS::Security::AccessToken;
34 namespace {
35     static char const *PKG_NAME = "ohos.dsoftbus.tool";
36 }
37 
38 using OHOS::HDI::DistributedAudio::Audio::V1_0::IAudioAdapter;
39 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioAdapterDescriptor;
40 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioFormat;
41 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioPort;
42 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioPortDirection;
43 using OHOS::HDI::DistributedAudio::Audio::V1_0::IAudioManager;
44 using OHOS::HDI::DistributedAudio::Audio::V1_0::IAudioRender;
45 using OHOS::HDI::DistributedAudio::Audio::V1_0::IAudioCapture;
46 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioSampleAttributes;
47 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioDeviceDescriptor;
48 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioCategory;
49 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioRouteNode;
50 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioExtParamKey;
51 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioRoute;
52 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioSceneDescriptor;
53 using OHOS::HDI::DistributedAudio::Audio::V1_0::IAudioCallback;
54 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioPortPin;
55 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioPortType;
56 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioPortRole;
57 using OHOS::HDI::DistributedAudio::Audio::V1_0::AudioCallbackType;
58 int32_t g_volume = 5;
59 static int32_t ParamEventCallback(AudioExtParamKey key, const char *condition, const char *value, void *reserved,
60     void *cookie);
61 class AudioParamCallbackImpl final : public IAudioCallback {
62 public:
AudioParamCallbackImpl()63     AudioParamCallbackImpl() {}
~AudioParamCallbackImpl()64     ~AudioParamCallbackImpl() override {}
65     int32_t RenderCallback(AudioCallbackType type, int8_t &reserved, int8_t &cookie) override;
66     int32_t ParamCallback(AudioExtParamKey key, const std::string &condition, const std::string &value,
67         int8_t &reserved, int8_t cookie) override;
68 };
69 
RenderCallback(AudioCallbackType type,int8_t & reserved,int8_t & cookie)70 int32_t AudioParamCallbackImpl::RenderCallback(AudioCallbackType type, int8_t &reserved, int8_t &cookie)
71 {
72     (void) type;
73     (void) reserved;
74     (void) cookie;
75     return DH_SUCCESS;
76 }
77 
ParamCallback(AudioExtParamKey key,const std::string & condition,const std::string & value,int8_t & reserved,int8_t cookie)78 int32_t AudioParamCallbackImpl::ParamCallback(AudioExtParamKey key, const std::string &condition,
79     const std::string &value, int8_t &reserved, int8_t cookie)
80 {
81     (void) cookie;
82     void *cookies = nullptr;
83     ParamEventCallback(static_cast<::AudioExtParamKey>(key), condition.c_str(),
84         value.c_str(), static_cast<void *>(&reserved), cookies);
85     return DH_SUCCESS;
86 }
87 
88 const int32_t CMD_FIND = 9;
89 const int32_t CMD_OPEN_SPK = 1;
90 const int32_t CMD_CLOSE_SPK = 2;
91 const int32_t CMD_START_SPK = 3;
92 const int32_t CMD_STOP_SPK = 4;
93 const int32_t CMD_OPEN_MIC = 5;
94 const int32_t CMD_CLOSE_MIC = 6;
95 const int32_t CMD_START_MIC = 7;
96 const int32_t CMD_STOP_MIC = 8;
97 const int32_t CMD_SET_VOL = 11;
98 const int32_t CMD_GET_VOL = 12;
99 
100 const char DEV_TYPE_SPK = '1';
101 const char DEV_TYPE_MIC = '2';
102 const char SPK_FILE_PATH[128] = "/data/test.wav";
103 const char MIC_FILE_PATH[128] = "/data/mic.pcm";
104 constexpr int32_t TYPE_OFFSET = 12;
105 constexpr int32_t AUDIO_SAMPLE_RATE = 48000;
106 constexpr int32_t VOLUME_MIN = 0;
107 constexpr int32_t VOLUME_MAX = 15;
108 constexpr int32_t RENDER_FRAME_SIZE = 3840;
109 constexpr int32_t RENDER_INTER_LEAVED = 1;
110 constexpr int32_t RENDER_STREAM_ID = 0;
111 constexpr int32_t RENDER_CHANNEL_MASK = 2;
112 constexpr int32_t CAPTURE_INTER_LEAVED = 1;
113 constexpr int32_t CAPTURE_STREAM_ID = 2;
114 constexpr int32_t CAPTURE_CHANNEL_MASK = 2;
115 constexpr int64_t AUDIO_FRAME_TIME_INTERFAL_DEFAULT = 21333;
116 
117 static OHOS::sptr<IAudioManager> g_manager = nullptr;
118 static OHOS::sptr<IAudioAdapter> g_adapter = nullptr;
119 static OHOS::sptr<IAudioRender> g_render = nullptr;
120 static OHOS::sptr<IAudioCapture> g_capture = nullptr;
121 static std::vector<AudioAdapterDescriptor> g_devices;
122 static OHOS::sptr<IAudioCallback> g_callbackStub = nullptr;
123 static std::string g_devId = "";
124 
125 static constexpr const char* PLAY_THREAD = "playThread";
126 static constexpr const char* CAPTURE_THREAD = "captureThread";
127 
128 uint32_t g_renderId = 0;
129 uint32_t g_captureId = 0;
130 int32_t g_frameNum = 0;
131 int32_t g_frameIndex = 0;
132 int32_t g_micFrameNum = 0;
133 bool g_isInitRenderData = false;
134 static std::vector<uint8_t*> renderData;
135 
136 static DeviceStatus g_spkStatus = DeviceStatus::DEVICE_IDLE;
137 static DeviceStatus g_micStatus = DeviceStatus::DEVICE_IDLE;
138 
139 static std::thread g_playingThread;
140 static std::thread g_capingThread;
141 FILE *g_micFile = nullptr;
142 
GetNowTimeUs()143 static int64_t GetNowTimeUs()
144 {
145     std::chrono::microseconds nowUs =
146         std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch());
147     return nowUs.count();
148 }
149 
InitTestDemo()150 int32_t InitTestDemo()
151 {
152     std::cout << "**********************************************************************************" << std::endl;
153     DHLOGI("**********************************************************************************");
154     std::cout << "Distributed Audio Test Demo Bin v1.3." << std::endl;
155     std::cout << "**********************************************************************************" << std::endl;
156     std::cout << std::endl;
157     std::cout << "Init distributed audio hdf service." << std::endl;
158     g_manager = IAudioManager::Get("daudio_primary_service", false);
159     if (g_manager == nullptr) {
160         std::cout << "Distributed audio manager is null, Please Check network!" << std::endl;
161         return ERR_DH_AUDIO_FAILED;
162     }
163     std::cout << "Load audio manager success." << std::endl;
164     FindAudioDevice();
165     if (g_devId.empty()) {
166         std::cout << "Cannot find distributed device. Please input 9 to query distribtued device." << std::endl;
167     } else {
168         std::cout << "Find one distributed device: " << g_devId << std::endl;
169     }
170     return DH_SUCCESS;
171 }
172 
FindAudioDevice()173 std::string FindAudioDevice()
174 {
175     if (g_manager == nullptr) {
176         std::cout << "Audio manager is null, Please Check network!" << std::endl;
177         return "false";
178     }
179     int32_t ret = g_manager->GetAllAdapters(g_devices);
180     if (ret != DH_SUCCESS) {
181         std::cout << "Get audio devices failed!" << std::endl;
182         return "false";
183     }
184     for (uint32_t index = 0; index < g_devices.size(); index++) {
185         const AudioAdapterDescriptor desc = g_devices[index];
186         if (index == 0) {
187             g_devId = desc.adapterName;
188             break;
189         }
190     }
191     return "true";
192 }
193 
HandleDevError(const char * condition,const char * value)194 static void HandleDevError(const char *condition, const char *value)
195 {
196     if (condition[TYPE_OFFSET] == DEV_TYPE_SPK && g_spkStatus != DeviceStatus::DEVICE_IDLE) {
197         CloseSpk();
198     }
199 
200     if (condition[TYPE_OFFSET] == DEV_TYPE_MIC && g_micStatus == DeviceStatus::DEVICE_IDLE) {
201         CloseMic();
202     }
203 
204     std::cout << "Receive abnormal event, Demo quit." << std::endl;
205 }
206 
ParamEventCallback(AudioExtParamKey key,const char * condition,const char * value,void * reserved,void * cookie)207 static int32_t ParamEventCallback(AudioExtParamKey key, const char *condition, const char *value, void *reserved,
208     void *cookie)
209 {
210     std::string val(value);
211     std::string con(condition);
212     std::cout << std::endl;
213     std::cout << "**********************************************************************************" << std::endl;
214     std::cout << "Event recived: " << key << std::endl;
215     std::cout << "Condition: " << con << std::endl;
216     std::cout << "Value: " << val << std::endl;
217     std::cout << "**********************************************************************************" << std::endl;
218     std::cout << std::endl;
219 
220     if (key == AudioExtParamKey::AUDIO_EXT_PARAM_KEY_STATUS && con.rfind("ERR_EVENT", 0) == 0) {
221         HandleDevError(condition, value);
222     }
223     return DH_SUCCESS;
224 }
225 
LoadSpkDev(const std::string & devId)226 static int32_t LoadSpkDev(const std::string &devId)
227 {
228     struct AudioAdapterDescriptor dev;
229     for (uint32_t index = 0; index < g_devices.size(); index++) {
230         struct AudioAdapterDescriptor desc = g_devices[index];
231         if (desc.adapterName == devId) {
232             dev = desc;
233             break;
234         }
235     }
236     if (dev.adapterName.data() == nullptr) {
237         std::cout << "Input device id is wrong." << std::endl;
238         FindAudioDevice();
239         return ERR_DH_AUDIO_FAILED;
240     }
241     if (g_manager == nullptr) {
242         return ERR_DH_AUDIO_FAILED;
243     }
244     if (g_adapter == nullptr) {
245         int32_t ret = g_manager->LoadAdapter(dev, g_adapter);
246         if (ret != DH_SUCCESS || g_adapter == nullptr) {
247             std::cout << "Load audio device failed, ret: " << ret << std::endl;
248             return ERR_DH_AUDIO_FAILED;
249         }
250     }
251     return DH_SUCCESS;
252 }
253 
OpenSpk(std::string devId)254 std::string OpenSpk(std::string devId)
255 {
256     if (g_spkStatus != DeviceStatus::DEVICE_IDLE) {
257         std::cout << "Speaker device is already opened." << std::endl;
258         return "true";
259     }
260     if (LoadSpkDev(devId) != DH_SUCCESS) {
261         std::cout << "Load spk failed" << std::endl;
262         return "false";
263     }
264 
265     g_callbackStub = new AudioParamCallbackImpl();
266     int32_t ret = g_adapter->RegExtraParamObserver(g_callbackStub, 0);
267     if (ret != DH_SUCCESS) {
268         std::cout << "Register observer failed, ret: " << ret << std::endl;
269         return "false";
270     }
271 
272     struct AudioDeviceDescriptor renderDesc;
273     renderDesc.pins = AudioPortPin::PIN_OUT_SPEAKER;
274     renderDesc.desc = "";
275     AudioSampleAttributes g_rattrs = {};
276     g_rattrs.type = AudioCategory::AUDIO_IN_MEDIA;
277     g_rattrs.interleaved = RENDER_INTER_LEAVED;
278     g_rattrs.streamId = RENDER_STREAM_ID;
279     g_rattrs.channelCount = RENDER_CHANNEL_MASK;
280     g_rattrs.sampleRate = AUDIO_SAMPLE_RATE;
281     g_rattrs.format = AudioFormat::AUDIO_FORMAT_TYPE_PCM_16_BIT;
282     ret = g_adapter->CreateRender(renderDesc, g_rattrs, g_render, g_renderId);
283     if (ret != DH_SUCCESS || g_render == nullptr) {
284         std::cout << "Open SPK device failed, ret: " << ret << std::endl;
285         return "false";
286     }
287     g_spkStatus = DeviceStatus::DEVICE_OPEN;
288     std::cout << "Open SPK device success." << std::endl;
289     return "true";
290 }
291 
WriteStreamWait(const int64_t & startTime)292 static void WriteStreamWait(const int64_t &startTime)
293 {
294     int64_t endTime = GetNowTimeUs();
295     int64_t passTime = endTime - startTime;
296 
297     if (passTime > AUDIO_FRAME_TIME_INTERFAL_DEFAULT) {
298         return;
299     }
300     int64_t remainTime = AUDIO_FRAME_TIME_INTERFAL_DEFAULT - passTime;
301     std::this_thread::sleep_for(std::chrono::microseconds(remainTime));
302 }
303 
Play()304 static void Play()
305 {
306     if (g_render == nullptr) {
307         std::cout << "SPK device is null." << std::endl;
308         return;
309     }
310     if (pthread_setname_np(pthread_self(), PLAY_THREAD) != DH_SUCCESS) {
311         std::cout << "Play thread setname failed." << std::endl;
312     }
313     std::cout << "Playing thread started." << std::endl;
314     g_render->Start();
315     g_spkStatus = DeviceStatus::DEVICE_START;
316 
317     uint64_t size = 0;
318     while (g_spkStatus == DeviceStatus::DEVICE_START) {
319         int64_t startTime = GetNowTimeUs();
320 
321         std::vector<int8_t> frameHal(RENDER_FRAME_SIZE);
322         int32_t ret = memcpy_s(frameHal.data(), RENDER_FRAME_SIZE, renderData[g_frameIndex], RENDER_FRAME_SIZE);
323         if (ret != EOK) {
324             DHLOGE("Copy render frame failed, error code %{public}d.", ret);
325             return;
326         }
327         ret = g_render->RenderFrame(frameHal, size);
328         if (ret != DH_SUCCESS) {
329             std::cout<<"RenderFrame failed, index: "<< g_frameIndex << ", ret:  " << ret << std::endl;
330         }
331         g_frameIndex++;
332         if (g_frameNum != 0 && g_frameIndex == g_frameNum) {
333             g_frameIndex = 0;
334         }
335         WriteStreamWait(startTime);
336     }
337     std::cout << "Playing thread stopped." << std::endl;
338 }
339 
StartRender()340 std::string StartRender()
341 {
342     if (g_spkStatus == DeviceStatus::DEVICE_IDLE) {
343         std::cout << "Speaker device is not opened, start render failed." << std::endl;
344         return "false";
345     }
346 
347     if (g_spkStatus == DeviceStatus::DEVICE_OPEN) {
348         WavHdr wavHeader;
349         size_t headerSize = sizeof(WavHdr);
350         if (!g_isInitRenderData) {
351             struct stat statbuf;
352             stat(SPK_FILE_PATH, &statbuf);
353             int32_t size = statbuf.st_size;
354             g_frameNum = (size - static_cast<int32_t>(headerSize)) / RENDER_FRAME_SIZE;
355             std::cout << "Audio file frame num: " << g_frameNum << std::endl;
356             for (int32_t j = 0; j < g_frameNum; j++) {
357                 uint8_t *frame = new uint8_t[RENDER_FRAME_SIZE]();
358                 renderData.push_back(frame);
359             }
360             g_isInitRenderData = true;
361         }
362         FILE *wavFile = fopen(SPK_FILE_PATH, "rb");
363 
364         if (wavFile == nullptr) {
365             DHLOGE("open spk file path failed!");
366             std::cout << "open spk file path failed!" << std::endl;
367             return "false";
368         }
369 
370         fread(&wavHeader, 1, headerSize, wavFile);
371         for (int32_t i = 0; i < g_frameNum; i++) {
372             fread(renderData[i], 1, RENDER_FRAME_SIZE, wavFile);
373         }
374         fclose(wavFile);
375         g_frameIndex = 0;
376         g_playingThread = std::thread(Play);
377         return "true";
378     }
379     if (g_spkStatus == DeviceStatus::DEVICE_START) {
380         std::cout << "Speaker device is started." << std::endl;
381         return "true";
382     }
383     if (g_spkStatus == DeviceStatus::DEVICE_STOP) {
384         g_playingThread = std::thread(Play);
385     }
386     return "true";
387 }
388 
StopRender()389 std::string StopRender()
390 {
391     if (g_render == nullptr) {
392         std::cout << "SPK device is null." << std::endl;
393         return "false";
394     }
395 
396     if (g_spkStatus == DeviceStatus::DEVICE_IDLE) {
397         std::cout << "Speaker device is not opened." << std::endl;
398         return "false";
399     }
400 
401     if (g_spkStatus == DeviceStatus::DEVICE_OPEN) {
402         std::cout << "Speaker device is not started." << std::endl;
403         return "false";
404     }
405 
406     if (g_spkStatus == DeviceStatus::DEVICE_STOP) {
407         std::cout << "Speaker device is already stoped." << std::endl;
408         return "true";
409     }
410 
411     g_spkStatus = DeviceStatus::DEVICE_STOP;
412     if (g_playingThread.joinable()) {
413         g_playingThread.join();
414     }
415     g_render->Stop();
416     return "true";
417 }
418 
CloseSpk()419 std::string CloseSpk()
420 {
421     if (g_spkStatus == DeviceStatus::DEVICE_IDLE) {
422         std::cout << "Speaker device is not opened." << std::endl;
423         return "false";
424     }
425 
426     if (g_spkStatus == DeviceStatus::DEVICE_START) {
427         StopRender();
428     }
429 
430     int32_t ret = g_adapter->DestroyRender(g_renderId);
431     if (ret != DH_SUCCESS) {
432         std::cout << "Close speaker failed" << std::endl;
433         return "false";
434     }
435     if (g_micStatus == DeviceStatus::DEVICE_IDLE) {
436         g_manager->UnloadAdapter(g_devId);
437         g_adapter = nullptr;
438     }
439     g_spkStatus = DeviceStatus::DEVICE_IDLE;
440 
441     if (g_isInitRenderData) {
442         for (auto &p : renderData) {
443             delete[] p;
444         }
445         renderData.clear();
446         g_isInitRenderData = false;
447     }
448     std::cout << "Close SPK device success." << std::endl;
449     return "true";
450 }
451 
LoadMicDev(const std::string & devId)452 static int32_t LoadMicDev(const std::string &devId)
453 {
454     struct AudioAdapterDescriptor dev;
455     for (uint32_t index = 0; index < g_devices.size(); index++) {
456         struct AudioAdapterDescriptor desc = g_devices[index];
457         if (desc.adapterName == devId) {
458             dev = desc;
459             break;
460         }
461     }
462     if (dev.adapterName.data() == nullptr) {
463         std::cout << "Input device id is wrong." << std::endl;
464         FindAudioDevice();
465         return ERR_DH_AUDIO_FAILED;
466     }
467     if (g_manager == nullptr) {
468         return ERR_DH_AUDIO_FAILED;
469     }
470     if (g_adapter == nullptr) {
471         int32_t ret = g_manager->LoadAdapter(dev, g_adapter);
472         if (ret != DH_SUCCESS || g_adapter == nullptr) {
473             std::cout << "Load audio device failed, ret: " << ret << std::endl;
474             return ERR_DH_AUDIO_FAILED;
475         }
476     }
477     return DH_SUCCESS;
478 }
479 
OpenMic(std::string devId)480 std::string OpenMic(std::string devId)
481 {
482     if (g_micStatus != DeviceStatus::DEVICE_IDLE) {
483         std::cout << "Mic device is already opened." << std::endl;
484         return "true";
485     }
486     if (LoadMicDev(devId) != DH_SUCCESS) {
487         std::cout << "Load audio device failed." << std::endl;
488         return "false";
489     }
490 
491     AudioDeviceDescriptor captureDesc;
492     captureDesc.pins = AudioPortPin::PIN_IN_MIC;
493     captureDesc.desc = "";
494     AudioSampleAttributes captureAttr;
495     captureAttr.type = AudioCategory::AUDIO_IN_MEDIA;
496     captureAttr.interleaved = CAPTURE_INTER_LEAVED;
497     captureAttr.streamId = CAPTURE_STREAM_ID;
498     captureAttr.channelCount = CAPTURE_CHANNEL_MASK;
499     captureAttr.sampleRate = AUDIO_SAMPLE_RATE;
500     captureAttr.format = AudioFormat::AUDIO_FORMAT_TYPE_PCM_16_BIT;
501     int32_t ret = g_adapter->CreateCapture(captureDesc, captureAttr, g_capture, g_captureId);
502     if (ret != DH_SUCCESS || g_capture == nullptr) {
503         std::cout << "Open MIC device failed." << std::endl;
504         return "false";
505     }
506     g_micStatus = DeviceStatus::DEVICE_OPEN;
507     std::cout << "Open MIC device success." << std::endl;
508     return "true";
509 }
510 
ReadStreamWait(const int64_t & startTime)511 static void ReadStreamWait(const int64_t &startTime)
512 {
513     int64_t endTime = GetNowTimeUs();
514     int32_t passTime = endTime - startTime;
515 
516     if (passTime > AUDIO_FRAME_TIME_INTERFAL_DEFAULT) {
517         return;
518     }
519     int64_t remainTime = AUDIO_FRAME_TIME_INTERFAL_DEFAULT - passTime;
520     std::this_thread::sleep_for(std::chrono::microseconds(remainTime));
521 }
522 
Capture()523 static void Capture()
524 {
525     if (g_capture == nullptr) {
526         std::cout << "MIC device is null." << std::endl;
527         return;
528     }
529     if (pthread_setname_np(pthread_self(), CAPTURE_THREAD) != DH_SUCCESS) {
530         std::cout << "Capture thread setname failed." << std::endl;
531     }
532     std::cout << "Capturing thread started." << std::endl;
533     g_capture->Start();
534     g_micStatus = DeviceStatus::DEVICE_START;
535 
536     uint64_t size = 0;
537     while (g_micStatus == DeviceStatus::DEVICE_START) {
538         std::vector<int8_t> data(RENDER_FRAME_SIZE);
539         int64_t startTime = GetNowTimeUs();
540         int32_t ret = g_capture->CaptureFrame(data, size);
541         if (ret != DH_SUCCESS) {
542             std::cout << "CaptureFrame failed, ret: " << ret << std::endl;
543             return;
544         }
545         size_t writeCnt = fwrite(data.data(), 1, RENDER_FRAME_SIZE, g_micFile);
546         if (static_cast<int32_t>(writeCnt) != RENDER_FRAME_SIZE) {
547             std::cout << "fwrite data failed." << std::endl;
548         }
549         g_micFrameNum++;
550         ReadStreamWait(startTime);
551     }
552     std::cout << "Capturing thread stopped." << std::endl;
553 }
554 
StartCapture()555 std::string StartCapture()
556 {
557     if (g_micStatus == DeviceStatus::DEVICE_IDLE) {
558         std::cout << "Mic device is not opened, start capture failed." << std::endl;
559         return "false";
560     }
561 
562     if (g_micStatus == DeviceStatus::DEVICE_OPEN) {
563         g_micFile = fopen(MIC_FILE_PATH, "ab+");
564         if (g_micFile == nullptr) {
565             std::cout << "Open pcm file failed." << std::endl;
566             return "false";
567         }
568         g_capingThread = std::thread(Capture);
569         return "true";
570     }
571 
572     if (g_micStatus == DeviceStatus::DEVICE_START) {
573         std::cout << "Mic device is already started." << std::endl;
574         return "true";
575     }
576 
577     if (g_micStatus == DeviceStatus::DEVICE_STOP) {
578         g_capingThread = std::thread(Capture);
579     }
580     return "true";
581 }
582 
StopCapture()583 std::string StopCapture()
584 {
585     if (g_capture == nullptr) {
586         std::cout << "MIC device is null." << std::endl;
587         return "false";
588     }
589     if (g_micStatus == DeviceStatus::DEVICE_IDLE) {
590         std::cout << "Mic device is not opened." << std::endl;
591         return "false";
592     }
593     if (g_micStatus == DeviceStatus::DEVICE_OPEN) {
594         std::cout << "Mic device is not started." << std::endl;
595         return "false";
596     }
597     if (g_micStatus == DeviceStatus::DEVICE_STOP) {
598         std::cout << "Mic device is already started." << std::endl;
599         return "false";
600     }
601     g_micStatus = DeviceStatus::DEVICE_STOP;
602     if (g_capingThread.joinable()) {
603         g_capingThread.join();
604     }
605     g_capture->Stop();
606     return "true";
607 }
608 
CloseMic()609 std::string CloseMic()
610 {
611     if (g_micStatus == DeviceStatus::DEVICE_IDLE) {
612         std::cout << "Mic device is not opened." << std::endl;
613         return "false";
614     }
615 
616     if (g_micStatus == DeviceStatus::DEVICE_START) {
617         StopCapture();
618     }
619 
620     int32_t ret = g_adapter->DestroyCapture(g_captureId);
621     if (ret != DH_SUCCESS) {
622         std::cout << "Close mic failed." << std::endl;
623         return "false";
624     }
625     if (g_spkStatus == DeviceStatus::DEVICE_IDLE) {
626         g_manager->UnloadAdapter(g_devId);
627         g_adapter = nullptr;
628     }
629     if (g_micFile != nullptr) {
630         fclose(g_micFile);
631         g_micFile = nullptr;
632     }
633     g_micStatus = DeviceStatus::DEVICE_IDLE;
634     std::cout << "Close MIC device success." << std::endl;
635     return "true";
636 }
637 
SetVolume(int vol)638 std::string SetVolume(int vol)
639 {
640     if (g_spkStatus == DeviceStatus::DEVICE_IDLE) {
641         std::cout << "Speaker is not opened, can not set volume." << std::endl;
642         return "false";
643     }
644     std::cout << "Please input volum to set [0,15]." << std::endl;
645     if (vol < VOLUME_MIN || vol > VOLUME_MAX) {
646         std::cout << "Volume is invalid." << std::endl;
647         return "false";
648     }
649     std::cout << "Set volume: " << vol << std::endl;
650     AudioExtParamKey key = AudioExtParamKey::AUDIO_EXT_PARAM_KEY_VOLUME;
651     std::string condition = "EVENT_TYPE=1;VOLUME_GROUP_ID=1;AUDIO_VOLUME_TYPE=1;";
652     std::string volStr = std::to_string(vol);
653     int32_t ret = g_adapter->SetExtraParams(key, condition, volStr);
654     if (ret != DH_SUCCESS) {
655         std::cout << "Set volume failed" << std::endl;
656         return "false";
657     }
658     return "true";
659 }
660 
GetVolume()661 std::string GetVolume()
662 {
663     if (g_spkStatus == DeviceStatus::DEVICE_IDLE) {
664         std::cout << "Speaker is not opened, can not get volume." << std::endl;
665         return "false";
666     }
667     AudioExtParamKey key = AudioExtParamKey::AUDIO_EXT_PARAM_KEY_VOLUME;
668     std::string condition = "EVENT_TYPE=1;VOLUME_GROUP_ID=1;AUDIO_VOLUME_TYPE=1;";
669     std::string vol;
670     int32_t ret = g_adapter->GetExtraParams(key, condition.c_str(), vol);
671     if (ret != DH_SUCCESS) {
672         std::cout << "Get Volume failed." << std::endl;
673         return "false";
674     }
675     std::cout << "Get volume success. volume: " << vol <<std::endl;
676     return "true";
677 }
678 
HandleAudioEvent(int32_t cmd)679 std::string HandleAudioEvent(int32_t cmd)
680 {
681     std::string res = "";
682     if (cmd == CMD_FIND) {
683         res = FindAudioDevice();
684     }
685     if (cmd == CMD_OPEN_SPK) {
686         res = OpenSpk(g_devId);
687     }
688     if (cmd == CMD_START_SPK) {
689         res = StartRender();
690     }
691     if (cmd == CMD_STOP_SPK) {
692         res = StopRender();
693     }
694     if (cmd == CMD_CLOSE_SPK) {
695         res = CloseSpk();
696     }
697     if (cmd == CMD_OPEN_MIC) {
698         res = OpenMic(g_devId);
699     }
700     if (cmd == CMD_START_MIC) {
701         res = StartCapture();
702     }
703     if (cmd == CMD_STOP_MIC) {
704         res = StopCapture();
705     }
706     if (cmd == CMD_CLOSE_MIC) {
707         res = CloseMic();
708     }
709     if (cmd == CMD_SET_VOL) {
710         res = SetVolume(g_volume);
711     }
712     if (cmd == CMD_GET_VOL) {
713         res = GetVolume();
714     }
715     return res;
716 }
717 
GetSyncOnlineDevices(std::string & netWorkId)718 int32_t GetSyncOnlineDevices(std::string& netWorkId)
719 {
720     uint64_t tokenId;
721     const char *perms[2];
722     perms[0] = OHOS_PERMISSION_DISTRIBUTED_SOFTBUS_CENTER;
723     perms[1] = OHOS_PERMISSION_DISTRIBUTED_DATASYNC;
724     NativeTokenInfoParams infoInstance = {
725         .dcapsNum = 0,
726         .permsNum = 2,
727         .aclsNum = 0,
728         .dcaps = NULL,
729         .perms = perms,
730         .acls = NULL,
731         .processName = "camera_test_demo",
732         .aplStr = "system_core",
733     };
734     tokenId = GetAccessTokenId(&infoInstance);
735     SetSelfTokenID(tokenId);
736     OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo();
737 
738     NodeBasicInfo localNodeinfo;
739     NodeBasicInfo *remoteNodeInfo = nullptr;
740     int32_t infoNum = 0;
741     std::cout << "-----------Local Device Info------" << std::endl;
742     if (GetLocalNodeDeviceInfo(PKG_NAME, &localNodeinfo) != 0) {
743         printf("LnnGetLocalNodeInfo Fail!\n");
744         return -1;
745     }
746     PrintNodeProperty(&localNodeinfo);
747     std::cout << "-------Remote Device info---------" << std::endl;
748     if (GetAllNodeDeviceInfo(PKG_NAME, &remoteNodeInfo, &infoNum) != 0) {
749         printf("GetAllNodeDeviceInfo Fail!\n");
750         return ERR_DH_AUDIO_FAILED;
751     }
752     std::cout << "Device Num = " << infoNum << std::endl;
753     for (int i = 0; i < infoNum; ++i) {
754         PrintNodeProperty(remoteNodeInfo + i, netWorkId);
755     }
756     FreeNodeInfo(remoteNodeInfo);
757     std::cout << "SoftBusDumpDeviceInfo complete!" << std::endl;
758     return 0;
759 }
760 
PrintNodeProperty(NodeBasicInfo * nodeInfo)761 void PrintNodeProperty(NodeBasicInfo *nodeInfo)
762 {
763     if (nodeInfo == nullptr) {
764         std::cout << "nodeInfo is nullptr" << std::endl;
765         return;
766     }
767 
768     printf("DeviceName = %s\n", nodeInfo->deviceName);
769     std::cout << "NetworkId = " << nodeInfo->networkId << std::endl;
770 
771     NodeDeviceInfoKey key = NODE_KEY_UDID;
772     unsigned char udid[UDID_BUF_LEN] = {0};
773     if (GetNodeKeyInfo(PKG_NAME, nodeInfo->networkId, key, udid, UDID_BUF_LEN) != 0) {
774         std::cout << "GetNodeKeyInfo Fail!" << std::endl;
775     } else {
776         std::cout << "Udid = " <<  reinterpret_cast<char *>(udid) << std::endl;
777     }
778     key = NODE_KEY_UUID;
779     unsigned char uuid[UUID_BUF_LEN] = {0};
780     if (GetNodeKeyInfo(PKG_NAME, nodeInfo->networkId, key, uuid, UUID_BUF_LEN) != 0) {
781         printf("GetNodeKeyInfo Fail!\n");
782     } else {
783         std::cout << "uuid = " <<  reinterpret_cast<char *>(uuid) << std::endl;
784     }
785 }
786 
PrintNodeProperty(NodeBasicInfo * nodeInfo,std::string & netWorkId)787 void PrintNodeProperty(NodeBasicInfo *nodeInfo, std::string& netWorkId)
788 {
789     if (nodeInfo == nullptr) {
790         std::cout << "nodeInfo is nullptr" << std::endl;
791         return;
792     }
793 
794     printf("DeviceName = %s\n", nodeInfo->deviceName);
795     netWorkId = nodeInfo->networkId;
796     std::cout << "NetworkId = " << nodeInfo->networkId << std::endl;
797 
798     NodeDeviceInfoKey key = NODE_KEY_UDID;
799     unsigned char udid[UDID_BUF_LEN] = {0};
800     if (GetNodeKeyInfo(PKG_NAME, nodeInfo->networkId, key, udid, UDID_BUF_LEN) != 0) {
801         std::cout << "GetNodeKeyInfo Fail!" << std::endl;
802     } else {
803         std::cout << "Udid = " <<  reinterpret_cast<char *>(udid) << std::endl;
804     }
805     key = NODE_KEY_UUID;
806     unsigned char uuid[UUID_BUF_LEN] = {0};
807     if (GetNodeKeyInfo(PKG_NAME, nodeInfo->networkId, key, uuid, UUID_BUF_LEN) != 0) {
808         printf("GetNodeKeyInfo Fail!\n");
809     } else {
810         std::cout << "uuid = " <<  reinterpret_cast<char *>(uuid) << std::endl;
811     }
812 }
813 
AddPermission(void)814 void AddPermission(void)
815 {
816     uint64_t tokenId;
817     const char *perms[2];
818     perms[0] = OHOS_PERMISSION_DISTRIBUTED_SOFTBUS_CENTER;
819     perms[1] = OHOS_PERMISSION_DISTRIBUTED_DATASYNC;
820     NativeTokenInfoParams infoTnstance = {
821         .dcapsNum = 0,
822         .permsNum = 2,
823         .aclsNum = 0,
824         .dcaps = NULL,
825         .perms = perms,
826         .acls = NULL,
827         .processName = "daudio_test_service",
828         .aplStr = "system_core",
829     };
830     tokenId = GetAccessTokenId(&infoTnstance);
831     SetSelfTokenID(tokenId);
832 }