fifo.h 6.58 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
#ifndef LMS_FIFO_BUFFER_H
#define LMS_FIFO_BUFFER_H

#include <mutex>
#include <atomic>
#include <vector>
#include <thread>
#include <condition_variable>
#include "dataTypes.h"

class LMS_SamplesFIFO
{
public:
    struct BufferInfo
    {
        uint32_t size;
        uint32_t itemsFilled;
    };

    BufferInfo GetInfo()
    {
        std::unique_lock<std::mutex> lck2(readLock);
        std::unique_lock<std::mutex> lck(writeLock);
        BufferInfo stats;
        stats.size = (uint32_t)mBuffer.size();
        stats.itemsFilled = mElementsFilled.load();
        return stats;
    }

	LMS_SamplesFIFO(uint32_t bufLength)
	{
        Reset(bufLength);
	}
	
	~LMS_SamplesFIFO(){};
	
    /** @brief inserts items to ring buffer
        @param buffer data source
        @param itemCount number of buffer items to insert
        @param timeout_ms timeout duration for operation
        @param overwrite enable to overwrite oldest items inside the buffer
        @return number of items added
    */
	uint32_t push_packet(SamplesPacket *buffer, const uint32_t itemCount, const uint32_t timeout_ms, const bool overwrite = true)
	{	
        uint32_t addedItems = 0;
        std::unique_lock<std::mutex> lck(writeLock);
        while (addedItems < itemCount)
        {            
            while (mElementsFilled.load() >= mBuffer.size()) //wait for free space to insert items
            {
                if (canWrite.wait_for(lck, std::chrono::milliseconds(timeout_ms)) == std::cv_status::timeout)
                    return addedItems; //dropped all items
            }

            uint32_t itemsToInsert = itemCount - addedItems;
            uint32_t itemsToEnd = (uint32_t)mBuffer.size() - mTail.load(); //might need to split memcpy into two operations
            if (itemsToInsert > itemsToEnd)
            {
                memcpy(&mBuffer[mTail], &buffer[addedItems], itemsToEnd*sizeof(SamplesPacket));
                memcpy(&mBuffer[0], &buffer[addedItems+itemsToEnd], (itemsToInsert - itemsToEnd)*sizeof(SamplesPacket));
            }
            else
                memcpy(&mBuffer[mTail], &buffer[addedItems], itemsToInsert*sizeof(SamplesPacket));
            mTail.store((mTail.load() + itemsToInsert) & (mBuffer.size() - 1));
            mElementsFilled.fetch_add(itemsToInsert);
            canRead.notify_one();
            addedItems += itemsToInsert;
        }
        return addedItems;
	}

    /** @brief inserts items to ring buffer
    @param buffer data source
    @param itemCount number of buffer items to insert
    @param timeout_ms timeout duration for operation
    @param overwrite enable to overwrite oldest items inside the buffer
    @return number of items added
    */
    uint32_t push_samples(const complex16_t *buffer, const uint32_t samplesCount, uint64_t timestamp, const uint32_t timeout_ms, const bool overwrite = true)
    {
        assert(buffer != nullptr);
        const int samplesInPacket = SamplesPacket::samplesCount;
        uint32_t samplesTaken = 0;
        std::unique_lock<std::mutex> lck(writeLock);
        while (samplesTaken < samplesCount)
        {   
            while (mElementsFilled.load() >= mBuffer.size()) //buffer might be full, wait for free slots
            {
                if (canWrite.wait_for(lck, std::chrono::milliseconds(timeout_ms)) == std::cv_status::timeout)
                    return samplesTaken;
            }

            int tailIndex = mTail.load(); //which element to fill
            while (mElementsFilled.load() < mBuffer.size() && samplesTaken < samplesCount) // not to release lock too often
            {
                mBuffer[tailIndex].timestamp = timestamp + samplesTaken;
                mBuffer[tailIndex].first = 0;
                mBuffer[tailIndex].last = 0;
                while (mBuffer[tailIndex].last < samplesInPacket && samplesTaken < samplesCount)
                {
                    mBuffer[tailIndex].samples[mBuffer[tailIndex].last++] = buffer[samplesTaken++];
                }
                mTail.store((tailIndex + 1) & (mBuffer.size() - 1));//advance to next one
                tailIndex = mTail.load();
                mElementsFilled.fetch_add(1);
                canRead.notify_one();
            }
        }
        return samplesTaken;
    }
	
    /** @brief Takes items out of ring buffer
        @param buffer data destination
        @param samplesCount number of samples to pop
		@param timestamp returns timestamp of the first sample in buffer
        @param timeout_ms timeout duration for operation
        @return number of samples returned
    */
    uint32_t pop_samples(complex16_t* buffer, const uint32_t samplesCount, uint64_t *timestamp, const uint32_t timeout_ms)
	{
        assert(buffer != nullptr);
        const int samplesInPacket = SamplesPacket::samplesCount;
        uint32_t samplesFilled = 0;		
		*timestamp = 0;
        std::unique_lock<std::mutex> lck(readLock);
        while (samplesFilled < samplesCount)
        {   
            while (mElementsFilled.load() == 0) //buffer might be empty, wait for packets
            {
                if (canRead.wait_for(lck, std::chrono::milliseconds(timeout_ms)) == std::cv_status::timeout)
                    return samplesFilled;
            }
			if(samplesFilled == 0)
                *timestamp = mBuffer[mHead.load()].timestamp + mBuffer[mHead.load()].first;
			
			while(mElementsFilled.load() > 0 && samplesFilled < samplesCount)
			{	
				int headIndex = mHead.load();
                while (mBuffer[headIndex].first < mBuffer[headIndex].last && samplesFilled < samplesCount)
				{
					buffer[samplesFilled++] = mBuffer[headIndex].samples[mBuffer[headIndex].first++];
				}
                if (mBuffer[headIndex].first == mBuffer[headIndex].last) //packet depleated
				{
                    mBuffer[headIndex].first = 0;
                    mBuffer[headIndex].last = 0;
                    mBuffer[headIndex].timestamp = 0;
					mHead.store( (headIndex + 1) & (mBuffer.size() - 1) );//advance to next one
                    headIndex = mHead.load();
					mElementsFilled.fetch_sub(1);
                    canWrite.notify_one();
				}
			}
        }
        return samplesFilled;
	}
	
	void Reset(uint32_t bufLength)
	{
        std::unique_lock<std::mutex> lck(writeLock);
        std::unique_lock<std::mutex> lck2(readLock);
		mBuffer.resize(bufLength);
		mHead.store(0);
		mTail.store(0);
        mElementsFilled.store(0);
	}
	
protected:
	std::vector<SamplesPacket> mBuffer;
    std::atomic<uint32_t> mHead;
    std::atomic<uint32_t> mTail;
    std::mutex writeLock;
    std::mutex readLock;
	std::atomic<uint32_t> mElementsFilled;
    std::condition_variable canWrite;
    std::condition_variable canRead;
};

#endif