1 /*******************************************************************************
2 * Copyright 2009-2016 Jörg Müller
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 #include "generator/SawtoothReader.h"
18
19 #include <cmath>
20
21 AUD_NAMESPACE_BEGIN
22
SawtoothReader(float frequency,SampleRate sampleRate)23 SawtoothReader::SawtoothReader(float frequency, SampleRate sampleRate) :
24 m_frequency(frequency),
25 m_position(0),
26 m_sample(0),
27 m_sampleRate(sampleRate)
28 {
29 }
30
setFrequency(float frequency)31 void SawtoothReader::setFrequency(float frequency)
32 {
33 m_frequency = frequency;
34 }
35
isSeekable() const36 bool SawtoothReader::isSeekable() const
37 {
38 return true;
39 }
40
seek(int position)41 void SawtoothReader::seek(int position)
42 {
43 m_position = position;
44 m_sample = std::fmod(m_position * m_frequency / (float)m_sampleRate + 1.0f, 2.0f) - 1.0f;
45 }
46
getLength() const47 int SawtoothReader::getLength() const
48 {
49 return -1;
50 }
51
getPosition() const52 int SawtoothReader::getPosition() const
53 {
54 return m_position;
55 }
56
getSpecs() const57 Specs SawtoothReader::getSpecs() const
58 {
59 Specs specs;
60 specs.rate = m_sampleRate;
61 specs.channels = CHANNELS_MONO;
62 return specs;
63 }
64
read(int & length,bool & eos,sample_t * buffer)65 void SawtoothReader::read(int& length, bool& eos, sample_t* buffer)
66 {
67 float k = 2.0 * m_frequency / m_sampleRate;
68
69 for(int i = 0; i < length; i++)
70 {
71 m_sample += k;
72
73 if(m_sample >= 1.0f)
74 m_sample -= std::floor(m_sample) + 1.0f;
75
76 buffer[i] = m_sample;
77 }
78
79 m_position += length;
80 eos = false;
81 }
82
83 AUD_NAMESPACE_END
84