1 /*
2  * Copyright (C) 2024 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 
16 #include "sample_buffer_queue.h"
17 #include <chrono>
18 #include "av_codec_sample_log.h"
19 #include "av_codec_sample_error.h"
20 
21 namespace OHOS {
22 namespace MediaAVCodec {
23 namespace Sample {
QueueBuffer(const CodecBufferInfo & bufferInfo)24 int32_t SampleBufferQueue::QueueBuffer(const CodecBufferInfo& bufferInfo)
25 {
26     std::unique_lock<std::mutex> lock(mutex_);
27     bufferQueue_.emplace(bufferInfo);
28     cond_.notify_all();
29     return AVCODEC_SAMPLE_ERR_OK;
30 }
31 
DequeueBuffer(int32_t timeoutMs)32 std::optional<CodecBufferInfo> SampleBufferQueue::DequeueBuffer(int32_t timeoutMs)
33 {
34     std::unique_lock<std::mutex> lock(mutex_);
35 
36     (void)cond_.wait_for(lock, std::chrono::milliseconds(timeoutMs), [this]() { return !bufferQueue_.empty(); });
37     CHECK_AND_RETURN_RET(!bufferQueue_.empty(), std::nullopt);
38 
39     CodecBufferInfo bufferInfo = bufferQueue_.front();
40     bufferQueue_.pop();
41     frameCount_++;
42 
43     return bufferInfo;
44 }
45 
Clear()46 int32_t SampleBufferQueue::Clear()
47 {
48     std::unique_lock<std::mutex> lock(mutex_);
49     auto emptyQueue = std::queue<CodecBufferInfo>();
50     bufferQueue_.swap(emptyQueue);
51 
52     return AVCODEC_SAMPLE_ERR_OK;
53 }
54 
GetFrameCount()55 uint32_t SampleBufferQueue::GetFrameCount()
56 {
57     return frameCount_;
58 }
59 
IncFrameCount()60 uint32_t SampleBufferQueue::IncFrameCount()
61 {
62     return ++frameCount_;
63 }
64 } // Sample
65 } // MediaAVCodec
66 } // OHOS