Mozzi  version v2.0
sound synthesis library for Arduino
SampleHuffman.h
1 /*
2  * SampleHuffman.h
3  *
4  * This file is part of Mozzi.
5  *
6  * Copyright 2013-2024 Tim Barrass and the Mozzi Team
7  *
8  * Mozzi is licensed under the GNU Lesser General Public Licence (LGPL) Version 2.1 or later.
9  *
10  */
11 
12 #ifndef SAMPLEHUFFMAN_H
13 #define SAMPLEHUFFMAN_H
14 
15 #include "mozzi_pgmspace.h"
16 
51 {
52 
53 public:
54 
60  SampleHuffman(uint8_t const * SOUNDDATA, int16_t const * HUFFMAN_DATA, uint32_t const SOUNDDATA_BITS):sounddata(SOUNDDATA),huffman(HUFFMAN_DATA),sounddata_bits(SOUNDDATA_BITS)
61  {
62  setLoopingOff();
63  }
64 
65 
70  inline
71  int16_t next()
72  {
73  if(datapos >= sounddata_bits){
74  if(looping){
75  // at end of sample, restart from zero, looping the sound
76  datapos = 0;
77  }else{
78  return 0;
79  }
80  }
81 
82  int16_t dif = decode();
83  current += dif; // add differential
84  return current;
85  }
86 
87 
90  inline
91  void setLoopingOn()
92  {
93  looping=true;
94  }
95 
96 
99  inline
101  {
102  looping=false;
103  }
104 
107  inline
108  void start()
109  {
110  current = 0;
111  datapos = 0;
112  bt = 0;
113  }
114 
115 private:
116  uint8_t const * sounddata;
117  int16_t const * huffman;
118  uint32_t const sounddata_bits;
119  uint32_t datapos; // current sample position
120  int16_t current; // current amplitude value
121  bool looping;
122  uint8_t bt;
123 
124  // Get one bit from sound data
125  inline
126  bool getbit()
127  {
128  const uint8_t b = datapos&7;
129  //static uint8_t bt;
130  if(!b) bt = FLASH_OR_RAM_READ<const uint8_t>(sounddata+((uint32_t)datapos>>3));
131  // extract the indexed bit
132  return ((uint8_t)bt>>(7-b))&1;
133  }
134 
135 
136  // Decode bit stream using Huffman codes
137  inline
138  int16_t decode()
139  {
140  int16_t const * huffcode = huffman;
141  do {
142  if(getbit()) {
143  const int16_t offs = FLASH_OR_RAM_READ<const int16_t>(huffcode);
144  huffcode += offs?offs+1:2;
145  }
146  datapos++;
147  }
148  while(FLASH_OR_RAM_READ<const int16_t>(huffcode++));
149  return FLASH_OR_RAM_READ<const int16_t>(huffcode);
150  }
151 
152 
153 };
154 
160 #endif // #ifndef SAMPLEHUFFMAN_H
A sample player for samples encoded with Huffman compression.
Definition: SampleHuffman.h:51
void setLoopingOn()
Turns looping on, with the whole sample length as the loop range.
Definition: SampleHuffman.h:91
void setLoopingOff()
Turns looping off.
void start()
Sets the playhead to the beginning of the sample.
SampleHuffman(uint8_t const *SOUNDDATA, int16_t const *HUFFMAN_DATA, uint32_t const SOUNDDATA_BITS)
Constructor.
Definition: SampleHuffman.h:60
int16_t next()
Update and return the next audio sample.
Definition: SampleHuffman.h:71