I noticed that the content of a LocalBuf is not cleared when the synth is freed as demonstrated in the example below. Is this normal/expected behaviour or a bug and is there any way to clear all LocalBufs (s.newBufferAllocators does not work)? I am on a M1/OSX 11.0 running SC in Rosetta.
(
x = {
var buf = LocalBuf(SampleRate.ir, 1).poll;
var sig = WhiteNoise.ar * 0.1;
var phasor = Phasor.ar(0, 1, 0, SampleRate.ir);
BufWr.ar(sig, buf, phasor);
Out.ar(0, BufRd.ar(1, buf, phasor))
}.play
)
// plays white noise as expected
x.free;
s.newBufferAllocators; // for good measure, does not change the behaviour
(
x = {
var buf = LocalBuf(SampleRate.ir, 1).poll;
var phasor = Phasor.ar(0, 1, 0, SampleRate.ir);
Out.ar(0, BufRd.ar(1, buf, phasor))
}.play
)
// still plays white noise - should't the buffer be completely empty? In both cases the bufnum is 1024
Discussion:
This is important when randomly accessing buffer slots (e.g. with a BufRd) or not overwriting them. Clear is not an efficient real time operation for larger buffers, so it should be only used when really needed - but then it is essential: a LocalBuf is “created” in each new synth, and it may reuse old space. So if an older synth has already ended, this part of memory may be the same as the new synth’s.
How do you make sure that different instances of a synthdef using LocalBuf use different LocalBufs?
SynthDef(\test, {
var buf = LocalBuf.new(SampleRate.ir, 1).clear;
buf.poll(1)
}).add
~x = Synth(\test)
~y = Synth(\test)
// both instances of the synth use the same LocalBuf - how do you force them to use different LocalBufs?
Or is it just the nature of LocalBuf, that the bufnum is chosen on synth definition time - would I have to use a normal buffer declared outside the synth in this case? The same problem seems to occur if I have two different synthdefs using a LocalBuf - they both refer to the same buf number.
They are different buffers created anew for each synth.
Each synth has a unique local buffer, these are not shared between all synths of the same Def. It is local to the synth.
However, when a synth is freed, the memory might be reused by another synth (which may or maybe have the same Def)
I believe there is a separate bufnum counter for local bufs.
If you try putting data into the buffers you should see they are unique per synth instance, despite the bufnums being equal. In other words, the number, too, is local to the synth, not the server, nor the Def.
@Jordan - thanks for clarifying, the identical bufnums threw me - upon testing I see that you are absolutely right - the buffers are different although the numbers are the same.