• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-2025 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 <cinttypes>
17 #include <condition_variable>
18 #include <cstdint>
19 #include <ctime>
20 #include <ostream>
21 #include <sstream>
22 #include <iostream>
23 #include <thread>
24 #include <mutex>
25 #include <map>
26 #include <securec.h>
27 
28 #include <sys/time.h>
29 
30 #include "audio_service_log.h"
31 #include "audio_errors.h"
32 #include "audio_utils.h"
33 #include "audio_system_manager.h"
34 #include "parameter.h"
35 #include "pcm2wav.h"
36 #include "audio_process_in_client.h"
37 #include "fast_audio_stream.h"
38 
39 using namespace std;
40 namespace OHOS {
41 namespace AudioStandard {
42 namespace {
43     static constexpr long WAV_HEADER_SIZE = 42;
44     static constexpr int64_t SECOND_TO_NANOSECOND = 1000000000;
45     static constexpr int64_t MIC_SLEEP_TIME_US = 2000000000;
46     constexpr int32_t SAMPLE_FORMAT_U8 = 8;
47     constexpr int32_t SAMPLE_FORMAT_S16LE = 16;
48     constexpr int32_t SAMPLE_FORMAT_S24LE = 24;
49     constexpr int32_t SAMPLE_FORMAT_S32LE = 32;
50     enum OperationCode : int32_t {
51         INVALID_OPERATION = -1,
52         INIT_LOCAL_SPK_PROCESS = 0,
53         INIT_REMOTE_SPK_PROCESS = 1,
54         START_SPK_PROCESS = 2,
55         PAUSE_SPK_PROCESS = 3,
56         RESUME_SPK_PROCESS = 4,
57         STOP_SPK_PROCESS = 5,
58         CHANGE_SPK_PROCESS_VOL = 6,
59         RELEASE_SPK_PROCESS = 7,
60 
61         START_LOOP_TEST = 10,
62         END_LOOP_TEST = 11,
63 
64         START_SIGNAL_TEST = 12,
65         END_SIGNAL_TEST = 13,
66 
67         INIT_LOCAL_MIC_PROCESS = 20,
68         INIT_REMOTE_MIC_PROCESS = 21,
69         START_MIC_PROCESS = 22,
70         PAUSE_MIC_PROCESS = 23,
71         RESUME_MIC_PROCESS = 24,
72         STOP_MIC_PROCESS = 25,
73         CHANGE_MIC_PROCESS_VOL = 26,
74         RELEASE_MIC_PROCESS = 27,
75 
76         LOCAL_LATENCY_TEST = 30,
77         REMOTE_LATENCY_TEST = 31,
78 
79         EXIT_INTERACTIVE_TEST = 40,
80     };
81 
82     enum AudioProcessTestType : int32_t {
83         INVALID_PROC_TEST = 0,
84         INTERACTIVE_RUN_SPK_TEST = 1,
85         AUTO_RUN_SPK_TEST = 2,
86         INTERACTIVE_RUN_MIC_TEST = 3,
87         AUTO_RUN_MIC_TEST = 4,
88         INTERACTIVE_RUN_LOOP = 5,
89         RENDER_SIGNAL_TEST = 6,
90         EXIT_PROC_TEST = 7,
91     };
92     enum TestMode : int32_t {
93         RENDER_FILE = 0,
94         RENDER_MIC_LOOP_DATA = 1,
95         RENDER_SIGNAL_DATA = 2,
96     };
97     static constexpr size_t CACHE_BUFFER_SIZE = 960;
98     TestMode g_testMode = RENDER_FILE;
99     bool g_renderSignal = false;
100     int64_t g_stampTime = 0;
101 }
102 
103 class AudioProcessTest;
104 shared_ptr<AudioProcessTest> g_audioProcessTest = nullptr;
105 std::string g_spkfilePath = "";
106 const std::string MIC_FILE_PATH = "/data/data/mic.pcm";
107 FILE *g_spkWavFile = nullptr;
108 FILE *g_micPcmFile = nullptr;
109 std::vector<int64_t> g_playBeepTime_;
110 std::vector<int64_t> g_captureBeepTime_;
111 bool g_isLatencyTesting = false;
112 int32_t g_setVol = 60000;
113 int32_t g_usPerMs = 1000;
114 mutex g_autoRunMutex;
115 condition_variable g_autoRunCV;
116 
117 unique_ptr<uint8_t[]> g_byteBuffer = nullptr;
118 BufferDesc g_cacheBuffer = {nullptr, 0, 0};
119 
120 string ConfigSpkTest(bool isRemote);
121 string CallStartSpk();
122 string CallPauseSpk();
123 string CallResumeSpk();
124 string CallStopSpk();
125 string SetSpkVolume();
126 string CallReleaseSpk();
127 
128 string StartSignalTest();
129 string EndSignalTest();
130 
131 string ConfigMicTest(bool isRemote);
132 string CallStartMic();
133 string CallPauseMic();
134 string CallResumeMic();
135 string CallStopMic();
136 string SetMicVolume();
137 string CallReleaseMic();
138 
139 void CountLatencyTime();
140 string LoopLatencyTest(bool isRemote);
141 string LocalLoopLatencyTest();
142 string RemoteLoopLatencyTest();
143 using CallTestOperationFunc = string (*)();
144 
145 std::map<int32_t, std::string> g_audioProcessTestType = {
146     {INTERACTIVE_RUN_SPK_TEST, "Interactive run spk process test"},
147     {AUTO_RUN_SPK_TEST, "Auto run spk process test"},
148     {INTERACTIVE_RUN_MIC_TEST, "Interactive run mic process test"},
149     {AUTO_RUN_MIC_TEST, "Auto run mic process test"},
150     {INTERACTIVE_RUN_LOOP, "Roundtrip latency test"},
151     {RENDER_SIGNAL_TEST, "Render signal latency test"},
152     {EXIT_PROC_TEST, "Exit audio process test"},
153 };
154 
155 std::map<int32_t, std::string> g_interactiveOptStrMap = {
156     {INIT_LOCAL_SPK_PROCESS, "call local spk init process"},
157     {INIT_REMOTE_SPK_PROCESS, "call remote spk init process"},
158     {START_SPK_PROCESS, "call start spk process"},
159     {PAUSE_SPK_PROCESS, "call pause spk process"},
160     {RESUME_SPK_PROCESS, "call resume spk process"},
161     {STOP_SPK_PROCESS, "call stop spk process"},
162     {CHANGE_SPK_PROCESS_VOL, "change spk process volume"},
163     {RELEASE_SPK_PROCESS, "release spk process"},
164 
165     {START_LOOP_TEST, "start loop"},
166     {END_LOOP_TEST, "end loop"},
167 
168     {START_SIGNAL_TEST, "start signal test"},
169     {END_SIGNAL_TEST, "end signal test"},
170 
171     {INIT_LOCAL_MIC_PROCESS, "call local mic init process"},
172     {INIT_REMOTE_MIC_PROCESS, "call remote mic init process"},
173     {START_MIC_PROCESS, "call start mic process"},
174     {PAUSE_MIC_PROCESS, "call pause mic process"},
175     {RESUME_MIC_PROCESS, "call resume mic process"},
176     {STOP_MIC_PROCESS, "call stop mic process"},
177     {CHANGE_MIC_PROCESS_VOL, "change mic process volume"},
178     {RELEASE_MIC_PROCESS, "release mic process"},
179 
180     {LOCAL_LATENCY_TEST, "call local loop latency test"},
181     {REMOTE_LATENCY_TEST, "call remote loop latency test"},
182 
183     {EXIT_INTERACTIVE_TEST, "exit interactive run test"},
184 };
185 
186 std::map<int32_t, CallTestOperationFunc> g_interactiveOptFuncMap = {
187     {START_SPK_PROCESS, CallStartSpk},
188     {PAUSE_SPK_PROCESS, CallPauseSpk},
189     {RESUME_SPK_PROCESS, CallResumeSpk},
190     {STOP_SPK_PROCESS, CallStopSpk},
191     {CHANGE_SPK_PROCESS_VOL, SetSpkVolume},
192     {RELEASE_SPK_PROCESS, CallReleaseSpk},
193 
194     {START_SIGNAL_TEST, StartSignalTest},
195     {END_SIGNAL_TEST, EndSignalTest},
196 
197     {START_MIC_PROCESS, CallStartMic},
198     {PAUSE_MIC_PROCESS, CallPauseMic},
199     {RESUME_MIC_PROCESS, CallResumeMic},
200     {STOP_MIC_PROCESS, CallStopMic},
201     {CHANGE_MIC_PROCESS_VOL, SetMicVolume},
202     {RELEASE_MIC_PROCESS, CallReleaseMic},
203 
204     {LOCAL_LATENCY_TEST, LocalLoopLatencyTest},
205     {REMOTE_LATENCY_TEST, RemoteLoopLatencyTest},
206 };
207 
208 class AudioProcessTestCallback : public AudioDataCallback {
209 public:
AudioProcessTestCallback(const std::shared_ptr<AudioProcessInClient> & procClient,int32_t spkLoopCnt,AudioMode clientMode)210     AudioProcessTestCallback(const std::shared_ptr<AudioProcessInClient> &procClient,
211         int32_t spkLoopCnt, AudioMode clientMode)
212         : procClient_(procClient), loopCount_(spkLoopCnt), clientMode_(clientMode) {};
213     ~AudioProcessTestCallback() = default;
214 
215     void OnHandleData(size_t length) override;
InitSignalBuffer(const BufferDesc & signalSoundBuffer)216     void InitSignalBuffer(const BufferDesc &signalSoundBuffer)
217     {
218         int ret = memset_s(signalSoundBuffer.buffer, signalSoundBuffer.bufLength, 0, signalSoundBuffer.bufLength);
219         if (ret != EOK) {
220             return;
221         }
222         const int channels = 2; // 2 channels
223         const int samplePerChannel = 96 / channels; // 96 for 1ms
224         int16_t *signalData = static_cast<int16_t *>(static_cast<void *>(signalSoundBuffer.buffer));
225         int16_t bound = 10;
226         for (int idx = 0; idx < samplePerChannel; idx++) {
227             signalData[channels * idx] = bound + static_cast<int16_t>(sinf(2.0f * static_cast<float>(M_PI) * idx /
228                 samplePerChannel) * (SHRT_MAX - bound));
229             for (int c = 1; c < channels; c++) {
230                 signalData[channels * idx + c] = signalData[channels * idx];
231             }
232         }
233     };
234 
235 private:
236     int32_t CaptureToFile(const BufferDesc &bufDesc);
237     int32_t RenderFromFile(const BufferDesc &bufDesc);
238     bool IsFrameHigh(const int16_t *audioData, const int32_t size, int32_t threshold);
239     int64_t RecordBeepTime(const uint8_t *base, const int32_t &sizePerFrame, bool &status);
240     int64_t GetNowTimeUs();
241 
HandleWriteLoopData(const BufferDesc & bufDesc)242     void HandleWriteLoopData(const BufferDesc &bufDesc)
243     {
244         loopCount_++;
245         int32_t periodCount = loopCount_ % 400; // 400 * 0.005 = 2s
246 
247         if (periodCount == 0) {
248             InitSignalBuffer(bufDesc); // set signal data
249             int64_t temp = ClockTime::GetCurNano() - g_stampTime;
250             std::cout << "client read-write latency:" << (temp / AUDIO_MS_PER_SECOND) << " us" << std::endl;
251             return;
252         }
253 
254         int32_t keepQuiteHold = 50;
255         if (periodCount > keepQuiteHold) {
256             return;
257         }
258 
259         // copy mic data in the cache buffer
260         int ret = memcpy_s(static_cast<void *>(bufDesc.buffer), bufDesc.bufLength,
261             static_cast<void *>(g_cacheBuffer.buffer), g_cacheBuffer.bufLength);
262         if (ret != EOK) {
263             AUDIO_WARNING_LOG("memcpy_s failed.");
264         }
265     };
266 
GetCurTime()267     void GetCurTime()
268     {
269         struct timeval tv;
270         struct timezone tz;
271         struct tm *t;
272 
273         gettimeofday(&tv, &tz);
274         t = localtime(&tv.tv_sec);
275         AUDIO_INFO_LOG("ClockTime::GetCurNano is %{public}" PRId64" Low-latency write first data start at"
276             ":%{public}04d-%{public}02d-%{public}02d %{public}02d:%{public}02d:%{public}02d.%{public}03" PRId64" ",
277             ClockTime::GetCurNano(), 1900 + t->tm_year, 1 + t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec,
278             static_cast<int64_t>(tv.tv_usec / AUDIO_MS_PER_SECOND));
279     }
280 
HandleWriteSignalData(const BufferDesc & bufDesc)281     void HandleWriteSignalData(const BufferDesc &bufDesc)
282     {
283         if (g_renderSignal) {
284             InitSignalBuffer(bufDesc);
285             GetCurTime();
286             g_renderSignal = false;
287         }
288     }
289 
290 private:
291     std::shared_ptr<AudioProcessInClient> procClient_ = nullptr;
292     int32_t loopCount_ = -1; // for loop
293     AudioMode clientMode_ = AUDIO_MODE_PLAYBACK;
294     bool renderFinish_ = false;
295     int32_t playIndex_ = 0;
296     int32_t recordIndex_ = 0;
297     bool isFirstRender = true;
298     bool isFirstCapture = true;
299     int32_t biHighFrameTimeMs = 900000;
300     int64_t playLastTime_ = 0;
301     int64_t recordLastTime_ = 0;
302 };
303 
304 class AudioProcessTest {
305 public:
306     AudioProcessTest() = default;
307     ~AudioProcessTest() = default;
308 
309     int32_t InitSpk(int32_t loopCount, bool isRemote);
310     bool IsInited();
311     bool StartSpk();
312     bool PauseSpk();
313     bool ResumeSpk();
314     bool SetSpkVolume(int32_t vol);
315     bool StopSpk();
316     bool ReleaseSpk();
317 
318     int32_t InitMic(bool isRemote);
319     bool StartMic();
320     bool PauseMic();
321     bool ResumeMic();
322     bool SetMicVolume(int32_t vol);
323     bool StopMic();
324     bool ReleaseMic();
325 
326     int32_t SelectDevice(DeviceRole deviceRole);
327 private:
328     std::shared_ptr<AudioProcessInClient> spkProcessClient_ = nullptr;
329     std::shared_ptr<AudioProcessInClient> micProcessClient_ = nullptr;
330     std::shared_ptr<AudioProcessTestCallback> spkProcClientCb_ = nullptr;
331     std::shared_ptr<AudioProcessTestCallback> micProcClientCb_ = nullptr;
332     std::shared_ptr<FastAudioStream> spkFastAudioStream_ = nullptr;
333     std::shared_ptr<FastAudioStream> micFastAudioStream_ = nullptr;
334     int32_t loopCount_ = -1; // for loop
335     bool isInited_ = false;
336 };
337 
GetNowTimeUs()338 int64_t AudioProcessTestCallback::GetNowTimeUs()
339 {
340     std::chrono::microseconds nowUs =
341         std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch());
342     return nowUs.count();
343 }
344 
IsFrameHigh(const int16_t * audioData,const int32_t size,int32_t threshold)345 bool AudioProcessTestCallback::IsFrameHigh(const int16_t *audioData, const int32_t size, int32_t threshold)
346 {
347     int32_t max = 0;
348     for (int32_t i = 0; i < size; i++) {
349         int16_t f = abs(audioData[i]);
350         if (f > max) {
351             max = f;
352         }
353     }
354     return (max >= threshold) ? true : false;
355 }
356 
RecordBeepTime(const uint8_t * base,const int32_t & sizePerFrame,bool & status)357 int64_t AudioProcessTestCallback::RecordBeepTime(const uint8_t *base, const int32_t &sizePerFrame, bool &status)
358 {
359     int32_t threadhold = 8000;
360     if (IsFrameHigh(reinterpret_cast<const int16_t *>(base),
361         sizePerFrame / sizeof(int16_t), threadhold) == true &&
362         status == true) {
363         status = false;
364         return GetNowTimeUs();
365     } else if (IsFrameHigh(reinterpret_cast<const int16_t *>(base),
366         sizePerFrame / sizeof(int16_t), threadhold) == false) {
367         status = true;
368     }
369     return 0;
370 }
371 
CaptureToFile(const BufferDesc & bufDesc)372 int32_t AudioProcessTestCallback::CaptureToFile(const BufferDesc &bufDesc)
373 {
374     CHECK_AND_RETURN_RET_LOG(g_micPcmFile != nullptr, ERR_INVALID_HANDLE,
375         "%{public}s g_micPcmFile is null.", __func__);
376 
377     size_t cnt = fwrite(bufDesc.buffer, 1, bufDesc.bufLength, g_micPcmFile);
378     CHECK_AND_RETURN_RET_LOG(cnt == bufDesc.bufLength, ERR_WRITE_FAILED,
379         "%{public}s fwrite fail, cnt %{public}zu, bufLength %{public}zu.", __func__, cnt, bufDesc.bufLength);
380     if (g_testMode == RENDER_MIC_LOOP_DATA) {
381         int ret = memcpy_s(static_cast<void *>(g_cacheBuffer.buffer), bufDesc.bufLength,
382             static_cast<void *>(bufDesc.buffer), bufDesc.bufLength);
383         if (ret != EOK) {
384             AUDIO_WARNING_LOG("memcpy_s failed.");
385         }
386         g_stampTime = ClockTime::GetCurNano();
387     }
388     if (g_isLatencyTesting) {
389         if (recordIndex_ == 0) {
390             cout << "First record time : " << GetNowTimeUs() << endl;
391         }
392 
393         int64_t bt = RecordBeepTime(bufDesc.buffer, bufDesc.bufLength, isFirstCapture);
394         if (bt != 0 && g_captureBeepTime_.size() < g_playBeepTime_.size()) {
395             if (GetNowTimeUs() - recordLastTime_ <= biHighFrameTimeMs) {
396                 cout << "catch high frame, but not in 900ms" << endl;
397                 recordIndex_++;
398                 return SUCCESS;
399             }
400             g_captureBeepTime_.push_back(bt);
401             recordLastTime_ = GetNowTimeUs();
402             cout << "Capture beep frame: " << recordIndex_ << " record time : " << GetNowTimeUs() << endl;
403         }
404     }
405     recordIndex_++;
406     return SUCCESS;
407 }
408 
RenderFromFile(const BufferDesc & bufDesc)409 int32_t AudioProcessTestCallback::RenderFromFile(const BufferDesc &bufDesc)
410 {
411     CHECK_AND_RETURN_RET_LOG(g_spkWavFile != nullptr, ERR_INVALID_HANDLE,
412         "%{public}s g_spkWavFile is null.", __func__);
413 
414     if (feof(g_spkWavFile)) {
415         loopCount_--;
416         if (loopCount_ < 0) {
417             fseek(g_spkWavFile, WAV_HEADER_SIZE, SEEK_SET); // infinite loop
418         } else if (loopCount_ == 0) {
419             renderFinish_ = true;
420             g_autoRunCV.notify_all();
421         } else {
422             fseek(g_spkWavFile, WAV_HEADER_SIZE, SEEK_SET);
423         }
424     }
425     if (renderFinish_) {
426         AUDIO_INFO_LOG("%{public}s render finish.", __func__);
427         return SUCCESS;
428     }
429     fread(bufDesc.buffer, 1, bufDesc.bufLength, g_spkWavFile);
430     if (g_isLatencyTesting) {
431         if (playIndex_ == 0) {
432             cout << "First play time: " << GetNowTimeUs() << endl;
433         }
434         int64_t bt = RecordBeepTime(bufDesc.buffer, bufDesc.bufLength, isFirstRender);
435         if (bt != 0) {
436             if (GetNowTimeUs() - playLastTime_ <= biHighFrameTimeMs) {
437                 cout << "Catch high frame, but not in 900ms" << endl;
438                 playIndex_++;
439                 return SUCCESS;
440             }
441             g_playBeepTime_.push_back(bt);
442             playLastTime_ = GetNowTimeUs();
443             cout << "Play beep frame: " << playIndex_ << "play time: " << GetNowTimeUs() << endl;
444         }
445     }
446     playIndex_++;
447     return SUCCESS;
448 }
449 
OnHandleData(size_t length)450 void AudioProcessTestCallback::OnHandleData(size_t length)
451 {
452     Trace callBack("client_n");
453     CHECK_AND_RETURN_LOG(procClient_ != nullptr, "%{public}s procClient is null.", __func__);
454 
455     BufferDesc bufDesc = {nullptr, 0, 0};
456     int32_t ret = procClient_->GetBufferDesc(bufDesc);
457     if (ret != SUCCESS || bufDesc.buffer == nullptr || bufDesc.bufLength ==0) {
458         cout << "GetBufferDesc failed." << endl;
459         return;
460     }
461 
462     if (clientMode_ == AUDIO_MODE_RECORD) {
463         ret = CaptureToFile(bufDesc);
464         CHECK_AND_RETURN_LOG(ret == SUCCESS, "%{public}s capture to file fail, ret %{public}d.",
465             __func__, ret);
466     } else {
467         if (g_testMode == TestMode::RENDER_FILE) {
468             ret = RenderFromFile(bufDesc);
469             CHECK_AND_RETURN_LOG(ret == SUCCESS, "%{public}s render from file fail, ret %{public}d.", __func__, ret);
470         } else if (g_testMode == TestMode::RENDER_MIC_LOOP_DATA) {
471             HandleWriteLoopData(bufDesc);
472         } else if (g_testMode == TestMode::RENDER_SIGNAL_DATA) {
473             HandleWriteSignalData(bufDesc);
474         }
475     }
476     ret = procClient_->Enqueue(bufDesc);
477     CHECK_AND_RETURN_LOG(ret == SUCCESS, "%{public}s enqueue buf fail, clientMode %{public}d, ret %{public}d.",
478         __func__, clientMode_, ret);
479 
480     callBack.End();
481 }
482 
GetSampleFormat(int32_t wavSampleFormat)483 inline AudioSampleFormat GetSampleFormat(int32_t wavSampleFormat)
484 {
485     switch (wavSampleFormat) {
486         case SAMPLE_FORMAT_U8:
487             return AudioSampleFormat::SAMPLE_U8;
488         case SAMPLE_FORMAT_S16LE:
489             return AudioSampleFormat::SAMPLE_S16LE;
490         case SAMPLE_FORMAT_S24LE:
491             return AudioSampleFormat::SAMPLE_S24LE;
492         case SAMPLE_FORMAT_S32LE:
493             return AudioSampleFormat::SAMPLE_S32LE;
494         default:
495             return AudioSampleFormat::INVALID_WIDTH;
496     }
497 }
498 
SelectDevice(DeviceRole deviceRole)499 int32_t AudioProcessTest::SelectDevice(DeviceRole deviceRole)
500 {
501     AudioSystemManager *manager = AudioSystemManager::GetInstance();
502     if (manager == nullptr) {
503         std::cout << "Get AudioSystemManager failed" << std::endl;
504         return ERR_INVALID_OPERATION;
505     }
506 
507     std::vector<std::shared_ptr<AudioDeviceDescriptor>> devices;
508     if (deviceRole == OUTPUT_DEVICE) {
509         devices = manager->GetDevices(DISTRIBUTED_OUTPUT_DEVICES_FLAG);
510     } else {
511         devices = manager->GetDevices(DISTRIBUTED_INPUT_DEVICES_FLAG);
512     }
513     if (devices.size() != 1) {
514         std::cout << "GetDevices failed, unsupported size:" << devices.size() << std::endl;
515         return ERR_INVALID_OPERATION;
516     }
517 
518     std::cout << "using device:" << devices[0]->networkId_ << std::endl;
519 
520     int32_t ret = 0;
521     if (deviceRole == OUTPUT_DEVICE) {
522         sptr<AudioRendererFilter> filter = new AudioRendererFilter();
523         filter->uid = getuid();
524         filter->rendererInfo.rendererFlags = STREAM_FLAG_FAST;
525         ret = manager->SelectOutputDevice(filter, devices);
526     } else {
527         sptr<AudioCapturerFilter> filter = new AudioCapturerFilter();
528         filter->uid = getuid();
529         filter->capturerInfo.sourceType = SOURCE_TYPE_MIC;
530         filter->capturerInfo.capturerFlags = STREAM_FLAG_FAST;
531         ret = manager->SelectInputDevice(filter, devices);
532     }
533 
534     if (ret == SUCCESS) {
535         std::cout << "SelectDevice seccess" << std::endl;
536     } else {
537         std::cout << "SelectDevice failed, ret:" << ret << std::endl;
538     }
539     return ret;
540 }
541 
InitSpk(int32_t loopCount,bool isRemote)542 int32_t AudioProcessTest::InitSpk(int32_t loopCount, bool isRemote)
543 {
544     if (loopCount < 0) {
545         loopCount_ = 1; // loop once
546     } else if (loopCount == 0) {
547         loopCount_ = -1; // infinite loop
548     } else {
549         loopCount_ = loopCount;
550     }
551     if (isRemote && SelectDevice(OUTPUT_DEVICE) != SUCCESS) {
552         std::cout << "Select remote device error." << std::endl;
553         return ERROR_UNSUPPORTED;
554     }
555 
556     AudioProcessConfig config;
557     config.appInfo.appPid = getpid();
558     config.appInfo.appUid = getuid();
559 
560     config.audioMode = AUDIO_MODE_PLAYBACK;
561 
562     config.rendererInfo.contentType = CONTENT_TYPE_MUSIC;
563     config.rendererInfo.streamUsage = STREAM_USAGE_MEDIA;
564     config.rendererInfo.rendererFlags = STREAM_FLAG_FAST;
565 
566     config.streamInfo.channels = STEREO;
567     config.streamInfo.encoding = ENCODING_PCM;
568     config.streamInfo.format = SAMPLE_S16LE;
569     config.streamInfo.samplingRate = SAMPLE_RATE_48000;
570 
571     config.streamType = STREAM_MUSIC;
572 
573     if (g_testMode == TestMode::RENDER_FILE) {
574         wav_hdr wavHeader;
575         size_t headerSize = sizeof(wav_hdr);
576         size_t bytesRead = fread(&wavHeader, 1, headerSize, g_spkWavFile);
577         if (bytesRead != headerSize) {
578             AUDIO_ERR_LOG("RenderCallbackTest: File header reading error");
579         }
580 
581         config.streamInfo.samplingRate = static_cast<AudioSamplingRate>(wavHeader.SamplesPerSec);
582         config.streamInfo.format = GetSampleFormat(wavHeader.bitsPerSample);
583         config.streamInfo.channels = static_cast<AudioChannel>(wavHeader.NumOfChan);
584 
585         cout << endl << "samplingRate:" << config.streamInfo.samplingRate << endl;
586         cout << "format:" << config.streamInfo.format << endl;
587         cout << "channels:" << config.streamInfo.channels << endl;
588     }
589 
590     spkFastAudioStream_ = std::make_shared<FastAudioStream>(config.streamType,
591         AUDIO_MODE_PLAYBACK, config.appInfo.appUid);
592     spkProcessClient_ = AudioProcessInClient::Create(config, spkFastAudioStream_);
593     CHECK_AND_RETURN_RET_LOG(spkProcessClient_ != nullptr, ERR_INVALID_HANDLE,
594         "Client test creat process client fail.");
595 
596     spkProcClientCb_ = std::make_shared<AudioProcessTestCallback>(spkProcessClient_, loopCount_, config.audioMode);
597     int32_t ret = spkProcessClient_->SaveDataCallback(spkProcClientCb_);
598     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Client test save data callback fail, ret %{public}d.", ret);
599     isInited_ = true;
600     return SUCCESS;
601 }
602 
IsInited()603 bool AudioProcessTest::IsInited()
604 {
605     return isInited_;
606 }
607 
StartSpk()608 bool AudioProcessTest::StartSpk()
609 {
610     CHECK_AND_RETURN_RET_LOG(spkProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
611     int32_t ret = spkProcessClient_->Start();
612     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
613     return true;
614 }
615 
PauseSpk()616 bool AudioProcessTest::PauseSpk()
617 {
618     CHECK_AND_RETURN_RET_LOG(spkProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
619     int32_t ret = spkProcessClient_->Pause();
620     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
621     return true;
622 }
623 
ResumeSpk()624 bool AudioProcessTest::ResumeSpk()
625 {
626     CHECK_AND_RETURN_RET_LOG(spkProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
627     int32_t ret = spkProcessClient_->Resume();
628     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
629     return true;
630 }
631 
SetSpkVolume(int32_t vol)632 bool AudioProcessTest::SetSpkVolume(int32_t vol)
633 {
634     CHECK_AND_RETURN_RET_LOG(spkProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
635     int32_t ret = spkProcessClient_->SetVolume(vol);
636     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
637     return true;
638 }
639 
StopSpk()640 bool AudioProcessTest::StopSpk()
641 {
642     CHECK_AND_RETURN_RET_LOG(spkProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
643     int32_t ret = spkProcessClient_->Stop();
644     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
645     return true;
646 }
647 
ReleaseSpk()648 bool AudioProcessTest::ReleaseSpk()
649 {
650     if (spkProcessClient_ == nullptr) {
651         AUDIO_INFO_LOG("%{public}s process client is already released.", __func__);
652         return true;
653     }
654     int32_t ret = spkProcessClient_->Release();
655     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test release fail, ret %{public}d.", ret);
656     spkProcessClient_ = nullptr;
657     AUDIO_INFO_LOG("client test set nullptr!");
658     return true;
659 }
660 
InitMic(bool isRemote)661 int32_t AudioProcessTest::InitMic(bool isRemote)
662 {
663     AudioProcessConfig config;
664     config.appInfo.appPid = getpid();
665     config.appInfo.appUid = getuid();
666 
667     config.audioMode = AUDIO_MODE_RECORD;
668     config.capturerInfo.sourceType = SOURCE_TYPE_MIC;
669     config.capturerInfo.capturerFlags = STREAM_FLAG_FAST;
670 
671     config.streamInfo.channels = STEREO;
672     config.streamInfo.encoding = ENCODING_PCM;
673     config.streamInfo.format = SAMPLE_S16LE;
674     config.streamInfo.samplingRate = SAMPLE_RATE_48000;
675 
676     if (isRemote && SelectDevice(INPUT_DEVICE) != SUCCESS) {
677         std::cout << "Select remote device error." << std::endl;
678         return ERROR_UNSUPPORTED;
679     }
680 
681     micFastAudioStream_ = std::make_shared<FastAudioStream>(config.streamType,
682         AUDIO_MODE_RECORD, config.appInfo.appUid);
683     micProcessClient_ = AudioProcessInClient::Create(config, micFastAudioStream_);
684     CHECK_AND_RETURN_RET_LOG(micProcessClient_ != nullptr, ERR_INVALID_HANDLE,
685         "Client test creat process client fail.");
686 
687     micProcClientCb_ = std::make_shared<AudioProcessTestCallback>(micProcessClient_, 0, config.audioMode);
688     int32_t ret = micProcessClient_->SaveDataCallback(micProcClientCb_);
689     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Client test save data callback fail, ret %{public}d.", ret);
690     return SUCCESS;
691 }
692 
StartMic()693 bool AudioProcessTest::StartMic()
694 {
695     CHECK_AND_RETURN_RET_LOG(micProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
696     int32_t ret = micProcessClient_->Start();
697     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
698     return true;
699 }
700 
PauseMic()701 bool AudioProcessTest::PauseMic()
702 {
703     CHECK_AND_RETURN_RET_LOG(micProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
704     int32_t ret = micProcessClient_->Pause();
705     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
706     return true;
707 }
708 
ResumeMic()709 bool AudioProcessTest::ResumeMic()
710 {
711     CHECK_AND_RETURN_RET_LOG(micProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
712     int32_t ret = micProcessClient_->Resume();
713     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
714     return true;
715 }
716 
SetMicVolume(int32_t vol)717 bool AudioProcessTest::SetMicVolume(int32_t vol)
718 {
719     CHECK_AND_RETURN_RET_LOG(micProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
720     int32_t ret = micProcessClient_->SetVolume(vol);
721     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
722     return true;
723 }
724 
StopMic()725 bool AudioProcessTest::StopMic()
726 {
727     CHECK_AND_RETURN_RET_LOG(micProcessClient_ != nullptr, false, "%{public}s process client is null.", __func__);
728     int32_t ret = micProcessClient_->Stop();
729     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
730     return true;
731 }
732 
ReleaseMic()733 bool AudioProcessTest::ReleaseMic()
734 {
735     if (micProcessClient_ == nullptr) {
736         AUDIO_INFO_LOG("%{public}s process client is already released.", __func__);
737         return true;
738     }
739     int32_t ret = micProcessClient_->Release();
740     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test release fail, ret %{public}d.", ret);
741     micProcessClient_ = nullptr;
742     AUDIO_INFO_LOG("client test set nullptr!");
743     return true;
744 }
745 
OpenSpkFile()746 bool OpenSpkFile()
747 {
748     if (g_spkWavFile != nullptr) {
749         AUDIO_ERR_LOG("Spk file has been opened, g_spkfilePath %{public}s", g_spkfilePath.c_str());
750         return true;
751     }
752 
753     char path[PATH_MAX] = { 0x00 };
754     if ((strlen(g_spkfilePath.c_str()) > PATH_MAX) || (realpath(g_spkfilePath.c_str(), path) == nullptr)) {
755         return false;
756     }
757     AUDIO_INFO_LOG("spk path = %{public}s", path);
758     g_spkWavFile = fopen(path, "rb");
759     if (g_spkWavFile == nullptr) {
760         AUDIO_ERR_LOG("Unable to open wave file");
761         return false;
762     }
763     return true;
764 }
765 
CloseSpkFile()766 void CloseSpkFile()
767 {
768     if (g_spkWavFile != nullptr) {
769         fclose(g_spkWavFile);
770         g_spkWavFile = nullptr;
771     }
772 }
773 
OpenMicFile()774 bool OpenMicFile()
775 {
776     if (g_micPcmFile != nullptr) {
777         AUDIO_ERR_LOG("Mic file has been opened, MIC_FILE_PATH %{public}s", MIC_FILE_PATH.c_str());
778         return true;
779     }
780 
781     AUDIO_INFO_LOG("mic path = %{public}s", MIC_FILE_PATH.c_str());
782     g_micPcmFile = fopen(MIC_FILE_PATH.c_str(), "ab+");
783     if (g_micPcmFile == nullptr) {
784         AUDIO_ERR_LOG("Unable to open wave file");
785         return false;
786     }
787     return true;
788 }
789 
CloseMicFile()790 void CloseMicFile()
791 {
792     if (g_micPcmFile != nullptr) {
793         fclose(g_micPcmFile);
794         g_micPcmFile = nullptr;
795     }
796 }
797 
GetArgs(const std::string & args)798 inline int32_t GetArgs(const std::string &args)
799 {
800     int32_t value = 0;
801     stringstream valueStr;
802     valueStr << args;
803     valueStr >> value;
804     return value;
805 }
806 
PrintInteractiveUsage()807 void PrintInteractiveUsage()
808 {
809     cout << endl << "======================= InteractiveRunTestSelect ============================" << endl;
810     cout << "You can respond to instructions for corresponding option:" << endl;
811     for (auto it = g_interactiveOptStrMap.begin(); it != g_interactiveOptStrMap.end(); it ++) {
812         cout << "\t enter " << it->first << " : " << it->second << endl;
813     }
814 }
815 
PrintProcTestUsage()816 void PrintProcTestUsage()
817 {
818     cout << endl << "========================== ProcessTestSelect ================================" << endl;
819     cout << "You can respond to instructions for corresponding test:" << endl;
820     for (auto it = g_audioProcessTestType.begin(); it != g_audioProcessTestType.end(); it ++) {
821         cout << it->first << ". " << it->second << endl;
822     }
823 }
824 
PrintUsage()825 void PrintUsage()
826 {
827     cout << "[Audio Process Client Test App]" << endl << endl;
828     cout << "Supported Functionalities:" << endl;
829     cout << "  a) Auto run local spk test." << endl;
830     cout << "  b) Interactive run local/remote spk test." << endl;
831     cout << "  c) Auto run remote mic test." << endl;
832     cout << "  d) Interactive run remote mic test." << endl;
833     cout << "================================Usage=======================================" << endl << endl;
834 
835     cout << "-a\n\tAuto run local spk process test, pelese input the following after select." << endl;
836     cout << "\tUsage : <wav-file-path> <play-loop-count>" << endl;
837     cout << "\t       if <play-loop-count> equals to 0, it will loop infinitely." << endl;
838     cout << "\tExample 1 : /data/data/48kHz_16bit.wav 0" << endl;
839     cout << "\tExample 2 : /data/data/48kHz_16bit.wav 2" << endl << endl;
840 
841     cout << "-b\n\tInteractive run local/remote spk test, pelese input the following after select." << endl;
842     cout << "\tUsage : <wav-file-path>" << endl;
843 
844     cout << "-c\n\tAuto run remote mic process test, pelese input the following after select." << endl;
845     cout << "\tUsage : <record-time-in-seconds>" << endl;
846     cout << "\tGenerate the specified time span record file, path : /data/data/mic.pcm" << endl;
847 
848     cout << "-d\n\tInteractive run remote mic test." << endl;
849     cout << "\tGenerate record file from start to stop, path : /data/data/mic.pcm" << endl;
850 }
851 
GetUserInput()852 int32_t GetUserInput()
853 {
854     int32_t res = -1; // result
855     size_t count = 3; // try three time
856     cout << ">>";
857     cin >> res;
858     while (cin.fail() && count-- > 0) {
859         cin.clear();
860         cin.ignore();
861         cout << "invalid input, not a number! Please retry with a number." << endl;
862         cout << ">>";
863         cin >> res;
864     }
865     return res;
866 }
867 
AutoRunSpk()868 void AutoRunSpk()
869 {
870     cout << "Auto run spk process test enter, please input loopCount and path:" << endl;
871     int32_t loopCount = GetUserInput();
872     std::string palyFilePath;
873     cin >> palyFilePath;
874     g_spkfilePath = palyFilePath;
875 
876     if (!OpenSpkFile()) {
877         cout << "open spk file path failed!" << g_spkfilePath << endl;
878         return;
879     }
880     if (g_audioProcessTest->InitSpk(loopCount, false) != SUCCESS) {
881         cout << "Spk init failed!" << endl;
882         return;
883     }
884 
885     do {
886         if (!g_audioProcessTest->StartSpk()) {
887             cout << "Spk start failed!" << endl;
888             break;
889         }
890         int volShift = 15; // helf of 1 << 16
891         if (!g_audioProcessTest->SetSpkVolume(1 << volShift)) {
892             cout << "Spk set volume " << volShift << " failed!" << endl;
893             break;
894         }
895 
896         unique_lock<mutex> lock(g_autoRunMutex);
897         g_autoRunCV.wait(lock);
898         cout << "AutoRunSpk end" << endl;
899 
900         if (!g_audioProcessTest->StopSpk()) {
901             cout << "Spk stop failed!" << endl;
902             break;
903         }
904     } while (false);
905 
906     if (!g_audioProcessTest->ReleaseSpk()) {
907         cout << "Spk release failed!" << endl;
908     }
909     CloseSpkFile();
910 }
911 
AutoRunMic()912 void AutoRunMic()
913 {
914     cout << "Auto run mic process test enter, please input recordTimeS:" << endl;
915     int32_t recordTimeS = GetUserInput();
916     if (!OpenMicFile()) {
917         cout << "open mic file path failed!" << g_spkfilePath << endl;
918         return;
919     }
920 
921     if (g_audioProcessTest->InitMic(false) != SUCCESS) {
922         cout << "Mic init failed!" << endl;
923         return;
924     }
925 
926     do {
927         if (!g_audioProcessTest->StartMic()) {
928             cout << "Mic start failed!" << endl;
929             break;
930         }
931         int volShift = 15; // helf of 1 << 16
932         if (!g_audioProcessTest->SetMicVolume(1 << volShift)) {
933             cout << "Mic set volume " << volShift << " failed!" << endl;
934             break;
935         }
936 
937         cout << "wait " << recordTimeS << "s for capture frame..." << endl;
938         ClockTime::RelativeSleep(recordTimeS * SECOND_TO_NANOSECOND);
939         cout << "AutoRunMic end" << endl;
940 
941         if (!g_audioProcessTest->StopMic()) {
942             cout << "Mic stop failed!" << endl;
943             break;
944         }
945     } while (false);
946 
947     if (!g_audioProcessTest->ReleaseMic()) {
948         cout << "Mic release failed!" << endl;
949     }
950     CloseMicFile();
951 }
952 
ConfigSpkTest(bool isRemote)953 string ConfigSpkTest(bool isRemote)
954 {
955     cout << "Please input spk file path:" << endl;
956     std::string palyFilePath;
957     cin >> palyFilePath;
958     g_spkfilePath = palyFilePath;
959 
960     if (!OpenSpkFile()) {
961         cout << "Open spk file path failed!" << g_spkfilePath << endl;
962         return "Open spk wav file fail";
963     }
964     int32_t ret = g_audioProcessTest->InitSpk(0, isRemote);
965     if (ret != SUCCESS) {
966         return "Spk init failed";
967     }
968     return "Spk init SUCCESS";
969 }
970 
LocalLoopLatencyTest()971 string LocalLoopLatencyTest()
972 {
973     return LoopLatencyTest(false);
974 }
975 
RemoteLoopLatencyTest()976 string RemoteLoopLatencyTest()
977 {
978     return LoopLatencyTest(true);
979 }
980 
CountLatencyTime()981 void CountLatencyTime()
982 {
983     int32_t playSize = g_playBeepTime_.size();
984     if (g_playBeepTime_.size() != g_captureBeepTime_.size()) {
985         cout << "Record num is not equal (" << playSize << "  " << g_captureBeepTime_.size() << ")" << endl;
986         return;
987     }
988     cout << "record " << playSize << "times frame high." << endl;
989     int32_t sum = 0;
990     for (int32_t i = 0; i < playSize; i++) {
991         cout << "Send: " << g_playBeepTime_[i] << " Received: " <<
992             g_captureBeepTime_[i] << endl;
993         cout << "Time is: " << ((g_captureBeepTime_[i] - g_playBeepTime_[i]) / g_usPerMs) << endl;
994         sum += g_captureBeepTime_[i] - g_playBeepTime_[i];
995     }
996     if (playSize == 0) {
997         cout << "playSize is 0;" << endl;
998         return;
999     }
1000     cout << "Remote audio latency in average is: " << sum / playSize << " (us)." << endl;
1001 
1002     g_playBeepTime_.clear();
1003     g_captureBeepTime_.clear();
1004     g_isLatencyTesting = false;
1005 }
1006 
LoopLatencyTest(bool isRemote)1007 string LoopLatencyTest(bool isRemote)
1008 {
1009     cout << "=== LoopLatencyTest ===";
1010     if (isRemote) {
1011         cout << "**Remote**" << endl;
1012     } else {
1013         cout << "**Local**" << endl;
1014     }
1015     g_isLatencyTesting = true;
1016 
1017     if (!OpenMicFile()) {
1018         return "Open mic file path failed!" + MIC_FILE_PATH;
1019     }
1020     g_audioProcessTest->InitMic(isRemote);
1021     g_audioProcessTest->StartMic();
1022     cout << "MIC start success, begin to record." << endl;
1023 
1024     g_spkfilePath = "/data/bi.wav";
1025     if (!OpenSpkFile()) {
1026         return "Open spk file path failed!" + g_spkfilePath;
1027     }
1028 
1029     int32_t ret = g_audioProcessTest->InitSpk(1, isRemote);
1030     if (ret != SUCCESS) {
1031         return "init spk failed";
1032     }
1033     g_audioProcessTest->StartSpk();
1034     g_audioProcessTest->SetSpkVolume(g_setVol);
1035     cout << "SPK start success. begin to play." << endl;
1036 
1037     cout << "running..." << endl;
1038 
1039     unique_lock<mutex> lock(g_autoRunMutex);
1040     g_autoRunCV.wait(lock);
1041     ClockTime::RelativeSleep(MIC_SLEEP_TIME_US);
1042     //release
1043     g_audioProcessTest->StopMic();
1044     g_audioProcessTest->ReleaseMic();
1045     CloseMicFile();
1046     cout << "MIC stop success." << endl;
1047 
1048     g_audioProcessTest->StopSpk();
1049     g_audioProcessTest->ReleaseSpk();
1050     CloseSpkFile();
1051     cout << "SPK stop success." << endl;
1052 
1053     // cout latency time
1054     CountLatencyTime();
1055     return "Loop latency test success";
1056 }
1057 
CallStartSpk()1058 string CallStartSpk()
1059 {
1060     if (!g_audioProcessTest->StartSpk()) {
1061         return "Spk start failed";
1062     }
1063     return "Spk start SUCCESS";
1064 }
1065 
CallPauseSpk()1066 string CallPauseSpk()
1067 {
1068     if (!g_audioProcessTest->PauseSpk()) {
1069         return "Spk pause failed";
1070     }
1071     return "Spk pause SUCCESS";
1072 }
1073 
CallResumeSpk()1074 string CallResumeSpk()
1075 {
1076     if (!g_audioProcessTest->ResumeSpk()) {
1077         return "Spk resume failed";
1078     }
1079     return "Spk resume SUCCESS";
1080 }
1081 
CallStopSpk()1082 string CallStopSpk()
1083 {
1084     if (!g_audioProcessTest->StopSpk()) {
1085         return "Spk stop failed";
1086     }
1087     return "Spk stop SUCCESS";
1088 }
1089 
SetSpkVolume()1090 string SetSpkVolume()
1091 {
1092     int32_t vol = GetUserInput();
1093     if (!g_audioProcessTest->SetSpkVolume(vol)) {
1094         return "Spk set volume failed";
1095     }
1096     return "Spk set volume SUCCESS";
1097 }
1098 
CallReleaseSpk()1099 string CallReleaseSpk()
1100 {
1101     if (!g_audioProcessTest->ReleaseSpk()) {
1102         return "Spk release failed";
1103     }
1104     CloseSpkFile();
1105     return "Spk release SUCCESS";
1106 }
1107 
ConfigMicTest(bool isRemote)1108 string ConfigMicTest(bool isRemote)
1109 {
1110     if (!OpenMicFile()) {
1111         cout << "Open mic file path failed!" << g_spkfilePath << endl;
1112         return "Open mic pcm file fail";
1113     }
1114 
1115     int32_t ret = g_audioProcessTest->InitMic(isRemote);
1116     if (ret != SUCCESS) {
1117         return "Mic init failed";
1118     }
1119     return "Mic init SUCCESS";
1120 }
1121 
CallStartMic()1122 string CallStartMic()
1123 {
1124     if (!g_audioProcessTest->StartMic()) {
1125         return "Mic start failed";
1126     }
1127     return "Mic start SUCCESS";
1128 }
1129 
CallPauseMic()1130 string CallPauseMic()
1131 {
1132     if (!g_audioProcessTest->PauseMic()) {
1133         return "Mic pause failed";
1134     }
1135     return "Mic pause SUCCESS";
1136 }
1137 
CallResumeMic()1138 string CallResumeMic()
1139 {
1140     if (!g_audioProcessTest->ResumeMic()) {
1141         return "Mic resume failed";
1142     }
1143     return "Mic resume SUCCESS";
1144 }
1145 
CallStopMic()1146 string CallStopMic()
1147 {
1148     if (!g_audioProcessTest->StopMic()) {
1149         return "Mic stop failed";
1150     }
1151     return "Mic stop SUCCESS";
1152 }
1153 
SetMicVolume()1154 string SetMicVolume()
1155 {
1156     int32_t vol = GetUserInput();
1157     if (!g_audioProcessTest->SetMicVolume(vol)) {
1158         return "Mic set volume failed";
1159     }
1160     return "Mic set volume SUCCESS";
1161 }
1162 
CallReleaseMic()1163 string CallReleaseMic()
1164 {
1165     if (!g_audioProcessTest->ReleaseMic()) {
1166         return "Mic release failed";
1167     }
1168     CloseMicFile();
1169     return "Mic release SUCCESS";
1170 }
1171 
StartLoopTest()1172 string StartLoopTest()
1173 {
1174     std::cout << ConfigMicTest(false);
1175     std::cout << CallStartMic();
1176     std::cout << endl;
1177 
1178     int32_t ret = g_audioProcessTest->InitSpk(0, false);
1179     if (ret != SUCCESS) {
1180         CallReleaseMic();
1181         return "init spk failed";
1182     } else {
1183         std::cout << "init spk success" << endl;
1184     }
1185 
1186     std::cout << CallStartSpk();
1187     std::cout << endl;
1188     return "StartLoopTest success!";
1189 }
1190 
EndLoopTest()1191 string EndLoopTest()
1192 {
1193     std::cout << CallReleaseSpk();
1194     std::cout << endl;
1195     std::cout << CallStopMic();
1196     std::cout << endl;
1197     std::cout << CallReleaseMic();
1198     std::cout << endl;
1199     return "EndLooptest";
1200 }
1201 
StartSignalTest()1202 string StartSignalTest()
1203 {
1204     if (g_audioProcessTest == nullptr) {
1205         return "StartSignalTest failed";
1206     }
1207 
1208     if (!g_audioProcessTest->IsInited()) {
1209         if (g_audioProcessTest->InitSpk(0, false) != SUCCESS) {
1210             return "init spk failed";
1211         }
1212         uint32_t tempSleep = 10000; // wait for 10ms
1213         usleep(tempSleep);
1214         CallStartSpk();
1215     }
1216     g_renderSignal = true;
1217     return "call signal";
1218 }
1219 
EndSignalTest()1220 string EndSignalTest()
1221 {
1222     return CallReleaseSpk();
1223 }
1224 
1225 
InitCachebuffer()1226 void InitCachebuffer()
1227 {
1228     g_byteBuffer = std::make_unique<uint8_t []>(CACHE_BUFFER_SIZE);
1229     g_cacheBuffer.buffer = g_byteBuffer.get();
1230     g_cacheBuffer.bufLength = CACHE_BUFFER_SIZE;
1231     g_cacheBuffer.dataLength = CACHE_BUFFER_SIZE;
1232 }
1233 
GetOptCode()1234 OperationCode GetOptCode()
1235 {
1236     int32_t res = GetUserInput();
1237     if (g_interactiveOptStrMap.count(res)) {
1238         return static_cast<OperationCode>(res);
1239     }
1240     return INVALID_OPERATION;
1241 }
1242 
InteractiveRun()1243 void InteractiveRun()
1244 {
1245     if (g_testMode == TestMode::RENDER_MIC_LOOP_DATA) {
1246         InitCachebuffer();
1247     }
1248     cout << "Interactive run process test enter." << endl;
1249     bool isInteractiveRun = true;
1250     while (isInteractiveRun) {
1251         PrintInteractiveUsage();
1252         OperationCode optCode = GetOptCode();
1253         switch (optCode) {
1254             case EXIT_INTERACTIVE_TEST:
1255                 isInteractiveRun = false;
1256                 break;
1257             case INIT_LOCAL_SPK_PROCESS:
1258                 cout << ConfigSpkTest(false) << endl;
1259                 break;
1260             case INIT_REMOTE_SPK_PROCESS:
1261                 cout << ConfigSpkTest(true) << endl;
1262                 break;
1263             case START_LOOP_TEST:
1264                 cout << StartLoopTest() << endl;
1265                 break;
1266             case END_LOOP_TEST:
1267                 cout << EndLoopTest() << endl;
1268                 break;
1269             case INIT_LOCAL_MIC_PROCESS:
1270                 cout << ConfigMicTest(false) << endl;
1271                 break;
1272             case INIT_REMOTE_MIC_PROCESS:
1273                 cout << ConfigMicTest(true) << endl;
1274                 break;
1275             case LOCAL_LATENCY_TEST:
1276                 cout << LocalLoopLatencyTest() << endl;
1277                 break;
1278             case REMOTE_LATENCY_TEST:
1279                 cout << RemoteLoopLatencyTest() << endl;
1280                 break;
1281             default:
1282                 auto it = g_interactiveOptFuncMap.find(optCode);
1283                 if (it != g_interactiveOptFuncMap.end() && it->second != nullptr) {
1284                     CallTestOperationFunc &func = it->second;
1285                     cout << (*func)() << endl;
1286                     break;
1287                 }
1288                 cout << "Invalid input :" << optCode << endl;
1289                 break;
1290         }
1291     }
1292     cout << "Interactive run process test end." << endl;
1293 }
1294 
SetSysPara(const std::string key,int32_t & value)1295 bool SetSysPara(const std::string key, int32_t &value)
1296 {
1297     auto res = SetParameter(key.c_str(), std::to_string(value).c_str());
1298     if (res < 0) {
1299         AUDIO_WARNING_LOG("SetSysPara fail, key:%{public}s res:%{public}d", key.c_str(), res);
1300         return false;
1301     }
1302     AUDIO_INFO_LOG("SetSysPara success.");
1303     return true;
1304 }
1305 } // namespace AudioStandard
1306 } // namespace OHOS
1307 
1308 using namespace OHOS::AudioStandard;
main()1309 int main()
1310 {
1311     AUDIO_INFO_LOG("AudioProcessClientTest test enter.");
1312 
1313     PrintUsage();
1314     g_audioProcessTest = make_shared<AudioProcessTest>();
1315 
1316     bool isProcTestRun = true;
1317     while (isProcTestRun) {
1318         PrintProcTestUsage();
1319         AudioProcessTestType procTestType = INVALID_PROC_TEST;
1320         g_testMode = TestMode::RENDER_FILE;
1321         int32_t res = GetUserInput();
1322         if (g_audioProcessTestType.count(res)) {
1323             procTestType = static_cast<AudioProcessTestType>(res);
1324         }
1325         switch (procTestType) {
1326             case INTERACTIVE_RUN_SPK_TEST:
1327             case INTERACTIVE_RUN_MIC_TEST:
1328                 InteractiveRun();
1329                 break;
1330             case INTERACTIVE_RUN_LOOP:
1331                 g_testMode = TestMode::RENDER_MIC_LOOP_DATA;
1332                 InteractiveRun();
1333                 break;
1334             case RENDER_SIGNAL_TEST:
1335                 g_testMode = TestMode::RENDER_SIGNAL_DATA;
1336                 InteractiveRun();
1337                 break;
1338             case AUTO_RUN_SPK_TEST:
1339                 AutoRunSpk();
1340                 break;
1341             case AUTO_RUN_MIC_TEST:
1342                 AutoRunMic();
1343                 break;
1344             case EXIT_PROC_TEST:
1345                 isProcTestRun = false;
1346                 break;
1347             default:
1348                 cout << "invalid input, procTestType: " << procTestType << endl;
1349                 break;
1350         }
1351     }
1352 
1353     AUDIO_INFO_LOG("AudioProcessClientTest test end.");
1354     return 0;
1355 }
1356