AudioResearchBlog

Covering all audio related stuff with special focus on programming and digital signal processing

Archive for the 'library' Category

CLAM processing generator script (example of use)

Posted by hordia on 7th July 2008

This script is about a basic code generation of a CLAM plugin. In some point I think this is some kind of meta-programming or perhaps the term “automatic programming” fits better. The basic idea is to specify some basic features of the planned new processing in a plain text and then, generate some code with the script, saving in this way many of the often repetitive and mechanical work needed to set-up a new processing from scratch. Main intention is to allow concentrate in the Do() function or plugin details quickly.

As an example, I will reproduce here how I worked with me some time ago:
 
One day, in the irc #clam channel:
“[11:51] <groton> Consul, do you know if there is any trigger-like processing unit, list when the volume gets louder than a threshold or something like that”

I’m not Consul in the irc (I’m hordia), but next day at my console…

cd CLAM/scripts/TemplatedPluginsGenerator
vi ThresholdTrigger.template

Name:ThresholdTriggerTemplate
BaseClass:Processing
i:AudioInPort,Audio Input
ic:0,1,Threshold
oc:0,1,Trigger

In words, this means a Processing template named “ThresholdTriggerTemplate” using “Processing” as a base class and with one input of “AudioInPort” type named “Audio Input”, with one in control in the 0..1 range named “Threshold” and one out control named “Trigger”. Of course, you can add as many inputs/outputs of ports or controls as you want.
 

This script creates the template:

./TemplateGenerator.py ThresholdTrigger.template

 
And this one the processing plugin:

./TemplatedPluginsGenerator.py ThresholdTrigger ThresholdTriggerTemplate "Hernán Ordiales" GPL 2008

Again in words, this means create a new processing called “ThresholdTrigger” based on the “ThresholdTriggerTemplate” filling the copyright with my name plus the current year and the license with the GPL text.

 
A final edit just typing the required code for the Do() function:

cd CLAM/plugins/ThresholdTrigger
vi ThresholdTrigger.hxx

#include <cmath>
 
bool Do()
{
       bool result = Do( mAudioInput.GetAudio() );
       mAudioInput.Consume();
       return result;
}
 
bool Do(const Audio& in)
{
       int size = in.GetSize();
       const DataArray& inb = in.GetBuffer();
       TData threshold = mThreshold.GetLastValue();
       bool trigger = 0;
       for (int i=0;i<size ;i++)
       {
               if (std::fabs(inb[i])>threshold)
                       trigger = 1;
       }
       mTrigger.SendControl(trigger);
       return true;
}
</size></cmath>

At this point, just remains add the basic SConstruct file for a CLAM plugin, compile it with the corresponding clam_prefix and install it:

scons install clam_prefix=$CLAM_PATH
NetworkEditor

And ready to use…

This example it’s very simple and has a poor implementation but was just to show the idea of how those scripts can save a lot of work.

Update: I made a frontend for these scripts: ProcessingCodeGenerator


, , , , , , , ,

Posted in audio, programming, c++, python, English, CLAM, plugins, library | 1 Comment »

New CLAM plugin: (’very’ for now) simple guitar distortion

Posted by hordia on 9th December 2007

A week or more ago, Daniel Vidal Chornet (collaborator of Musix) asked me if i can develop guitar distortion effects, because he couldn’t find something decent that suits his needs, i said “sadly i have no idea about distortions effects and anyway i have no time right now to do that”, but then i remembered how useful could be the clam framework and i tried to do a little spike about. Results were better than i had expected at first (is not a super cool distortion, but at least sound like one).

Basically i merged and tweaked a couple of simple/base algorithms found in the web for distortion and compression and in less than 30 minutes i had something working and sounds like a guitar distortion (”clean” ones seems to sound better easily). I was amazed how fast and easy (develop and test in clam/networkeditor, once you get the basis) was. I think right now is far to be a good distortion, but as learning process and first demo seems very good.

Here some sound examples:

Original:
(dvlc-guitar.ogg)

With distortion:
(guitardist-ex1.ogg)

Test network looks like:

