• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 #ifndef LOG_TAG
16 #define LOG_TAG "FastAudioStream"
17 #endif
18 
19 #include <chrono>
20 #include <thread>
21 #include <vector>
22 
23 #include "audio_errors.h"
24 #include "audio_capturer_log.h"
25 #include "audio_utils.h"
26 
27 #include "fast_audio_stream.h"
28 
29 using namespace std;
30 
31 namespace OHOS {
32 namespace AudioStandard {
FastAudioStream(AudioStreamType eStreamType,AudioMode eMode,int32_t appUid)33 FastAudioStream::FastAudioStream(AudioStreamType eStreamType, AudioMode eMode, int32_t appUid)
34     : eStreamType_(eStreamType),
35       eMode_(eMode),
36       state_(NEW),
37       renderMode_(RENDER_MODE_CALLBACK),
38       captureMode_(CAPTURE_MODE_CALLBACK)
39 {
40     AUDIO_INFO_LOG("FastAudioStream ctor, appUID = %{public}d", appUid);
41     audioStreamTracker_ = std::make_unique<AudioStreamTracker>(eMode, appUid);
42     AUDIO_DEBUG_LOG("AudioStreamTracker created");
43 }
44 
~FastAudioStream()45 FastAudioStream::~FastAudioStream()
46 {
47     if (state_ != RELEASED && state_ != NEW) {
48         ReleaseAudioStream(false);
49     }
50 }
51 
SetClientID(int32_t clientPid,int32_t clientUid,uint32_t appTokenId,uint64_t fullTokenId)52 void FastAudioStream::SetClientID(int32_t clientPid, int32_t clientUid, uint32_t appTokenId, uint64_t fullTokenId)
53 {
54     AUDIO_INFO_LOG("Set client PID: %{public}d, UID: %{public}d", clientPid, clientUid);
55     clientPid_ = clientPid;
56     clientUid_ = clientUid;
57     appTokenId_ = appTokenId;
58     fullTokenId_ = fullTokenId;
59 }
60 
UpdatePlaybackCaptureConfig(const AudioPlaybackCaptureConfig & config)61 int32_t FastAudioStream::UpdatePlaybackCaptureConfig(const AudioPlaybackCaptureConfig &config)
62 {
63     AUDIO_ERR_LOG("Unsupported operation!");
64     return ERR_NOT_SUPPORTED;
65 }
66 
SetRendererInfo(const AudioRendererInfo & rendererInfo)67 void FastAudioStream::SetRendererInfo(const AudioRendererInfo &rendererInfo)
68 {
69     rendererInfo_ = rendererInfo;
70     rendererInfo_.samplingRate = static_cast<AudioSamplingRate>(streamInfo_.samplingRate);
71 }
72 
SetCapturerInfo(const AudioCapturerInfo & capturerInfo)73 void FastAudioStream::SetCapturerInfo(const AudioCapturerInfo &capturerInfo)
74 {
75     capturerInfo_ = capturerInfo;
76     capturerInfo_.samplingRate = static_cast<AudioSamplingRate>(streamInfo_.samplingRate);
77 }
78 
InitializeAudioProcessConfig(AudioProcessConfig & config,const AudioStreamParams & info)79 int32_t FastAudioStream::InitializeAudioProcessConfig(AudioProcessConfig &config, const AudioStreamParams &info)
80 {
81     config.appInfo.appPid = clientPid_;
82     config.appInfo.appUid = clientUid_;
83     config.audioMode = eMode_;
84     config.streamInfo.channels = static_cast<AudioChannel>(info.channels);
85     config.streamInfo.encoding = static_cast<AudioEncodingType>(info.encoding);
86     config.streamInfo.format = static_cast<AudioSampleFormat>(info.format);
87     config.streamInfo.samplingRate = static_cast<AudioSamplingRate>(info.samplingRate);
88     config.streamType = eStreamType_;
89     config.originalSessionId = info.originalSessionId;
90     if (eMode_ == AUDIO_MODE_PLAYBACK) {
91         AUDIO_DEBUG_LOG("FastAudioStream: Initialize playback");
92         config.rendererInfo.contentType = rendererInfo_.contentType;
93         config.rendererInfo.streamUsage = rendererInfo_.streamUsage;
94         config.rendererInfo.rendererFlags = STREAM_FLAG_FAST;
95         config.rendererInfo.originalFlag = rendererInfo_.originalFlag;
96     } else if (eMode_ == AUDIO_MODE_RECORD) {
97         AUDIO_DEBUG_LOG("FastAudioStream: Initialize recording");
98         config.capturerInfo.sourceType = capturerInfo_.sourceType;
99         config.capturerInfo.capturerFlags = STREAM_FLAG_FAST;
100         config.capturerInfo.originalFlag = capturerInfo_.originalFlag;
101     } else {
102         return ERR_INVALID_OPERATION;
103     }
104     return SUCCESS;
105 }
106 
SetAudioStreamInfo(const AudioStreamParams info,const std::shared_ptr<AudioClientTracker> & proxyObj)107 int32_t FastAudioStream::SetAudioStreamInfo(const AudioStreamParams info,
108     const std::shared_ptr<AudioClientTracker> &proxyObj)
109 {
110     AUDIO_INFO_LOG("FastAudioStreamInfo, Sampling rate: %{public}d, channels: %{public}d, format: %{public}d,"
111         " stream type: %{public}d", info.samplingRate, info.channels, info.format, eStreamType_);
112     CHECK_AND_RETURN_RET_LOG(processClient_ == nullptr, ERR_INVALID_OPERATION,
113         "Process is already inited, reset stream info is not supported.");
114     streamInfo_ = info;
115     if (state_ != NEW) {
116         AUDIO_INFO_LOG("FastAudioStream: State is not new, release existing stream");
117         StopAudioStream();
118         ReleaseAudioStream(false);
119     }
120     AudioProcessConfig config;
121     int32_t ret = InitializeAudioProcessConfig(config, info);
122     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Initialize failed.");
123     CHECK_AND_RETURN_RET_LOG(AudioProcessInClient::CheckIfSupport(config), ERR_INVALID_PARAM,
124         "Stream is not supported.");
125     processconfig_ = config;
126     processClient_ = AudioProcessInClient::Create(config);
127     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_INVALID_PARAM,
128         "Client test creat process client fail.");
129     state_ = PREPARED;
130     proxyObj_ = proxyObj;
131 
132     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
133         processClient_->GetSessionID(sessionId_);
134 
135         AudioRegisterTrackerInfo registerTrackerInfo;
136         UpdateRegisterTrackerInfo(registerTrackerInfo);
137         audioStreamTracker_->RegisterTracker(registerTrackerInfo, proxyObj);
138     }
139     return SUCCESS;
140 }
141 
GetAudioStreamInfo(AudioStreamParams & audioStreamInfo)142 int32_t FastAudioStream::GetAudioStreamInfo(AudioStreamParams &audioStreamInfo)
143 {
144     AUDIO_INFO_LOG("GetAudioStreamInfo enter.");
145     audioStreamInfo = streamInfo_;
146     return SUCCESS;
147 }
148 
CheckRecordingCreate(uint32_t appTokenId,uint64_t appFullTokenId,int32_t appUid,SourceType sourceType)149 bool FastAudioStream::CheckRecordingCreate(uint32_t appTokenId, uint64_t appFullTokenId, int32_t appUid,
150     SourceType sourceType)
151 {
152     AUDIO_ERR_LOG("Not supported operation");
153     return false;
154 }
155 
CheckRecordingStateChange(uint32_t appTokenId,uint64_t appFullTokenId,int32_t appUid,AudioPermissionState state)156 bool FastAudioStream::CheckRecordingStateChange(uint32_t appTokenId, uint64_t appFullTokenId, int32_t appUid,
157     AudioPermissionState state)
158 {
159     AUDIO_ERR_LOG("Not supported operation");
160     return false;
161 }
162 
GetAudioSessionID(uint32_t & sessionID)163 int32_t FastAudioStream::GetAudioSessionID(uint32_t &sessionID)
164 {
165     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED,
166         "GetAudioSessionID failed: null process");
167     int32_t ret = processClient_->GetSessionID(sessionID);
168     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "GetSessionID error.");
169     return ret;
170 }
171 
GetAudioPipeType(AudioPipeType & pipeType)172 void FastAudioStream::GetAudioPipeType(AudioPipeType &pipeType)
173 {
174     pipeType = eMode_ == AUDIO_MODE_PLAYBACK ? rendererInfo_.pipeType : capturerInfo_.pipeType;
175 }
176 
GetState()177 State FastAudioStream::GetState()
178 {
179     return state_;
180 }
181 
GetAudioTime(Timestamp & timestamp,Timestamp::Timestampbase base)182 bool FastAudioStream::GetAudioTime(Timestamp &timestamp, Timestamp::Timestampbase base)
183 {
184     CHECK_AND_RETURN_RET_LOG(base == Timestamp::MONOTONIC, false, "GetAudioTime failed: invalid base");
185 
186     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "GetAudioTime failed: null process");
187     int64_t timeSec = 0;
188     int64_t timeNsec = 0;
189     bool ret = processClient_->GetAudioTime(timestamp.framePosition, timeSec, timeNsec);
190     CHECK_AND_RETURN_RET_LOG(ret, false, "GetBufferSize error.");
191     timestamp.time.tv_sec = timeSec;
192     timestamp.time.tv_nsec = timeNsec;
193     return true;
194 }
195 
GetAudioPosition(Timestamp & timestamp,Timestamp::Timestampbase base)196 bool FastAudioStream::GetAudioPosition(Timestamp &timestamp, Timestamp::Timestampbase base)
197 {
198     return GetAudioTime(timestamp, base);
199 }
200 
GetBufferSize(size_t & bufferSize)201 int32_t FastAudioStream::GetBufferSize(size_t &bufferSize)
202 {
203     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "GetBufferSize failed: null process");
204     int32_t ret = processClient_->GetBufferSize(bufferSize);
205     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "GetBufferSize error.");
206     return ret;
207 }
208 
GetFrameCount(uint32_t & frameCount)209 int32_t FastAudioStream::GetFrameCount(uint32_t &frameCount)
210 {
211     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "GetFrameCount failed: null process");
212     int32_t ret = processClient_->GetFrameCount(frameCount);
213     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "GetFrameCount error.");
214     return ret;
215 }
216 
GetLatency(uint64_t & latency)217 int32_t FastAudioStream::GetLatency(uint64_t &latency)
218 {
219     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "GetLatency failed: null process");
220     int32_t ret = processClient_->GetLatency(latency);
221     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "GetLatency error.");
222     return ret;
223 }
224 
SetAudioStreamType(AudioStreamType audioStreamType)225 int32_t FastAudioStream::SetAudioStreamType(AudioStreamType audioStreamType)
226 {
227     // Stream type can only be set when create.
228     AUDIO_ERR_LOG("Unsupported operation: SetAudioStreamType");
229     return ERR_INVALID_OPERATION;
230 }
231 
SetVolume(float volume)232 int32_t FastAudioStream::SetVolume(float volume)
233 {
234     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "SetVolume failed: null process");
235     int32_t ret = SUCCESS;
236     cacheVolume_ = volume;
237     if (!silentModeAndMixWithOthers_) {
238         ret = processClient_->SetVolume(volume);
239         CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetVolume error.");
240     }
241     return ret;
242 }
243 
GetVolume()244 float FastAudioStream::GetVolume()
245 {
246     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, 1.0f, "SetVolume failed: null process"); // 1.0f for default
247     if (silentModeAndMixWithOthers_) {
248         return cacheVolume_;
249     } else {
250         return processClient_->GetVolume();
251     }
252 }
253 
SetDuckVolume(float volume)254 int32_t FastAudioStream::SetDuckVolume(float volume)
255 {
256     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "SetDuckVolume failed: null process");
257     int32_t ret = processClient_->SetDuckVolume(volume);
258     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetDuckVolume error.");
259     return ret;
260 }
261 
SetSilentModeAndMixWithOthers(bool on)262 void FastAudioStream::SetSilentModeAndMixWithOthers(bool on)
263 {
264     if (!silentModeAndMixWithOthers_ && on) {
265         SetVolume(0.0);
266     } else if (silentModeAndMixWithOthers_ && !on) {
267         SetVolume(cacheVolume_);
268     }
269     silentModeAndMixWithOthers_ = on;
270 }
271 
GetSilentModeAndMixWithOthers()272 bool FastAudioStream::GetSilentModeAndMixWithOthers()
273 {
274     return silentModeAndMixWithOthers_;
275 }
276 
SetRenderRate(AudioRendererRate renderRate)277 int32_t FastAudioStream::SetRenderRate(AudioRendererRate renderRate)
278 {
279     CHECK_AND_RETURN_RET(RENDER_RATE_NORMAL != renderRate, SUCCESS);
280     AUDIO_ERR_LOG("Unsupported operation: SetRenderRate");
281     return ERR_INVALID_OPERATION;
282 }
283 
GetRenderRate()284 AudioRendererRate FastAudioStream::GetRenderRate()
285 {
286     return renderRate_;
287 }
288 
SetStreamCallback(const std::shared_ptr<AudioStreamCallback> & callback)289 int32_t FastAudioStream::SetStreamCallback(const std::shared_ptr<AudioStreamCallback> &callback)
290 {
291     AUDIO_INFO_LOG("SetStreamCallback enter.");
292     // note: need add support
293     return SUCCESS;
294 }
295 
SetRenderMode(AudioRenderMode renderMode)296 int32_t FastAudioStream::SetRenderMode(AudioRenderMode renderMode)
297 {
298     CHECK_AND_RETURN_RET_LOG(renderMode == RENDER_MODE_CALLBACK && eMode_ == AUDIO_MODE_PLAYBACK,
299         ERR_INVALID_OPERATION, "SetRenderMode is not supported.");
300     return SUCCESS;
301 }
302 
GetRenderMode()303 AudioRenderMode FastAudioStream::GetRenderMode()
304 {
305     AUDIO_INFO_LOG("GetRenderMode enter.");
306     return renderMode_;
307 }
308 
SetRendererWriteCallback(const std::shared_ptr<AudioRendererWriteCallback> & callback)309 int32_t FastAudioStream::SetRendererWriteCallback(const std::shared_ptr<AudioRendererWriteCallback> &callback)
310 {
311     AUDIO_INFO_LOG("SetRendererWriteCallback enter.");
312     CHECK_AND_RETURN_RET_LOG(callback && processClient_ && eMode_ == AUDIO_MODE_PLAYBACK,
313         ERR_INVALID_PARAM, "callback is nullptr");
314     spkProcClientCb_ = std::make_shared<FastAudioStreamRenderCallback>(callback, *this);
315     int32_t ret = processClient_->SaveDataCallback(spkProcClientCb_);
316     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Client test save data callback fail, ret %{public}d.", ret);
317     return SUCCESS;
318 }
319 
SetRendererFirstFrameWritingCallback(const std::shared_ptr<AudioRendererFirstFrameWritingCallback> & callback)320 int32_t FastAudioStream::SetRendererFirstFrameWritingCallback(
321     const std::shared_ptr<AudioRendererFirstFrameWritingCallback> &callback)
322 {
323     AUDIO_INFO_LOG("SetRendererFirstFrameWritingCallback in.");
324     CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "callback is nullptr");
325     firstFrameWritingCb_ = callback;
326     return SUCCESS;
327 }
328 
SetCaptureMode(AudioCaptureMode captureMode)329 int32_t FastAudioStream::SetCaptureMode(AudioCaptureMode captureMode)
330 {
331     CHECK_AND_RETURN_RET_LOG(captureMode == CAPTURE_MODE_CALLBACK && eMode_ == AUDIO_MODE_RECORD,
332         ERR_INVALID_OPERATION, "SetCaptureMode is not supported.");
333     return SUCCESS;
334 }
335 
GetCaptureMode()336 AudioCaptureMode FastAudioStream::GetCaptureMode()
337 {
338     return captureMode_;
339 }
340 
SetCapturerReadCallback(const std::shared_ptr<AudioCapturerReadCallback> & callback)341 int32_t FastAudioStream::SetCapturerReadCallback(const std::shared_ptr<AudioCapturerReadCallback> &callback)
342 {
343     AUDIO_INFO_LOG("SetCapturerReadCallback enter.");
344     CHECK_AND_RETURN_RET_LOG(callback && processClient_ && eMode_ == AUDIO_MODE_RECORD,
345         ERR_INVALID_PARAM, "callback or client is nullptr or mode is not record.");
346     micProcClientCb_ = std::make_shared<FastAudioStreamCaptureCallback>(callback);
347     int32_t ret = processClient_->SaveDataCallback(micProcClientCb_);
348     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Client save data callback fail, ret %{public}d.", ret);
349     return SUCCESS;
350 }
351 
GetBufferDesc(BufferDesc & bufDesc)352 int32_t FastAudioStream::GetBufferDesc(BufferDesc &bufDesc)
353 {
354     AUDIO_DEBUG_LOG("GetBufferDesc enter.");
355     CHECK_AND_RETURN_RET_LOG(processClient_, ERR_INVALID_OPERATION, "spkClient is null.");
356     int32_t ret = processClient_->GetBufferDesc(bufDesc);
357     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS && bufDesc.buffer != nullptr && bufDesc.bufLength != 0,
358         -1, "GetBufferDesc failed.");
359     return SUCCESS;
360 }
361 
GetBufQueueState(BufferQueueState & bufState)362 int32_t FastAudioStream::GetBufQueueState(BufferQueueState &bufState)
363 {
364     AUDIO_INFO_LOG("GetBufQueueState enter.");
365     // note: add support
366     return SUCCESS;
367 }
368 
Enqueue(const BufferDesc & bufDesc)369 int32_t FastAudioStream::Enqueue(const BufferDesc &bufDesc)
370 {
371     AUDIO_DEBUG_LOG("Enqueue enter.");
372     CHECK_AND_RETURN_RET_LOG(processClient_, ERR_INVALID_OPERATION,
373         "spkClient is null.");
374     int32_t ret = processClient_->Enqueue(bufDesc);
375     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, -1, "Enqueue failed.");
376     return SUCCESS;
377 }
378 
SetPreferredFrameSize(int32_t frameSize)379 void FastAudioStream::SetPreferredFrameSize(int32_t frameSize)
380 {
381     std::lock_guard<std::mutex> lockSetPreferredFrameSize(setPreferredFrameSizeMutex_);
382     userSettedPreferredFrameSize_ = frameSize;
383     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "process client is null.");
384     processClient_->SetPreferredFrameSize(frameSize);
385 }
386 
UpdateLatencyTimestamp(std::string & timestamp,bool isRenderer)387 void FastAudioStream::UpdateLatencyTimestamp(std::string &timestamp, bool isRenderer)
388 {
389     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "process client is null.");
390     processClient_->UpdateLatencyTimestamp(timestamp, isRenderer);
391 }
392 
Clear()393 int32_t FastAudioStream::Clear()
394 {
395     AUDIO_INFO_LOG("Clear will do nothing.");
396 
397     return SUCCESS;
398 }
399 
SetLowPowerVolume(float volume)400 int32_t FastAudioStream::SetLowPowerVolume(float volume)
401 {
402     AUDIO_INFO_LOG("SetLowPowerVolume enter.");
403     return SUCCESS;
404 }
405 
GetLowPowerVolume()406 float FastAudioStream::GetLowPowerVolume()
407 {
408     AUDIO_INFO_LOG("GetLowPowerVolume enter.");
409     return 1.0f;
410 }
411 
SetOffloadMode(int32_t state,bool isAppBack)412 int32_t FastAudioStream::SetOffloadMode(int32_t state, bool isAppBack)
413 {
414     AUDIO_WARNING_LOG("SetOffloadMode enter.");
415     return ERR_NOT_SUPPORTED;
416 }
417 
UnsetOffloadMode()418 int32_t FastAudioStream::UnsetOffloadMode()
419 {
420     AUDIO_WARNING_LOG("UnsetOffloadMode enter.");
421     return ERR_NOT_SUPPORTED;
422 }
423 
GetSingleStreamVolume()424 float FastAudioStream::GetSingleStreamVolume()
425 {
426     AUDIO_INFO_LOG("GetSingleStreamVolume enter.");
427     return 1.0f;
428 }
429 
GetAudioEffectMode()430 AudioEffectMode FastAudioStream::GetAudioEffectMode()
431 {
432     AUDIO_ERR_LOG("GetAudioEffectMode not supported");
433     return EFFECT_NONE;
434 }
435 
SetAudioEffectMode(AudioEffectMode effectMode)436 int32_t FastAudioStream::SetAudioEffectMode(AudioEffectMode effectMode)
437 {
438     AUDIO_ERR_LOG("SetAudioEffectMode not supported");
439     return ERR_NOT_SUPPORTED;
440 }
441 
GetFramesWritten()442 int64_t FastAudioStream::GetFramesWritten()
443 {
444     int64_t result = -1; // -1 invalid frame
445     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, result, "GetFramesWritten failed: null process");
446     result = processClient_->GetFramesWritten();
447     return result;
448 }
449 
GetFramesRead()450 int64_t FastAudioStream::GetFramesRead()
451 {
452     int64_t result = -1; // -1 invalid frame
453     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, result, "GetFramesRead failed: null process");
454     result = processClient_->GetFramesRead();
455     return result;
456 }
457 
SetSpeed(float speed)458 int32_t FastAudioStream::SetSpeed(float speed)
459 {
460     AUDIO_ERR_LOG("SetSpeed is not supported");
461     return ERR_OPERATION_FAILED;
462 }
463 
GetSpeed()464 float FastAudioStream::GetSpeed()
465 {
466     AUDIO_ERR_LOG("GetSpeed is not supported");
467     return static_cast<float>(ERROR);
468 }
469 
ChangeSpeed(uint8_t * buffer,int32_t bufferSize,std::unique_ptr<uint8_t[]> & outBuffer,int32_t & outBufferSize)470 int32_t FastAudioStream::ChangeSpeed(uint8_t *buffer, int32_t bufferSize,
471     std::unique_ptr<uint8_t []> &outBuffer, int32_t &outBufferSize)
472 {
473     AUDIO_ERR_LOG("ChangeSpeed is not supported");
474     return ERR_OPERATION_FAILED;
475 }
476 
StartAudioStream(StateChangeCmdType cmdType,AudioStreamDeviceChangeReasonExt reason)477 bool FastAudioStream::StartAudioStream(StateChangeCmdType cmdType,
478     AudioStreamDeviceChangeReasonExt reason)
479 {
480     AUDIO_PRERELEASE_LOGI("StartAudioStream enter.");
481     CHECK_AND_RETURN_RET_LOG((state_ == PREPARED) || (state_ == STOPPED) || (state_ == PAUSED),
482         false, "Illegal state:%{public}u", state_);
483 
484     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "Start failed, process is null.");
485     if (spkProcClientCb_ != nullptr) {
486         AUDIO_DEBUG_LOG("StartAudioStream: reset the first frame state before starting");
487         spkProcClientCb_->ResetFirstFrameState();
488     }
489     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
490         audioStreamTracker_->FetchOutputDeviceForTrack(sessionId_, RUNNING, clientPid_, rendererInfo_, reason);
491         audioStreamTracker_->FetchInputDeviceForTrack(sessionId_, RUNNING, clientPid_, capturerInfo_);
492     }
493     int32_t ret = ERROR;
494     if (state_ == PAUSED || state_ == STOPPED) {
495         ret = processClient_->Resume();
496     } else {
497         ret = processClient_->Start();
498     }
499     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
500     state_ = RUNNING;
501 
502     AUDIO_DEBUG_LOG("StartAudioStream SUCCESS, sessionId: %{public}d", sessionId_);
503 
504     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
505         AUDIO_DEBUG_LOG("AudioStream:Calling Update tracker for Running");
506         audioStreamTracker_->UpdateTracker(sessionId_, state_, clientPid_, rendererInfo_, capturerInfo_);
507     }
508 
509     return true;
510 }
511 
PauseAudioStream(StateChangeCmdType cmdType)512 bool FastAudioStream::PauseAudioStream(StateChangeCmdType cmdType)
513 {
514     AUDIO_PRERELEASE_LOGI("PauseAudioStream enter.");
515     CHECK_AND_RETURN_RET_LOG(state_ == RUNNING, false,
516         "state is not RUNNING. Illegal state:%{public}u", state_);
517     State oldState = state_;
518 
519     state_ = PAUSED;
520     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "Pause failed, process is null.");
521     int32_t ret = processClient_->Pause();
522     if (ret != SUCCESS) {
523         AUDIO_ERR_LOG("StreamPause fail,ret:%{public}d", ret);
524         state_ = oldState;
525         return false;
526     }
527 
528     AUDIO_DEBUG_LOG("PauseAudioStream SUCCESS, sessionId: %{public}d", sessionId_);
529     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
530         AUDIO_DEBUG_LOG("AudioStream:Calling Update tracker for Pause");
531         audioStreamTracker_->UpdateTracker(sessionId_, state_, clientPid_, rendererInfo_, capturerInfo_);
532     }
533     return true;
534 }
535 
StopAudioStream()536 bool FastAudioStream::StopAudioStream()
537 {
538     CHECK_AND_RETURN_RET_LOG((state_ == RUNNING) || (state_ == PAUSED), false,
539         "State is not RUNNING. Illegal state:%{public}u", state_);
540     State oldState = state_;
541     state_ = STOPPED; // Set it before stopping as Read/Write and Stop can be called from different threads
542 
543     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "Stop failed, process is null.");
544     int32_t ret = processClient_->Stop();
545     if (ret != SUCCESS) {
546         AUDIO_ERR_LOG("StreamStop fail,ret:%{public}d", ret);
547         state_ = oldState;
548         return false;
549     }
550 
551     AUDIO_INFO_LOG("StopAudioStream SUCCESS, sessionId: %{public}d", sessionId_);
552     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
553         AUDIO_DEBUG_LOG("AudioStream:Calling Update tracker for stop");
554         audioStreamTracker_->UpdateTracker(sessionId_, state_, clientPid_, rendererInfo_, capturerInfo_);
555     }
556     return true;
557 }
558 
FlushAudioStream()559 bool FastAudioStream::FlushAudioStream()
560 {
561     AUDIO_PRERELEASE_LOGI("FlushAudioStream enter.");
562     return true;
563 }
564 
DrainAudioStream(bool stopFlag)565 bool FastAudioStream::DrainAudioStream(bool stopFlag)
566 {
567     AUDIO_INFO_LOG("Drain stream SUCCESS");
568     return true;
569 }
570 
ReleaseAudioStream(bool releaseRunner,bool isSwitchStream)571 bool FastAudioStream::ReleaseAudioStream(bool releaseRunner, bool isSwitchStream)
572 {
573     CHECK_AND_RETURN_RET_LOG(state_ != RELEASED && state_ != NEW,
574         false, "Illegal state: state = %{public}u", state_);
575     // If state_ is RUNNING try to Stop it first and Release
576     if (state_ == RUNNING) {
577         StopAudioStream();
578     }
579 
580     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "Release failed, process is null.");
581     processClient_->Release(isSwitchStream);
582     state_ = RELEASED;
583     AUDIO_INFO_LOG("ReleaseAudiostream SUCCESS, sessionId: %{public}d", sessionId_);
584     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
585         AUDIO_DEBUG_LOG("AudioStream:Calling Update tracker for release");
586         audioStreamTracker_->UpdateTracker(sessionId_, state_, clientPid_, rendererInfo_, capturerInfo_);
587     }
588     return true;
589 }
590 
Read(uint8_t & buffer,size_t userSize,bool isBlockingRead)591 int32_t FastAudioStream::Read(uint8_t &buffer, size_t userSize, bool isBlockingRead)
592 {
593     AUDIO_ERR_LOG("Unsupported operation: read");
594     return ERR_INVALID_OPERATION;
595 }
596 
Write(uint8_t * buffer,size_t buffer_size)597 int32_t FastAudioStream::Write(uint8_t *buffer, size_t buffer_size)
598 {
599     AUDIO_ERR_LOG("Unsupported operation: Write");
600     return ERR_INVALID_OPERATION;
601 }
602 
Write(uint8_t * pcmBuffer,size_t pcmBufferSize,uint8_t * metaBuffer,size_t metaBufferSize)603 int32_t FastAudioStream::Write(uint8_t *pcmBuffer, size_t pcmBufferSize, uint8_t *metaBuffer, size_t metaBufferSize)
604 {
605     AUDIO_ERR_LOG("Unsupported operation: Write");
606     return ERR_INVALID_OPERATION;
607 }
608 
GetUnderflowCount()609 uint32_t FastAudioStream::GetUnderflowCount()
610 {
611     AUDIO_INFO_LOG("GetUnderflowCount enter.");
612     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, 0, "process client is null.");
613     underflowCount_ = processClient_->GetUnderflowCount();
614     return underflowCount_;
615 }
616 
GetOverflowCount()617 uint32_t FastAudioStream::GetOverflowCount()
618 {
619     AUDIO_INFO_LOG("enter.");
620     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, 0, "process client is null.");
621     overflowCount_ = processClient_->GetOverflowCount();
622     return overflowCount_;
623 }
624 
SetUnderflowCount(uint32_t underflowCount)625 void FastAudioStream::SetUnderflowCount(uint32_t underflowCount)
626 {
627     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "process client is null.");
628     processClient_->SetUnderflowCount(underflowCount);
629 }
630 
SetOverflowCount(uint32_t overflowCount)631 void FastAudioStream::SetOverflowCount(uint32_t overflowCount)
632 {
633     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "process client is null.");
634     processClient_->SetOverflowCount(overflowCount);
635 }
636 
SetRendererPositionCallback(int64_t markPosition,const std::shared_ptr<RendererPositionCallback> & callback)637 void FastAudioStream::SetRendererPositionCallback(int64_t markPosition,
638     const std::shared_ptr<RendererPositionCallback> &callback)
639 {
640     AUDIO_INFO_LOG("Registering render frame position callback mark position");
641     // note: need support
642 }
643 
UnsetRendererPositionCallback()644 void FastAudioStream::UnsetRendererPositionCallback()
645 {
646     AUDIO_INFO_LOG("Unregistering render frame position callback");
647     // note: need support
648 }
649 
SetRendererPeriodPositionCallback(int64_t periodPosition,const std::shared_ptr<RendererPeriodPositionCallback> & callback)650 void FastAudioStream::SetRendererPeriodPositionCallback(int64_t periodPosition,
651     const std::shared_ptr<RendererPeriodPositionCallback> &callback)
652 {
653     AUDIO_INFO_LOG("Registering render period position callback");
654 }
655 
UnsetRendererPeriodPositionCallback()656 void FastAudioStream::UnsetRendererPeriodPositionCallback()
657 {
658     AUDIO_INFO_LOG("Unregistering render period position callback");
659 }
660 
SetCapturerPositionCallback(int64_t markPosition,const std::shared_ptr<CapturerPositionCallback> & callback)661 void FastAudioStream::SetCapturerPositionCallback(int64_t markPosition,
662     const std::shared_ptr<CapturerPositionCallback> &callback)
663 {
664     AUDIO_INFO_LOG("Registering capture frame position callback, mark position");
665 }
666 
UnsetCapturerPositionCallback()667 void FastAudioStream::UnsetCapturerPositionCallback()
668 {
669     AUDIO_INFO_LOG("Unregistering capture frame position callback");
670 }
671 
SetCapturerPeriodPositionCallback(int64_t periodPosition,const std::shared_ptr<CapturerPeriodPositionCallback> & callback)672 void FastAudioStream::SetCapturerPeriodPositionCallback(int64_t periodPosition,
673     const std::shared_ptr<CapturerPeriodPositionCallback> &callback)
674 {
675     AUDIO_INFO_LOG("Registering period position callback");
676 }
677 
UnsetCapturerPeriodPositionCallback()678 void FastAudioStream::UnsetCapturerPeriodPositionCallback()
679 {
680     AUDIO_INFO_LOG("Unregistering period position callback");
681 }
682 
SetRendererSamplingRate(uint32_t sampleRate)683 int32_t FastAudioStream::SetRendererSamplingRate(uint32_t sampleRate)
684 {
685     AUDIO_ERR_LOG("SetRendererSamplingRate  is not supported");
686 
687     return ERR_OPERATION_FAILED;
688 }
689 
GetRendererSamplingRate()690 uint32_t FastAudioStream::GetRendererSamplingRate()
691 {
692     AUDIO_INFO_LOG("GetRendererSamplingRate enter.");
693     return streamInfo_.samplingRate;
694 }
695 
SetBufferSizeInMsec(int32_t bufferSizeInMsec)696 int32_t FastAudioStream::SetBufferSizeInMsec(int32_t bufferSizeInMsec)
697 {
698     AUDIO_ERR_LOG("SetBufferSizeInMsec is not supported");
699     // note: add support
700     return ERR_NOT_SUPPORTED;
701 }
702 
SetApplicationCachePath(const std::string cachePath)703 void FastAudioStream::SetApplicationCachePath(const std::string cachePath)
704 {
705     AUDIO_INFO_LOG("SetApplicationCachePath to %{public}s", cachePath.c_str());
706 
707     cachePath_ = cachePath;
708 }
SetInnerCapturerState(bool isInnerCapturer)709 void FastAudioStream::SetInnerCapturerState(bool isInnerCapturer)
710 {
711     AUDIO_ERR_LOG("SetInnerCapturerState is not supported");
712 }
713 
SetWakeupCapturerState(bool isWakeupCapturer)714 void FastAudioStream::SetWakeupCapturerState(bool isWakeupCapturer)
715 {
716     AUDIO_ERR_LOG("SetWakeupCapturerState is not supported");
717 }
718 
SetCapturerSource(int capturerSource)719 void FastAudioStream::SetCapturerSource(int capturerSource)
720 {
721     AUDIO_ERR_LOG("SetCapturerSource is not supported");
722 }
723 
SetPrivacyType(AudioPrivacyType privacyType)724 void FastAudioStream::SetPrivacyType(AudioPrivacyType privacyType)
725 {
726     AUDIO_ERR_LOG("SetPrivacyType is not supported");
727 }
728 
GetStreamClass()729 IAudioStream::StreamClass FastAudioStream::GetStreamClass()
730 {
731     return IAudioStream::StreamClass::FAST_STREAM;
732 }
733 
SetStreamTrackerState(bool trackerRegisteredState)734 void FastAudioStream::SetStreamTrackerState(bool trackerRegisteredState)
735 {
736     streamTrackerRegistered_ = trackerRegisteredState;
737 }
738 
GetSwitchInfo(IAudioStream::SwitchInfo & info)739 void FastAudioStream::GetSwitchInfo(IAudioStream::SwitchInfo& info)
740 {
741     GetAudioStreamInfo(info.params);
742     info.rendererInfo = rendererInfo_;
743     info.capturerInfo = capturerInfo_;
744     info.eStreamType = eStreamType_;
745     info.state = state_;
746     info.sessionId = sessionId_;
747     info.cachePath = cachePath_;
748 
749     info.clientPid = clientPid_;
750     info.clientUid = clientUid_;
751 
752     info.volume = GetVolume();
753     info.effectMode = GetAudioEffectMode();
754     info.renderMode = renderMode_;
755     info.captureMode = captureMode_;
756     info.renderRate = renderRate_;
757 
758     info.underFlowCount = GetUnderflowCount();
759     info.overFlowCount = GetOverflowCount();
760 
761     info.silentModeAndMixWithOthers = silentModeAndMixWithOthers_;
762 
763     {
764         std::lock_guard<std::mutex> lock(setPreferredFrameSizeMutex_);
765         info.userSettedPreferredFrameSize = userSettedPreferredFrameSize_;
766     }
767 
768     if (spkProcClientCb_) {
769         info.rendererWriteCallback = spkProcClientCb_->GetRendererWriteCallback();
770     }
771     if (micProcClientCb_) {
772         info.capturerReadCallback = micProcClientCb_->GetCapturerReadCallback();
773     }
774     if (firstFrameWritingCb_) {
775         info.rendererFirstFrameWritingCallback = firstFrameWritingCb_;
776     }
777 }
778 
OnFirstFrameWriting()779 void FastAudioStream::OnFirstFrameWriting()
780 {
781     CHECK_AND_RETURN_LOG(firstFrameWritingCb_!= nullptr, "firstFrameWritingCb_ is null.");
782     uint64_t latency = 0;
783     this->GetLatency(latency);
784     firstFrameWritingCb_->OnFirstFrameWriting(latency);
785 }
786 
OnHandleData(size_t length)787 void FastAudioStreamRenderCallback::OnHandleData(size_t length)
788 {
789     CHECK_AND_RETURN_LOG(rendererWriteCallback_!= nullptr, "OnHandleData failed: rendererWriteCallback_ is null.");
790     if (!hasFirstFrameWrited_) {
791         AUDIO_DEBUG_LOG("OnHandleData: send the first frame writing event to audio haptic player");
792         audioStreamImpl_.OnFirstFrameWriting();
793         hasFirstFrameWrited_ = true;
794     }
795     rendererWriteCallback_->OnWriteData(length);
796 }
797 
ResetFirstFrameState()798 void FastAudioStreamRenderCallback::ResetFirstFrameState()
799 {
800     AUDIO_DEBUG_LOG("ResetFirstFrameState: set the hasFirstFrameWrited_ to false");
801     hasFirstFrameWrited_ = false;
802 }
803 
GetRendererWriteCallback() const804 std::shared_ptr<AudioRendererWriteCallback> FastAudioStreamRenderCallback::GetRendererWriteCallback() const
805 {
806     return rendererWriteCallback_;
807 }
808 
GetCapturerReadCallback() const809 std::shared_ptr<AudioCapturerReadCallback> FastAudioStreamCaptureCallback::GetCapturerReadCallback() const
810 {
811     return captureCallback_;
812 }
813 
OnHandleData(size_t length)814 void FastAudioStreamCaptureCallback::OnHandleData(size_t length)
815 {
816     CHECK_AND_RETURN_LOG(captureCallback_!= nullptr, "OnHandleData failed: captureCallback_ is null.");
817     captureCallback_->OnReadData(length);
818 }
819 
SetChannelBlendMode(ChannelBlendMode blendMode)820 int32_t FastAudioStream::SetChannelBlendMode(ChannelBlendMode blendMode)
821 {
822     AUDIO_ERR_LOG("SetChannelBlendMode is not supported");
823     return SUCCESS;
824 }
825 
SetVolumeWithRamp(float volume,int32_t duration)826 int32_t FastAudioStream::SetVolumeWithRamp(float volume, int32_t duration)
827 {
828     AUDIO_ERR_LOG("SetVolumeWithRamp is not supported");
829     return SUCCESS;
830 }
831 
UpdateRegisterTrackerInfo(AudioRegisterTrackerInfo & registerTrackerInfo)832 void FastAudioStream::UpdateRegisterTrackerInfo(AudioRegisterTrackerInfo &registerTrackerInfo)
833 {
834     rendererInfo_.samplingRate = static_cast<AudioSamplingRate>(streamInfo_.samplingRate);
835     capturerInfo_.samplingRate = static_cast<AudioSamplingRate>(streamInfo_.samplingRate);
836 
837     registerTrackerInfo.sessionId = sessionId_;
838     registerTrackerInfo.clientPid = clientPid_;
839     registerTrackerInfo.state = state_;
840     registerTrackerInfo.rendererInfo = rendererInfo_;
841     registerTrackerInfo.capturerInfo = capturerInfo_;
842 }
843 
RestoreAudioStream(bool needStoreState)844 bool FastAudioStream::RestoreAudioStream(bool needStoreState)
845 {
846     CHECK_AND_RETURN_RET_LOG(proxyObj_ != nullptr, false, "proxyObj_ is null");
847     CHECK_AND_RETURN_RET_LOG(state_ != NEW && state_ != INVALID && state_ != RELEASED, true,
848         "state_ is %{public}d, no need for restore", state_);
849     bool result = false;
850     State oldState = state_;
851     state_ = NEW;
852     SetStreamTrackerState(false);
853     if (processClient_ != nullptr) {
854         processClient_->Stop();
855         processClient_->Release();
856         processClient_ = nullptr;
857     }
858     int32_t ret = SetAudioStreamInfo(streamInfo_, proxyObj_);
859     if (ret != SUCCESS) {
860         goto error;
861     }
862     switch (oldState) {
863         case RUNNING:
864             CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "processClient_ is null");
865             ret = processClient_->SaveDataCallback(spkProcClientCb_);
866             if (ret != SUCCESS) {
867                 goto error;
868             }
869             result = StartAudioStream();
870             break;
871         case PAUSED:
872             result = StartAudioStream() && PauseAudioStream();
873             break;
874         case STOPPED:
875         case STOPPING:
876             result = StartAudioStream() && StopAudioStream();
877             break;
878         default:
879             break;
880     }
881     if (!result) {
882         goto error;
883     }
884     return result;
885 
886 error:
887     AUDIO_ERR_LOG("RestoreAudioStream failed");
888     state_ = oldState;
889     return false;
890 }
891 
GetOffloadEnable()892 bool FastAudioStream::GetOffloadEnable()
893 {
894     AUDIO_WARNING_LOG("not supported in fast audio stream");
895     return false;
896 }
897 
GetSpatializationEnabled()898 bool FastAudioStream::GetSpatializationEnabled()
899 {
900     AUDIO_WARNING_LOG("not supported in fast audio stream");
901     return false;
902 }
903 
GetHighResolutionEnabled()904 bool FastAudioStream::GetHighResolutionEnabled()
905 {
906     AUDIO_WARNING_LOG("not supported in fast audio stream");
907     return false;
908 }
909 } // namespace AudioStandard
910 } // namespace OHOS
911