Audacity 3.2.0
FifoBuffer.cpp
Go to the documentation of this file.
1/**********************************************************************
2
3 Audacity: A Digital Audio Editor
4
5 FifoBuffer.h
6
7 Dmitry Vedenko
8
9**********************************************************************/
10
11#include "FifoBuffer.h"
12
13#include <algorithm>
14
16 : Data(size)
17{
18}
19
21{
22 WritePosition = 0;
23 ReadPosition = 0;
24}
25
27 : mPageSize { pageSize }
28{
29}
30
31int64_t FifoBuffer::Write(const void* dataPtr, int64_t size)
32{
33 const int8_t* data = static_cast<const int8_t*>(dataPtr);
34
35 auto bytesLeft = size;
36
37 while (bytesLeft > 0)
38 {
39 if (
40 mActivePages.empty() ||
41 mActivePages.back()->WritePosition == mPageSize)
42 {
43 if (mFreePages.empty())
44 {
45 mAllocatedPages.emplace_back(mPageSize);
46 mFreePages.push_back(&mAllocatedPages.back());
47 }
48
49 mActivePages.push(mFreePages.back());
50 mFreePages.pop_back();
51 }
52
53 auto& page = mActivePages.back();
54 auto toWrite = std::min(
55 bytesLeft, static_cast<int64_t>(mPageSize - page->WritePosition));
56
57 std::copy(data, data + toWrite, page->Data.begin() + page->WritePosition);
58 page->WritePosition += toWrite;
59 mAvaliable += toWrite;
60
61 data += toWrite;
62 bytesLeft -= toWrite;
63 }
64
65 return size;
66}
67
68int64_t FifoBuffer::Read(void* data, int64_t size)
69{
71
72 int8_t* dataPtr = static_cast<int8_t*>(data);
73
74 int bytesRead = 0;
75
76 while (size > 0)
77 {
78 auto& page = mActivePages.front();
79 auto toRead =
80 std::min(size, static_cast<int64_t>(mPageSize - page->ReadPosition));
81
83 page->Data.begin() + page->ReadPosition,
84 page->Data.begin() + page->ReadPosition + toRead, dataPtr);
85 page->ReadPosition += toRead;
86 mAvaliable -= toRead;
87
88 dataPtr += toRead;
89 size -= toRead;
90 bytesRead += toRead;
91
92 if (page->ReadPosition == mPageSize)
93 {
94 page->Reset();
95 mFreePages.push_back(page);
96 mActivePages.pop();
97 }
98 }
99
100 return bytesRead;
101}
102
104{
105 return mAvaliable;
106}
int min(int a, int b)
FifoBuffer(int pageSize)
Definition: FifoBuffer.cpp:26
int64_t Write(const void *data, int64_t size)
Definition: FifoBuffer.cpp:31
const int mPageSize
Definition: FifoBuffer.h:45
int64_t Read(void *data, int64_t size)
Definition: FifoBuffer.cpp:68
int64_t GetAvailable() const
Definition: FifoBuffer.cpp:103
int64_t mAvaliable
Definition: FifoBuffer.h:44
std::deque< Page * > mFreePages
Definition: FifoBuffer.h:42
std::queue< Page * > mActivePages
Definition: FifoBuffer.h:41
std::deque< Page > mAllocatedPages
Definition: FifoBuffer.h:39
void copy(const T *src, T *dst, int32_t n)
Definition: VectorOps.h:40
Page(int size)
Definition: FifoBuffer.cpp:15