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 FAST_AUDIO_STREAM_H
16 #define FAST_AUDIO_STREAM_H
17
18 #ifndef LOG_TAG
19 #define LOG_TAG "CapturerInClientInner"
20 #endif
21
22 #include "capturer_in_client.h"
23
24 #include <atomic>
25 #include <cinttypes>
26 #include <condition_variable>
27 #include <sstream>
28 #include <string>
29 #include <mutex>
30 #include <thread>
31
32 #include "iservice_registry.h"
33 #include "system_ability_definition.h"
34 #include "securec.h"
35
36 #include "ipc_stream.h"
37 #include "audio_capturer_log.h"
38 #include "audio_errors.h"
39 #include "volume_tools.h"
40 #include "audio_manager_base.h"
41 #include "audio_ring_cache.h"
42 #include "audio_utils.h"
43 #include "audio_policy_manager.h"
44 #include "audio_server_death_recipient.h"
45 #include "audio_stream_tracker.h"
46 #include "audio_system_manager.h"
47 #include "audio_process_config.h"
48 #include "ipc_stream_listener_impl.h"
49 #include "ipc_stream_listener_stub.h"
50 #include "callback_handler.h"
51 #include "audio_safe_block_queue.h"
52
53 namespace OHOS {
54 namespace AudioStandard {
55 namespace {
56 static const size_t MAX_CLIENT_READ_SIZE = 20 * 1024 * 1024; // 20M
57 static const int32_t CREATE_TIMEOUT_IN_SECOND = 9; // 9S
58 static const int32_t OPERATION_TIMEOUT_IN_MS = 1000; // 1000ms
59 static const int32_t LOGLITMITTIMES = 20;
60 const uint64_t AUDIO_US_PER_MS = 1000;
61 const uint64_t AUDIO_US_PER_S = 1000000;
62 const uint64_t DEFAULT_BUF_DURATION_IN_USEC = 20000; // 20ms
63 const uint64_t MAX_BUF_DURATION_IN_USEC = 2000000; // 2S
64 const int64_t INVALID_FRAME_SIZE = -1;
65 static const int32_t SHORT_TIMEOUT_IN_MS = 20; // ms
66 static constexpr int CB_QUEUE_CAPACITY = 3;
67 constexpr int32_t RETRY_WAIT_TIME_MS = 500; // 500ms
68 constexpr int32_t MAX_RETRY_COUNT = 8;
69 }
70
71 class CapturerInClientInner : public CapturerInClient, public IStreamListener, public IHandler,
72 public std::enable_shared_from_this<CapturerInClientInner> {
73 public:
74 CapturerInClientInner(AudioStreamType eStreamType, int32_t appUid);
75 ~CapturerInClientInner();
76
77 // IStreamListener
78 int32_t OnOperationHandled(Operation operation, int64_t result) override;
79
80 void SetClientID(int32_t clientPid, int32_t clientUid, uint32_t appTokenId, uint64_t fullTokenId) override;
81
82 int32_t UpdatePlaybackCaptureConfig(const AudioPlaybackCaptureConfig &config) override;
83 void SetRendererInfo(const AudioRendererInfo &rendererInfo) override;
84 void SetCapturerInfo(const AudioCapturerInfo &capturerInfo) override;
85 int32_t GetAudioStreamInfo(AudioStreamParams &info) override;
86 int32_t SetAudioStreamInfo(const AudioStreamParams info,
87 const std::shared_ptr<AudioClientTracker> &proxyObj,
88 const AudioPlaybackCaptureConfig &config = AudioPlaybackCaptureConfig()) override;
89 State GetState() override;
90 int32_t GetAudioSessionID(uint32_t &sessionID) override;
91 void GetAudioPipeType(AudioPipeType &pipeType) override;
92 bool GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base) override;
93 bool GetAudioPosition(Timestamp ×tamp, Timestamp::Timestampbase base) override;
94 int32_t GetBufferSize(size_t &bufferSize) override;
95 int32_t GetFrameCount(uint32_t &frameCount) override;
96 int32_t GetLatency(uint64_t &latency) override;
97 int32_t SetAudioStreamType(AudioStreamType audioStreamType) override;
98 float GetVolume() override;
99 int32_t SetVolume(float volume) override;
100 int32_t SetDuckVolume(float volume) override;
101 int32_t SetMute(bool mute) override;
102 int32_t SetRenderRate(AudioRendererRate renderRate) override;
103 AudioRendererRate GetRenderRate() override;
104 int32_t SetStreamCallback(const std::shared_ptr<AudioStreamCallback> &callback) override;
105 int32_t SetSpeed(float speed) override;
106 float GetSpeed() override;
107 int32_t ChangeSpeed(uint8_t *buffer, int32_t bufferSize, std::unique_ptr<uint8_t[]> &outBuffer,
108 int32_t &outBufferSize) override;
109
110 // callback mode api
111 AudioRenderMode GetRenderMode() override;
112 int32_t SetRenderMode(AudioRenderMode renderMode) override;
113 int32_t SetRendererWriteCallback(const std::shared_ptr<AudioRendererWriteCallback> &callback) override;
114 int32_t SetCaptureMode(AudioCaptureMode captureMode) override;
115 void InitCallbackLoop();
116 AudioCaptureMode GetCaptureMode() override;
117 int32_t SetCapturerReadCallback(const std::shared_ptr<AudioCapturerReadCallback> &callback) override;
118 int32_t GetBufferDesc(BufferDesc &bufDesc) override;
119 int32_t Clear() override;
120 int32_t GetBufQueueState(BufferQueueState &bufState) override;
121 int32_t Enqueue(const BufferDesc &bufDesc) override;
122
123 int32_t SetLowPowerVolume(float volume) override;
124 float GetLowPowerVolume() override;
125 int32_t UnsetOffloadMode() override;
126 int32_t SetOffloadMode(int32_t state, bool isAppBack) override;
127 float GetSingleStreamVolume() override;
128 AudioEffectMode GetAudioEffectMode() override;
129 int32_t SetAudioEffectMode(AudioEffectMode effectMode) override;
130 int64_t GetFramesRead() override;
131 int64_t GetFramesWritten() override;
132
133 void SetInnerCapturerState(bool isInnerCapturer) override;
134 void SetWakeupCapturerState(bool isWakeupCapturer) override;
135 void SetPrivacyType(AudioPrivacyType privacyType) override;
136 void SetCapturerSource(int capturerSource) override;
137
138 // Common APIs
139 bool StartAudioStream(StateChangeCmdType cmdType = CMD_FROM_CLIENT,
140 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN) override;
141 bool PauseAudioStream(StateChangeCmdType cmdType = CMD_FROM_CLIENT) override;
142 bool StopAudioStream() override;
143 bool FlushAudioStream() override;
144 bool ReleaseAudioStream(bool releaseRunner = true, bool isSwitchStream = false) override;
145
146 // Playback related APIs
147 bool DrainAudioStream(bool stopFlag = false) override;
148 int32_t Write(uint8_t *buffer, size_t bufferSize) override;
149 int32_t Write(uint8_t *pcmBuffer, size_t pcmBufferSize, uint8_t *metaBuffer, size_t metaBufferSize) override;
150 void SetPreferredFrameSize(int32_t frameSize) override;
151 void UpdateLatencyTimestamp(std::string ×tamp, bool isRenderer) override;
152 int32_t SetRendererFirstFrameWritingCallback(
153 const std::shared_ptr<AudioRendererFirstFrameWritingCallback> &callback) override;
154 void OnFirstFrameWriting() override;
155
156 // Recording related APIs
157 int32_t Read(uint8_t &buffer, size_t userSize, bool isBlockingRead) override;
158
159 // Position and period callbacks
160 void SetCapturerPositionCallback(int64_t markPosition,
161 const std::shared_ptr<CapturerPositionCallback> &callback) override;
162 void UnsetCapturerPositionCallback() override;
163 void SetCapturerPeriodPositionCallback(int64_t periodPosition,
164 const std::shared_ptr<CapturerPeriodPositionCallback> &callback) override;
165 void UnsetCapturerPeriodPositionCallback() override;
166 void SetRendererPositionCallback(int64_t markPosition,
167 const std::shared_ptr<RendererPositionCallback> &callback) override;
168 void UnsetRendererPositionCallback() override;
169 void SetRendererPeriodPositionCallback(int64_t periodPosition,
170 const std::shared_ptr<RendererPeriodPositionCallback> &callback) override;
171 void UnsetRendererPeriodPositionCallback() override;
172
173 uint32_t GetUnderflowCount() override;
174 uint32_t GetOverflowCount() override;
175 void SetUnderflowCount(uint32_t underflowCount) override;
176 void SetOverflowCount(uint32_t overflowCount) override;
177
178 uint32_t GetRendererSamplingRate() override;
179 int32_t SetRendererSamplingRate(uint32_t sampleRate) override;
180 int32_t SetBufferSizeInMsec(int32_t bufferSizeInMsec) override;
181 int32_t SetChannelBlendMode(ChannelBlendMode blendMode) override;
182 int32_t SetVolumeWithRamp(float volume, int32_t duration) override;
183
184 void SetStreamTrackerState(bool trackerRegisteredState) override;
185 void GetSwitchInfo(IAudioStream::SwitchInfo& info) override;
186
187 IAudioStream::StreamClass GetStreamClass() override;
188
189 void SetSilentModeAndMixWithOthers(bool on) override;
190
191 bool GetSilentModeAndMixWithOthers() override;
192
193 static void AudioServerDied(pid_t pid, pid_t uid);
194
195 void OnHandle(uint32_t code, int64_t data) override;
196 void InitCallbackHandler();
197 void SafeSendCallbackEvent(uint32_t eventCode, int64_t data);
198
199 void SendCapturerMarkReachedEvent(int64_t capturerMarkPosition);
200 void SendCapturerPeriodReachedEvent(int64_t capturerPeriodSize);
201
202 void HandleCapturerPositionChanges(size_t bytesRead);
203 void HandleStateChangeEvent(int64_t data);
204 void HandleCapturerMarkReachedEvent(int64_t capturerMarkPosition);
205 void HandleCapturerPeriodReachedEvent(int64_t capturerPeriodNumber);
206
207 static const sptr<IStandardAudioService> GetAudioServerProxy();
208
209 bool RestoreAudioStream(bool needStoreState = true) override;
210
211 bool GetOffloadEnable() override;
212 bool GetSpatializationEnabled() override;
213 bool GetHighResolutionEnabled() override;
214 int32_t SetDefaultOutputDevice(const DeviceType defaultOutputDevice) override;
215 DeviceType GetDefaultOutputDevice() override;
216 int32_t GetAudioTimestampInfo(Timestamp ×tamp, Timestamp::Timestampbase base) override;
217 void SetSwitchingStatus(bool isSwitching) override;
218 void GetRestoreInfo(RestoreInfo &restoreInfo) override;
219 void SetRestoreInfo(RestoreInfo &restoreInfo) override;
220 RestoreStatus CheckRestoreStatus() override;
221 RestoreStatus SetRestoreStatus(RestoreStatus restoreStatus) override;
222 void FetchDeviceForSplitStream() override;
223
224 private:
225 void RegisterTracker(const std::shared_ptr<AudioClientTracker> &proxyObj);
226 void UpdateTracker(const std::string &updateCase);
227
228 int32_t DeinitIpcStream();
229
230 int32_t InitIpcStream(const AudioPlaybackCaptureConfig &filterConfig);
231
232 const AudioProcessConfig ConstructConfig();
233
234 int32_t InitCacheBuffer(size_t targetSize);
235 int32_t InitSharedBuffer();
236 int32_t FlushRingCache();
237
238 void GetStreamSwitchInfo(IAudioStream::SwitchInfo& info);
239
240 int32_t StateCmdTypeToParams(int64_t ¶ms, State state, StateChangeCmdType cmdType);
241 int32_t ParamsToStateCmdType(int64_t params, State &state, StateChangeCmdType &cmdType);
242
243 void InitCallbackBuffer(uint64_t bufferDurationInUs);
244 bool ReadCallbackFunc();
245 // for callback mode. Check status if not running, wait for start or release.
246 bool WaitForRunning();
247
248 int32_t HandleCapturerRead(size_t &readSize, size_t &userSize, uint8_t &buffer, bool isBlockingRead);
249 int32_t RegisterCapturerInClientPolicyServerDiedCb();
250 int32_t UnregisterCapturerInClientPolicyServerDiedCb();
251 private:
252 AudioStreamType eStreamType_;
253 int32_t appUid_;
254 uint32_t sessionId_ = 0;
255 int32_t clientUid_ = -1;
256 int32_t clientPid_ = -1;
257 uint32_t appTokenId_ = 0;
258 uint64_t fullTokenId_ = 0;
259
260 std::atomic<uint32_t> readLogTimes_ = 0;
261
262 std::unique_ptr<AudioStreamTracker> audioStreamTracker_ = nullptr;
263 bool streamTrackerRegistered_ = false;
264
265 AudioRendererInfo rendererInfo_ = {}; // not in use
266 AudioCapturerInfo capturerInfo_ = {};
267
268 int32_t bufferSizeInMsec_ = 20; // 20ms
269
270 // callback mode
271 AudioCaptureMode capturerMode_ = CAPTURE_MODE_NORMAL;
272 std::thread callbackLoop_; // thread for callback to client and write.
273 std::atomic<bool> cbThreadReleased_ = true;
274 std::mutex readCbMutex_; // lock for change or use callback
275 std::condition_variable cbThreadCv_;
276 std::shared_ptr<AudioCapturerReadCallback> readCb_ = nullptr;
277 std::mutex cbBufferMutex_;
278 std::unique_ptr<uint8_t[]> cbBuffer_ {nullptr};
279 size_t cbBufferSize_ = 0;
280 AudioSafeBlockQueue<BufferDesc> cbBufferQueue_; // only one cbBuffer_
281
282 AudioPlaybackCaptureConfig filterConfig_ = {{{}, FilterMode::INCLUDE, {}, FilterMode::INCLUDE}, false};
283 bool isInnerCapturer_ = false;
284 bool isWakeupCapturer_ = false;
285
286 bool needSetThreadPriority_ = true;
287
288 AudioStreamParams streamParams_; // in plan: replace it with AudioCapturerParams
289
290 // callbacks
291 std::mutex streamCbMutex_;
292 std::weak_ptr<AudioStreamCallback> streamCallback_;
293
294 size_t cacheSizeInByte_ = 0;
295 uint32_t spanSizeInFrame_ = 0;
296 size_t clientSpanSizeInByte_ = 0;
297 size_t sizePerFrameInByte_ = 4; // 16bit 2ch as default
298
299 // using this lock when change status_
300 std::mutex statusMutex_;
301 std::atomic<State> state_ = INVALID;
302 // for status operation wait and notify
303 std::mutex callServerMutex_;
304 std::condition_variable callServerCV_;
305
306 Operation notifiedOperation_ = MAX_OPERATION_CODE;
307 int64_t notifiedResult_ = 0;
308
309 // read data
310 std::mutex readDataMutex_;
311 std::condition_variable readDataCV_;
312
313 uint32_t overflowCount_ = 0;
314 // ipc stream related
315 AudioProcessConfig clientConfig_;
316 sptr<IpcStreamListenerImpl> listener_ = nullptr;
317 sptr<IpcStream> ipcStream_ = nullptr;
318 std::shared_ptr<OHAudioBuffer> clientBuffer_ = nullptr;
319
320 // buffer handle
321 std::unique_ptr<AudioRingCache> ringCache_ = nullptr;
322 std::mutex readMutex_; // used for prevent multi thread call read
323
324 // Mark reach and period reach callback
325 uint64_t totalBytesRead_ = 0;
326 std::mutex markReachMutex_;
327 bool capturerMarkReached_ = false;
328 int64_t capturerMarkPosition_ = 0;
329 std::shared_ptr<CapturerPositionCallback> capturerPositionCallback_ = nullptr;
330
331 std::mutex periodReachMutex_;
332 int64_t capturerPeriodSize_ = 0;
333 int64_t capturerPeriodRead_ = 0;
334 std::shared_ptr<CapturerPeriodPositionCallback> capturerPeriodPositionCallback_ = nullptr;
335
336 mutable int64_t volumeDataCount_ = 0;
337 std::string logUtilsTag_ = "";
338
339 // Event handler
340 bool runnerReleased_ = false;
341 std::mutex runnerMutex_;
342 std::shared_ptr<CallbackHandler> callbackHandler_ = nullptr;
343
344 std::shared_ptr<AudioClientTracker> proxyObj_ = nullptr;
345
346 bool paramsIsSet_ = false;
347 int32_t innerCapId_ = 0;
348
349 enum {
350 STATE_CHANGE_EVENT = 0,
351 RENDERER_MARK_REACHED_EVENT,
352 RENDERER_PERIOD_REACHED_EVENT,
353 CAPTURER_PERIOD_REACHED_EVENT,
354 CAPTURER_MARK_REACHED_EVENT,
355 };
356
357 enum : int64_t {
358 HANDLER_PARAM_INVALID = -1,
359 HANDLER_PARAM_NEW = 0,
360 HANDLER_PARAM_PREPARED,
361 HANDLER_PARAM_RUNNING,
362 HANDLER_PARAM_STOPPED,
363 HANDLER_PARAM_RELEASED,
364 HANDLER_PARAM_PAUSED,
365 HANDLER_PARAM_STOPPING,
366 HANDLER_PARAM_RUNNING_FROM_SYSTEM,
367 HANDLER_PARAM_PAUSED_FROM_SYSTEM,
368 };
369 };
370
GetInstance(AudioStreamType eStreamType,int32_t appUid)371 std::shared_ptr<CapturerInClient> CapturerInClient::GetInstance(AudioStreamType eStreamType, int32_t appUid)
372 {
373 return std::make_shared<CapturerInClientInner>(eStreamType, appUid);
374 }
375
CapturerInClientInner(AudioStreamType eStreamType,int32_t appUid)376 CapturerInClientInner::CapturerInClientInner(AudioStreamType eStreamType, int32_t appUid) : eStreamType_(eStreamType),
377 appUid_(appUid), cbBufferQueue_(CB_QUEUE_CAPACITY)
378 {
379 AUDIO_INFO_LOG("Create with StreamType:%{public}d appUid:%{public}d ", eStreamType_, appUid_);
380 audioStreamTracker_ = std::make_unique<AudioStreamTracker>(AUDIO_MODE_RECORD, appUid);
381 state_ = NEW;
382 }
383
~CapturerInClientInner()384 CapturerInClientInner::~CapturerInClientInner()
385 {
386 AUDIO_INFO_LOG("~CapturerInClientInner()");
387 CapturerInClientInner::ReleaseAudioStream(true);
388 AUDIO_INFO_LOG("[%{public}s] volume data counts: %{public}" PRId64, logUtilsTag_.c_str(), volumeDataCount_);
389 }
390
OnOperationHandled(Operation operation,int64_t result)391 int32_t CapturerInClientInner::OnOperationHandled(Operation operation, int64_t result)
392 {
393 // read/write operation may print many log, use debug.
394 if (operation == UPDATE_STREAM) {
395 AUDIO_DEBUG_LOG("OnOperationHandled() UPDATE_STREAM result:%{public}" PRId64".", result);
396 // notify write if blocked
397 readDataCV_.notify_all();
398 return SUCCESS;
399 }
400
401 if (operation == BUFFER_OVERFLOW) {
402 AUDIO_WARNING_LOG("recv overflow %{public}d", overflowCount_);
403 // in plan next: do more to reduce overflow
404 readDataCV_.notify_all();
405 return SUCCESS;
406 }
407
408 if (operation == RESTORE_SESSION) {
409 if (audioStreamTracker_ && audioStreamTracker_.get()) {
410 audioStreamTracker_->FetchInputDeviceForTrack(sessionId_, state_, clientPid_, capturerInfo_);
411 }
412 return SUCCESS;
413 }
414
415 AUDIO_INFO_LOG("OnOperationHandled() recv operation:%{public}d result:%{public}" PRId64".", operation, result);
416 std::unique_lock<std::mutex> lock(callServerMutex_);
417 notifiedOperation_ = operation;
418 notifiedResult_ = result;
419
420 if (notifiedResult_ == SUCCESS) {
421 std::unique_lock<std::mutex> lock(streamCbMutex_);
422 std::shared_ptr<AudioStreamCallback> streamCb = streamCallback_.lock();
423 switch (operation) {
424 case START_STREAM :
425 state_ = RUNNING;
426 break;
427 case PAUSE_STREAM :
428 state_ = PAUSED;
429 break;
430 case STOP_STREAM :
431 state_ = STOPPED;
432 default :
433 break;
434 }
435 if (streamCb != nullptr) {
436 streamCb->OnStateChange(state_, CMD_FROM_SYSTEM);
437 }
438 }
439
440 callServerCV_.notify_all();
441 return SUCCESS;
442 }
443
SetClientID(int32_t clientPid,int32_t clientUid,uint32_t appTokenId,uint64_t fullTokenId)444 void CapturerInClientInner::SetClientID(int32_t clientPid, int32_t clientUid, uint32_t appTokenId, uint64_t fullTokenId)
445 {
446 AUDIO_INFO_LOG("PID:%{public}d UID:%{public}d.", clientPid, clientUid);
447 clientPid_ = clientPid;
448 clientUid_ = clientUid;
449 appTokenId_ = appTokenId;
450 fullTokenId_ = fullTokenId;
451 return;
452 }
453
UpdatePlaybackCaptureConfig(const AudioPlaybackCaptureConfig & config)454 int32_t CapturerInClientInner::UpdatePlaybackCaptureConfig(const AudioPlaybackCaptureConfig &config)
455 {
456 #ifdef HAS_FEATURE_INNERCAPTURER
457 AUDIO_INFO_LOG("client set %{public}s", ProcessConfig::DumpInnerCapConfig(config).c_str());
458 CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, ERR_ILLEGAL_STATE, "IpcStream is already nullptr");
459 int32_t ret = ipcStream_->UpdatePlaybackCaptureConfig(config);
460 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "failed: %{public}d", ret);
461
462 filterConfig_ = config;
463 #endif
464 return SUCCESS;
465 }
466
SetRendererInfo(const AudioRendererInfo & rendererInfo)467 void CapturerInClientInner::SetRendererInfo(const AudioRendererInfo &rendererInfo)
468 {
469 AUDIO_WARNING_LOG("SetRendererInfo is not supported");
470 return;
471 }
472
SetCapturerInfo(const AudioCapturerInfo & capturerInfo)473 void CapturerInClientInner::SetCapturerInfo(const AudioCapturerInfo &capturerInfo)
474 {
475 capturerInfo_ = capturerInfo;
476 capturerInfo_.samplingRate = static_cast<AudioSamplingRate>(streamParams_.samplingRate);
477 capturerInfo_.encodingType = streamParams_.encoding;
478 capturerInfo_.channelLayout = streamParams_.channelLayout;
479 AUDIO_INFO_LOG("SetCapturerInfo with SourceType %{public}d flag %{public}d", capturerInfo_.sourceType,
480 capturerInfo_.capturerFlags);
481 return;
482 }
483
RegisterTracker(const std::shared_ptr<AudioClientTracker> & proxyObj)484 void CapturerInClientInner::RegisterTracker(const std::shared_ptr<AudioClientTracker> &proxyObj)
485 {
486 if (audioStreamTracker_ && audioStreamTracker_.get() && !streamTrackerRegistered_) {
487 // make sure sessionId_ is set before.
488 AUDIO_INFO_LOG("Calling register tracker, sessionid = %{public}d", sessionId_);
489 AudioRegisterTrackerInfo registerTrackerInfo;
490
491 capturerInfo_.samplingRate = static_cast<AudioSamplingRate>(streamParams_.samplingRate);
492 registerTrackerInfo.sessionId = sessionId_;
493 registerTrackerInfo.clientPid = clientPid_;
494 registerTrackerInfo.state = state_;
495 registerTrackerInfo.rendererInfo = rendererInfo_;
496 registerTrackerInfo.capturerInfo = capturerInfo_;
497 registerTrackerInfo.appTokenId = appTokenId_;
498
499 audioStreamTracker_->RegisterTracker(registerTrackerInfo, proxyObj);
500 streamTrackerRegistered_ = true;
501 }
502 }
503
UpdateTracker(const std::string & updateCase)504 void CapturerInClientInner::UpdateTracker(const std::string &updateCase)
505 {
506 if (audioStreamTracker_ && audioStreamTracker_.get()) {
507 AUDIO_DEBUG_LOG("Capturer:Calling Update tracker for %{public}s", updateCase.c_str());
508 audioStreamTracker_->UpdateTracker(sessionId_, state_, clientPid_, rendererInfo_, capturerInfo_);
509 }
510 }
511
SetAudioStreamInfo(const AudioStreamParams info,const std::shared_ptr<AudioClientTracker> & proxyObj,const AudioPlaybackCaptureConfig & config)512 int32_t CapturerInClientInner::SetAudioStreamInfo(const AudioStreamParams info,
513 const std::shared_ptr<AudioClientTracker> &proxyObj,
514 const AudioPlaybackCaptureConfig &config)
515 {
516 AUDIO_INFO_LOG("AudioStreamInfo, Sampling rate: %{public}d, channels: %{public}d, format: %{public}d, stream type:"
517 " %{public}d, encoding type: %{public}d", info.samplingRate, info.channels, info.format, eStreamType_,
518 info.encoding);
519 AudioXCollie guard("CapturerInClientInner::SetAudioStreamInfo", CREATE_TIMEOUT_IN_SECOND);
520 if (!IsFormatValid(info.format) || !IsEncodingTypeValid(info.encoding) || !IsSamplingRateValid(info.samplingRate)) {
521 AUDIO_ERR_LOG("CapturerInClient: Unsupported audio parameter");
522 return ERR_NOT_SUPPORTED;
523 }
524 if (!IsRecordChannelRelatedInfoValid(info.channels, info.channelLayout)) {
525 AUDIO_ERR_LOG("Invalid sink channel %{public}d or channel layout %{public}" PRIu64, info.channels,
526 info.channelLayout);
527 return ERR_NOT_SUPPORTED;
528 }
529
530 CHECK_AND_RETURN_RET_LOG(IAudioStream::GetByteSizePerFrame(info, sizePerFrameInByte_) == SUCCESS,
531 ERROR_INVALID_PARAM, "GetByteSizePerFrame failed with invalid params");
532
533 if (state_ != NEW) {
534 AUDIO_INFO_LOG("State is %{public}d, not new, release existing stream and recreate.", state_.load());
535 int32_t ret = DeinitIpcStream();
536 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "release existing stream failed.");
537 }
538
539 streamParams_ = info; // keep it for later use
540 paramsIsSet_ = true;
541 int32_t initRet = InitIpcStream(config);
542 CHECK_AND_RETURN_RET_LOG(initRet == SUCCESS, initRet, "Init stream failed: %{public}d", initRet);
543 state_ = PREPARED;
544 logUtilsTag_ = "[" + std::to_string(sessionId_) + "]NormalCapturer";
545
546 proxyObj_ = proxyObj;
547 RegisterTracker(proxyObj);
548 return SUCCESS;
549 }
550
551 std::mutex g_serverMutex;
552 sptr<IStandardAudioService> g_ServerProxy = nullptr;
GetAudioServerProxy()553 const sptr<IStandardAudioService> CapturerInClientInner::GetAudioServerProxy()
554 {
555 std::lock_guard<std::mutex> lock(g_serverMutex);
556 if (g_ServerProxy == nullptr) {
557 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
558 if (samgr == nullptr) {
559 AUDIO_ERR_LOG("GetAudioServerProxy: get sa manager failed");
560 return nullptr;
561 }
562 sptr<IRemoteObject> object = samgr->GetSystemAbility(AUDIO_DISTRIBUTED_SERVICE_ID);
563 if (object == nullptr) {
564 AUDIO_ERR_LOG("GetAudioServerProxy: get audio service remote object failed");
565 return nullptr;
566 }
567 g_ServerProxy = iface_cast<IStandardAudioService>(object);
568 if (g_ServerProxy == nullptr) {
569 AUDIO_ERR_LOG("GetAudioServerProxy: get audio service proxy failed");
570 return nullptr;
571 }
572
573 // register death recipent to restore proxy
574 sptr<AudioServerDeathRecipient> asDeathRecipient =
575 new(std::nothrow) AudioServerDeathRecipient(getpid(), getuid());
576 if (asDeathRecipient != nullptr) {
577 asDeathRecipient->SetNotifyCb([] (pid_t pid, pid_t uid) { AudioServerDied(pid, uid); });
578 bool result = object->AddDeathRecipient(asDeathRecipient);
579 if (!result) {
580 AUDIO_ERR_LOG("GetAudioServerProxy: failed to add deathRecipient");
581 }
582 }
583 }
584 sptr<IStandardAudioService> gasp = g_ServerProxy;
585 return gasp;
586 }
587
AudioServerDied(pid_t pid,pid_t uid)588 void CapturerInClientInner::AudioServerDied(pid_t pid, pid_t uid)
589 {
590 AUDIO_INFO_LOG("audio server died clear proxy, will restore proxy in next call");
591 std::lock_guard<std::mutex> lock(g_serverMutex);
592 g_ServerProxy = nullptr;
593 }
594
OnHandle(uint32_t code,int64_t data)595 void CapturerInClientInner::OnHandle(uint32_t code, int64_t data)
596 {
597 AUDIO_DEBUG_LOG("On handle event, event code: %{public}d, data: %{public}" PRIu64 "", code, data);
598 switch (code) {
599 case STATE_CHANGE_EVENT:
600 HandleStateChangeEvent(data);
601 break;
602 case RENDERER_MARK_REACHED_EVENT:
603 HandleCapturerMarkReachedEvent(data);
604 break;
605 case RENDERER_PERIOD_REACHED_EVENT:
606 HandleCapturerPeriodReachedEvent(data);
607 break;
608 default:
609 break;
610 }
611 }
612
HandleStateChangeEvent(int64_t data)613 void CapturerInClientInner::HandleStateChangeEvent(int64_t data)
614 {
615 State state = INVALID;
616 StateChangeCmdType cmdType = CMD_FROM_CLIENT;
617 ParamsToStateCmdType(data, state, cmdType);
618 std::unique_lock<std::mutex> lock(streamCbMutex_);
619 std::shared_ptr<AudioStreamCallback> streamCb = streamCallback_.lock();
620 if (streamCb != nullptr) {
621 state = state != STOPPING ? state : STOPPED; // client only need STOPPED
622 streamCb->OnStateChange(state, cmdType);
623 }
624 }
625
HandleCapturerMarkReachedEvent(int64_t capturerMarkPosition)626 void CapturerInClientInner::HandleCapturerMarkReachedEvent(int64_t capturerMarkPosition)
627 {
628 AUDIO_DEBUG_LOG("Start HandleCapturerMarkReachedEvent");
629 std::unique_lock<std::mutex> lock(markReachMutex_);
630 if (capturerPositionCallback_) {
631 capturerPositionCallback_->OnMarkReached(capturerMarkPosition);
632 }
633 }
634
HandleCapturerPeriodReachedEvent(int64_t capturerPeriodNumber)635 void CapturerInClientInner::HandleCapturerPeriodReachedEvent(int64_t capturerPeriodNumber)
636 {
637 AUDIO_DEBUG_LOG("Start HandleCapturerPeriodReachedEvent");
638 std::unique_lock<std::mutex> lock(periodReachMutex_);
639 if (capturerPeriodPositionCallback_) {
640 capturerPeriodPositionCallback_->OnPeriodReached(capturerPeriodNumber);
641 }
642 }
643
644 // OnCapturerMarkReach by eventHandler
SendCapturerMarkReachedEvent(int64_t capturerMarkPosition)645 void CapturerInClientInner::SendCapturerMarkReachedEvent(int64_t capturerMarkPosition)
646 {
647 SafeSendCallbackEvent(RENDERER_MARK_REACHED_EVENT, capturerMarkPosition);
648 }
649
650 // OnCapturerPeriodReach by eventHandler
SendCapturerPeriodReachedEvent(int64_t capturerPeriodSize)651 void CapturerInClientInner::SendCapturerPeriodReachedEvent(int64_t capturerPeriodSize)
652 {
653 SafeSendCallbackEvent(RENDERER_PERIOD_REACHED_EVENT, capturerPeriodSize);
654 }
655
ParamsToStateCmdType(int64_t params,State & state,StateChangeCmdType & cmdType)656 int32_t CapturerInClientInner::ParamsToStateCmdType(int64_t params, State &state, StateChangeCmdType &cmdType)
657 {
658 cmdType = CMD_FROM_CLIENT;
659 switch (params) {
660 case HANDLER_PARAM_NEW:
661 state = NEW;
662 break;
663 case HANDLER_PARAM_PREPARED:
664 state = PREPARED;
665 break;
666 case HANDLER_PARAM_RUNNING:
667 state = RUNNING;
668 break;
669 case HANDLER_PARAM_STOPPED:
670 state = STOPPED;
671 break;
672 case HANDLER_PARAM_RELEASED:
673 state = RELEASED;
674 break;
675 case HANDLER_PARAM_PAUSED:
676 state = PAUSED;
677 break;
678 case HANDLER_PARAM_STOPPING:
679 state = STOPPING;
680 break;
681 case HANDLER_PARAM_RUNNING_FROM_SYSTEM:
682 state = RUNNING;
683 cmdType = CMD_FROM_SYSTEM;
684 break;
685 case HANDLER_PARAM_PAUSED_FROM_SYSTEM:
686 state = PAUSED;
687 cmdType = CMD_FROM_SYSTEM;
688 break;
689 default:
690 state = INVALID;
691 break;
692 }
693 return SUCCESS;
694 }
695
StateCmdTypeToParams(int64_t & params,State state,StateChangeCmdType cmdType)696 int32_t CapturerInClientInner::StateCmdTypeToParams(int64_t ¶ms, State state, StateChangeCmdType cmdType)
697 {
698 if (cmdType == CMD_FROM_CLIENT) {
699 params = static_cast<int64_t>(state);
700 return SUCCESS;
701 }
702 switch (state) {
703 case RUNNING:
704 params = HANDLER_PARAM_RUNNING_FROM_SYSTEM;
705 break;
706 case PAUSED:
707 params = HANDLER_PARAM_PAUSED_FROM_SYSTEM;
708 break;
709 default:
710 params = HANDLER_PARAM_INVALID;
711 break;
712 }
713 return SUCCESS;
714 }
715
SafeSendCallbackEvent(uint32_t eventCode,int64_t data)716 void CapturerInClientInner::SafeSendCallbackEvent(uint32_t eventCode, int64_t data)
717 {
718 std::lock_guard<std::mutex> lock(runnerMutex_);
719 AUDIO_INFO_LOG("Send callback event, code: %{public}u, data: %{public}" PRId64 "", eventCode, data);
720 CHECK_AND_RETURN_LOG(callbackHandler_ != nullptr && runnerReleased_ == false, "Runner is Released");
721 callbackHandler_->SendCallbackEvent(eventCode, data);
722 }
723
InitCallbackHandler()724 void CapturerInClientInner::InitCallbackHandler()
725 {
726 if (callbackHandler_ == nullptr) {
727 callbackHandler_ = CallbackHandler::GetInstance(shared_from_this(), "OS_AudioStateCB");
728 }
729 }
730
731 // call this without lock, we should be able to call deinit in any case.
DeinitIpcStream()732 int32_t CapturerInClientInner::DeinitIpcStream()
733 {
734 CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, SUCCESS, "IpcStream is already nullptr");
735 ipcStream_->Release();
736 // in plan:
737 ipcStream_ = nullptr;
738 ringCache_->ResetBuffer();
739 return SUCCESS;
740 }
741
ConstructConfig()742 const AudioProcessConfig CapturerInClientInner::ConstructConfig()
743 {
744 AudioProcessConfig config = {};
745 // in plan: get token id
746 config.appInfo.appPid = clientPid_;
747 config.appInfo.appUid = clientUid_;
748 config.appInfo.appTokenId = appTokenId_;
749 config.appInfo.appFullTokenId = fullTokenId_;
750
751 config.streamInfo.channels = static_cast<AudioChannel>(streamParams_.channels);
752 config.streamInfo.encoding = static_cast<AudioEncodingType>(streamParams_.encoding);
753 config.streamInfo.format = static_cast<AudioSampleFormat>(streamParams_.format);
754 config.streamInfo.samplingRate = static_cast<AudioSamplingRate>(streamParams_.samplingRate);
755 config.streamInfo.channelLayout = static_cast<AudioChannelLayout>(streamParams_.channelLayout);
756 config.originalSessionId = streamParams_.originalSessionId;
757
758 config.audioMode = AUDIO_MODE_RECORD;
759
760 if (capturerInfo_.capturerFlags != 0) {
761 AUDIO_WARNING_LOG("ConstructConfig find Capturer flag invalid:%{public}d", capturerInfo_.capturerFlags);
762 capturerInfo_.capturerFlags = 0;
763 }
764 config.capturerInfo = capturerInfo_;
765
766 config.rendererInfo = {};
767
768 config.streamType = eStreamType_;
769
770 config.isInnerCapturer = isInnerCapturer_;
771 config.isWakeupCapturer = isWakeupCapturer_;
772 config.innerCapId = innerCapId_;
773
774 clientConfig_ = config;
775 return config;
776 }
777
InitSharedBuffer()778 int32_t CapturerInClientInner::InitSharedBuffer()
779 {
780 CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, ERR_OPERATION_FAILED, "InitSharedBuffer failed, null ipcStream_.");
781 int32_t ret = ipcStream_->ResolveBuffer(clientBuffer_);
782 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS && clientBuffer_ != nullptr, ret, "ResolveBuffer failed:%{public}d", ret);
783
784 uint32_t totalSizeInFrame = 0;
785 uint32_t byteSizePerFrame = 0;
786 ret = clientBuffer_->GetSizeParameter(totalSizeInFrame, spanSizeInFrame_, byteSizePerFrame);
787
788 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS && byteSizePerFrame == sizePerFrameInByte_, ret, "ResolveBuffer failed"
789 ":%{public}d", ret);
790
791 clientSpanSizeInByte_ = spanSizeInFrame_ * byteSizePerFrame;
792
793 AUDIO_INFO_LOG("totalSizeInFrame_[%{public}u] spanSizeInFrame_[%{public}u] sizePerFrameInByte_["
794 "%{public}zu] clientSpanSizeInByte_[%{public}zu]", totalSizeInFrame, spanSizeInFrame_, sizePerFrameInByte_,
795 clientSpanSizeInByte_);
796
797 return SUCCESS;
798 }
799
800 // InitCacheBuffer should be able to modify the cache size between clientSpanSizeInByte_ and 4 * clientSpanSizeInByte_
InitCacheBuffer(size_t targetSize)801 int32_t CapturerInClientInner::InitCacheBuffer(size_t targetSize)
802 {
803 CHECK_AND_RETURN_RET_LOG(clientSpanSizeInByte_ != 0, ERR_OPERATION_FAILED, "clientSpanSizeInByte_ invalid");
804
805 AUDIO_INFO_LOG("old size:%{public}zu, new size:%{public}zu", cacheSizeInByte_, targetSize);
806 cacheSizeInByte_ = targetSize;
807
808 if (ringCache_ == nullptr) {
809 ringCache_ = AudioRingCache::Create(cacheSizeInByte_);
810 } else {
811 OptResult result = ringCache_->ReConfig(cacheSizeInByte_, false); // false --> clear buffer
812 if (result.ret != OPERATION_SUCCESS) {
813 AUDIO_ERR_LOG("ReConfig AudioRingCache to size %{public}u failed:ret%{public}zu", result.ret, targetSize);
814 return ERR_OPERATION_FAILED;
815 }
816 }
817
818 return SUCCESS;
819 }
820
InitIpcStream(const AudioPlaybackCaptureConfig & filterConfig)821 int32_t CapturerInClientInner::InitIpcStream(const AudioPlaybackCaptureConfig &filterConfig)
822 {
823 AUDIO_INFO_LOG("Init Ipc stream");
824 AudioProcessConfig config = ConstructConfig();
825
826 sptr<IStandardAudioService> gasp = CapturerInClientInner::GetAudioServerProxy();
827 CHECK_AND_RETURN_RET_LOG(gasp != nullptr, ERR_OPERATION_FAILED, "Create failed, can not get service.");
828 int32_t errorCode = 0;
829 sptr<IRemoteObject> ipcProxy = gasp->CreateAudioProcess(config, errorCode, filterConfig);
830 for (int32_t retrycount = 0; (errorCode == ERR_RETRY_IN_CLIENT) && (retrycount < MAX_RETRY_COUNT); retrycount++) {
831 AUDIO_WARNING_LOG("retry in client");
832 std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_WAIT_TIME_MS));
833 ipcProxy = gasp->CreateAudioProcess(config, errorCode);
834 }
835 CHECK_AND_RETURN_RET_LOG(errorCode == SUCCESS, errorCode, "failed with create audio stream fail.");
836 CHECK_AND_RETURN_RET_LOG(ipcProxy != nullptr, ERR_OPERATION_FAILED, "failed with null ipcProxy.");
837 ipcStream_ = iface_cast<IpcStream>(ipcProxy);
838 CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, ERR_OPERATION_FAILED, "failed when iface_cast.");
839
840 // in plan: old listener_ is destoried here, will server receive dieth notify?
841 listener_ = sptr<IpcStreamListenerImpl>::MakeSptr(shared_from_this());
842 int32_t ret = ipcStream_->RegisterStreamListener(listener_->AsObject());
843 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "RegisterStreamListener failed:%{public}d", ret);
844
845 ret = InitSharedBuffer();
846 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "InitSharedBuffer failed:%{public}d", ret);
847
848 ret = InitCacheBuffer(clientSpanSizeInByte_);
849 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "InitCacheBuffer failed:%{public}d", ret);
850
851 ret = ipcStream_->GetAudioSessionID(sessionId_);
852 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "GetAudioSessionID failed:%{public}d", ret);
853
854 InitCallbackHandler();
855 return SUCCESS;
856 }
857
GetAudioStreamInfo(AudioStreamParams & info)858 int32_t CapturerInClientInner::GetAudioStreamInfo(AudioStreamParams &info)
859 {
860 CHECK_AND_RETURN_RET_LOG(paramsIsSet_ == true, ERR_OPERATION_FAILED, "Params is not set");
861 info = streamParams_;
862 return SUCCESS;
863 }
864
GetAudioSessionID(uint32_t & sessionID)865 int32_t CapturerInClientInner::GetAudioSessionID(uint32_t &sessionID)
866 {
867 CHECK_AND_RETURN_RET_LOG((state_ != RELEASED) && (state_ != NEW), ERR_ILLEGAL_STATE,
868 "State error %{public}d", state_.load());
869 sessionID = sessionId_;
870 return SUCCESS;
871 }
872
GetAudioPipeType(AudioPipeType & pipeType)873 void CapturerInClientInner::GetAudioPipeType(AudioPipeType &pipeType)
874 {
875 pipeType = capturerInfo_.pipeType;
876 }
877
GetState()878 State CapturerInClientInner::GetState()
879 {
880 return state_;
881 }
882
GetAudioTime(Timestamp & timestamp,Timestamp::Timestampbase base)883 bool CapturerInClientInner::GetAudioTime(Timestamp ×tamp, Timestamp::Timestampbase base)
884 {
885 CHECK_AND_RETURN_RET_LOG(paramsIsSet_ == true, false, "Params is not set");
886 CHECK_AND_RETURN_RET_LOG(state_ != STOPPED, false, "Invalid status:%{public}d", state_.load());
887 uint64_t currentReadPos = totalBytesRead_ / sizePerFrameInByte_;
888 timestamp.framePosition = currentReadPos;
889
890 uint64_t writePos = 0;
891 int64_t handleTime = 0;
892 CHECK_AND_RETURN_RET_LOG(clientBuffer_ != nullptr, false, "invalid buffer status");
893 clientBuffer_->GetHandleInfo(writePos, handleTime);
894 if (writePos == 0 || handleTime == 0) {
895 AUDIO_WARNING_LOG("GetHandleInfo may failed");
896 }
897
898 int64_t deltaPos = writePos >= currentReadPos ? static_cast<int64_t>(writePos - currentReadPos) : 0;
899 int64_t tempLatency = 25000000; // 25000000 -> 25 ms
900 int64_t deltaTime = deltaPos * AUDIO_MS_PER_SECOND /
901 static_cast<int64_t>(streamParams_.samplingRate) * AUDIO_US_PER_S;
902
903 handleTime = handleTime + deltaTime + tempLatency;
904 timestamp.time.tv_sec = static_cast<time_t>(handleTime / AUDIO_NS_PER_SECOND);
905 timestamp.time.tv_nsec = static_cast<time_t>(handleTime % AUDIO_NS_PER_SECOND);
906
907 return true;
908 }
909
GetAudioPosition(Timestamp & timestamp,Timestamp::Timestampbase base)910 bool CapturerInClientInner::GetAudioPosition(Timestamp ×tamp, Timestamp::Timestampbase base)
911 {
912 return GetAudioTime(timestamp, base);
913 }
914
GetBufferSize(size_t & bufferSize)915 int32_t CapturerInClientInner::GetBufferSize(size_t &bufferSize)
916 {
917 CHECK_AND_RETURN_RET_LOG(state_ != RELEASED, ERR_ILLEGAL_STATE, "Capturer stream is released");
918 bufferSize = clientSpanSizeInByte_;
919 if (capturerMode_ == CAPTURE_MODE_CALLBACK) {
920 bufferSize = cbBufferSize_;
921 }
922 AUDIO_DEBUG_LOG("Buffer size is %{public}zu, mode is %{public}s", bufferSize, capturerMode_ == CAPTURE_MODE_NORMAL ?
923 "CAPTURE_MODE_NORMAL" : "CAPTURE_MODE_CALLBACK");
924 return SUCCESS;
925 }
926
GetFrameCount(uint32_t & frameCount)927 int32_t CapturerInClientInner::GetFrameCount(uint32_t &frameCount)
928 {
929 CHECK_AND_RETURN_RET_LOG(state_ != RELEASED, ERR_ILLEGAL_STATE, "Capturer stream is released");
930 CHECK_AND_RETURN_RET_LOG(sizePerFrameInByte_ != 0, ERR_ILLEGAL_STATE, "sizePerFrameInByte_ is 0!");
931 frameCount = spanSizeInFrame_;
932 if (capturerMode_ == CAPTURE_MODE_CALLBACK) {
933 frameCount = cbBufferSize_ / sizePerFrameInByte_;
934 }
935 AUDIO_INFO_LOG("Frame count is %{public}u, mode is %{public}s", frameCount, capturerMode_ == CAPTURE_MODE_NORMAL ?
936 "CAPTURE_MODE_NORMAL" : "CAPTURE_MODE_CALLBACK");
937 return SUCCESS;
938 }
939
GetLatency(uint64_t & latency)940 int32_t CapturerInClientInner::GetLatency(uint64_t &latency)
941 {
942 // GetLatency is never called in audio_capturer.cpp
943 latency = 150000; // unit is us, 150000 is 150ms
944 return ERROR;
945 }
946
SetAudioStreamType(AudioStreamType audioStreamType)947 int32_t CapturerInClientInner::SetAudioStreamType(AudioStreamType audioStreamType)
948 {
949 AUDIO_ERR_LOG("Change stream type %{public}d to %{public}d is not supported", eStreamType_, audioStreamType);
950 return ERROR;
951 }
952
SetVolume(float volume)953 int32_t CapturerInClientInner::SetVolume(float volume)
954 {
955 AUDIO_WARNING_LOG("SetVolume is only for renderer");
956 return ERROR;
957 }
958
GetVolume()959 float CapturerInClientInner::GetVolume()
960 {
961 AUDIO_WARNING_LOG("GetVolume is only for renderer");
962 return 0.0;
963 }
964
SetMute(bool mute)965 int32_t CapturerInClientInner::SetMute(bool mute)
966 {
967 AUDIO_WARNING_LOG("only for renderer");
968 return ERROR;
969 }
970
SetDuckVolume(float volume)971 int32_t CapturerInClientInner::SetDuckVolume(float volume)
972 {
973 AUDIO_WARNING_LOG("only for renderer");
974 return ERROR;
975 }
976
SetSpeed(float speed)977 int32_t CapturerInClientInner::SetSpeed(float speed)
978 {
979 AUDIO_ERR_LOG("SetSpeed is not supported");
980 return ERROR;
981 }
982
GetSpeed()983 float CapturerInClientInner::GetSpeed()
984 {
985 AUDIO_ERR_LOG("GetSpeed is not supported");
986 return 1.0;
987 }
988
ChangeSpeed(uint8_t * buffer,int32_t bufferSize,std::unique_ptr<uint8_t[]> & outBuffer,int32_t & outBufferSize)989 int32_t CapturerInClientInner::ChangeSpeed(uint8_t *buffer, int32_t bufferSize, std::unique_ptr<uint8_t []> &outBuffer,
990 int32_t &outBufferSize)
991 {
992 AUDIO_ERR_LOG("ChangeSpeed is not supported");
993 return ERROR;
994 }
995
SetRenderRate(AudioRendererRate renderRate)996 int32_t CapturerInClientInner::SetRenderRate(AudioRendererRate renderRate)
997 {
998 AUDIO_WARNING_LOG("SetRenderRate is only for renderer");
999 return ERROR;
1000 }
1001
GetRenderRate()1002 AudioRendererRate CapturerInClientInner::GetRenderRate()
1003 {
1004 AUDIO_WARNING_LOG("GetRenderRate is only for renderer");
1005 return RENDER_RATE_NORMAL; // not supported
1006 }
1007
SetStreamCallback(const std::shared_ptr<AudioStreamCallback> & callback)1008 int32_t CapturerInClientInner::SetStreamCallback(const std::shared_ptr<AudioStreamCallback> &callback)
1009 {
1010 if (callback == nullptr) {
1011 AUDIO_ERR_LOG("SetStreamCallback failed. callback == nullptr");
1012 return ERR_INVALID_PARAM;
1013 }
1014
1015 std::unique_lock<std::mutex> lock(streamCbMutex_);
1016 streamCallback_ = callback;
1017 lock.unlock();
1018
1019 if (state_ != PREPARED) {
1020 return SUCCESS;
1021 }
1022 SafeSendCallbackEvent(STATE_CHANGE_EVENT, PREPARED);
1023 return SUCCESS;
1024 }
1025
SetRenderMode(AudioRenderMode renderMode)1026 int32_t CapturerInClientInner::SetRenderMode(AudioRenderMode renderMode)
1027 {
1028 AUDIO_WARNING_LOG("SetRenderMode is only for renderer");
1029 return ERROR;
1030 }
1031
GetRenderMode()1032 AudioRenderMode CapturerInClientInner::GetRenderMode()
1033 {
1034 AUDIO_WARNING_LOG("GetRenderMode is only for renderer");
1035 return RENDER_MODE_NORMAL; // not supported
1036 }
1037
SetRendererWriteCallback(const std::shared_ptr<AudioRendererWriteCallback> & callback)1038 int32_t CapturerInClientInner::SetRendererWriteCallback(const std::shared_ptr<AudioRendererWriteCallback> &callback)
1039 {
1040 AUDIO_WARNING_LOG("SetRendererWriteCallback is only for renderer");
1041 return ERROR;
1042 }
1043
InitCallbackBuffer(uint64_t bufferDurationInUs)1044 void CapturerInClientInner::InitCallbackBuffer(uint64_t bufferDurationInUs)
1045 {
1046 if (bufferDurationInUs > MAX_BUF_DURATION_IN_USEC) {
1047 AUDIO_ERR_LOG("InitCallbackBuffer with invalid duration %{public}" PRIu64", use default instead.",
1048 bufferDurationInUs);
1049 bufferDurationInUs = DEFAULT_BUF_DURATION_IN_USEC;
1050 }
1051 // Calculate buffer size based on duration.
1052 cbBufferSize_ = static_cast<size_t>(bufferDurationInUs * streamParams_.samplingRate / AUDIO_US_PER_S) *
1053 sizePerFrameInByte_;
1054 AUDIO_INFO_LOG("InitCallbackBuffer with duration %{public}" PRIu64", size: %{public}zu", bufferDurationInUs,
1055 cbBufferSize_);
1056 std::lock_guard<std::mutex> lock(cbBufferMutex_);
1057 cbBuffer_ = std::make_unique<uint8_t[]>(cbBufferSize_);
1058 BufferDesc temp = {cbBuffer_.get(), cbBufferSize_, cbBufferSize_};
1059 cbBufferQueue_.Clear();
1060 cbBufferQueue_.Push(temp);
1061 }
1062
InitCallbackLoop()1063 void CapturerInClientInner::InitCallbackLoop()
1064 {
1065 cbThreadReleased_ = false;
1066 auto weakRef = weak_from_this();
1067
1068 // OS_AudioWriteCB
1069 callbackLoop_ = std::thread([weakRef] {
1070 bool keepRunning = true;
1071 std::shared_ptr<CapturerInClientInner> strongRef = weakRef.lock();
1072 if (strongRef != nullptr) {
1073 strongRef->cbThreadCv_.notify_one();
1074 AUDIO_INFO_LOG("Thread start, sessionID :%{public}d", strongRef->sessionId_);
1075 } else {
1076 AUDIO_WARNING_LOG("Strong ref is nullptr, could cause error");
1077 }
1078 strongRef = nullptr;
1079 // start loop
1080 while (keepRunning) {
1081 strongRef = weakRef.lock();
1082 if (strongRef == nullptr) {
1083 AUDIO_INFO_LOG("CapturerInClientInner destroyed");
1084 break;
1085 }
1086 keepRunning = strongRef->ReadCallbackFunc(); // Main operation in callback loop
1087 }
1088 if (strongRef != nullptr) {
1089 AUDIO_INFO_LOG("CBThread end sessionID :%{public}d", strongRef->sessionId_);
1090 }
1091 });
1092 pthread_setname_np(callbackLoop_.native_handle(), "OS_AudioReadCb");
1093 }
1094
SetCaptureMode(AudioCaptureMode captureMode)1095 int32_t CapturerInClientInner::SetCaptureMode(AudioCaptureMode captureMode)
1096 {
1097 AUDIO_INFO_LOG("Set mode to %{public}s", captureMode == CAPTURE_MODE_NORMAL ? "CAPTURE_MODE_NORMAL" :
1098 "CAPTURE_MODE_CALLBACK");
1099 if (capturerMode_ == captureMode) {
1100 return SUCCESS;
1101 }
1102
1103 // capturerMode_ is inited as CAPTURE_MODE_NORMAL, can only be set to CAPTURE_MODE_CALLBACK.
1104 if (capturerMode_ == CAPTURE_MODE_CALLBACK && captureMode == CAPTURE_MODE_NORMAL) {
1105 AUDIO_ERR_LOG("Set capturer mode from callback to normal is not supported.");
1106 return ERR_INCORRECT_MODE;
1107 }
1108
1109 // state check
1110 if (state_ != PREPARED && state_ != NEW) {
1111 AUDIO_ERR_LOG("Set capturer mode failed. invalid state:%{public}d", state_.load());
1112 return ERR_ILLEGAL_STATE;
1113 }
1114 capturerMode_ = captureMode;
1115
1116 // init callbackLoop_
1117 InitCallbackLoop();
1118
1119 std::unique_lock<std::mutex> threadStartlock(statusMutex_);
1120 bool stopWaiting = cbThreadCv_.wait_for(threadStartlock, std::chrono::milliseconds(SHORT_TIMEOUT_IN_MS), [this] {
1121 return cbThreadReleased_ == false; // When thread is started, cbThreadReleased_ will be false. So stop waiting.
1122 });
1123 if (!stopWaiting) {
1124 AUDIO_WARNING_LOG("Init OS_AudioReadCB thread time out");
1125 }
1126
1127 CHECK_AND_RETURN_RET_LOG(streamParams_.samplingRate != 0, ERR_ILLEGAL_STATE, "invalid sample rate");
1128
1129 uint64_t bufferDurationInUs = spanSizeInFrame_ * AUDIO_US_PER_S / streamParams_.samplingRate;
1130 InitCallbackBuffer(bufferDurationInUs);
1131 return SUCCESS;
1132 }
1133
GetCaptureMode()1134 AudioCaptureMode CapturerInClientInner::GetCaptureMode()
1135 {
1136 AUDIO_INFO_LOG("capturer mode is %{public}s", capturerMode_ == CAPTURE_MODE_NORMAL ? "CAPTURE_MODE_NORMAL" :
1137 "CAPTURE_MODE_CALLBACK");
1138 return capturerMode_;
1139 }
1140
SetCapturerReadCallback(const std::shared_ptr<AudioCapturerReadCallback> & callback)1141 int32_t CapturerInClientInner::SetCapturerReadCallback(const std::shared_ptr<AudioCapturerReadCallback> &callback)
1142 {
1143 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "Invalid null callback");
1144 CHECK_AND_RETURN_RET_LOG(capturerMode_ == CAPTURE_MODE_CALLBACK, ERR_INCORRECT_MODE, "incorrect capturer mode");
1145 std::lock_guard<std::mutex> lock(readCbMutex_);
1146 readCb_ = callback;
1147 return SUCCESS;
1148 }
1149
WaitForRunning()1150 bool CapturerInClientInner::WaitForRunning()
1151 {
1152 Trace trace("CapturerInClientInner::WaitForRunning");
1153 // check capturer state_: call client write only in running else wait on statusMutex_
1154 std::unique_lock<std::mutex> stateLock(statusMutex_);
1155 if (state_ != RUNNING) {
1156 bool stopWaiting = cbThreadCv_.wait_for(stateLock, std::chrono::milliseconds(OPERATION_TIMEOUT_IN_MS), [this] {
1157 return state_ == RUNNING || cbThreadReleased_;
1158 });
1159 if (cbThreadReleased_) {
1160 AUDIO_INFO_LOG("CBThread end in non-running status, sessionID :%{public}d", sessionId_);
1161 return false;
1162 }
1163 if (!stopWaiting) {
1164 AUDIO_INFO_LOG("Wait timeout, current state_ is %{public}d", state_.load()); // wait 0.5s
1165 return false;
1166 }
1167 }
1168 return true;
1169 }
1170
ReadCallbackFunc()1171 bool CapturerInClientInner::ReadCallbackFunc()
1172 {
1173 if (cbThreadReleased_) {
1174 return false;
1175 }
1176 Trace traceLoop("CapturerInClientInner::WriteCallbackFunc");
1177 if (!WaitForRunning()) {
1178 return true;
1179 }
1180
1181 // If client didn't call GetBufferDesc/Enqueue in OnReadData, pop will block here.
1182 BufferDesc temp = cbBufferQueue_.Pop();
1183 if (temp.buffer == nullptr) {
1184 AUDIO_WARNING_LOG("Queue pop error: get nullptr.");
1185 return false;
1186 }
1187
1188 std::unique_lock<std::mutex> lockBuffer(cbBufferMutex_);
1189 // call read here.
1190 int32_t result = Read(*temp.buffer, temp.bufLength, true); // blocking read
1191 if (result < 0 || result != static_cast<int32_t>(cbBufferSize_)) {
1192 AUDIO_WARNING_LOG("Call read error, ret:%{public}d, cbBufferSize_:%{public}zu", result, cbBufferSize_);
1193 }
1194 if (state_ != RUNNING) {
1195 return true;
1196 }
1197 lockBuffer.unlock();
1198
1199 // call client read
1200 Trace traceCb("CapturerInClientInner::OnReadData");
1201 std::unique_lock<std::mutex> lockCb(readCbMutex_);
1202 if (readCb_ != nullptr) {
1203 readCb_->OnReadData(cbBufferSize_);
1204 }
1205 lockCb.unlock();
1206 traceCb.End();
1207 return true;
1208 }
1209
1210
GetBufferDesc(BufferDesc & bufDesc)1211 int32_t CapturerInClientInner::GetBufferDesc(BufferDesc &bufDesc)
1212 {
1213 Trace trace("CapturerInClientInner::GetBufferDesc");
1214 if (capturerMode_ != CAPTURE_MODE_CALLBACK) {
1215 AUDIO_ERR_LOG("Not supported. mode is not callback.");
1216 return ERR_INCORRECT_MODE;
1217 }
1218 std::lock_guard<std::mutex> lock(cbBufferMutex_);
1219 bufDesc.buffer = cbBuffer_.get();
1220 bufDesc.bufLength = cbBufferSize_;
1221 bufDesc.dataLength = cbBufferSize_;
1222 return SUCCESS;
1223 }
1224
GetBufQueueState(BufferQueueState & bufState)1225 int32_t CapturerInClientInner::GetBufQueueState(BufferQueueState &bufState)
1226 {
1227 Trace trace("CapturerInClientInner::GetBufQueueState");
1228 if (capturerMode_ != CAPTURE_MODE_CALLBACK) {
1229 AUDIO_ERR_LOG("Not supported, mode is not callback.");
1230 return ERR_INCORRECT_MODE;
1231 }
1232 // only one buffer in queue.
1233 bufState.numBuffers = 1;
1234 bufState.currentIndex = 0;
1235 return SUCCESS;
1236 }
1237
Enqueue(const BufferDesc & bufDesc)1238 int32_t CapturerInClientInner::Enqueue(const BufferDesc &bufDesc)
1239 {
1240 Trace trace("CapturerInClientInner::Enqueue");
1241 if (capturerMode_ != CAPTURE_MODE_CALLBACK) {
1242 AUDIO_ERR_LOG("Not supported, mode is not callback.");
1243 return ERR_INCORRECT_MODE;
1244 }
1245 std::lock_guard<std::mutex> lock(cbBufferMutex_);
1246
1247 if (bufDesc.bufLength != cbBufferSize_ || bufDesc.dataLength != cbBufferSize_) {
1248 AUDIO_ERR_LOG("Enqueue invalid bufLength:%{public}zu or dataLength:%{public}zu, should be %{public}zu",
1249 bufDesc.bufLength, bufDesc.dataLength, cbBufferSize_);
1250 return ERR_INVALID_INDEX;
1251 }
1252 if (bufDesc.buffer != cbBuffer_.get()) {
1253 AUDIO_WARNING_LOG("Enqueue buffer is not from us.");
1254 }
1255
1256 // if Enqueue is not called in OnReadData, loop thread will block on pop, wait for the Push call here.
1257 BufferDesc temp = {cbBuffer_.get(), cbBufferSize_, cbBufferSize_};
1258 cbBufferQueue_.Push(temp);
1259 // Call read may block, so put it in loop callbackLoop_
1260 return SUCCESS;
1261 }
1262
Clear()1263 int32_t CapturerInClientInner::Clear()
1264 {
1265 Trace trace("CapturerInClientInner::Clear");
1266 if (capturerMode_ != CAPTURE_MODE_CALLBACK) {
1267 AUDIO_ERR_LOG("Not supported, mode is not callback.");
1268 return ERR_INCORRECT_MODE;
1269 }
1270 std::lock_guard<std::mutex> lock(cbBufferMutex_);
1271 int32_t ret = memset_s(cbBuffer_.get(), cbBufferSize_, 0, cbBufferSize_);
1272 CHECK_AND_RETURN_RET_LOG(ret == EOK, ERR_OPERATION_FAILED, "Clear buffer fail, ret %{public}d.", ret);
1273 return SUCCESS;
1274 }
1275
SetLowPowerVolume(float volume)1276 int32_t CapturerInClientInner::SetLowPowerVolume(float volume)
1277 {
1278 AUDIO_WARNING_LOG("SetLowPowerVolume is only for renderer");
1279 return ERROR;
1280 }
1281
GetLowPowerVolume()1282 float CapturerInClientInner::GetLowPowerVolume()
1283 {
1284 AUDIO_WARNING_LOG("GetLowPowerVolume is only for renderer");
1285 return 0.0;
1286 }
1287
SetOffloadMode(int32_t state,bool isAppBack)1288 int32_t CapturerInClientInner::SetOffloadMode(int32_t state, bool isAppBack)
1289 {
1290 AUDIO_WARNING_LOG("SetOffloadMode is only for renderer");
1291 return ERROR;
1292 }
1293
UnsetOffloadMode()1294 int32_t CapturerInClientInner::UnsetOffloadMode()
1295 {
1296 AUDIO_WARNING_LOG("UnsetOffloadMode is only for renderer");
1297 return ERROR;
1298 }
1299
GetSingleStreamVolume()1300 float CapturerInClientInner::GetSingleStreamVolume()
1301 {
1302 AUDIO_WARNING_LOG("GetSingleStreamVolume is only for renderer");
1303 return 0.0;
1304 }
1305
GetAudioEffectMode()1306 AudioEffectMode CapturerInClientInner::GetAudioEffectMode()
1307 {
1308 AUDIO_WARNING_LOG("GetAudioEffectMode is only for renderer");
1309 return EFFECT_NONE;
1310 }
1311
SetAudioEffectMode(AudioEffectMode effectMode)1312 int32_t CapturerInClientInner::SetAudioEffectMode(AudioEffectMode effectMode)
1313 {
1314 AUDIO_WARNING_LOG("SetAudioEffectMode is only for renderer");
1315 return ERROR;
1316 }
1317
GetFramesWritten()1318 int64_t CapturerInClientInner::GetFramesWritten()
1319 {
1320 AUDIO_WARNING_LOG("GetFramesWritten is only for renderer");
1321 return -1;
1322 }
1323
GetFramesRead()1324 int64_t CapturerInClientInner::GetFramesRead()
1325 {
1326 CHECK_AND_RETURN_RET_LOG(sizePerFrameInByte_ != 0, INVALID_FRAME_SIZE, "sizePerFrameInByte_ is 0!");
1327 uint64_t readFrameNumber = totalBytesRead_ / sizePerFrameInByte_;
1328 return readFrameNumber;
1329 }
1330
1331 // Will only take effect before SetAudioStreaminfo
SetInnerCapturerState(bool isInnerCapturer)1332 void CapturerInClientInner::SetInnerCapturerState(bool isInnerCapturer)
1333 {
1334 isInnerCapturer_ = isInnerCapturer;
1335 AUDIO_INFO_LOG("SetInnerCapturerState %{public}s", (isInnerCapturer_ ? "true" : "false"));
1336 return;
1337 }
1338
1339 // Will only take effect before SetAudioStreaminfo
SetWakeupCapturerState(bool isWakeupCapturer)1340 void CapturerInClientInner::SetWakeupCapturerState(bool isWakeupCapturer)
1341 {
1342 isWakeupCapturer_ = isWakeupCapturer;
1343 AUDIO_INFO_LOG("SetWakeupCapturerState %{public}s", (isWakeupCapturer_ ? "true" : "false"));
1344 return;
1345 }
1346
SetCapturerSource(int capturerSource)1347 void CapturerInClientInner::SetCapturerSource(int capturerSource)
1348 {
1349 // capturerSource is kept in capturerInfo_, no need to be set again.
1350 (void)capturerSource;
1351 return;
1352 }
1353
SetPrivacyType(AudioPrivacyType privacyType)1354 void CapturerInClientInner::SetPrivacyType(AudioPrivacyType privacyType)
1355 {
1356 AUDIO_WARNING_LOG("SetPrivacyType is only for renderer");
1357 return;
1358 }
1359
StartAudioStream(StateChangeCmdType cmdType,AudioStreamDeviceChangeReasonExt reason)1360 bool CapturerInClientInner::StartAudioStream(StateChangeCmdType cmdType, AudioStreamDeviceChangeReasonExt reason)
1361 {
1362 Trace trace("CapturerInClientInner::StartAudioStream " + std::to_string(sessionId_));
1363 std::unique_lock<std::mutex> statusLock(statusMutex_);
1364 if (state_ != PREPARED && state_ != STOPPED && state_ != PAUSED) {
1365 AUDIO_ERR_LOG("Start failed Illegal state: %{public}d", state_.load());
1366 return false;
1367 }
1368
1369 if (audioStreamTracker_ && audioStreamTracker_.get()) {
1370 audioStreamTracker_->FetchInputDeviceForTrack(sessionId_, RUNNING, clientPid_, capturerInfo_);
1371 }
1372
1373 CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, false, "ipcStream is not inited!");
1374 int32_t ret = ipcStream_->Start();
1375 if (ret != SUCCESS) {
1376 AUDIO_ERR_LOG("Start call server failed: %{public}u", ret);
1377 return false;
1378 }
1379
1380 std::unique_lock<std::mutex> waitLock(callServerMutex_);
1381 bool stopWaiting = callServerCV_.wait_for(waitLock, std::chrono::milliseconds(OPERATION_TIMEOUT_IN_MS), [this] {
1382 return notifiedOperation_ == START_STREAM; // will be false when got notified.
1383 });
1384
1385 if (notifiedOperation_ != START_STREAM || notifiedResult_ != SUCCESS) {
1386 AUDIO_ERR_LOG("Start failed: %{public}s Operation:%{public}d result:%{public}" PRId64".",
1387 (!stopWaiting ? "timeout" : "no timeout"), notifiedOperation_, notifiedResult_);
1388 return false;
1389 }
1390 waitLock.unlock();
1391
1392 state_ = RUNNING; // change state_ to RUNNING, then notify cbThread
1393 if (capturerMode_ == CAPTURE_MODE_CALLBACK) {
1394 if (cbBufferQueue_.IsEmpty()) {
1395 cbBufferQueue_.Push({cbBuffer_.get(), cbBufferSize_, cbBufferSize_});
1396 }
1397 // start the callback-write thread
1398 cbThreadCv_.notify_all();
1399 }
1400 statusLock.unlock();
1401 // in plan: call HiSysEventWrite
1402 int64_t param = -1;
1403 StateCmdTypeToParams(param, state_, cmdType);
1404 SafeSendCallbackEvent(STATE_CHANGE_EVENT, param);
1405
1406 AUDIO_INFO_LOG("Start SUCCESS, sessionId: %{public}d, uid: %{public}d", sessionId_, clientUid_);
1407 UpdateTracker("RUNNING");
1408 return true;
1409 }
1410
PauseAudioStream(StateChangeCmdType cmdType)1411 bool CapturerInClientInner::PauseAudioStream(StateChangeCmdType cmdType)
1412 {
1413 Trace trace("CapturerInClientInner::PauseAudioStream " + std::to_string(sessionId_));
1414 std::unique_lock<std::mutex> statusLock(statusMutex_);
1415 if (state_ != RUNNING) {
1416 AUDIO_ERR_LOG("Pause State is not RUNNING. Illegal state:%{public}u", state_.load());
1417 return false;
1418 }
1419
1420 CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, false, "ipcStream is not inited!");
1421 int32_t ret = ipcStream_->Pause();
1422 if (ret != SUCCESS) {
1423 AUDIO_ERR_LOG("Pause call server failed:%{public}u", ret);
1424 return false;
1425 }
1426 std::unique_lock<std::mutex> waitLock(callServerMutex_);
1427 bool stopWaiting = callServerCV_.wait_for(waitLock, std::chrono::milliseconds(OPERATION_TIMEOUT_IN_MS), [this] {
1428 return notifiedOperation_ == PAUSE_STREAM; // will be false when got notified.
1429 });
1430
1431 if (notifiedOperation_ != PAUSE_STREAM || notifiedResult_ != SUCCESS) {
1432 AUDIO_ERR_LOG("Pause failed: %{public}s Operation:%{public}d result:%{public}" PRId64".",
1433 (!stopWaiting ? "timeout" : "no timeout"), notifiedOperation_, notifiedResult_);
1434 return false;
1435 }
1436 waitLock.unlock();
1437
1438 state_ = PAUSED;
1439 statusLock.unlock();
1440
1441 // waiting for review: use send event to clent with cmdType | call OnStateChange | call HiSysEventWrite
1442 int64_t param = -1;
1443 StateCmdTypeToParams(param, state_, cmdType);
1444 SafeSendCallbackEvent(STATE_CHANGE_EVENT, param);
1445
1446 AUDIO_INFO_LOG("Pause SUCCESS, sessionId: %{public}d, uid: %{public}d, mode %{public}s", sessionId_, clientUid_,
1447 capturerMode_ == CAPTURE_MODE_NORMAL ? "CAPTURE_MODE_NORMAL" : "CAPTURE_MODE_CALLBACK");
1448 UpdateTracker("PAUSED");
1449 return true;
1450 }
1451
StopAudioStream()1452 bool CapturerInClientInner::StopAudioStream()
1453 {
1454 Trace trace("CapturerInClientInner::StopAudioStream " + std::to_string(sessionId_));
1455 AUDIO_INFO_LOG("Stop begin for sessionId %{public}d uid: %{public}d", sessionId_, clientUid_);
1456 std::unique_lock<std::mutex> statusLock(statusMutex_);
1457 if (state_ == STOPPED) {
1458 AUDIO_INFO_LOG("Capturer in client is already stopped");
1459 return true;
1460 }
1461 if ((state_ != RUNNING) && (state_ != PAUSED)) {
1462 AUDIO_ERR_LOG("Stop failed. Illegal state:%{public}u", state_.load());
1463 return false;
1464 }
1465
1466 CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, false, "ipcStream is not inited!");
1467 int32_t ret = ipcStream_->Stop();
1468 if (ret != SUCCESS) {
1469 AUDIO_ERR_LOG("Stop call server failed:%{public}u", ret);
1470 return false;
1471 }
1472
1473 if (capturerMode_ == CAPTURE_MODE_CALLBACK) {
1474 state_ = STOPPING;
1475 AUDIO_INFO_LOG("Stop begin in callback mode sessionId %{public}d uid: %{public}d", sessionId_, clientUid_);
1476 }
1477
1478 std::unique_lock<std::mutex> waitLock(callServerMutex_);
1479 bool stopWaiting = callServerCV_.wait_for(waitLock, std::chrono::milliseconds(OPERATION_TIMEOUT_IN_MS), [this] {
1480 return notifiedOperation_ == STOP_STREAM; // will be false when got notified.
1481 });
1482
1483 if (notifiedOperation_ != STOP_STREAM || notifiedResult_ != SUCCESS) {
1484 AUDIO_ERR_LOG("Stop failed: %{public}s Operation:%{public}d result:%{public}" PRId64".",
1485 (!stopWaiting ? "timeout" : "no timeout"), notifiedOperation_, notifiedResult_);
1486 state_ = INVALID;
1487 return false;
1488 }
1489 waitLock.unlock();
1490
1491 state_ = STOPPED;
1492 statusLock.unlock();
1493
1494 SafeSendCallbackEvent(STATE_CHANGE_EVENT, state_);
1495
1496 AUDIO_INFO_LOG("Stop SUCCESS, sessionId: %{public}d, uid: %{public}d", sessionId_, clientUid_);
1497 UpdateTracker("STOPPED");
1498 return true;
1499 }
1500
ReleaseAudioStream(bool releaseRunner,bool isSwitchStream)1501 bool CapturerInClientInner::ReleaseAudioStream(bool releaseRunner, bool isSwitchStream)
1502 {
1503 (void)isSwitchStream;
1504 std::unique_lock<std::mutex> statusLock(statusMutex_);
1505 if (state_ == RELEASED) {
1506 AUDIO_WARNING_LOG("Already release, do nothing");
1507 return true;
1508 }
1509 state_ = RELEASED;
1510 statusLock.unlock();
1511
1512 Trace trace("CapturerInClientInner::ReleaseAudioStream " + std::to_string(sessionId_));
1513 if (ipcStream_ != nullptr) {
1514 ipcStream_->Release();
1515 } else {
1516 AUDIO_WARNING_LOG("Release while ipcStream is null");
1517 }
1518
1519 // no lock, call release in any case, include blocked case.
1520 {
1521 std::lock_guard<std::mutex> runnerlock(runnerMutex_);
1522 if (releaseRunner && callbackHandler_ != nullptr) {
1523 AUDIO_INFO_LOG("runner remove");
1524 callbackHandler_->ReleaseEventRunner();
1525 runnerReleased_ = true;
1526 callbackHandler_ = nullptr;
1527 }
1528 }
1529
1530 // clear write callback
1531 if (capturerMode_ == CAPTURE_MODE_CALLBACK) {
1532 cbThreadReleased_ = true; // stop loop
1533 if (cbBufferQueue_.IsEmpty()) {
1534 cbBufferQueue_.PushNoWait({nullptr, 0, 0});
1535 }
1536 cbThreadCv_.notify_all();
1537 readDataCV_.notify_all();
1538 if (callbackLoop_.joinable()) {
1539 callbackLoop_.detach();
1540 }
1541 }
1542 paramsIsSet_ = false;
1543
1544 std::unique_lock<std::mutex> lock(streamCbMutex_);
1545 std::shared_ptr<AudioStreamCallback> streamCb = streamCallback_.lock();
1546 if (streamCb != nullptr) {
1547 AUDIO_INFO_LOG("Notify client the state is released");
1548 streamCb->OnStateChange(RELEASED, CMD_FROM_CLIENT);
1549 }
1550 lock.unlock();
1551
1552 UpdateTracker("RELEASED");
1553 AUDIO_INFO_LOG("Release end, sessionId: %{public}d, uid: %{public}d", sessionId_, clientUid_);
1554 return true;
1555 }
1556
FlushAudioStream()1557 bool CapturerInClientInner::FlushAudioStream()
1558 {
1559 Trace trace("CapturerInClientInner::FlushAudioStream " + std::to_string(sessionId_));
1560 std::unique_lock<std::mutex> statusLock(statusMutex_);
1561 if ((state_ != RUNNING) && (state_ != PAUSED) && (state_ != STOPPED)) {
1562 AUDIO_ERR_LOG("Flush failed. Illegal state:%{public}u", state_.load());
1563 return false;
1564 }
1565 CHECK_AND_RETURN_RET_LOG(FlushRingCache() == SUCCESS, false, "Flush cache failed");
1566
1567 CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, false, "ipcStream is not inited!");
1568 int32_t ret = ipcStream_->Flush();
1569 if (ret != SUCCESS) {
1570 AUDIO_ERR_LOG("Flush call server failed:%{public}u", ret);
1571 return false;
1572 }
1573 std::unique_lock<std::mutex> waitLock(callServerMutex_);
1574 bool stopWaiting = callServerCV_.wait_for(waitLock, std::chrono::milliseconds(OPERATION_TIMEOUT_IN_MS), [this] {
1575 return notifiedOperation_ == FLUSH_STREAM; // will be false when got notified.
1576 });
1577
1578 if (notifiedOperation_ != FLUSH_STREAM || notifiedResult_ != SUCCESS) {
1579 AUDIO_ERR_LOG("Flush failed: %{public}s Operation:%{public}d result:%{public}" PRId64".",
1580 (!stopWaiting ? "timeout" : "no timeout"), notifiedOperation_, notifiedResult_);
1581 notifiedOperation_ = MAX_OPERATION_CODE;
1582 return false;
1583 }
1584 notifiedOperation_ = MAX_OPERATION_CODE;
1585 waitLock.unlock();
1586 AUDIO_INFO_LOG("Flush stream SUCCESS, sessionId: %{public}d", sessionId_);
1587 return true;
1588 }
1589
FlushRingCache()1590 int32_t CapturerInClientInner::FlushRingCache()
1591 {
1592 ringCache_->ResetBuffer();
1593 return SUCCESS;
1594 }
1595
DrainAudioStream(bool stopFlag)1596 bool CapturerInClientInner::DrainAudioStream(bool stopFlag)
1597 {
1598 AUDIO_ERR_LOG("Drain is not supported");
1599 return false;
1600 }
1601
SetPreferredFrameSize(int32_t frameSize)1602 void CapturerInClientInner::SetPreferredFrameSize(int32_t frameSize)
1603 {
1604 AUDIO_WARNING_LOG("Not Supported Yet");
1605 }
1606
UpdateLatencyTimestamp(std::string & timestamp,bool isRenderer)1607 void CapturerInClientInner::UpdateLatencyTimestamp(std::string ×tamp, bool isRenderer)
1608 {
1609 sptr<IStandardAudioService> gasp = CapturerInClientInner::GetAudioServerProxy();
1610 if (gasp == nullptr) {
1611 AUDIO_ERR_LOG("LatencyMeas failed to get AudioServerProxy");
1612 return;
1613 }
1614 gasp->UpdateLatencyTimestamp(timestamp, isRenderer);
1615 }
1616
SetRendererFirstFrameWritingCallback(const std::shared_ptr<AudioRendererFirstFrameWritingCallback> & callback)1617 int32_t CapturerInClientInner::SetRendererFirstFrameWritingCallback(
1618 const std::shared_ptr<AudioRendererFirstFrameWritingCallback> &callback)
1619 {
1620 AUDIO_ERR_LOG("SetRendererFirstFrameWritingCallback is not supported for capturer");
1621 return ERR_INVALID_OPERATION;
1622 }
1623
OnFirstFrameWriting()1624 void CapturerInClientInner::OnFirstFrameWriting()
1625 {
1626 AUDIO_ERR_LOG("OnFirstFrameWriting is not supported for capturer");
1627 }
1628
Write(uint8_t * pcmBuffer,size_t pcmBufferSize,uint8_t * metaBuffer,size_t metaBufferSize)1629 int32_t CapturerInClientInner::Write(uint8_t *pcmBuffer, size_t pcmBufferSize, uint8_t *metaBuffer,
1630 size_t metaBufferSize)
1631 {
1632 AUDIO_ERR_LOG("Write is not supported");
1633 return ERR_INVALID_OPERATION;
1634 }
1635
Write(uint8_t * buffer,size_t bufferSize)1636 int32_t CapturerInClientInner::Write(uint8_t *buffer, size_t bufferSize)
1637 {
1638 AUDIO_ERR_LOG("Write is not supported");
1639 return ERR_INVALID_OPERATION;
1640 }
1641
HandleCapturerRead(size_t & readSize,size_t & userSize,uint8_t & buffer,bool isBlockingRead)1642 int32_t CapturerInClientInner::HandleCapturerRead(size_t &readSize, size_t &userSize, uint8_t &buffer,
1643 bool isBlockingRead)
1644 {
1645 Trace trace("CapturerInClientInner::HandleCapturerRead " + std::to_string(userSize));
1646 while (readSize < userSize) {
1647 AUDIO_DEBUG_LOG("readSize %{public}zu < userSize %{public}zu", readSize, userSize);
1648 OptResult result = ringCache_->GetReadableSize();
1649 CHECK_AND_RETURN_RET_LOG(result.ret == OPERATION_SUCCESS, ERROR, "GetReadableSize err %{public}d", result.ret);
1650 size_t readableSize = std::min(result.size, userSize - readSize);
1651 if (readSize + result.size >= userSize) { // If ringCache is sufficient
1652 result = ringCache_->Dequeue({&buffer + (readSize), readableSize});
1653 CHECK_AND_RETURN_RET_LOG(result.ret == OPERATION_SUCCESS, ERROR, "DequeueCache err %{public}d", result.ret);
1654 readSize += readableSize;
1655 return readSize; // data size
1656 }
1657 if (result.size != 0) {
1658 result = ringCache_->Dequeue({&buffer + readSize, result.size});
1659 CHECK_AND_RETURN_RET_LOG(result.ret == OPERATION_SUCCESS, ERROR, "Dequeue failed %{public}d", result.ret);
1660 readSize += result.size;
1661 }
1662 uint64_t availableSizeInFrame = clientBuffer_->GetCurWriteFrame() - clientBuffer_->GetCurReadFrame();
1663 AUDIO_DEBUG_LOG("availableSizeInFrame %{public}" PRId64 "", availableSizeInFrame);
1664 if (availableSizeInFrame > 0) { // If OHAudioBuffer has data
1665 BufferDesc currentOHBuffer_ = {};
1666 clientBuffer_->GetReadbuffer(clientBuffer_->GetCurReadFrame(), currentOHBuffer_);
1667 BufferWrap bufferWrap = {currentOHBuffer_.buffer, clientSpanSizeInByte_};
1668 ringCache_->Enqueue(bufferWrap);
1669 memset_s(static_cast<void *>(bufferWrap.dataPtr), bufferWrap.dataSize, 0, bufferWrap.dataSize);
1670 clientBuffer_->SetCurReadFrame(clientBuffer_->GetCurReadFrame() + spanSizeInFrame_);
1671 } else {
1672 if (!isBlockingRead) {
1673 return readSize; // Return buffer immediately
1674 }
1675 // wait for server read some data
1676 std::unique_lock<std::mutex> readLock(readDataMutex_);
1677 bool isTimeout = !readDataCV_.wait_for(readLock,
1678 std::chrono::milliseconds(OPERATION_TIMEOUT_IN_MS), [this] {
1679 return clientBuffer_->GetCurWriteFrame() > clientBuffer_->GetCurReadFrame() || state_ != RUNNING;
1680 });
1681 CHECK_AND_RETURN_RET_LOG(state_ == RUNNING, ERR_ILLEGAL_STATE, "State is not running");
1682 CHECK_AND_RETURN_RET_LOG(isTimeout == false, ERROR, "Wait timeout");
1683 }
1684 }
1685 return readSize;
1686 }
1687
Read(uint8_t & buffer,size_t userSize,bool isBlockingRead)1688 int32_t CapturerInClientInner::Read(uint8_t &buffer, size_t userSize, bool isBlockingRead)
1689 {
1690 Trace trace("CapturerInClientInner::Read " + std::to_string(userSize));
1691
1692 CHECK_AND_RETURN_RET_LOG(userSize < MAX_CLIENT_READ_SIZE && userSize > 0,
1693 ERR_INVALID_PARAM, "invalid size %{public}zu", userSize);
1694
1695 std::unique_lock<std::mutex> statusLock(statusMutex_); // status check
1696 if (state_ != RUNNING) {
1697 if (readLogTimes_ < LOGLITMITTIMES) {
1698 readLogTimes_.fetch_add(1);
1699 AUDIO_ERR_LOG("Illegal state:%{public}u", state_.load());
1700 } else {
1701 AUDIO_DEBUG_LOG("Illegal state:%{public}u", state_.load());
1702 }
1703 return ERR_ILLEGAL_STATE;
1704 } else {
1705 readLogTimes_ = 0;
1706 }
1707
1708 statusLock.unlock();
1709
1710 std::lock_guard<std::mutex> lock(readMutex_);
1711 // if first call, call set thread priority. if thread tid change recall set thread priority
1712 if (needSetThreadPriority_) {
1713 CHECK_AND_RETURN_RET_LOG(ipcStream_ != nullptr, ERROR, "ipcStream_ is null");
1714 ipcStream_->RegisterThreadPriority(gettid(),
1715 AudioSystemManager::GetInstance()->GetSelfBundleName(clientConfig_.appInfo.appUid));
1716 needSetThreadPriority_ = false;
1717 }
1718
1719 size_t readSize = 0;
1720 int32_t res = HandleCapturerRead(readSize, userSize, buffer, isBlockingRead);
1721 CHECK_AND_RETURN_RET_LOG(res >= 0, ERROR, "HandleCapturerRead err : %{public}d", res);
1722 BufferDesc tmpBuffer = {reinterpret_cast<uint8_t *>(&buffer), userSize, userSize};
1723 VolumeTools::DfxOperation(tmpBuffer, clientConfig_.streamInfo, logUtilsTag_, volumeDataCount_);
1724 HandleCapturerPositionChanges(readSize);
1725 return readSize;
1726 }
1727
HandleCapturerPositionChanges(size_t bytesRead)1728 void CapturerInClientInner::HandleCapturerPositionChanges(size_t bytesRead)
1729 {
1730 totalBytesRead_ += bytesRead;
1731 if (sizePerFrameInByte_ == 0) {
1732 AUDIO_ERR_LOG("HandleCapturerPositionChanges: sizePerFrameInByte_ is 0");
1733 return;
1734 }
1735 uint64_t readFrameNumber = totalBytesRead_ / sizePerFrameInByte_;
1736 AUDIO_DEBUG_LOG("totalBytesRead_ %{public}" PRId64 ", frame size: %{public}zu", totalBytesRead_,
1737 sizePerFrameInByte_);
1738 {
1739 std::lock_guard<std::mutex> lock(markReachMutex_);
1740 if (!capturerMarkReached_) {
1741 AUDIO_DEBUG_LOG("Frame mark position: %{public}" PRId64 ", Total frames read: %{public}" PRId64,
1742 capturerMarkPosition_, static_cast<int64_t>(readFrameNumber));
1743 if (readFrameNumber >= static_cast<uint64_t>(capturerMarkPosition_)) {
1744 AUDIO_DEBUG_LOG("capturerInClient OnMarkReached");
1745 SendCapturerMarkReachedEvent(capturerMarkPosition_);
1746 capturerMarkReached_ = true;
1747 }
1748 }
1749 }
1750
1751 {
1752 std::lock_guard<std::mutex> lock(periodReachMutex_);
1753 capturerPeriodRead_ += static_cast<int64_t>(bytesRead / sizePerFrameInByte_);
1754 AUDIO_DEBUG_LOG("Frame period number: %{public}" PRId64 ", Total frames written: %{public}" PRId64,
1755 static_cast<int64_t>(capturerPeriodRead_), static_cast<int64_t>(totalBytesRead_));
1756 if (capturerPeriodRead_ >= capturerPeriodSize_ && capturerPeriodSize_ > 0) {
1757 capturerPeriodRead_ %= capturerPeriodSize_;
1758 AUDIO_DEBUG_LOG("OnPeriodReached, remaining frames: %{public}" PRId64,
1759 static_cast<int64_t>(capturerPeriodRead_));
1760 SendCapturerPeriodReachedEvent(capturerPeriodSize_);
1761 }
1762 }
1763 }
1764
GetUnderflowCount()1765 uint32_t CapturerInClientInner::GetUnderflowCount()
1766 {
1767 // not supported for capturer
1768 AUDIO_WARNING_LOG("No Underflow in Capturer");
1769 return 0;
1770 }
1771
GetOverflowCount()1772 uint32_t CapturerInClientInner::GetOverflowCount()
1773 {
1774 return overflowCount_;
1775 }
1776
SetUnderflowCount(uint32_t underflowCount)1777 void CapturerInClientInner::SetUnderflowCount(uint32_t underflowCount)
1778 {
1779 // not supported for capturer
1780 AUDIO_WARNING_LOG("No Underflow in Capturer");
1781 return;
1782 }
1783
SetOverflowCount(uint32_t overflowCount)1784 void CapturerInClientInner::SetOverflowCount(uint32_t overflowCount)
1785 {
1786 overflowCount_ = overflowCount;
1787 }
1788
SetCapturerPositionCallback(int64_t markPosition,const std::shared_ptr<CapturerPositionCallback> & callback)1789 void CapturerInClientInner::SetCapturerPositionCallback(int64_t markPosition, const
1790 std::shared_ptr<CapturerPositionCallback> &callback)
1791 {
1792 std::lock_guard<std::mutex> lock(markReachMutex_);
1793 CHECK_AND_RETURN_LOG(callback != nullptr, "CapturerPositionCallback is nullptr");
1794 capturerPositionCallback_ = callback;
1795 capturerMarkPosition_ = markPosition;
1796 capturerMarkReached_ = false;
1797 }
1798
UnsetCapturerPositionCallback()1799 void CapturerInClientInner::UnsetCapturerPositionCallback()
1800 {
1801 std::lock_guard<std::mutex> lock(markReachMutex_);
1802 capturerPositionCallback_ = nullptr;
1803 capturerMarkPosition_ = 0;
1804 capturerMarkReached_ = false;
1805 }
1806
SetCapturerPeriodPositionCallback(int64_t periodPosition,const std::shared_ptr<CapturerPeriodPositionCallback> & callback)1807 void CapturerInClientInner::SetCapturerPeriodPositionCallback(int64_t periodPosition,
1808 const std::shared_ptr<CapturerPeriodPositionCallback> &callback)
1809 {
1810 std::lock_guard<std::mutex> lock(periodReachMutex_);
1811 CHECK_AND_RETURN_LOG(callback != nullptr, "CapturerPeriodPositionCallback is nullptr");
1812 capturerPeriodPositionCallback_ = callback;
1813 capturerPeriodSize_ = periodPosition;
1814 totalBytesRead_ = 0;
1815 capturerPeriodRead_ = 0;
1816 }
1817
UnsetCapturerPeriodPositionCallback()1818 void CapturerInClientInner::UnsetCapturerPeriodPositionCallback()
1819 {
1820 std::lock_guard<std::mutex> lock(periodReachMutex_);
1821 capturerPeriodPositionCallback_ = nullptr;
1822 capturerPeriodSize_ = 0;
1823 totalBytesRead_ = 0;
1824 capturerPeriodRead_ = 0;
1825 }
1826
SetRendererPositionCallback(int64_t markPosition,const std::shared_ptr<RendererPositionCallback> & callback)1827 void CapturerInClientInner::SetRendererPositionCallback(int64_t markPosition,
1828 const std::shared_ptr<RendererPositionCallback> &callback)
1829 {
1830 AUDIO_ERR_LOG("SetRendererPositionCallback is not supported");
1831 return;
1832 }
1833
UnsetRendererPositionCallback()1834 void CapturerInClientInner::UnsetRendererPositionCallback()
1835 {
1836 AUDIO_ERR_LOG("UnsetRendererPositionCallback is not supported");
1837 return;
1838 }
1839
SetRendererPeriodPositionCallback(int64_t periodPosition,const std::shared_ptr<RendererPeriodPositionCallback> & callback)1840 void CapturerInClientInner::SetRendererPeriodPositionCallback(int64_t periodPosition,
1841 const std::shared_ptr<RendererPeriodPositionCallback> &callback)
1842 {
1843 AUDIO_ERR_LOG("SetRendererPeriodPositionCallback is not supported");
1844 return;
1845 }
1846
UnsetRendererPeriodPositionCallback()1847 void CapturerInClientInner::UnsetRendererPeriodPositionCallback()
1848 {
1849 AUDIO_ERR_LOG("UnsetRendererPeriodPositionCallback is not supported");
1850 return;
1851 }
1852
SetRendererSamplingRate(uint32_t sampleRate)1853 int32_t CapturerInClientInner::SetRendererSamplingRate(uint32_t sampleRate)
1854 {
1855 // in plan
1856 return ERROR;
1857 }
1858
GetRendererSamplingRate()1859 uint32_t CapturerInClientInner::GetRendererSamplingRate()
1860 {
1861 // in plan
1862 return 0; // not supported
1863 }
1864
SetBufferSizeInMsec(int32_t bufferSizeInMsec)1865 int32_t CapturerInClientInner::SetBufferSizeInMsec(int32_t bufferSizeInMsec)
1866 {
1867 // bufferSizeInMsec is checked between 5ms and 20ms.
1868 bufferSizeInMsec_ = bufferSizeInMsec;
1869 AUDIO_INFO_LOG("SetBufferSizeInMsec to %{public}d", bufferSizeInMsec_);
1870 if (capturerMode_ == CAPTURE_MODE_CALLBACK) {
1871 uint64_t bufferDurationInUs = static_cast<uint64_t>(bufferSizeInMsec_ * AUDIO_US_PER_MS);
1872 InitCallbackBuffer(bufferDurationInUs);
1873 }
1874 return SUCCESS;
1875 }
1876
SetChannelBlendMode(ChannelBlendMode blendMode)1877 int32_t CapturerInClientInner::SetChannelBlendMode(ChannelBlendMode blendMode)
1878 {
1879 AUDIO_WARNING_LOG("not supported in capturer");
1880 return ERROR;
1881 }
1882
SetVolumeWithRamp(float volume,int32_t duration)1883 int32_t CapturerInClientInner::SetVolumeWithRamp(float volume, int32_t duration)
1884 {
1885 AUDIO_WARNING_LOG("not supported in capturer");
1886 return ERROR;
1887 }
1888
SetStreamTrackerState(bool trackerRegisteredState)1889 void CapturerInClientInner::SetStreamTrackerState(bool trackerRegisteredState)
1890 {
1891 streamTrackerRegistered_ = trackerRegisteredState;
1892 }
1893
GetSwitchInfo(IAudioStream::SwitchInfo & info)1894 void CapturerInClientInner::GetSwitchInfo(IAudioStream::SwitchInfo& info)
1895 {
1896 info.params = streamParams_;
1897
1898 info.rendererInfo = rendererInfo_;
1899 info.capturerInfo = capturerInfo_;
1900 info.eStreamType = eStreamType_;
1901 info.state = state_;
1902 info.sessionId = sessionId_;
1903 info.streamTrackerRegistered = streamTrackerRegistered_;
1904 GetStreamSwitchInfo(info);
1905 }
1906
GetStreamSwitchInfo(IAudioStream::SwitchInfo & info)1907 void CapturerInClientInner::GetStreamSwitchInfo(IAudioStream::SwitchInfo& info)
1908 {
1909 info.overFlowCount = overflowCount_;
1910 info.clientPid = clientPid_;
1911 info.clientUid = clientUid_;
1912
1913 info.frameMarkPosition = static_cast<uint64_t>(capturerMarkPosition_);
1914 info.capturePositionCb = capturerPositionCallback_;
1915
1916 info.framePeriodNumber = static_cast<uint64_t>(capturerPeriodSize_);
1917 info.capturePeriodPositionCb = capturerPeriodPositionCallback_;
1918
1919 info.capturerReadCallback = readCb_;
1920 }
1921
GetOffloadEnable()1922 bool CapturerInClientInner::GetOffloadEnable()
1923 {
1924 AUDIO_WARNING_LOG("not supported in capturer");
1925 return false;
1926 }
1927
GetSpatializationEnabled()1928 bool CapturerInClientInner::GetSpatializationEnabled()
1929 {
1930 AUDIO_WARNING_LOG("not supported in capturer");
1931 return false;
1932 }
1933
GetHighResolutionEnabled()1934 bool CapturerInClientInner::GetHighResolutionEnabled()
1935 {
1936 AUDIO_WARNING_LOG("not supported in capturer");
1937 return false;
1938 }
1939
GetStreamClass()1940 IAudioStream::StreamClass CapturerInClientInner::GetStreamClass()
1941 {
1942 return PA_STREAM;
1943 }
1944
SetSilentModeAndMixWithOthers(bool on)1945 void CapturerInClientInner::SetSilentModeAndMixWithOthers(bool on)
1946 {
1947 AUDIO_WARNING_LOG("not supported in capturer");
1948 return;
1949 }
1950
GetSilentModeAndMixWithOthers()1951 bool CapturerInClientInner::GetSilentModeAndMixWithOthers()
1952 {
1953 AUDIO_WARNING_LOG("not supported in capturer");
1954 return false;
1955 }
1956
RestoreAudioStream(bool needStoreState)1957 bool CapturerInClientInner::RestoreAudioStream(bool needStoreState)
1958 {
1959 CHECK_AND_RETURN_RET_LOG(proxyObj_ != nullptr, false, "proxyObj_ is null");
1960 CHECK_AND_RETURN_RET_LOG(state_ != NEW && state_ != INVALID && state_ != RELEASED, true,
1961 "state_ is %{public}d, no need for restore", state_.load());
1962 bool result = false;
1963 State oldState = state_;
1964 state_ = NEW;
1965 SetStreamTrackerState(false);
1966
1967 int32_t ret = SetAudioStreamInfo(streamParams_, proxyObj_);
1968 if (ret != SUCCESS) {
1969 goto error;
1970 }
1971 #ifdef HAS_FEATURE_INNERCAPTURER
1972 // for inner-capturer
1973 if (capturerInfo_.sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE) {
1974 ret = UpdatePlaybackCaptureConfig(filterConfig_);
1975 if (ret != SUCCESS) {
1976 goto error;
1977 }
1978 }
1979 #endif
1980 switch (oldState) {
1981 case RUNNING:
1982 result = StartAudioStream();
1983 break;
1984 case PAUSED:
1985 result = StartAudioStream() && PauseAudioStream();
1986 break;
1987 case STOPPED:
1988 case STOPPING:
1989 result = StartAudioStream() && StopAudioStream();
1990 break;
1991 default:
1992 break;
1993 }
1994 if (!result) {
1995 goto error;
1996 }
1997 return result;
1998
1999 error:
2000 AUDIO_ERR_LOG("RestoreAudioStream failed");
2001 state_ = oldState;
2002 return false;
2003 }
2004
SetDefaultOutputDevice(const DeviceType defaultOutputDevice)2005 int32_t CapturerInClientInner::SetDefaultOutputDevice(const DeviceType defaultOutputDevice)
2006 {
2007 (void)defaultOutputDevice;
2008 AUDIO_WARNING_LOG("not supported in capturer");
2009 return ERROR;
2010 }
2011
GetDefaultOutputDevice()2012 DeviceType CapturerInClientInner::GetDefaultOutputDevice()
2013 {
2014 AUDIO_WARNING_LOG("not supported in capturer");
2015 return DEVICE_TYPE_NONE;
2016 }
2017
2018 // diffrence from GetAudioPosition only when set speed
GetAudioTimestampInfo(Timestamp & timestamp,Timestamp::Timestampbase base)2019 int32_t CapturerInClientInner::GetAudioTimestampInfo(Timestamp ×tamp, Timestamp::Timestampbase base)
2020 {
2021 return GetAudioTime(timestamp, base);
2022 }
2023
SetSwitchingStatus(bool isSwitching)2024 void CapturerInClientInner::SetSwitchingStatus(bool isSwitching)
2025 {
2026 AUDIO_WARNING_LOG("not supported in capturer");
2027 }
2028
GetRestoreInfo(RestoreInfo & restoreInfo)2029 void CapturerInClientInner::GetRestoreInfo(RestoreInfo &restoreInfo)
2030 {
2031 CHECK_AND_RETURN_LOG(clientBuffer_ != nullptr, "Client OHAudioBuffer is nullptr");
2032 clientBuffer_->GetRestoreInfo(restoreInfo);
2033 return;
2034 }
2035
SetRestoreInfo(RestoreInfo & restoreInfo)2036 void CapturerInClientInner::SetRestoreInfo(RestoreInfo &restoreInfo)
2037 {
2038 CHECK_AND_RETURN_LOG(clientBuffer_ != nullptr, "Client OHAudioBuffer is nullptr");
2039 clientBuffer_->SetRestoreInfo(restoreInfo);
2040 return;
2041 }
2042
CheckRestoreStatus()2043 RestoreStatus CapturerInClientInner::CheckRestoreStatus()
2044 {
2045 CHECK_AND_RETURN_RET_LOG(clientBuffer_ != nullptr, RESTORE_ERROR, "Client OHAudioBuffer is nullptr");
2046 return clientBuffer_->CheckRestoreStatus();
2047 }
2048
SetRestoreStatus(RestoreStatus restoreStatus)2049 RestoreStatus CapturerInClientInner::SetRestoreStatus(RestoreStatus restoreStatus)
2050 {
2051 CHECK_AND_RETURN_RET_LOG(clientBuffer_ != nullptr, RESTORE_ERROR, "Client OHAudioBuffer is nullptr");
2052 return clientBuffer_->SetRestoreStatus(restoreStatus);
2053 }
2054
FetchDeviceForSplitStream()2055 void CapturerInClientInner::FetchDeviceForSplitStream()
2056 {
2057 AUDIO_INFO_LOG("Fetch input device for split stream %{public}u", sessionId_);
2058 if (audioStreamTracker_ && audioStreamTracker_.get()) {
2059 audioStreamTracker_->FetchInputDeviceForTrack(sessionId_, state_, clientPid_, capturerInfo_);
2060 } else {
2061 AUDIO_WARNING_LOG("Tracker is nullptr, fail to split stream %{public}u", sessionId_);
2062 }
2063 SetRestoreStatus(NO_NEED_FOR_RESTORE);
2064 }
2065 } // namespace AudioStandard
2066 } // namespace OHOS
2067 #endif // FAST_AUDIO_STREAM_H
2068