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 "sequence/SuperposeReader.h"
18 #include "Exception.h"
19 
20 #include <algorithm>
21 #include <cstring>
22 
23 AUD_NAMESPACE_BEGIN
24 
SuperposeReader(std::shared_ptr<IReader> reader1,std::shared_ptr<IReader> reader2)25 SuperposeReader::SuperposeReader(std::shared_ptr<IReader> reader1, std::shared_ptr<IReader> reader2) :
26 	m_reader1(reader1), m_reader2(reader2)
27 {
28 }
29 
~SuperposeReader()30 SuperposeReader::~SuperposeReader()
31 {
32 }
33 
isSeekable() const34 bool SuperposeReader::isSeekable() const
35 {
36 	return m_reader1->isSeekable() && m_reader2->isSeekable();
37 }
38 
seek(int position)39 void SuperposeReader::seek(int position)
40 {
41 	m_reader1->seek(position);
42 	m_reader2->seek(position);
43 }
44 
getLength() const45 int SuperposeReader::getLength() const
46 {
47 	int len1 = m_reader1->getLength();
48 	int len2 = m_reader2->getLength();
49 	if((len1 < 0) || (len2 < 0))
50 		return -1;
51 	return std::max(len1, len2);
52 }
53 
getPosition() const54 int SuperposeReader::getPosition() const
55 {
56 	int pos1 = m_reader1->getPosition();
57 	int pos2 = m_reader2->getPosition();
58 	return std::max(pos1, pos2);
59 }
60 
getSpecs() const61 Specs SuperposeReader::getSpecs() const
62 {
63 	return m_reader1->getSpecs();
64 }
65 
read(int & length,bool & eos,sample_t * buffer)66 void SuperposeReader::read(int& length, bool& eos, sample_t* buffer)
67 {
68 	Specs specs = m_reader1->getSpecs();
69 	Specs s2 = m_reader2->getSpecs();
70 	if(!AUD_COMPARE_SPECS(specs, s2))
71 		AUD_THROW(StateException, "Two readers with different specifiactions cannot be superposed.");
72 
73 	int samplesize = AUD_SAMPLE_SIZE(specs);
74 
75 	m_buffer.assureSize(length * samplesize);
76 
77 	int len1 = length;
78 	m_reader1->read(len1, eos, buffer);
79 
80 	if(len1 < length)
81 		std::memset(buffer + len1 * specs.channels, 0, (length - len1) * samplesize);
82 
83 	int len2 = length;
84 	bool eos2;
85 	sample_t* buf = m_buffer.getBuffer();
86 	m_reader2->read(len2, eos2, buf);
87 
88 	for(int i = 0; i < len2 * specs.channels; i++)
89 		buffer[i] += buf[i];
90 
91 	length = std::max(len1, len2);
92 	eos &= eos2;
93 }
94 
95 AUD_NAMESPACE_END
96