Debian Codegraph @

src/core/util_buffers.h

raw symbols SCIP
1 /*----------------------------------------------------------------------------
2 ChucK Strongly-timed Audio Programming Language
3 Compiler, Virtual Machine, and Synthesis Engine
4
5 Copyright (c) 2003 Ge Wang and Perry R. Cook. All rights reserved.
6 http://chuck.stanford.edu/
7 http://chuck.cs.princeton.edu/
8
9 This program is free software; you can redistribute it and/or modify
10 it under the dual-license terms of EITHER the MIT License OR the GNU
11 General Public License (the latter as published by the Free Software
12 Foundation; either version 2 of the License or, at your option, any
13 later version).
14
15 This program is distributed in the hope that it will be useful and/or
16 interesting, but WITHOUT ANY WARRANTY; without even the implied warranty
17 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 MIT Licence and/or the GNU General Public License for details.
19
20 You should have received a copy of the MIT License and the GNU General
21 Public License (GPL) along with this program; a copy of the GPL can also
22 be obtained by writing to the Free Software Foundation, Inc., 59 Temple
23 Place, Suite 330, Boston, MA 02111-1307 U.S.A.
24 -----------------------------------------------------------------------------*/
25
26 //-----------------------------------------------------------------------------
27 // file: util_buffers.h
28 // desc: buffer utilities
29 //
30 // author: Ge Wang ([email protected])
31 // Perry R. Cook ([email protected])
32 // Ananya Misra ([email protected])
33 // date: Spring 2004
34 // Summer 2005 - allow multiple readers
35 //-----------------------------------------------------------------------------
36 #ifndef __UTIL_BUFFERS_H__
37 #define __UTIL_BUFFERS_H__
38
39 #include "chuck_oo.h"
40 #include "chuck_errmsg.h"
41 #ifndef __DISABLE_THREADS__
42 #include "util_thread.h"
43 #endif
44 #include <vector>
45 #include <queue>
46 #include <iostream>
47 #include <atomic> // c++11
48
49 #define DWORD__ t_CKUINT
50 #define SINT__ t_CKINT
51 #define UINT__ DWORD__
52 #define BOOL__ DWORD__
53 #define BYTE__ unsigned char
54
55 #ifndef TRUE
56 #define TRUE 1
57 #define FALSE 0
58 #endif
59
60
61 class CBufferSimple;
62
63
64 //-----------------------------------------------------------------------------
65 // name: class CBufferAdvance
66 // desc: circular buffer
67 //-----------------------------------------------------------------------------
68 class CBufferAdvance
69 {
70 public:
71 CBufferAdvance();
72 ~CBufferAdvance();
73
74 public:
75 BOOL__ initialize( UINT__ num_elem, UINT__ width, CBufferSimple * event_buffer = NULL );
76 void cleanup();
77
78 public:
79 UINT__ get( void * data, UINT__ num_elem, UINT__ read_offset_index );
80 void put( void * data, UINT__ num_elem );
81 BOOL__ empty( UINT__ read_offset_index );
82 UINT__ join( Chuck_Event * event = NULL );
83 void resign( UINT__ read_offset_index );
84
85 protected:
86 BYTE__ * m_data;
87 UINT__ m_data_width;
88 //UINT__ m_read_offset;
89
90 // this holds the offset allocated by join(), paired with an optional
91 // Chuck_Event to notify when things are put in the buffer
92 struct ReadOffset
93 {
94 SINT__ read_offset;
95 Chuck_Event * event;
96 ReadOffset( SINT__ ro, Chuck_Event * e = NULL )
97 { read_offset = ro; event = e; }
98 };
99 std::vector<ReadOffset> m_read_offsets;
100 std::queue<UINT__> m_free;
101
102 SINT__ m_write_offset;
103 SINT__ m_max_elem;
104
105 // TODO: necessary?
106 #ifndef __DISABLE_THREADS__
107 XMutex m_mutex;
108 #endif
109
110 CBufferSimple * m_event_buffer;
111 };
112
113
114
115
116 //-----------------------------------------------------------------------------
117 // name: class CBufferSimple
118 // desc: circular buffer - one reader one writer
119 //-----------------------------------------------------------------------------
120 class CBufferSimple
121 {
122 public:
123 CBufferSimple();
124 ~CBufferSimple();
125
126 public:
127 BOOL__ initialize( UINT__ num_elem, UINT__ width );
128 void cleanup();
129
130 public:
131 UINT__ get( void * data, UINT__ num_elem );
132 void put( void * data, UINT__ num_elem );
133
134 protected:
135 BYTE__ * m_data;
136 UINT__ m_data_width;
137 UINT__ m_read_offset;
138 UINT__ m_write_offset;
139 UINT__ m_max_elem;
140
141 #ifndef __DISABLE_THREADS__
142 // added | 1.5.1.5 (ge & andrew) twilight zone
143 XMutex m_mutex;
144 #endif
145 };
146
147
148
149
150 //-----------------------------------------------------------------------------
151 // name: class AccumBuffer
152 // desc: circular buffer for sample accumulation
153 //-----------------------------------------------------------------------------
154 class AccumBuffer
155 {
156 public:
157 AccumBuffer();
158 ~AccumBuffer();
159
160 public:
161 t_CKINT resize( t_CKINT new_size );
162 void cleanup();
163
164 public:
165 void put( SAMPLE next );
166 void get( SAMPLE * buffer, t_CKINT num_elem );
167 void get_most_recent( SAMPLE * buffer, t_CKINT num_elem );
168
169 protected:
170 SAMPLE * m_data;
171 t_CKUINT m_write_offset;
172 t_CKUINT m_max_elem;
173 };
174
175
176
177
178 //-----------------------------------------------------------------------------
179 // name: class DeccumBuffer
180 // desc: circular buffer for sample deccumulation
181 //-----------------------------------------------------------------------------
182 class DeccumBuffer
183 {
184 public:
185 DeccumBuffer();
186 ~DeccumBuffer();
187
188 public:
189 t_CKINT resize( t_CKINT new_size );
190 void cleanup();
191
192 public:
193 void put( SAMPLE * next, t_CKINT num_elem );
194 void get( SAMPLE * out );
195 void get( SAMPLE * buffer, t_CKINT num_elem );
196
197 protected:
198 SAMPLE * m_data;
199 t_CKUINT m_read_offset;
200 t_CKUINT m_max_elem;
201 };
202
203
204
205
206 //-----------------------------------------------------------------------------
207 // name: class CircularBuffer
208 // desc: templated circular buffer
209 //-----------------------------------------------------------------------------
210 template<typename T>
211 class CircularBuffer
212 {
213 public:
214 CircularBuffer(size_t numElements) :
215 m_read(0),
216 m_write(0),
217 m_numElements(numElements+1) // need 1 element to pad
218 {
219 // allocate
220 m_elements = new T[m_numElements];
221 }
222
223 ~CircularBuffer()
224 {
225 CK_SAFE_DELETE_ARRAY( m_elements );
226 // if(m_elements != NULL)
227 // {
228 // delete[] m_elements;
229 // m_elements = NULL;
230 // }
231 }
232
233 // put one element
234 // returns number of elements successfully put
235 size_t put(T element)
236 {
237 // check for overflow
238 if( (m_write + 1)%m_numElements == m_read )
239 {
240 // no space | 1.5.0.1 (ge) added log message
241 EM_log( CK_LOG_WARNING, "[circular-buffer]: buffer full, dropping items!" );
242 return 0;
243 }
244
245 m_elements[m_write] = element;
246 m_write = (m_write+1)%m_numElements;
247 return 1;
248 }
249
250 // get one element
251 // returns number of elements successfully got
252 size_t get(T &element)
253 {
254 if(m_read == m_write)
255 {
256 // nothing to get
257 return 0;
258 }
259
260 element = m_elements[m_read];
261
262 m_read = (m_read+1)%m_numElements;
263
264 return 1;
265 }
266
267 // peek at element i without removing it
268 // i = 1 would correspond to the least recently put element;
269 // i = -1 would correspond to the most recent (not implemented)
270 // returns 1 if elements successfully peeked
271 size_t peek(T &element, size_t i)
272 {
273 if(i == 0)
274 return 0;
275
276 if(i > 0 && i <= numElements())
277 {
278 element = m_elements[(m_read+(i-1))%m_numElements];
279 return 1;
280 }
281
282 return 0;
283 }
284
285 void clear() { m_write = m_read; }
286
287 // return maximum number of elements that can be held
288 size_t maxElements() { return m_numElements-1; }
289
290 // return if buffer is full
291 bool atMaximum() { return (m_write + 1)%m_numElements == m_read; }
292
293 // return number of valid elements in the buffer
294 size_t numElements()
295 {
296 if(m_read == m_write)
297 return 0;
298 else if(m_read < m_write)
299 return m_write - m_read;
300 else
301 return m_numElements - m_read + m_write;
302 }
303
304 private:
305 T * m_elements;
306 size_t m_read, m_write;
307 const size_t m_numElements;
308 };
309
310
311
312
313 //-----------------------------------------------------------------------------
314 // name: class FastCircularBuffer
315 // desc: uses memcpy instead of assignment
316 // useful for streaming large blocks of data
317 //-----------------------------------------------------------------------------
318 class FastCircularBuffer
319 {
320 public:
321 FastCircularBuffer();
322 ~FastCircularBuffer();
323
324 public:
325 t_CKUINT initialize( t_CKUINT num_elem, t_CKUINT width );
326 void cleanup();
327
328 public:
329 t_CKUINT get( void * data, t_CKUINT num_elem );
330 t_CKUINT put( void * data, t_CKUINT num_elem );
331 inline bool hasMore() { return (m_read_offset != m_write_offset); }
332 inline void clear() { m_read_offset = m_write_offset = 0; }
333
334 protected:
335 t_CKBYTE * m_data;
336 t_CKUINT m_data_width;
337 t_CKUINT m_read_offset;
338 t_CKUINT m_write_offset;
339 t_CKUINT m_max_elem;
340 };
341
342
343
344
345 //-----------------------------------------------------------------------------
346 // name: FinalRingBuffer
347 // desc: hopefully this will be the last lock-free queue we need to implement...
348 // hopefully not like FinalFantasy which has sequels
349 //
350 // added 1.5.2.5 (ge) | adapted from:
351 // Lock-Free Ring Buffer (LFRB) for embedded systems
352 // GitHub: https://github.com/QuantumLeaps/lock-free-ring-buffer
353 // SPDX-License-Identifier: MIT
354 //-----------------------------------------------------------------------------
355 /* the following FinalBufferAtomic type is assumed to be "atomic" in a
356 * target CPU, meaning that the CPU needs to write the whole FinalBufferAtomic
357 * in one machine instruction. An example of violating this assumption would
358 * be an 8-bit CPU, which writes uint16_t (2-bytes) in 2 machine instructions.
359 * For such 8-bit CPU, the maximum size of FinalBufferAtomic would be uint8_t
360 * (1-byte).
361 *
362 * Another case of violating the "atomic" writes to FinalBufferAtomic type
363 * would be misalignment of a FinalBufferAtomic variable in memory, which could
364 * cause the compiler to generate multiple instructions to write a
365 * FinalBufferAtomic value. Therefore, it is further assumed that all
366 * FinalBufferAtomic variables in the following FinalBuffer struct *are*
367 * correctly aligned for "atomic" access. In practice, most C compilers
368 * should provide such natural alignment (by inserting some padding into the
369 * ::FinalRingBuffer class/struct, if necessary). */
370 //-----------------------------------------------------------------------------
371 typedef std::atomic_ulong FinalRingBufferAtomic;
372 //-----------------------------------------------------------------------------
373 template <typename T>
374 class FinalRingBuffer
375 {
376 public:
377 FinalRingBuffer();
378 ~FinalRingBuffer();
379 // reset length of buffer (capacity)
380 void init( t_CKUINT capacity );
381
382 public:
383 bool put( T & element );
384 bool get( T * pElement );
385 bool more();
386
387 protected:
388 /* the type of ring buffer elements is not critical for the lock-free
389 * operation and does not need to be "atomic". For example, it can be
390 * an integer type (uint16_t, uint32_t, uint64_t), a pointer type,
391 * or even a struct type. */
392 T * m_buf; // pointer to the start of the ring buffer
393 FinalRingBufferAtomic m_end; // offset of the end of the ring buffer
394 FinalRingBufferAtomic m_head; // offset to where next el. will be inserted
395 FinalRingBufferAtomic m_tail; // offset of where next el. will be removed
396 };
397
398 template <typename T>
399 FinalRingBuffer<T>::FinalRingBuffer()
400 {
401 m_buf = NULL;
402 m_end = m_head = m_tail = 0;
403 }
404
405 template <typename T>
406 void FinalRingBuffer<T>::init( t_CKUINT capacity )
407 {
408 // dealloc
409 CK_SAFE_DELETE_ARRAY( m_buf );
410 // allocate
411 m_buf = new T[capacity];
412 m_end = capacity;
413 m_head = m_tail = 0;
414 }
415
416 template <typename T>
417 FinalRingBuffer<T>::~FinalRingBuffer()
418 {
419 CK_SAFE_DELETE_ARRAY( m_buf );
420 m_end = m_head = m_tail = 0;
421 }
422
423 template <typename T>
424 bool FinalRingBuffer<T>::put( T & element )
425 {
426 // check
427 if( !m_buf ) return false;
428
429 // local head variable (need to be atomic?)
430 t_CKUINT head = m_head + 1;
431 if( head == m_end ) head = 0;
432
433 // buffer NOT full?
434 if( head != m_tail )
435 {
436 // copy the element into the buffer
437 m_buf[m_head] = element;
438 // update the head to a *valid* index
439 m_head = head;
440 // element placed in the buffer
441 return true;
442 }
443
444 // element NOT placed in the buffer
445 return false;
446 }
447
448 template <typename T>
449 bool FinalRingBuffer<T>::get( T * pElement )
450 {
451 // check for NULL
452 if( !m_buf || !pElement ) return false;
453
454 // local tail variable (need to be atomic?)
455 t_CKUINT tail = m_tail;
456 // ring buffer NOT empty?
457 if( m_head != tail )
458 {
459 // copy element
460 *pElement = m_buf[tail];
461 // advance local tail
462 ++tail; if( tail == m_end ) { tail = 0; }
463 // update the tail to a *valid* index
464 m_tail = tail;
465 // gotten
466 return true;
467 }
468
469 // not gotten
470 return false;
471 }
472
473 template <typename T>
474 bool FinalRingBuffer<T>::more()
475 {
476 // has elements?
477 return m_head != m_tail;
478 }
479
480
481
482
483 ////-----------------------------------------------------------------------------
484 //// name: class XCircleBuffer
485 //// desc: templated circular buffer class (different impl from ge-X-lib)
486 //// NOTE: the lock-free queue DOES NOT WORK; can crash; keeping for study
487 //// NOTE: use FinalRingBuffer instead | 1.5.2.5 (ge)
488 ////-----------------------------------------------------------------------------
489 //template <typename T>
490 //class XCircleBuffer
491 //{
492 //public:
493 // XCircleBuffer( long length = 0 );
494 // ~XCircleBuffer();
495 //
496 //public:
497 // // reset length of buffer (capacity)
498 // void init( long length );
499 // // get length
500 // long length() const;
501 // // clear (does no explicit memory management)
502 // void clear();
503 //
504 //public:
505 // // put an element into the buffer - the item will be copied
506 // // NOTE: if over-capacity, will discard least recently put item
507 // void put( const T & item );
508 // // get next item (FIFO)
509 // bool get( T * pItem );
510 // // number of valid elements in buffer
511 // long numElements() const;
512 // // are there more elements?
513 // bool more() const;
514 // // get elements without advancing - returns number of valid elements
515 // long peek( T * array, long numItems, unsigned long stride = 0 );
516 // // pop
517 // long pop( long numItems = 1 );
518 //
519 //protected: // helper functions
520 // inline void advanceWrite();
521 // inline void advanceRead();
522 //
523 //protected:
524 // // the buffer
525 // T * m_buffer;
526 // // the buffer length (capacity)
527 // std::atomic_ulong m_length;
528 // // write index
529 // std::atomic_ulong m_writeIndex;
530 // // read index
531 // std::atomic_ulong m_readIndex;
532 // // num elements
533 // std::atomic_ulong m_numElements;
534 //};
535 //
536 //
537 //
538 //
539 ////-----------------------------------------------------------------------------
540 //// name: XCircleBuffer()
541 //// desc: constructor
542 ////-----------------------------------------------------------------------------
543 //template <typename T>
544 //XCircleBuffer<T>::XCircleBuffer( long length )
545 //{
546 // // zero out first
547 // m_buffer = NULL;
548 // m_length = m_readIndex = m_writeIndex = m_numElements = 0;
549 //
550 // // call init
551 // this->init( length );
552 //}
553 //
554 //
555 //
556 //
557 ////-----------------------------------------------------------------------------
558 //// name: ~XCircleBuffer
559 //// desc: destructor
560 ////-----------------------------------------------------------------------------
561 //template <typename T>
562 //XCircleBuffer<T>::~XCircleBuffer()
563 //{
564 //
565 //}
566 //
567 //
568 //
569 //
570 ////-----------------------------------------------------------------------------
571 //// name: init()
572 //// desc: reset length of buffer
573 ////-----------------------------------------------------------------------------
574 //template <typename T>
575 //void XCircleBuffer<T>::init( long length )
576 //{
577 // // clean up is necessary
578 // if( m_buffer )
579 // {
580 // // delete array - should call destructors and zero out variable
581 // CK_SAFE_DELETE_ARRAY( m_buffer );
582 // // zero out
583 // m_length = m_readIndex = m_writeIndex = m_numElements = 0;
584 // }
585 //
586 // // sanity check
587 // if( length < 0 )
588 // {
589 // // doh
590 // std::cerr << "[XCircleBuffer]: error invalid length '"
591 // << length << "' requested" << std::endl;
592 //
593 // return;
594 // }
595 //
596 // // check for zero length
597 // if( length == 0 ) return;
598 //
599 // // allocate
600 // m_buffer = new T[length];
601 // // check
602 // if( m_buffer == NULL )
603 // {
604 // // doh
605 // std::cerr << "[XCircleBuffer]: failed to allocate buffer of length '"
606 // << length << "'..." << std::endl;
607 //
608 // return;
609 // }
610 //
611 // // save
612 // m_length = length;
613 // // zero out
614 // m_readIndex = m_writeIndex = m_numElements = 0;
615 //}
616 //
617 //
618 //
619 //
620 ////-----------------------------------------------------------------------------
621 //// name: length()
622 //// desc: get length
623 ////-----------------------------------------------------------------------------
624 //template <typename T>
625 //long XCircleBuffer<T>::length() const
626 //{
627 // return m_length;
628 //}
629 //
630 //
631 //
632 //
633 ////-----------------------------------------------------------------------------
634 //// name: clear()
635 //// desc: clear (does no explicit memory management)
636 ////-----------------------------------------------------------------------------
637 //template <typename T>
638 //void XCircleBuffer<T>::clear()
639 //{
640 // // zero out
641 // m_readIndex = m_writeIndex = m_numElements = 0;
642 //}
643 //
644 //
645 //
646 //
647 ////-----------------------------------------------------------------------------
648 //// name: advanceWrite()
649 //// desc: helper to advance write index
650 ////-----------------------------------------------------------------------------
651 //template <typename T>
652 //void XCircleBuffer<T>::advanceWrite()
653 //{
654 // // increment
655 // m_writeIndex++;
656 //
657 // // check for bounds
658 // if( m_writeIndex >= m_length )
659 // {
660 // // wrap
661 // m_writeIndex -= m_length;
662 // }
663 //
664 // // increment count
665 // m_numElements++;
666 //}
667 //
668 //
669 //
670 //
671 ////-----------------------------------------------------------------------------
672 //// name: advanceRead()
673 //// desc: helper to advance read index
674 ////-----------------------------------------------------------------------------
675 //template <typename T>
676 //void XCircleBuffer<T>::advanceRead()
677 //{
678 // // increment
679 // m_readIndex++;
680 //
681 // // check for bounds
682 // if( m_readIndex >= m_length )
683 // {
684 // // wrap
685 // m_readIndex -= m_length;
686 // }
687 //
688 // // decrement count
689 // m_numElements--;
690 //}
691 //
692 //
693 //
694 //
695 ////-----------------------------------------------------------------------------
696 //// name: put()
697 //// desc: put an element into the buffer - the item will be copied
698 //// if over-capacity, will discard least recently put item
699 ////-----------------------------------------------------------------------------
700 //template <typename T>
701 //void XCircleBuffer<T>::put( const T & item )
702 //{
703 // // sanity check
704 // if( m_buffer == NULL ) return;
705 //
706 // // copy it
707 // m_buffer[m_writeIndex] = item;
708 //
709 // // advance write index
710 // advanceWrite();
711 //
712 // // if read and write pointer are the same, over-capacity
713 // if( m_writeIndex == m_readIndex )
714 // {
715 // // warning | 1.5.0.1 (ge) make this a log message
716 // EM_log( CK_LOG_WARNING, "[circular-buffer]: buffer full, dropping items!" );
717 // // advance read!
718 // advanceRead();
719 // }
720 //}
721 //
722 //
723 //
724 //
725 ////-----------------------------------------------------------------------------
726 //// name: numElements()
727 //// desc: get number of valid elements in buffer
728 ////-----------------------------------------------------------------------------
729 //template <typename T>
730 //long XCircleBuffer<T>::numElements() const
731 //{
732 // // return our count
733 // return m_numElements;
734 //}
735 //
736 //
737 //
738 //
739 ////-----------------------------------------------------------------------------
740 //// name: hasMore()
741 //// desc: are there more elements?
742 ////-----------------------------------------------------------------------------
743 //template <typename T>
744 //bool XCircleBuffer<T>::more() const
745 //{
746 // return m_numElements > 0;
747 //}
748 //
749 //
750 //
751 //
752 ////-----------------------------------------------------------------------------
753 //// name: peek
754 //// desc: get elements without advancing - returns number returned
755 ////-----------------------------------------------------------------------------
756 //template <typename T>
757 //long XCircleBuffer<T>::peek( T * array, long numItems, unsigned long stride )
758 //{
759 // // sanity check
760 // if( m_buffer == NULL ) return 0;
761 //
762 // // sanity check (so the wrap can be sure to land inbounds)
763 // if( stride >= m_length ) return 0;
764 //
765 // // count
766 // long count = 0;
767 // // actual count, taking stride out of the equation
768 // long actualCount = 0;
769 //
770 // // starting index
771 // long index = m_writeIndex - 1;
772 // if( index < 0 ) index += m_length;
773 //
774 // // while need more but haven't reached write index...
775 // while( (count < numItems) && (count < m_numElements) )
776 // {
777 // // copy
778 // array[actualCount] = m_buffer[index];
779 // // increment
780 // count++; count += stride;
781 // // advance
782 // index--; index -= stride;
783 // // actual count, don't stride
784 // actualCount++;
785 // // wrap
786 // if( index < 0 ) index += m_length;
787 // }
788 //
789 // // reverse contents
790 // for( int i = 0; i < actualCount/2; i++ )
791 // {
792 // T v = array[i];
793 // array[i] = array[actualCount-1-i];
794 // array[actualCount-1-i] = v;
795 // }
796 //
797 // return actualCount;
798 //}
799 //
800 //
801 //
802 //
803 ////-----------------------------------------------------------------------------
804 //// name: pop()
805 //// desc: pop one or more elements
806 ////-----------------------------------------------------------------------------
807 //template <typename T>
808 //long XCircleBuffer<T>::pop( long numItems )
809 //{
810 // // sanity check
811 // if( m_buffer == NULL ) return 0;
812 //
813 // // count
814 // long count = 0;
815 //
816 // // while there is more to pop and need to pop more
817 // while( more() && count < numItems )
818 // {
819 // // advance read
820 // advanceRead();
821 // // increment count
822 // count++;
823 // }
824 //
825 // return count;
826 //}
827 //
828 //
829 //
830 //
831 ////-----------------------------------------------------------------------------
832 //// name: get()
833 //// desc: get next read element
834 ////-----------------------------------------------------------------------------
835 //template <typename T>
836 //bool XCircleBuffer<T>::get( T * result )
837 //{
838 // // sanity check
839 // if( m_buffer == NULL || m_readIndex == m_writeIndex ) return false;
840 //
841 // // get item to read
842 // *result = m_buffer[m_readIndex];
843 // // advance read
844 // advanceRead();
845 //
846 // return true;
847 //}
848
849
850
851
852 #endif