Distortion NE network

 

The source code is here (as NetworkEditor plugin): GuitarDistortion.tar.gz

Some optional tweaks could include add a three band filter but i’m still not sure if it’s better to put it at first or at the end.

Special thanks for testing and audio samples to Daniel Vidal Chornet. I should take from my closet my fender stratocaster and do my own samples :-D . OTOH, we already arrange to do a remote gig with this.

Another useful NetworkEditor processings plugins i had made during this “work”:

  • AutomaticGainControl: Adaptative automatic gain control. Given an output reference and step response adjusts the output volume to keep it constant (AutomaticGainControl.tar.gz)
  • AudioSwitch: Switchs between a configurable amount of inputs (like a multiplexer) (AudioSwitch.tar.gz)

 
Related: LADSPA versions of my recent simple distortions
Update: Distortion rack prototype


, , , , , , , , , ,

Posted in audio, algorithms, effects, free software, programming, GPL, c++, English, CLAM, plugins, library | 6 Comments »

Introducción a CLAM

Posted by hordia on 12th July 2007

CLAM es un completo framework para hacer investigación y desarrollo sobre audio y música (esto también incluye aplicaciones para usuarios finales). Ofrece un modelo conceptual y herramientas para el análisis, la síntesis y el procesamiento de señales de audio. Tiene una interfaz muy amigable, es Software Libre, multiplataforma y esta escrito en C++ (en muchas de sus aplicaciones utiliza tiempo real).

A pesar de que tuvo su origen en una Universidad de Barcelona, España, la documentación en español sobre este framework es escasa, asi que me decidí a hacer una pequeña introducción sobre las cosas básicas, pero con links (eso si, la mayoria en inglés) para el que quiera ir más allá. Pienso que le puede servir a más de uno para empezar.

Básicamente hay dos perfiles: el de usuario final (de las aplicaciones) y el de desarrolladores que quieran escribir sus propios programas sobre este framework.

En este momento se compone de 4 programas principales:
 
NetworkEditor:
Es una aplicación que permite conectar módulos en forma de red de procesamiento al estilo pd (pero mucho más amigable), MaxMSP o Reaktor (o para los que usan matlab, tipo simulink). Estas redes se ejecutan en tiempo real y se pueden correr con jack, portaudio, LADSPA o VST como backend.
Una de las características más interesantes es que esta red se puede exportar y después correr con una interfaz gráfica diseñada con QTDesigner (ambos programas exportan a un xml que luego se corre con la aplicación Prototyper)

Recomiendo ver esta presentación: “Visual prototyping of audio applications

Es decir, un usuario que no es programador puede armar complejos plugins o aplicaciones sin escribir una sola línea de código. También es muy útil para armar prototipos de futuras aplicaciones o desarrollos.
En este momento se esta integrando con LADSPA, lv2 y se planea reforzar aún más la posibilidad de usar plugins externos (como un módulo más) dentro del NetworkEditor y vicerversa, usar estas redes como plugins en otras aplicaciones.

Para el que quiera empezar, recomiendo esto:

 
Annotator:
Es un programa para hacer transcripciones, en el estilo de Sonic Visualizer. Muy potente y con características que lo hacen único.

Para conocer más:

 
SMSTools:
Un analizador de señales de audio en el estilo de wavesurfer que soporta diferentes tipos de visualización como spectogramas, y todas las derivadas del módelo Sinusoides + Residuo asi como trasnformaciones complejas basadas en este modelo (gender change, pitch-shifting, morph, etc) y muchas otras cosas más (ver tutorial).

 
Voice2MIDI:
Convierte voz en MIDI. Esta comentado en este artículo de linuxjournal.

 
Para desarrolladores, sirve como entorno para realizar sus propias aplicaciones de forma fácil o como herramienta para hacer prototipos de sus futuras implementaciones.

Recomiendo:

Si uno quiere, puede aportar al proyecto mandando ‘patchs’ de código a los desarrolladores principales y hasta convertirse en ‘developer’ luego de haber mandado varios de ellos.

 
En fin, es un proyecto bastante grande y ambicioso. Incluso hay miles de desarrollos más sobre el mismo que no están en el ‘paquete principal’, pero me pareció útil dar un panorama general porque tal vez sea tan abarcativo que maree un poco para el que recién escucha algo de él.

