Normalize

I am wondering if in Csound exists an opcode to normalize the audio and avoid clippings, something to use in the end of the orc.
Thanks

Probably not...

Not sure why I seem to be the one answering [*trying* to answer...] questions, as I'm not the expert around here (:-)), and I could well be wrong. Anyhow...

I can't see any way that you could truly normalize the output, simply because you can't tell where the peaks are going to be until you get there, and you can't very well modify values already output. An app like 'sox' can normalize because it reads the whole audio first, can find the peaks, and adjust appropriately.

There is the 'clip' opcode, that does a "soft limit" of the output, which would sort of work if overranges are only slight, but it's not really 'normalizing'.

Maybe your best bet would be to record your output in floating point, then use Audacity or sox or some such app to do the normalization before writing it back out as standard 16-bit audio. (Haven't tried it, so don't take my word...)

Possible solution

There exists a solution that works for some, but not all situations. The idea is to use a global variable or bus that collects all the audio, and then use a single instrument at the end of a Csound chain to write to the output. The following mixes all the audio to a chn software bus named "mixer", then outputs the sound in instr 2:

instr 1
iamp = p4
ifreq = p5
a1 oscils 0dbfs * iamp, ifreq, 0
chnmix a1, "mixer"
endin

instr 2
iamp = 1
a1 chnget "mixer"
out a1 * iamp

azero = 0
chnset azero, "mixer" ; be sure to zero out "mixer"
endin
...
i1 0 10 0.2 440
i1 0 10 0.6 262
i1 0 10 0.1 1000
i1 0 10 0.3 75
i1 0 10 0.2 502
i2 0 10

If you are using the command-line, you can enter csound -d -n myfile.csd, which will give you the overall amps. Divide 32767 by the overall amps, and replace the value in iamp in instr 2 with the result. Run the score again and it will spit out a normalized file.

The score above returns an overall amps of 44156.1. Setting iamp in instr 2 to iamp = 32767 / 441561.1 in effect normalizes the csd file.

Best,
Jake

----
The Csound Blog
http://www.thumbuki.com/csound/blog