Linus Nilsson | cb9198e | 2020-04-01 13:38:09 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2020 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_NDEBUG 0 |
| 18 | #define LOG_TAG "MediaSampleQueue" |
| 19 | |
| 20 | #include <android-base/logging.h> |
| 21 | #include <media/MediaSampleQueue.h> |
| 22 | |
| 23 | namespace android { |
| 24 | |
| 25 | bool MediaSampleQueue::enqueue(const std::shared_ptr<MediaSample>& sample) { |
| 26 | std::scoped_lock<std::mutex> lock(mMutex); |
| 27 | if (!mAborted) { |
| 28 | mSampleQueue.push(sample); |
| 29 | mCondition.notify_one(); |
| 30 | } |
| 31 | return mAborted; |
| 32 | } |
| 33 | |
| 34 | // Unfortunately std::unique_lock is incompatible with -Wthread-safety |
| 35 | bool MediaSampleQueue::dequeue(std::shared_ptr<MediaSample>* sample) NO_THREAD_SAFETY_ANALYSIS { |
| 36 | std::unique_lock<std::mutex> lock(mMutex); |
| 37 | while (mSampleQueue.empty() && !mAborted) { |
| 38 | mCondition.wait(lock); |
| 39 | } |
| 40 | |
| 41 | if (!mAborted) { |
| 42 | if (sample != nullptr) { |
| 43 | *sample = mSampleQueue.front(); |
| 44 | } |
| 45 | mSampleQueue.pop(); |
| 46 | } |
| 47 | return mAborted; |
| 48 | } |
| 49 | |
Linus Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 50 | bool MediaSampleQueue::isEmpty() { |
| 51 | std::scoped_lock<std::mutex> lock(mMutex); |
| 52 | return mSampleQueue.empty(); |
| 53 | } |
| 54 | |
Linus Nilsson | cb9198e | 2020-04-01 13:38:09 -0700 | [diff] [blame] | 55 | void MediaSampleQueue::abort() { |
| 56 | std::scoped_lock<std::mutex> lock(mMutex); |
| 57 | // Clear the queue and notify consumers. |
| 58 | std::queue<std::shared_ptr<MediaSample>> empty = {}; |
| 59 | std::swap(mSampleQueue, empty); |
| 60 | mAborted = true; |
| 61 | mCondition.notify_all(); |
| 62 | } |
| 63 | } // namespace android |