Como ya dije, es multiplataforma y esta disponible para GNU/Linux (con paquetes para varias distribuciones), Windows y Mac (ver más y descargar)

Otro links interesantes:


, , , , , , , , , , , , , , , , , , , , ,

Posted in audio, algorithms, effects, signal processing, music, free software, programming, GNU/Linux, GPL, c++, noise, libraries, midi, publications, projects, Castellano, CLAM, standards, speech, GSoC2007, GUI, library | No Comments »

Funciones para trabajar con wav’s vectorialmente en python

Posted by hordia on 27th December 2006

A raíz de que desde hace un tiempo me puse en campaña para intentar reemplazar matlab con python (en realidad usar python para lo que hasta ahora usaba matlab) es que me vi obligado a implementar las siguientes funciones para poder trabajar con archivos wavs como si fueran vectores.

Serían las equivalentes a las funciones wavread y wavwrite de matlab.

wavread: recibe un wav y devuelve un vector normalizado entre -1 y 1, su frecuencia de muestreo y la cantidad de bits por muestra.

# Example: [ y, Fs, bits ] = wavread( 'filename' )
def wavread( name ):
	file = wave.open( name, 'r' )
	[Channels,Bytes,Fs,Frames,Compress,CompressName] = file.getparams() # (nchannels, sampwidth in bytes, sampling frequency, nframes, comptype, compname)
	Bits = Bytes*8 # 16 bits per sample
	Data = file.readframes( Frames )
	Data = fromstring( Data, Int16 ) / 32767.0 # -1..1 values, Int16 because Bits=2x8=16
	print "Fs: ",Fs,"\nBits: ",Bits,"\nChannels: ",Channels
	file.close()
	return Data, Fs, Bits
 
# Example: wavwrite( y, Fs, filename )
def wavwrite( data_array, Fs, name ):
	file = wave.open( name, 'w' )
	file.setframerate( Fs ) # sets sampling frequency
	file.setnchannels( 1 ) # sets number of channels
	file.setsampwidth( 2 ) # number of bytes: 16bits/8=2, 16 bits per sample
 
	clipped = False
	block_size = 1024*10 # write block size: 10k
	a_max = 32767 # max amp
	a_min = -32767 # min amp
	n = 0
	len_data_array = len( data_array ) # 2 bytes (int16) data
	while n < len_data_array :
		frame = '' # string frame of 'block_size'
		for i in range( block_size ) :
			if n < len_data_array :
				twodatabytes = int( data_array[n] * a_max )
				if twodatabytes > a_max or twodatabytes < a_min : clipped = True
				twodatabytes = min( max(twodatabytes,a_min), a_max ) # normalization, -32767..32767
				#twodatabytes.clip( min=a_min, max=a_max ) # normalization, -32767..32767
				frame += chr( twodatabytes & 0xFF ) # takes first byte, converts it to char and adds it to the frame
				frame += chr( (twodatabytes >> 8) & 0xFF ) # takes the second byte
				n += 1
		file.writeframes( frame )
	if clipped == True : print "Warning: Some values were clipped"
	print "Final length:", len_data_array/512,"kb" # n*2/1024 (bytes size/1024) = n/512
	file.close()

Nota: recomiendo bajar este archivo wav_array.py y no copiar directamente el código desde aca ya que debido al plugin para syntax highlight, el código puede no haber quedado correctamente indentado y tal vez no funcione bien al ser interpretado por python

Update: Aprovechando estas funciones y a manera de ejemplo también escribí el equivalente al post “Convolución circular rápida (aplicación en reverbs)” pero en python. El código es este: fast_conv.py.

Update 2: Para wavs de 8 bits ver: “Trabajar con wavs de 8 bits en python


, , , , , ,

Posted in audio, programming, GPL, formats, python, Castellano, library | No Comments »

 
Cerrar
Enviar por Correo