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