Skip to content

Instantly share code, notes, and snippets.

@FeepingCreature
Created September 29, 2012 11:20
Show Gist options
  • Save FeepingCreature/3803724 to your computer and use it in GitHub Desktop.
Save FeepingCreature/3803724 to your computer and use it in GitHub Desktop.
module std.sound.threaded; // separate playback thread
import std.sound.base, std.thread, std.time, std.list;
class ThreadedOutput : SoundOutput {
ThreadPool tp;
SoundOutput sup;
int maxOutstandingSamples;
void init(SoundOutput sup) {
tp = new ThreadPool 1;
this.sup = sup;
maxOutstandingSamples = 32768;
m = new Mutex;
gotNewData = new Semaphore;
tp.addTask &playBuffer;
}
void wait() sleep(0.01);
void playBuffer() {
using LockedMutex:m {
while (true) {
while (buffer.hasData) {
scope data = buffer.popTail();
bufferlen -= data.length;
// writeln "dump $(data.length), left $(bufferlen)";
using UnlockedMutex:m sup.dump data;
}
using UnlockedMutex:m gotNewData.claim();
}
}
}
DoubleLinkedList!(Sample[]) buffer;
int bufferlen;
Mutex m;
Semaphore gotNewData;
void block() {
using LockedMutex:m {
while (bufferlen) using UnlockedMutex:m wait;
}
}
override {
void open() sup.open;
void close() { block; sup.close; }
void writeCopydump(int len) {
if (!len) return;
auto copy = copydump[0..len].dup;
using LockedMutex:m {
if (!buffer.hasData) gotNewData.release();
buffer.pushHead copy;
bufferlen += len;
while (bufferlen > maxOutstandingSamples)
using UnlockedMutex:m wait;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment