• 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 #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 
26 #include "fast_audio_stream.h"
27 
28 using namespace std;
29 
30 namespace OHOS {
31 namespace AudioStandard {
FastAudioStream(AudioStreamType eStreamType,AudioMode eMode,int32_t appUid)32 FastAudioStream::FastAudioStream(AudioStreamType eStreamType, AudioMode eMode, int32_t appUid)
33     : eStreamType_(eStreamType),
34       eMode_(eMode),
35       state_(NEW),
36       renderMode_(RENDER_MODE_CALLBACK),
37       captureMode_(CAPTURE_MODE_CALLBACK)
38 {
39     AUDIO_INFO_LOG("FastAudioStream ctor, appUID = %{public}d", appUid);
40     audioStreamTracker_ = std::make_unique<AudioStreamTracker>(eMode, appUid);
41     AUDIO_DEBUG_LOG("AudioStreamTracker created");
42 }
43 
~FastAudioStream()44 FastAudioStream::~FastAudioStream()
45 {
46     if (state_ != RELEASED && state_ != NEW) {
47         ReleaseAudioStream(false);
48     }
49     AUDIO_INFO_LOG("FastAudioStream dtor, session %{public}u", sessionId_);
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 fast stream client PID:%{public}d UID:%{public}d appTokenId:%{public}u "
55         "fullTokenId:%{public}" PRIu64, clientPid, clientUid, appTokenId, fullTokenId);
56     clientPid_ = clientPid;
57     clientUid_ = clientUid;
58     appTokenId_ = appTokenId;
59     fullTokenId_ = fullTokenId;
60 }
61 
UpdatePlaybackCaptureConfig(const AudioPlaybackCaptureConfig & config)62 int32_t FastAudioStream::UpdatePlaybackCaptureConfig(const AudioPlaybackCaptureConfig &config)
63 {
64     AUDIO_ERR_LOG("Unsupported operation!");
65     return ERR_NOT_SUPPORTED;
66 }
67 
SetRendererInfo(const AudioRendererInfo & rendererInfo)68 void FastAudioStream::SetRendererInfo(const AudioRendererInfo &rendererInfo)
69 {
70     rendererInfo_ = rendererInfo;
71     rendererInfo_.samplingRate = static_cast<AudioSamplingRate>(streamInfo_.samplingRate);
72 }
73 
GetRendererInfo(AudioRendererInfo & rendererInfo)74 void FastAudioStream::GetRendererInfo(AudioRendererInfo &rendererInfo)
75 {
76     rendererInfo = rendererInfo_;
77 }
78 
SetCapturerInfo(const AudioCapturerInfo & capturerInfo)79 void FastAudioStream::SetCapturerInfo(const AudioCapturerInfo &capturerInfo)
80 {
81     capturerInfo_ = capturerInfo;
82     capturerInfo_.samplingRate = static_cast<AudioSamplingRate>(streamInfo_.samplingRate);
83 }
84 
InitializeAudioProcessConfig(AudioProcessConfig & config,const AudioStreamParams & info)85 int32_t FastAudioStream::InitializeAudioProcessConfig(AudioProcessConfig &config, const AudioStreamParams &info)
86 {
87     config.appInfo.appPid = clientPid_;
88     config.appInfo.appUid = clientUid_;
89     config.appInfo.appTokenId = appTokenId_;
90     config.appInfo.appFullTokenId = fullTokenId_;
91     config.audioMode = eMode_;
92     config.streamInfo.channels = static_cast<AudioChannel>(info.channels);
93     config.streamInfo.encoding = static_cast<AudioEncodingType>(info.encoding);
94     config.streamInfo.format = static_cast<AudioSampleFormat>(info.format);
95     config.streamInfo.samplingRate = static_cast<AudioSamplingRate>(info.samplingRate);
96     config.streamType = eStreamType_;
97     config.originalSessionId = info.originalSessionId;
98     if (eMode_ == AUDIO_MODE_PLAYBACK) {
99         AUDIO_DEBUG_LOG("FastAudioStream: Initialize playback");
100         config.rendererInfo.contentType = rendererInfo_.contentType;
101         config.rendererInfo.streamUsage = rendererInfo_.streamUsage;
102         config.rendererInfo.rendererFlags = STREAM_FLAG_FAST;
103         config.rendererInfo.volumeMode = rendererInfo_.volumeMode;
104         config.rendererInfo.isVirtualKeyboard = rendererInfo_.isVirtualKeyboard;
105         config.rendererInfo.originalFlag = rendererInfo_.originalFlag;
106         config.rendererInfo.playerType = rendererInfo_.playerType;
107         config.rendererInfo.expectedPlaybackDurationBytes = rendererInfo_.expectedPlaybackDurationBytes;
108         config.rendererInfo.isLoopback = rendererInfo_.isLoopback;
109         config.rendererInfo.loopbackMode = rendererInfo_.loopbackMode;
110     } else if (eMode_ == AUDIO_MODE_RECORD) {
111         AUDIO_DEBUG_LOG("FastAudioStream: Initialize recording");
112         config.capturerInfo.sourceType = capturerInfo_.sourceType;
113         config.capturerInfo.capturerFlags = STREAM_FLAG_FAST;
114         config.capturerInfo.originalFlag = capturerInfo_.originalFlag;
115         config.capturerInfo.recorderType = capturerInfo_.recorderType;
116         config.capturerInfo.isLoopback = capturerInfo_.isLoopback;
117         config.capturerInfo.loopbackMode = capturerInfo_.loopbackMode;
118     } else {
119         return ERR_INVALID_OPERATION;
120     }
121     return SUCCESS;
122 }
123 
SetAudioStreamInfo(const AudioStreamParams info,const std::shared_ptr<AudioClientTracker> & proxyObj,const AudioPlaybackCaptureConfig & filterConfig)124 int32_t FastAudioStream::SetAudioStreamInfo(const AudioStreamParams info,
125     const std::shared_ptr<AudioClientTracker> &proxyObj,
126     const AudioPlaybackCaptureConfig &filterConfig)
127 {
128     AUDIO_INFO_LOG("FastAudioStreamInfo, Sampling rate: %{public}d, channels: %{public}d, format: %{public}d,"
129         " stream type: %{public}d", info.samplingRate, info.channels, info.format, eStreamType_);
130     CHECK_AND_RETURN_RET_LOG(processClient_ == nullptr, ERR_INVALID_OPERATION,
131         "Process is already inited, reset stream info is not supported.");
132     streamInfo_ = info;
133     if (state_ != NEW) {
134         AUDIO_INFO_LOG("FastAudioStream: State is not new, release existing stream");
135         StopAudioStream();
136         ReleaseAudioStream(false);
137     }
138     AudioProcessConfig config;
139     int32_t ret = InitializeAudioProcessConfig(config, info);
140     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Initialize failed.");
141     CHECK_AND_RETURN_RET_LOG(AudioProcessInClient::CheckIfSupport(config), ERR_INVALID_PARAM,
142         "Stream is not supported.");
143     processconfig_ = config;
144     // OS_AudioPlayCb/RecordCb should lock weak_ptr of FastAudioStream before calling OnWriteData to
145     // avoid using FastAudioStream after free in callback.
146     auto weakStream = weak_from_this();
147     processClient_ = AudioProcessInClient::Create(config, weakStream);
148     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_INVALID_PARAM,
149         "Client test creat process client fail.");
150     state_ = PREPARED;
151     proxyObj_ = proxyObj;
152 
153     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
154         processClient_->GetSessionID(sessionId_);
155 
156         AudioRegisterTrackerInfo registerTrackerInfo;
157         UpdateRegisterTrackerInfo(registerTrackerInfo);
158         audioStreamTracker_->RegisterTracker(registerTrackerInfo, proxyObj);
159     }
160     InitCallbackHandler();
161     return SUCCESS;
162 }
163 
InitCallbackHandler()164 void FastAudioStream::InitCallbackHandler()
165 {
166     std::lock_guard<std::mutex> lock(runnerMutex_);
167     if (callbackHandler_ == nullptr) {
168         callbackHandler_ = CallbackHandler::GetInstance(shared_from_this(), "OS_AudioStateCB");
169     }
170 }
171 
SafeSendCallbackEvent(uint32_t eventCode,int64_t data)172 void FastAudioStream::SafeSendCallbackEvent(uint32_t eventCode, int64_t data)
173 {
174     std::lock_guard<std::mutex> lock(runnerMutex_);
175     AUDIO_INFO_LOG("Send callback event, code: %{public}u, data: %{public}" PRId64, eventCode, data);
176     CHECK_AND_RETURN_LOG(callbackHandler_ != nullptr && runnerReleased_ == false, "Runner is Released");
177     callbackHandler_->SendCallbackEvent(eventCode, data);
178 }
179 
OnHandle(uint32_t code,int64_t data)180 void FastAudioStream::OnHandle(uint32_t code, int64_t data)
181 {
182     AUDIO_DEBUG_LOG("On handle event, event code: %{public}u, data: %{public}" PRId64, code, data);
183     switch (code) {
184         case STATE_CHANGE_EVENT:
185             HandleStateChangeEvent(data);
186             break;
187         default:
188             break;
189     }
190 }
191 
HandleStateChangeEvent(int64_t data)192 void FastAudioStream::HandleStateChangeEvent(int64_t data)
193 {
194     State state = INVALID;
195     StateChangeCmdType cmdType = CMD_FROM_CLIENT;
196     ParamsToStateCmdType(data, state, cmdType);
197     std::unique_lock<std::mutex> lock(streamCbMutex_);
198     std::shared_ptr<AudioStreamCallback> streamCb = streamCallback_.lock();
199     if (streamCb != nullptr) {
200         state = state != STOPPING ? state : STOPPED; // client only need STOPPED
201         streamCb->OnStateChange(state, cmdType);
202     }
203 }
204 
ParamsToStateCmdType(int64_t params,State & state,StateChangeCmdType & cmdType)205 int32_t FastAudioStream::ParamsToStateCmdType(int64_t params, State &state, StateChangeCmdType &cmdType)
206 {
207     cmdType = CMD_FROM_CLIENT;
208     switch (params) {
209         case HANDLER_PARAM_NEW:
210             state = NEW;
211             break;
212         case HANDLER_PARAM_PREPARED:
213             state = PREPARED;
214             break;
215         case HANDLER_PARAM_RUNNING:
216             state = RUNNING;
217             break;
218         case HANDLER_PARAM_STOPPED:
219             state = STOPPED;
220             break;
221         case HANDLER_PARAM_RELEASED:
222             state = RELEASED;
223             break;
224         case HANDLER_PARAM_PAUSED:
225             state = PAUSED;
226             break;
227         case HANDLER_PARAM_STOPPING:
228             state = STOPPING;
229             break;
230         case HANDLER_PARAM_RUNNING_FROM_SYSTEM:
231             state = RUNNING;
232             cmdType = CMD_FROM_SYSTEM;
233             break;
234         case HANDLER_PARAM_PAUSED_FROM_SYSTEM:
235             state = PAUSED;
236             cmdType = CMD_FROM_SYSTEM;
237             break;
238         default:
239             state = INVALID;
240             break;
241     }
242     return SUCCESS;
243 }
244 
GetAudioStreamInfo(AudioStreamParams & audioStreamInfo)245 int32_t FastAudioStream::GetAudioStreamInfo(AudioStreamParams &audioStreamInfo)
246 {
247     AUDIO_INFO_LOG("enter.");
248     audioStreamInfo = streamInfo_;
249     return SUCCESS;
250 }
251 
GetAudioSessionID(uint32_t & sessionID)252 int32_t FastAudioStream::GetAudioSessionID(uint32_t &sessionID)
253 {
254     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED,
255         "GetAudioSessionID failed: null process");
256     int32_t ret = processClient_->GetSessionID(sessionID);
257     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "GetSessionID error.");
258     return ret;
259 }
260 
GetAudioPipeType(AudioPipeType & pipeType)261 void FastAudioStream::GetAudioPipeType(AudioPipeType &pipeType)
262 {
263     pipeType = eMode_ == AUDIO_MODE_PLAYBACK ? rendererInfo_.pipeType : capturerInfo_.pipeType;
264 }
265 
GetState()266 State FastAudioStream::GetState()
267 {
268     std::lock_guard lock(switchingMutex_);
269     if (switchingInfo_.isSwitching_) {
270         AUDIO_INFO_LOG("switching, return state in switchingInfo");
271         return switchingInfo_.state_;
272     }
273     return state_;
274 }
275 
GetAudioTime(Timestamp & timestamp,Timestamp::Timestampbase base)276 bool FastAudioStream::GetAudioTime(Timestamp &timestamp, Timestamp::Timestampbase base)
277 {
278     CHECK_AND_RETURN_RET_LOG(base == Timestamp::MONOTONIC, false, "GetAudioTime failed: invalid base");
279 
280     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "GetAudioTime failed: null process");
281     int64_t timeSec = 0;
282     int64_t timeNsec = 0;
283     bool ret = processClient_->GetAudioTime(timestamp.framePosition, timeSec, timeNsec);
284     CHECK_AND_RETURN_RET_LOG(ret, false, "GetBufferSize error.");
285     timestamp.time.tv_sec = timeSec;
286     timestamp.time.tv_nsec = timeNsec;
287     return true;
288 }
289 
SetSwitchInfoTimestamp(std::vector<std::pair<uint64_t,uint64_t>> lastFramePosAndTimePair,std::vector<std::pair<uint64_t,uint64_t>> lastFramePosAndTimePairWithSpeed)290 void FastAudioStream::SetSwitchInfoTimestamp(
291     std::vector<std::pair<uint64_t, uint64_t>> lastFramePosAndTimePair,
292     std::vector<std::pair<uint64_t, uint64_t>> lastFramePosAndTimePairWithSpeed)
293 {
294     (void)lastFramePosAndTimePair;
295     (void)lastFramePosAndTimePairWithSpeed;
296     AUDIO_INFO_LOG("fast stream not support timestamp re-set when stream switching");
297 }
298 
GetAudioPosition(Timestamp & timestamp,Timestamp::Timestampbase base)299 bool FastAudioStream::GetAudioPosition(Timestamp &timestamp, Timestamp::Timestampbase base)
300 {
301     return GetAudioTime(timestamp, base);
302 }
303 
GetBufferSize(size_t & bufferSize)304 int32_t FastAudioStream::GetBufferSize(size_t &bufferSize)
305 {
306     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "GetBufferSize failed: null process");
307     int32_t ret = processClient_->GetBufferSize(bufferSize);
308     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "GetBufferSize error.");
309     return ret;
310 }
311 
GetFrameCount(uint32_t & frameCount)312 int32_t FastAudioStream::GetFrameCount(uint32_t &frameCount)
313 {
314     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "GetFrameCount failed: null process");
315     int32_t ret = processClient_->GetFrameCount(frameCount);
316     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "GetFrameCount error.");
317     return ret;
318 }
319 
GetLatency(uint64_t & latency)320 int32_t FastAudioStream::GetLatency(uint64_t &latency)
321 {
322     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "GetLatency failed: null process");
323     int32_t ret = processClient_->GetLatency(latency);
324     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "GetLatency error.");
325     return ret;
326 }
327 
SetAudioStreamType(AudioStreamType audioStreamType)328 int32_t FastAudioStream::SetAudioStreamType(AudioStreamType audioStreamType)
329 {
330     // Stream type can only be set when create.
331     AUDIO_ERR_LOG("Unsupported operation: SetAudioStreamType");
332     return ERR_INVALID_OPERATION;
333 }
334 
SetVolume(float volume)335 int32_t FastAudioStream::SetVolume(float volume)
336 {
337     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "SetVolume failed: null process");
338     int32_t ret = SUCCESS;
339     ret = processClient_->SetVolume(volume);
340     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetVolume error.");
341     return ret;
342 }
343 
GetVolume()344 float FastAudioStream::GetVolume()
345 {
346     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, 1.0f, "SetVolume failed: null process"); // 1.0f for default
347     return processClient_->GetVolume();
348 }
349 
SetLoudnessGain(float loudnessGain)350 int32_t FastAudioStream::SetLoudnessGain(float loudnessGain)
351 {
352     AUDIO_WARNING_LOG("SetLoudnessGain is only for renderer");
353     return ERROR;
354 }
355 
GetLoudnessGain()356 float FastAudioStream::GetLoudnessGain()
357 {
358     AUDIO_WARNING_LOG("GetLoudnessGain is only for renderer");
359     return 0.0;
360 }
361 
SetMute(bool mute,StateChangeCmdType cmdType)362 int32_t FastAudioStream::SetMute(bool mute, StateChangeCmdType cmdType)
363 {
364     muteCmd_ = cmdType;
365     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "SetMute failed: null process");
366     int32_t ret = processClient_->SetMute(mute);
367     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetMute error.");
368     return ret;
369 }
370 
GetMute()371 bool FastAudioStream::GetMute()
372 {
373     return processClient_->GetMute();
374 }
375 
SetSourceDuration(int64_t duration)376 int32_t FastAudioStream::SetSourceDuration(int64_t duration)
377 {
378     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "SetMute failed: null process");
379     int32_t ret = processClient_->SetSourceDuration(duration);
380     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetSourceDuration error.");
381     return ret;
382 }
383 
SetDuckVolume(float volume)384 int32_t FastAudioStream::SetDuckVolume(float volume)
385 {
386     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "SetDuckVolume failed: null process");
387     int32_t ret = processClient_->SetDuckVolume(volume);
388     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetDuckVolume error.");
389     return ret;
390 }
391 
GetDuckVolume()392 float FastAudioStream::GetDuckVolume()
393 {
394     return processClient_->GetDuckVolume();
395 }
396 
SetSilentModeAndMixWithOthers(bool on)397 void FastAudioStream::SetSilentModeAndMixWithOthers(bool on)
398 {
399     AUDIO_PRERELEASE_LOGI("%{public}d", on);
400     silentModeAndMixWithOthers_ = on;
401     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "processClient is null.");
402     processClient_->SetSilentModeAndMixWithOthers(on);
403 }
404 
GetSilentModeAndMixWithOthers()405 bool FastAudioStream::GetSilentModeAndMixWithOthers()
406 {
407     return silentModeAndMixWithOthers_;
408 }
409 
SetRenderRate(AudioRendererRate renderRate)410 int32_t FastAudioStream::SetRenderRate(AudioRendererRate renderRate)
411 {
412     CHECK_AND_RETURN_RET(RENDER_RATE_NORMAL != renderRate, SUCCESS);
413     AUDIO_ERR_LOG("Unsupported operation: SetRenderRate");
414     return ERR_INVALID_OPERATION;
415 }
416 
GetRenderRate()417 AudioRendererRate FastAudioStream::GetRenderRate()
418 {
419     return renderRate_;
420 }
421 
SetStreamCallback(const std::shared_ptr<AudioStreamCallback> & callback)422 int32_t FastAudioStream::SetStreamCallback(const std::shared_ptr<AudioStreamCallback> &callback)
423 {
424     AUDIO_INFO_LOG("enter.");
425 
426     if (callback == nullptr) {
427         AUDIO_ERR_LOG("SetStreamCallback failed. callback == nullptr");
428         return ERR_INVALID_PARAM;
429     }
430 
431     std::unique_lock<std::mutex> lock(streamCbMutex_);
432     streamCallback_ = callback;
433     lock.unlock();
434 
435     if (state_ != PREPARED) {
436         return SUCCESS;
437     }
438     SafeSendCallbackEvent(STATE_CHANGE_EVENT, PREPARED);
439     return SUCCESS;
440 }
441 
SetRenderMode(AudioRenderMode renderMode)442 int32_t FastAudioStream::SetRenderMode(AudioRenderMode renderMode)
443 {
444     CHECK_AND_RETURN_RET_LOG(renderMode == RENDER_MODE_CALLBACK && eMode_ == AUDIO_MODE_PLAYBACK,
445         ERR_INVALID_OPERATION, "SetRenderMode is not supported.");
446     return SUCCESS;
447 }
448 
GetRenderMode()449 AudioRenderMode FastAudioStream::GetRenderMode()
450 {
451     AUDIO_INFO_LOG("enter.");
452     return renderMode_;
453 }
454 
SetRendererWriteCallback(const std::shared_ptr<AudioRendererWriteCallback> & callback)455 int32_t FastAudioStream::SetRendererWriteCallback(const std::shared_ptr<AudioRendererWriteCallback> &callback)
456 {
457     AUDIO_INFO_LOG("SetRendererWriteCallback enter.");
458     CHECK_AND_RETURN_RET_LOG(callback && processClient_ && eMode_ == AUDIO_MODE_PLAYBACK,
459         ERR_INVALID_PARAM, "callback is nullptr");
460     spkProcClientCb_ = std::make_shared<FastAudioStreamRenderCallback>(callback, *this);
461     int32_t ret = processClient_->SaveDataCallback(spkProcClientCb_);
462     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Client test save data callback fail, ret %{public}d.", ret);
463     return SUCCESS;
464 }
465 
SetRendererFirstFrameWritingCallback(const std::shared_ptr<AudioRendererFirstFrameWritingCallback> & callback)466 int32_t FastAudioStream::SetRendererFirstFrameWritingCallback(
467     const std::shared_ptr<AudioRendererFirstFrameWritingCallback> &callback)
468 {
469     AUDIO_INFO_LOG("SetRendererFirstFrameWritingCallback in.");
470     CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "callback is nullptr");
471     firstFrameWritingCb_ = callback;
472     return SUCCESS;
473 }
474 
SetCaptureMode(AudioCaptureMode captureMode)475 int32_t FastAudioStream::SetCaptureMode(AudioCaptureMode captureMode)
476 {
477     CHECK_AND_RETURN_RET_LOG(captureMode == CAPTURE_MODE_CALLBACK && eMode_ == AUDIO_MODE_RECORD,
478         ERR_INVALID_OPERATION, "SetCaptureMode is not supported.");
479     return SUCCESS;
480 }
481 
GetCaptureMode()482 AudioCaptureMode FastAudioStream::GetCaptureMode()
483 {
484     return captureMode_;
485 }
486 
SetCapturerReadCallback(const std::shared_ptr<AudioCapturerReadCallback> & callback)487 int32_t FastAudioStream::SetCapturerReadCallback(const std::shared_ptr<AudioCapturerReadCallback> &callback)
488 {
489     AUDIO_INFO_LOG("SetCapturerReadCallback enter.");
490     CHECK_AND_RETURN_RET_LOG(callback && processClient_ && eMode_ == AUDIO_MODE_RECORD,
491         ERR_INVALID_PARAM, "callback or client is nullptr or mode is not record.");
492     micProcClientCb_ = std::make_shared<FastAudioStreamCaptureCallback>(callback);
493     int32_t ret = processClient_->SaveDataCallback(micProcClientCb_);
494     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Client save data callback fail, ret %{public}d.", ret);
495     return SUCCESS;
496 }
497 
GetBufferDesc(BufferDesc & bufDesc)498 int32_t FastAudioStream::GetBufferDesc(BufferDesc &bufDesc)
499 {
500     AUDIO_DEBUG_LOG("enter.");
501     CHECK_AND_RETURN_RET_LOG(processClient_, ERR_INVALID_OPERATION, "spkClient is null.");
502     int32_t ret = processClient_->GetBufferDesc(bufDesc);
503     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS && bufDesc.buffer != nullptr && bufDesc.bufLength != 0,
504         -1, "GetBufferDesc failed.");
505     return SUCCESS;
506 }
507 
GetBufQueueState(BufferQueueState & bufState)508 int32_t FastAudioStream::GetBufQueueState(BufferQueueState &bufState)
509 {
510     AUDIO_INFO_LOG("enter.");
511     // note: add support
512     return SUCCESS;
513 }
514 
Enqueue(const BufferDesc & bufDesc)515 int32_t FastAudioStream::Enqueue(const BufferDesc &bufDesc)
516 {
517     AUDIO_DEBUG_LOG("Enqueue enter.");
518     CHECK_AND_RETURN_RET_LOG(processClient_, ERR_INVALID_OPERATION,
519         "spkClient is null.");
520     int32_t ret = processClient_->Enqueue(bufDesc);
521     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, -1, "Enqueue failed.");
522     return SUCCESS;
523 }
524 
SetPreferredFrameSize(int32_t frameSize)525 void FastAudioStream::SetPreferredFrameSize(int32_t frameSize)
526 {
527     std::lock_guard<std::mutex> lockSetPreferredFrameSize(setPreferredFrameSizeMutex_);
528     userSettedPreferredFrameSize_ = frameSize;
529     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "process client is null.");
530     processClient_->SetPreferredFrameSize(frameSize);
531 }
532 
UpdateLatencyTimestamp(std::string & timestamp,bool isRenderer)533 void FastAudioStream::UpdateLatencyTimestamp(std::string &timestamp, bool isRenderer)
534 {
535     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "process client is null.");
536     processClient_->UpdateLatencyTimestamp(timestamp, isRenderer);
537 }
538 
Clear()539 int32_t FastAudioStream::Clear()
540 {
541     AUDIO_INFO_LOG("Clear will do nothing.");
542 
543     return SUCCESS;
544 }
545 
SetLowPowerVolume(float volume)546 int32_t FastAudioStream::SetLowPowerVolume(float volume)
547 {
548     AUDIO_INFO_LOG("enter.");
549     return SUCCESS;
550 }
551 
GetLowPowerVolume()552 float FastAudioStream::GetLowPowerVolume()
553 {
554     AUDIO_INFO_LOG("enter.");
555     return 1.0f;
556 }
557 
SetOffloadMode(int32_t state,bool isAppBack)558 int32_t FastAudioStream::SetOffloadMode(int32_t state, bool isAppBack)
559 {
560     AUDIO_WARNING_LOG("enter.");
561     return ERR_NOT_SUPPORTED;
562 }
563 
UnsetOffloadMode()564 int32_t FastAudioStream::UnsetOffloadMode()
565 {
566     AUDIO_WARNING_LOG("enter.");
567     return ERR_NOT_SUPPORTED;
568 }
569 
GetSingleStreamVolume()570 float FastAudioStream::GetSingleStreamVolume()
571 {
572     AUDIO_INFO_LOG("enter.");
573     return 1.0f;
574 }
575 
GetAudioEffectMode()576 AudioEffectMode FastAudioStream::GetAudioEffectMode()
577 {
578     AUDIO_ERR_LOG("GetAudioEffectMode not supported");
579     return EFFECT_NONE;
580 }
581 
SetAudioEffectMode(AudioEffectMode effectMode)582 int32_t FastAudioStream::SetAudioEffectMode(AudioEffectMode effectMode)
583 {
584     AUDIO_ERR_LOG("SetAudioEffectMode not supported");
585     return ERR_NOT_SUPPORTED;
586 }
587 
GetFramesWritten()588 int64_t FastAudioStream::GetFramesWritten()
589 {
590     int64_t result = -1; // -1 invalid frame
591     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, result, "GetFramesWritten failed: null process");
592     result = processClient_->GetFramesWritten();
593     return result;
594 }
595 
GetFramesRead()596 int64_t FastAudioStream::GetFramesRead()
597 {
598     int64_t result = -1; // -1 invalid frame
599     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, result, "GetFramesRead failed: null process");
600     result = processClient_->GetFramesRead();
601     return result;
602 }
603 
SetSpeed(float speed)604 int32_t FastAudioStream::SetSpeed(float speed)
605 {
606     AUDIO_ERR_LOG("SetSpeed is not supported");
607     return ERR_OPERATION_FAILED;
608 }
609 
SetPitch(float pitch)610 int32_t FastAudioStream::SetPitch(float pitch)
611 {
612     AUDIO_ERR_LOG("SetPitch is not supported");
613     return ERR_OPERATION_FAILED;
614 }
615 
GetSpeed()616 float FastAudioStream::GetSpeed()
617 {
618     AUDIO_ERR_LOG("GetSpeed is not supported");
619     return static_cast<float>(ERROR);
620 }
621 
622 // only call from StartAudioStream
RegisterThreadPriorityOnStart(StateChangeCmdType cmdType)623 void FastAudioStream::RegisterThreadPriorityOnStart(StateChangeCmdType cmdType)
624 {
625     pid_t tid;
626     switch (rendererInfo_.playerType) {
627         case PLAYER_TYPE_ARKTS_AUDIO_RENDERER:
628             // main thread
629             tid = getpid();
630             break;
631         case PLAYER_TYPE_OH_AUDIO_RENDERER:
632             tid = gettid();
633             break;
634         default:
635             return;
636     }
637 
638     if (cmdType == CMD_FROM_CLIENT) {
639         std::lock_guard lock(lastCallStartByUserTidMutex_);
640         lastCallStartByUserTid_ = tid;
641     } else if (cmdType == CMD_FROM_SYSTEM) {
642         std::lock_guard lock(lastCallStartByUserTidMutex_);
643         CHECK_AND_RETURN_LOG(lastCallStartByUserTid_.has_value(), "has not value");
644         tid = lastCallStartByUserTid_.value();
645     } else {
646         AUDIO_ERR_LOG("illegal param");
647         return;
648     }
649 
650     processClient_->RegisterThreadPriority(tid,
651         AudioSystemManager::GetInstance()->GetSelfBundleName(processconfig_.appInfo.appUid), METHOD_START);
652 }
653 
StartAudioStream(StateChangeCmdType cmdType,AudioStreamDeviceChangeReasonExt reason)654 bool FastAudioStream::StartAudioStream(StateChangeCmdType cmdType,
655     AudioStreamDeviceChangeReasonExt reason)
656 {
657     AUDIO_PRERELEASE_LOGI("StartAudioStream enter.");
658     CHECK_AND_RETURN_RET_LOG((state_ == PREPARED) || (state_ == STOPPED) || (state_ == PAUSED),
659         false, "Illegal state:%{public}u", state_);
660 
661     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "Start failed, process is null.");
662     if (spkProcClientCb_ != nullptr) {
663         AUDIO_DEBUG_LOG("StartAudioStream: reset the first frame state before starting");
664         spkProcClientCb_->ResetFirstFrameState();
665     }
666     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
667         audioStreamTracker_->FetchOutputDeviceForTrack(sessionId_, RUNNING, clientPid_, rendererInfo_, reason);
668         audioStreamTracker_->FetchInputDeviceForTrack(sessionId_, RUNNING, clientPid_, capturerInfo_);
669     }
670     int32_t ret = ERROR;
671     if (state_ == PAUSED || state_ == STOPPED) {
672         ret = processClient_->Resume();
673     } else {
674         ret = processClient_->Start();
675     }
676     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, false, "Client test stop fail, ret %{public}d.", ret);
677     state_ = RUNNING;
678 
679     AUDIO_DEBUG_LOG("StartAudioStream SUCCESS, sessionId: %{public}d", sessionId_);
680 
681     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
682         AUDIO_DEBUG_LOG("AudioStream:Calling Update tracker for Running");
683         audioStreamTracker_->UpdateTracker(sessionId_, state_, clientPid_, rendererInfo_, capturerInfo_);
684     }
685 
686     RegisterThreadPriorityOnStart(cmdType);
687 
688     SafeSendCallbackEvent(STATE_CHANGE_EVENT, state_);
689     return true;
690 }
691 
PauseAudioStream(StateChangeCmdType cmdType)692 bool FastAudioStream::PauseAudioStream(StateChangeCmdType cmdType)
693 {
694     AUDIO_PRERELEASE_LOGI("PauseAudioStream enter.");
695     CHECK_AND_RETURN_RET_LOG(state_ == RUNNING, false,
696         "state is not RUNNING. Illegal state:%{public}u", state_);
697     State oldState = state_;
698 
699     state_ = PAUSED;
700     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "Pause failed, process is null.");
701     int32_t ret = processClient_->Pause();
702     if (ret != SUCCESS) {
703         AUDIO_ERR_LOG("StreamPause fail,ret:%{public}d", ret);
704         state_ = oldState;
705         return false;
706     }
707 
708     AUDIO_DEBUG_LOG("PauseAudioStream SUCCESS, sessionId: %{public}d", sessionId_);
709     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
710         AUDIO_DEBUG_LOG("AudioStream:Calling Update tracker for Pause");
711         audioStreamTracker_->UpdateTracker(sessionId_, state_, clientPid_, rendererInfo_, capturerInfo_);
712     }
713 
714     SafeSendCallbackEvent(STATE_CHANGE_EVENT, state_);
715     return true;
716 }
717 
StopAudioStream()718 bool FastAudioStream::StopAudioStream()
719 {
720     CHECK_AND_RETURN_RET_LOG((state_ == RUNNING) || (state_ == PAUSED), false,
721         "State is not RUNNING. Illegal state:%{public}u", state_);
722     State oldState = state_;
723     state_ = STOPPED; // Set it before stopping as Read/Write and Stop can be called from different threads
724 
725     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "Stop failed, process is null.");
726     int32_t ret = processClient_->Stop();
727     if (ret != SUCCESS) {
728         AUDIO_ERR_LOG("StreamStop fail,ret:%{public}d", ret);
729         state_ = oldState;
730         return false;
731     }
732 
733     AUDIO_INFO_LOG("StopAudioStream SUCCESS, sessionId: %{public}d", sessionId_);
734     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
735         AUDIO_DEBUG_LOG("AudioStream:Calling Update tracker for stop");
736         audioStreamTracker_->UpdateTracker(sessionId_, state_, clientPid_, rendererInfo_, capturerInfo_);
737     }
738 
739     SafeSendCallbackEvent(STATE_CHANGE_EVENT, state_);
740     return true;
741 }
742 
FlushAudioStream()743 bool FastAudioStream::FlushAudioStream()
744 {
745     AUDIO_PRERELEASE_LOGI("FlushAudioStream enter.");
746     return true;
747 }
748 
DrainAudioStream(bool stopFlag)749 bool FastAudioStream::DrainAudioStream(bool stopFlag)
750 {
751     AUDIO_INFO_LOG("Drain stream SUCCESS");
752     return true;
753 }
754 
ReleaseAudioStream(bool releaseRunner,bool isSwitchStream)755 bool FastAudioStream::ReleaseAudioStream(bool releaseRunner, bool isSwitchStream)
756 {
757     CHECK_AND_RETURN_RET_LOG(state_ != RELEASED && state_ != NEW,
758         false, "Illegal state: state = %{public}u", state_);
759     // If state_ is RUNNING try to Stop it first and Release
760     if (state_ == RUNNING) {
761         StopAudioStream();
762     }
763 
764     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "Release failed, process is null.");
765     processClient_->Release(isSwitchStream);
766     state_ = RELEASED;
767     AUDIO_INFO_LOG("ReleaseAudiostream SUCCESS, sessionId: %{public}d", sessionId_);
768     if (audioStreamTracker_ != nullptr && audioStreamTracker_.get()) {
769         AUDIO_DEBUG_LOG("AudioStream:Calling Update tracker for release");
770         audioStreamTracker_->UpdateTracker(sessionId_, state_, clientPid_, rendererInfo_, capturerInfo_);
771     }
772 
773     std::unique_lock<std::mutex> lock(streamCbMutex_);
774     std::shared_ptr<AudioStreamCallback> streamCb = streamCallback_.lock();
775     if (streamCb != nullptr) {
776         AUDIO_INFO_LOG("Notify client the state is released");
777         streamCb->OnStateChange(RELEASED, CMD_FROM_CLIENT);
778     }
779     lock.unlock();
780     return true;
781 }
782 
Read(uint8_t & buffer,size_t userSize,bool isBlockingRead)783 int32_t FastAudioStream::Read(uint8_t &buffer, size_t userSize, bool isBlockingRead)
784 {
785     AUDIO_ERR_LOG("Unsupported operation: read");
786     return ERR_INVALID_OPERATION;
787 }
788 
Write(uint8_t * buffer,size_t buffer_size)789 int32_t FastAudioStream::Write(uint8_t *buffer, size_t buffer_size)
790 {
791     AUDIO_ERR_LOG("Unsupported operation: Write");
792     return ERR_INVALID_OPERATION;
793 }
794 
Write(uint8_t * pcmBuffer,size_t pcmBufferSize,uint8_t * metaBuffer,size_t metaBufferSize)795 int32_t FastAudioStream::Write(uint8_t *pcmBuffer, size_t pcmBufferSize, uint8_t *metaBuffer, size_t metaBufferSize)
796 {
797     AUDIO_ERR_LOG("Unsupported operation: Write");
798     return ERR_INVALID_OPERATION;
799 }
800 
GetUnderflowCount()801 uint32_t FastAudioStream::GetUnderflowCount()
802 {
803     AUDIO_INFO_LOG("GetUnderflowCount enter.");
804     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, 0, "process client is null.");
805     underflowCount_ = processClient_->GetUnderflowCount();
806     return underflowCount_;
807 }
808 
GetOverflowCount()809 uint32_t FastAudioStream::GetOverflowCount()
810 {
811     AUDIO_INFO_LOG("enter.");
812     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, 0, "process client is null.");
813     overflowCount_ = processClient_->GetOverflowCount();
814     return overflowCount_;
815 }
816 
SetUnderflowCount(uint32_t underflowCount)817 void FastAudioStream::SetUnderflowCount(uint32_t underflowCount)
818 {
819     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "process client is null.");
820     processClient_->SetUnderflowCount(underflowCount);
821 }
822 
SetOverflowCount(uint32_t overflowCount)823 void FastAudioStream::SetOverflowCount(uint32_t overflowCount)
824 {
825     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "process client is null.");
826     processClient_->SetOverflowCount(overflowCount);
827 }
828 
SetRendererPositionCallback(int64_t markPosition,const std::shared_ptr<RendererPositionCallback> & callback)829 void FastAudioStream::SetRendererPositionCallback(int64_t markPosition,
830     const std::shared_ptr<RendererPositionCallback> &callback)
831 {
832     AUDIO_INFO_LOG("Registering render frame position callback mark position");
833     // note: need support
834 }
835 
UnsetRendererPositionCallback()836 void FastAudioStream::UnsetRendererPositionCallback()
837 {
838     AUDIO_INFO_LOG("Unregistering render frame position callback");
839     // note: need support
840 }
841 
SetRendererPeriodPositionCallback(int64_t periodPosition,const std::shared_ptr<RendererPeriodPositionCallback> & callback)842 void FastAudioStream::SetRendererPeriodPositionCallback(int64_t periodPosition,
843     const std::shared_ptr<RendererPeriodPositionCallback> &callback)
844 {
845     AUDIO_INFO_LOG("Registering render period position callback");
846 }
847 
UnsetRendererPeriodPositionCallback()848 void FastAudioStream::UnsetRendererPeriodPositionCallback()
849 {
850     AUDIO_INFO_LOG("Unregistering render period position callback");
851 }
852 
SetCapturerPositionCallback(int64_t markPosition,const std::shared_ptr<CapturerPositionCallback> & callback)853 void FastAudioStream::SetCapturerPositionCallback(int64_t markPosition,
854     const std::shared_ptr<CapturerPositionCallback> &callback)
855 {
856     AUDIO_INFO_LOG("Registering capture frame position callback, mark position");
857 }
858 
UnsetCapturerPositionCallback()859 void FastAudioStream::UnsetCapturerPositionCallback()
860 {
861     AUDIO_INFO_LOG("Unregistering capture frame position callback");
862 }
863 
SetCapturerPeriodPositionCallback(int64_t periodPosition,const std::shared_ptr<CapturerPeriodPositionCallback> & callback)864 void FastAudioStream::SetCapturerPeriodPositionCallback(int64_t periodPosition,
865     const std::shared_ptr<CapturerPeriodPositionCallback> &callback)
866 {
867     AUDIO_INFO_LOG("Registering period position callback");
868 }
869 
UnsetCapturerPeriodPositionCallback()870 void FastAudioStream::UnsetCapturerPeriodPositionCallback()
871 {
872     AUDIO_INFO_LOG("Unregistering period position callback");
873 }
874 
SetRendererSamplingRate(uint32_t sampleRate)875 int32_t FastAudioStream::SetRendererSamplingRate(uint32_t sampleRate)
876 {
877     AUDIO_ERR_LOG("SetRendererSamplingRate  is not supported");
878 
879     return ERR_OPERATION_FAILED;
880 }
881 
GetRendererSamplingRate()882 uint32_t FastAudioStream::GetRendererSamplingRate()
883 {
884     AUDIO_INFO_LOG("GetRendererSamplingRate enter.");
885     return streamInfo_.samplingRate;
886 }
887 
SetBufferSizeInMsec(int32_t bufferSizeInMsec)888 int32_t FastAudioStream::SetBufferSizeInMsec(int32_t bufferSizeInMsec)
889 {
890     AUDIO_ERR_LOG("SetBufferSizeInMsec is not supported");
891     // note: add support
892     return ERR_NOT_SUPPORTED;
893 }
894 
SetInnerCapturerState(bool isInnerCapturer)895 void FastAudioStream::SetInnerCapturerState(bool isInnerCapturer)
896 {
897     AUDIO_ERR_LOG("SetInnerCapturerState is not supported");
898 }
899 
SetWakeupCapturerState(bool isWakeupCapturer)900 void FastAudioStream::SetWakeupCapturerState(bool isWakeupCapturer)
901 {
902     AUDIO_ERR_LOG("SetWakeupCapturerState is not supported");
903 }
904 
SetCapturerSource(int capturerSource)905 void FastAudioStream::SetCapturerSource(int capturerSource)
906 {
907     AUDIO_ERR_LOG("SetCapturerSource is not supported");
908 }
909 
SetPrivacyType(AudioPrivacyType privacyType)910 void FastAudioStream::SetPrivacyType(AudioPrivacyType privacyType)
911 {
912     AUDIO_ERR_LOG("SetPrivacyType is not supported");
913 }
914 
GetStreamClass()915 IAudioStream::StreamClass FastAudioStream::GetStreamClass()
916 {
917     return IAudioStream::StreamClass::FAST_STREAM;
918 }
919 
SetStreamTrackerState(bool trackerRegisteredState)920 void FastAudioStream::SetStreamTrackerState(bool trackerRegisteredState)
921 {
922     streamTrackerRegistered_ = trackerRegisteredState;
923 }
924 
GetSwitchInfo(IAudioStream::SwitchInfo & info)925 void FastAudioStream::GetSwitchInfo(IAudioStream::SwitchInfo& info)
926 {
927     GetAudioStreamInfo(info.params);
928     info.rendererInfo = rendererInfo_;
929     info.capturerInfo = capturerInfo_;
930     info.eStreamType = eStreamType_;
931     info.state = state_;
932     info.sessionId = sessionId_;
933 
934     info.clientPid = clientPid_;
935     info.clientUid = clientUid_;
936 
937     info.volume = GetVolume();
938     info.duckVolume = GetDuckVolume();
939     info.effectMode = GetAudioEffectMode();
940     info.renderMode = renderMode_;
941     info.captureMode = captureMode_;
942     info.renderRate = renderRate_;
943 
944     info.underFlowCount = GetUnderflowCount();
945     info.overFlowCount = GetOverflowCount();
946 
947     info.silentModeAndMixWithOthers = silentModeAndMixWithOthers_;
948     info.defaultOutputDevice = defaultOutputDevice_;
949 
950     {
951         std::lock_guard<std::mutex> lock(setPreferredFrameSizeMutex_);
952         info.userSettedPreferredFrameSize = userSettedPreferredFrameSize_;
953     }
954 
955     {
956         std::lock_guard<std::mutex> lock(lastCallStartByUserTidMutex_);
957         info.lastCallStartByUserTid = lastCallStartByUserTid_;
958     }
959 
960     if (spkProcClientCb_) {
961         info.rendererWriteCallback = spkProcClientCb_->GetRendererWriteCallback();
962     }
963     if (micProcClientCb_) {
964         info.capturerReadCallback = micProcClientCb_->GetCapturerReadCallback();
965     }
966     if (firstFrameWritingCb_) {
967         info.rendererFirstFrameWritingCallback = firstFrameWritingCb_;
968     }
969 }
970 
OnFirstFrameWriting()971 void FastAudioStream::OnFirstFrameWriting()
972 {
973     CHECK_AND_RETURN(firstFrameWritingCb_!= nullptr);
974     uint64_t latency = 0;
975     this->GetLatency(latency);
976     firstFrameWritingCb_->OnFirstFrameWriting(latency);
977 }
978 
ResetFirstFrameState()979 void FastAudioStream::ResetFirstFrameState()
980 {
981     if (spkProcClientCb_ != nullptr) {
982         AUDIO_DEBUG_LOG("FastAudioStream::ResetFirstFrameState: reset the first frame state");
983         spkProcClientCb_->ResetFirstFrameState();
984     }
985 }
986 
SetAudioHapticsSyncId(const int32_t & audioHapticsSyncId)987 void FastAudioStream::SetAudioHapticsSyncId(const int32_t &audioHapticsSyncId)
988 {
989     CHECK_AND_RETURN_LOG(processClient_ != nullptr, "Start failed, process is null.");
990     processClient_->SetAudioHapticsSyncId(audioHapticsSyncId);
991 }
992 
OnHandleData(size_t length)993 void FastAudioStreamRenderCallback::OnHandleData(size_t length)
994 {
995     CHECK_AND_RETURN_LOG(rendererWriteCallback_!= nullptr, "OnHandleData failed: rendererWriteCallback_ is null.");
996     if (!hasFirstFrameWrited_.load()) {
997         AUDIO_DEBUG_LOG("OnHandleData: send the first frame writing event to audio haptic player");
998         audioStreamImpl_.OnFirstFrameWriting();
999         hasFirstFrameWrited_.store(true);
1000     }
1001     rendererWriteCallback_->OnWriteData(length);
1002 }
1003 
ResetFirstFrameState()1004 void FastAudioStreamRenderCallback::ResetFirstFrameState()
1005 {
1006     AUDIO_DEBUG_LOG("ResetFirstFrameState: set the hasFirstFrameWrited_ to false");
1007     hasFirstFrameWrited_.store(false);
1008 }
1009 
GetRendererWriteCallback() const1010 std::shared_ptr<AudioRendererWriteCallback> FastAudioStreamRenderCallback::GetRendererWriteCallback() const
1011 {
1012     return rendererWriteCallback_;
1013 }
1014 
GetCapturerReadCallback() const1015 std::shared_ptr<AudioCapturerReadCallback> FastAudioStreamCaptureCallback::GetCapturerReadCallback() const
1016 {
1017     return captureCallback_;
1018 }
1019 
OnHandleData(size_t length)1020 void FastAudioStreamCaptureCallback::OnHandleData(size_t length)
1021 {
1022     CHECK_AND_RETURN_LOG(captureCallback_!= nullptr, "OnHandleData failed: captureCallback_ is null.");
1023     captureCallback_->OnReadData(length);
1024 }
1025 
SetChannelBlendMode(ChannelBlendMode blendMode)1026 int32_t FastAudioStream::SetChannelBlendMode(ChannelBlendMode blendMode)
1027 {
1028     AUDIO_ERR_LOG("SetChannelBlendMode is not supported");
1029     return SUCCESS;
1030 }
1031 
SetVolumeWithRamp(float volume,int32_t duration)1032 int32_t FastAudioStream::SetVolumeWithRamp(float volume, int32_t duration)
1033 {
1034     AUDIO_ERR_LOG("SetVolumeWithRamp is not supported");
1035     return SUCCESS;
1036 }
1037 
UpdateRegisterTrackerInfo(AudioRegisterTrackerInfo & registerTrackerInfo)1038 void FastAudioStream::UpdateRegisterTrackerInfo(AudioRegisterTrackerInfo &registerTrackerInfo)
1039 {
1040     rendererInfo_.samplingRate = static_cast<AudioSamplingRate>(streamInfo_.samplingRate);
1041     capturerInfo_.samplingRate = static_cast<AudioSamplingRate>(streamInfo_.samplingRate);
1042 
1043     registerTrackerInfo.sessionId = sessionId_;
1044     registerTrackerInfo.clientPid = clientPid_;
1045     registerTrackerInfo.state = state_;
1046     registerTrackerInfo.rendererInfo = rendererInfo_;
1047     registerTrackerInfo.capturerInfo = capturerInfo_;
1048 }
1049 
RestoreAudioStream(bool needStoreState)1050 bool FastAudioStream::RestoreAudioStream(bool needStoreState)
1051 {
1052     CHECK_AND_RETURN_RET_LOG(proxyObj_ != nullptr, false, "proxyObj_ is null");
1053     CHECK_AND_RETURN_RET_LOG(state_ != NEW && state_ != INVALID && state_ != RELEASED, true,
1054         "state_ is %{public}d, no need for restore", state_);
1055     bool result = false;
1056     State oldState = state_;
1057     state_ = NEW;
1058     SetStreamTrackerState(false);
1059     if (processClient_ != nullptr) {
1060         processClient_->Stop();
1061         processClient_->Release();
1062         processClient_ = nullptr;
1063     }
1064     if (SetAudioStreamInfo(streamInfo_, proxyObj_) != SUCCESS || SetCallbacksWhenRestore() != SUCCESS) {
1065         goto error;
1066     }
1067 
1068     SetDefaultOutputDevice(defaultOutputDevice_);
1069 
1070     switch (oldState) {
1071         case RUNNING:
1072             result = StartAudioStream();
1073             break;
1074         case PAUSED:
1075             result = StartAudioStream() && PauseAudioStream();
1076             break;
1077         case STOPPED:
1078             [[fallthrough]];
1079         case STOPPING:
1080             result = StartAudioStream() && StopAudioStream();
1081             break;
1082         default:
1083             break;
1084     }
1085     if (!result) {
1086         goto error;
1087     }
1088     return result;
1089 error:
1090     AUDIO_ERR_LOG("RestoreAudioStream failed");
1091     state_ = oldState;
1092     return false;
1093 }
1094 
JoinCallbackLoop()1095 void FastAudioStream::JoinCallbackLoop()
1096 {
1097     if (processClient_ != nullptr) {
1098         processClient_->JoinCallbackLoop();
1099     } else {
1100         AUDIO_WARNING_LOG("processClient_ is nullptr!");
1101     }
1102 }
1103 
GetOffloadEnable()1104 bool FastAudioStream::GetOffloadEnable()
1105 {
1106     AUDIO_WARNING_LOG("not supported in fast audio stream");
1107     return false;
1108 }
1109 
GetSpatializationEnabled()1110 bool FastAudioStream::GetSpatializationEnabled()
1111 {
1112     AUDIO_WARNING_LOG("not supported in fast audio stream");
1113     return false;
1114 }
1115 
GetHighResolutionEnabled()1116 bool FastAudioStream::GetHighResolutionEnabled()
1117 {
1118     AUDIO_WARNING_LOG("not supported in fast audio stream");
1119     return false;
1120 }
1121 
SetDefaultOutputDevice(const DeviceType defaultOutputDevice,bool skipForce)1122 int32_t FastAudioStream::SetDefaultOutputDevice(const DeviceType defaultOutputDevice, bool skipForce)
1123 {
1124     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERR_OPERATION_FAILED, "set failed: null process");
1125     int32_t ret = processClient_->SetDefaultOutputDevice(defaultOutputDevice, skipForce);
1126     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetDefaultOutputDevice error.");
1127     defaultOutputDevice_ = defaultOutputDevice;
1128     return SUCCESS;
1129 }
1130 
GetFastStatus()1131 FastStatus FastAudioStream::GetFastStatus()
1132 {
1133     return FASTSTATUS_FAST;
1134 }
1135 
GetDefaultOutputDevice()1136 DeviceType FastAudioStream::GetDefaultOutputDevice()
1137 {
1138     return defaultOutputDevice_;
1139 }
1140 
1141 // diffrence from GetAudioPosition only when set speed
GetAudioTimestampInfo(Timestamp & timestamp,Timestamp::Timestampbase base)1142 int32_t FastAudioStream::GetAudioTimestampInfo(Timestamp &timestamp, Timestamp::Timestampbase base)
1143 {
1144     return GetAudioTime(timestamp, base) ? SUCCESS : ERR_OPERATION_FAILED;
1145 }
1146 
SetSwitchingStatus(bool isSwitching)1147 void FastAudioStream::SetSwitchingStatus(bool isSwitching)
1148 {
1149     std::lock_guard lock(switchingMutex_);
1150     if (isSwitching) {
1151         switchingInfo_ = {true, state_};
1152     } else {
1153         switchingInfo_ = {false, INVALID};
1154     }
1155 }
1156 
SetCallbacksWhenRestore()1157 int32_t FastAudioStream::SetCallbacksWhenRestore()
1158 {
1159     int32_t ret = SUCCESS;
1160     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, ERROR_INVALID_PARAM, "processClient_ is null");
1161     if (eMode_ == AUDIO_MODE_PLAYBACK) {
1162         ret = processClient_->SaveDataCallback(spkProcClientCb_);
1163     } else if (eMode_ == AUDIO_MODE_RECORD) {
1164         ret = processClient_->SaveDataCallback(micProcClientCb_);
1165     }
1166     return ret;
1167 }
1168 
GetRestoreInfo(RestoreInfo & restoreInfo)1169 void FastAudioStream::GetRestoreInfo(RestoreInfo &restoreInfo)
1170 {
1171     processClient_->GetRestoreInfo(restoreInfo);
1172     return;
1173 }
1174 
SetRestoreInfo(RestoreInfo & restoreInfo)1175 void FastAudioStream::SetRestoreInfo(RestoreInfo &restoreInfo)
1176 {
1177     processClient_->SetRestoreInfo(restoreInfo);
1178     return;
1179 }
1180 
CheckRestoreStatus()1181 RestoreStatus FastAudioStream::CheckRestoreStatus()
1182 {
1183     if (spkProcClientCb_ == nullptr && micProcClientCb_ == nullptr) {
1184         AUDIO_INFO_LOG("Fast stream without callback, restore to normal");
1185         renderMode_ = RENDER_MODE_NORMAL;
1186         captureMode_ = CAPTURE_MODE_NORMAL;
1187         return NEED_RESTORE_TO_NORMAL;
1188     }
1189     return processClient_->CheckRestoreStatus();
1190 }
1191 
SetRestoreStatus(RestoreStatus restoreStatus)1192 RestoreStatus FastAudioStream::SetRestoreStatus(RestoreStatus restoreStatus)
1193 {
1194     return processClient_->SetRestoreStatus(restoreStatus);
1195 }
1196 
FetchDeviceForSplitStream()1197 void FastAudioStream::FetchDeviceForSplitStream()
1198 {
1199     AUDIO_WARNING_LOG("Fast stream does not support split stream");
1200     if (processClient_) {
1201         processClient_->SetRestoreStatus(NO_NEED_FOR_RESTORE);
1202     }
1203 }
1204 
SetCallStartByUserTid(pid_t tid)1205 void FastAudioStream::SetCallStartByUserTid(pid_t tid)
1206 {
1207     std::lock_guard lock(lastCallStartByUserTidMutex_);
1208     lastCallStartByUserTid_ = tid;
1209 }
1210 
SetCallbackLoopTid(int32_t tid)1211 void FastAudioStream::SetCallbackLoopTid(int32_t tid)
1212 {
1213     AUDIO_INFO_LOG("Callback loop tid: %{public}d", tid);
1214     callbackLoopTid_ = tid;
1215     callbackLoopTidCv_.notify_all();
1216 }
1217 
GetCallbackLoopTid()1218 int32_t FastAudioStream::GetCallbackLoopTid()
1219 {
1220     std::unique_lock<std::mutex> waitLock(callbackLoopTidMutex_);
1221     bool stopWaiting = callbackLoopTidCv_.wait_for(waitLock, std::chrono::seconds(1), [this] {
1222         return callbackLoopTid_ != -1; // callbackLoopTid_ will change when got notified.
1223     });
1224 
1225     if (!stopWaiting) {
1226         AUDIO_WARNING_LOG("Wait timeout");
1227         callbackLoopTid_ = 0; // set tid to prevent get operation from getting stuck
1228     }
1229     return callbackLoopTid_;
1230 }
1231 
ResetCallbackLoopTid()1232 void FastAudioStream::ResetCallbackLoopTid()
1233 {
1234     AUDIO_INFO_LOG("to -1");
1235     callbackLoopTid_ = -1;
1236 }
1237 
GetStopFlag() const1238 bool FastAudioStream::GetStopFlag() const
1239 {
1240     CHECK_AND_RETURN_RET_LOG(processClient_ != nullptr, false, "processClient_ is null");
1241     return processClient_->GetStopFlag();
1242 }
1243 } // namespace AudioStandard
1244 } // namespace OHOS
1245