1 /*
2  * Copyright (C) 2023 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 #pragma once
18 
19 #include <stddef.h>
20 #include <stdint.h>
21 
22 #include <queue>
23 #include <thread>
24 
25 class BufferWriterQueue {
26 public:
27     constexpr static int kDelayOnFailedWriteMs = 5;
28     constexpr static int kQueueMaxSizeLimit = 4800;  // 2X max_dgram_qlen
29 
30     BufferWriterQueue();
31     virtual ~BufferWriterQueue();
32 
33     bool write(const uint8_t* buffer, size_t size, uint32_t atomId);
34 
35     size_t getQueueSize() const;
36 
37     void drainQueue();
38 
39     struct Cmd {
40         uint8_t* buffer = NULL;
41         int atomId = 0;
42         int size = 0;
43     };
44 
45     virtual bool handleCommand(const Cmd& cmd) const;
46 
47 private:
48     std::condition_variable mCondition;
49     mutable std::mutex mMutex;
50     std::queue<Cmd> mCmdQueue;
51     std::atomic_bool mDoTerminate = false;
52     std::thread mWorkThread;
53 
54     static Cmd createWriteBufferCmd(const uint8_t* buffer, size_t size, uint32_t atomId);
55 
56     bool pushToQueue(const Cmd& cmd);
57 
58     void terminate();
59 
60     void processCommands();
61 };
62