blob: ddaabe8319ac80f399ab7808021ba766d53e557c [file] [log] [blame]
jiabin2a594622021-10-14 00:32:25 +00001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AAudioCommandQueue"
18//#define LOG_NDEBUG 0
19
20#include <chrono>
21
22#include <utils/Log.h>
23
24#include "AAudioCommandQueue.h"
25
26namespace aaudio {
27
28aaudio_result_t AAudioCommandQueue::sendCommand(std::shared_ptr<AAudioCommand> command) {
29 {
30 std::scoped_lock<std::mutex> _l(mLock);
31 mCommands.push(command);
32 mWaitWorkCond.notify_one();
33 }
34
35 std::unique_lock _cl(command->lock);
36 android::base::ScopedLockAssertion lockAssertion(command->lock);
37 ALOGV("Sending command %d, wait for reply(%d) with timeout %jd",
38 command->operationCode, command->isWaitingForReply, command->timeoutNanoseconds);
39 // `mWaitForReply` is first initialized when the command is constructed. It will be flipped
40 // when the command is completed.
41 auto timeoutExpire = std::chrono::steady_clock::now()
42 + std::chrono::nanoseconds(command->timeoutNanoseconds);
43 while (command->isWaitingForReply) {
44 if (command->conditionVariable.wait_until(_cl, timeoutExpire)
45 == std::cv_status::timeout) {
46 ALOGD("Command %d time out", command->operationCode);
47 command->result = AAUDIO_ERROR_TIMEOUT;
48 command->isWaitingForReply = false;
49 }
50 }
51 ALOGV("Command %d sent with result as %d", command->operationCode, command->result);
52 return command->result;
53}
54
55std::shared_ptr<AAudioCommand> AAudioCommandQueue::waitForCommand(int64_t timeoutNanos) {
56 std::shared_ptr<AAudioCommand> command;
57 {
58 std::unique_lock _l(mLock);
59 android::base::ScopedLockAssertion lockAssertion(mLock);
60 if (timeoutNanos >= 0) {
61 mWaitWorkCond.wait_for(_l, std::chrono::nanoseconds(timeoutNanos), [this]() {
62 android::base::ScopedLockAssertion lockAssertion(mLock);
63 return !mRunning || !mCommands.empty();
64 });
65 } else {
66 mWaitWorkCond.wait(_l, [this]() {
67 android::base::ScopedLockAssertion lockAssertion(mLock);
68 return !mRunning || !mCommands.empty();
69 });
70 }
71 if (!mCommands.empty()) {
72 command = mCommands.front();
73 mCommands.pop();
74 }
75 }
76 return command;
77}
78
79void AAudioCommandQueue::stopWaiting() {
80 std::scoped_lock<std::mutex> _l(mLock);
81 mRunning = false;
82 mWaitWorkCond.notify_one();
83}
84
85} // namespace aaudio