summaryrefslogtreecommitdiff
path: root/src/audiocache.cc
blob: e098fd00a88e0bcacbe5c7de9d6a54f9406a5cb3 (plain)
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/***************************************************************************
 *            audiocache.cc
 *
 *  Fri Apr 10 10:39:24 CEST 2015
 *  Copyright 2015 Jonas Suhr Christensen
 *  jsc@umbraculum.org
 ****************************************************************************/

/*
 *  This file is part of DrumGizmo.
 *
 *  DrumGizmo is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  DrumGizmo is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with DrumGizmo; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */
#include "audiocache.h"

#include <mutex>

#include <string.h>
#include <stdio.h>
#include <assert.h>

#include <hugin.hpp>

#include "audiocachefile.h"

#define CHUNKSIZE(x) (x * CHUNK_MULTIPLIER)

AudioCache::~AudioCache()
{
	DEBUG(cache, "~AudioCache() pre\n");

	deinit();
	delete[] nodata;

	DEBUG(cache, "~AudioCache() post\n");
}

void AudioCache::init(size_t poolsize)
{
	setAsyncMode(true);

	id_manager.init(poolsize);
	event_handler.start();
}

void AudioCache::deinit()
{
	event_handler.stop();
}

// Invariant: initial_samples_needed < preloaded audio data
sample_t* AudioCache::open(const AudioFile& file, size_t initial_samples_needed,
                           int channel, cacheid_t& id)
{
	if(!file.isValid())
	{
		// File preload not yet ready - skip this sample.
		id = CACHE_DUMMYID;
		assert(nodata);
		return nodata;
	}

	// Register a new id for this cache session.
	id = id_manager.registerID({});

	// If we are out of available ids we get CACHE_DUMMYID
	if(id == CACHE_DUMMYID)
	{
		// Use nodata buffer instead.
		assert(nodata);
		return nodata;
	}

	// Get the cache_t connected with the registered id.
	cache_t& c = id_manager.getCache(id);

	c.afile = &event_handler.openFile(file.filename);
	c.channel = channel;

	// Next call to 'next()' will read from this point.
	c.localpos = initial_samples_needed;

	c.front = nullptr; // This is allocated when needed.
	c.back = nullptr; // This is allocated when needed.

	// cropped_size is the preload chunk size cropped to sample length.
	size_t cropped_size = file.preloadedsize - c.localpos;
	cropped_size /= framesize;
	cropped_size *= framesize;
	cropped_size += initial_samples_needed;

	if(file.preloadedsize == file.size)
	{
		// We have preloaded the entire file, so use it.
		cropped_size = file.preloadedsize;
	}

	c.preloaded_samples = file.data;
	c.preloaded_samples_size = cropped_size;

	// Next read from disk will read from this point.
	c.pos = cropped_size;//c.preloaded_samples_size;

	// Only load next buffer if there are more data in the file to be loaded...
	if(c.pos < file.size)
	{
		if(c.back == nullptr)
		{
			c.back = new sample_t[CHUNKSIZE(framesize)];
		}

		event_handler.pushLoadNextEvent(c.afile, c.channel, c.pos,
		                                c.back, &c.ready);
	}

	return c.preloaded_samples; // return preloaded data
}

sample_t* AudioCache::next(cacheid_t id, size_t& size)
{
	size = framesize;

	if(id == CACHE_DUMMYID)
	{
		assert(nodata);
		return nodata;
	}

	cache_t& c = id_manager.getCache(id);

	if(c.preloaded_samples)
	{

		// We are playing from memory:
		if(c.localpos < c.preloaded_samples_size)
		{
			sample_t* s = c.preloaded_samples + c.localpos;
			c.localpos += framesize;
			return s;
		}

		c.preloaded_samples = nullptr; // Start using samples from disk.

	}
	else
	{

		// We are playing from cache:
		if(c.localpos < CHUNKSIZE(framesize))
		{
			sample_t* s = c.front + c.localpos;
			c.localpos += framesize;
			return s;
		}
	}

	// Check for buffer underrun
	if(!c.ready)
	{
		// Just return silence.
		++number_of_underruns;
		return nodata;
	}

	// Swap buffers
	std::swap(c.front, c.back);

	// Next time we go here we have already read the first frame.
	c.localpos = framesize;

	c.pos += CHUNKSIZE(framesize);

	// Does the file have remaining unread samples?
	if(c.pos < c.afile->getSize())
	{
		// Do we have a back buffer to read into?
		if(c.back == nullptr)
		{
			c.back = new sample_t[CHUNKSIZE(framesize)];
		}

		event_handler.pushLoadNextEvent(c.afile, c.channel, c.pos,
		                                c.back, &c.ready);
	}

	// We should always have a front buffer at this point.
	assert(c.front);

	return c.front;
}

bool AudioCache::isReady(cacheid_t id)
{
	if(id == CACHE_DUMMYID)
	{
		return true;
	}

	cache_t& cache = id_manager.getCache(id);
	return cache.ready;
}

void AudioCache::close(cacheid_t id)
{
	if(id == CACHE_DUMMYID)
	{
		return;
	}

	event_handler.pushCloseEvent(id);
}

void AudioCache::setFrameSize(size_t framesize)
{
	DEBUG(cache, "%s\n", __PRETTY_FUNCTION__);

	// Make sure the event handler thread is stalled while we set the framesize
	// state.
	std::lock_guard<AudioCacheEventHandler> event_handler_lock(event_handler);

	// NOTE: Not threaded...
	//std::lock_guard<AudioCacheIDManager> id_manager_lock(id_manager);

	if(framesize > this->framesize)
	{
		delete[] nodata;
		nodata = new sample_t[framesize];

		for(size_t i = 0; i < framesize; ++i)
		{
			nodata[i] = 0.0f;
		}
	}

	this->framesize = framesize;

	event_handler.setChunkSize(CHUNKSIZE(framesize));
}

size_t AudioCache::frameSize() const
{
	return framesize;
}

void AudioCache::setAsyncMode(bool async)
{
	event_handler.setThreaded(async);
}

bool AudioCache::asyncMode() const
{
	return event_handler.getThreaded();
}

size_t AudioCache::getNumberOfUnderruns() const
{
	return number_of_underruns;
}

void AudioCache::resetNumberOfUnderruns()
{
	number_of_underruns = 0;
}