AudioResearchBlog

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

Archive for the 'free software' Category

High abstraction level audio plugins specification (and code generation)

Posted by hordia on 17th May 2010

If you ever wrote at least 2 audio plugins in your life, for sure you have noticed you had to write a lot of duplicated code. In other words, most of the times, writing a plugin there is very little entropy from your code.

My first approach to this problem was some years ago when i did a simple code generator of the base code of a clam plugin (see these clam-devel threads for more info ‘Commit #11195: templated plugins generator‘ and ‘Frontend for automatic generation of plugin code‘)

Now i’m with a simple but i think powerful project (derived from the needs i noticed at club de audio de la fiuba) to have an application to generate code of different standards using XML based specifications. Then, as before, you nearly only need to write the signal processing code of the plugin (and can forget about the mechanical work).

The idea is to get VST, LADSPA, lv2, CLAM, Audio Units and possibly others standards base code ready to compile for different operating systems and using different build systems. Indeed, once finished, will be easy to implement new modules for others plugins specifications since will consist only into implement an interface.

My proposed xml specification (comments and suggestions are welcome!), showed as a clam plugin definition example is here. Basically contains metadata, input and output ports and controls and other build definitions:

< ?xml version="1.0" encoding="UTF-8"?>
< !DOCTYPE AudioPlugin SYSTEM "AudioPluginDef.dtd">
<audioplugin Version="0.1">
        <metadata>
                <name>TestRtPlugin</name>
                <description>This is a test realtime audio plugin</description>
                <authors>Fulano, Sultano, Mengano</authors>
                <copyright Year="2010">Club de Audio FIUBA</copyright>
                <license>GPL</license>
                <category>Plugins</category>
        </metadata>
 
        <inputs>
                <port Name="L Input">AudioInPort</port>
                <port Name="R Input">AudioInPort</port>
 
                <control Name="Gain" Min="0." Max="1.0" DefaultValue=".5">InControlFloat</control>
        </inputs>
 
        <outputs>
                <port Name="L Output">AudioOutPort</port>
                <port Name="R Output">AudioOutPort</port>
        </outputs>
 
        <outputplugin Standard="CLAM" BuildSystem="Scons" OS="Linux">
                <basetemplatename>Default</basetemplatename>
 
                <clam_defaultconfig> <!--  CLAM plugin specific configuration -->
                        <baseclass>Processing</baseclass>
                        <withconfig>True</withconfig>
                </clam_defaultconfig>
        </outputplugin>
</audioplugin>

I also thought about an UID (Uniqued ID) field at metadata, there is not showed in the example since is not needed to clam plugins.

There is also a .dtd file to check the correctness of the plugin spec.


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

Posted in audio, signal processing, free software, programming, python, projects, English, CLAM, standards, plugins, specifications, ideas, ClubAudioFiuba | No Comments »

Some experience with CLAM inside an audio club at FIUBA, Argentina

Posted by hordia on 11th March 2010

(Note: I wrote this as something to tell to the clam-devel mailing list about some of my source-code commits)

About eight months ago, there was a foundation of something like an “audio club” in my university [1]. As soon i learned about that, i quickly got in touch with them and noticed that there was a major interest in analog issues (the only audio area with at least elective, courses in the university). So i told them about all the cool things that are available and ready to do with digital audio, mostly signal processing related. I talked in general, but of course i also talked about clam, with all its prototyping, real-time and easy development of plugins features. Even many of them ended installing and using it, and some even developing with more or less help. One thing to notice is that most of them are students from first years and most (but not all) are students with a basic programming level (because they are from electronics) but strong dsp knowledge (behind this is an university with more emphasis in theory than practice)
We started specifying plugins from a more abstract level (inputs/outputs/controls) and generating the source code base using
CLAM’s Templated Plugins Code Generator [2] and prototyping some simple applications. But one of the things we ended up doing was to take advantage of clam as platform to prototype medic related applications like filter ECG signal from noise in realtime, and some like _vice-versa_, i mean applying some processing knowledge from that area to audio.

Some of that work (one hour per week average) it’s now in the repo, most remarkable i think are filters work, by above the adaptative notch one (which even was used as a demo of a talk of one of the members about the steepest descent algorithm and its application to filter ECG signals)

Some development screenshots:
http://clam-project.org/wiki/Image:FilterByCoefExample.jpg
http://clam-project.org/wiki/Image:FilterExample-LP-HP.jpg
http://clam-project.org/wiki/Image:ThreeBandFilterOutputWithWhiteNoiseAsInput.jpg
http://clam-project.org/wiki/Image:GaussianWhiteNoiseHistogram.jpg
http://clam-project.org/wiki/Image:UniformWhiteNoiseHistogram.jpg

[0] FIUBA: Engineering Faculty of Buenos Aires University
[1] Group: http://code.google.com/p/club-audio-fiuba
Source code repo: http://groups.google.com/group/club_de_audio_fiuba
[2] http://audiores.uint8.com.ar/blog/2009/08/17/showing-a-little-about-clam-as-a-prototyping-tool-at-the-audio-club-of-fiuba/


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

Posted in audio, algorithms, effects, signal processing, free software, programming, matlab, GPL, c++, blog, noise, python, projects, math, English, CLAM, news, plugins, ideas, ClubAudioFiuba | No Comments »

Showing a little about CLAM as a prototyping tool at the Audio Club of FIUBA

Posted by hordia on 17th August 2009

Last week, at the recent ‘audio club’ of my university, I was showing how to work with the CLAM framework as a tool to prototype realtime audio signal processing applications in a simple and fast way.

We started with an example network to show some about the NetworkEditor capabilities: karaoke.clamnetwork
Karaoke

After that, we continue with a simple ‘diodo distortion’ plugin:

We specified and generated the source code base in this way:
Especificación de distorsión tipo diodo

We wrote this code:

bool Do()
        {
            bool result = Do( mEntrada.GetAudio(), mSalida.GetAudio() );
 
            mEntrada.Consume();
            mSalida.Produce();
 
            return result;
        }
   
        bool Do(const Audio& in, Audio& out)
        {
            int size = in.GetSize();
 
            const DataArray& inb = in.GetBuffer();
            DataArray& outb = out.GetBuffer();
 
            for (int i=0;i<size ;i++)
            {
                if ( fabs(inb[i])>0.8 )
                    outb[i] = inb[i]&lt;0.? -0.8:0.8;
                else
                    outb[i] = inb[i];
            }
            return true;
        }
</size>

And built this net to try it:
Red para probar distorsión de diodo

The source code of the plugin ready to be compiled is here: pluginDistorsiónDiodo_ClubAudioFiuba.tar.gz

As extra, I leave here pluginDistorsiónDiodoConControlDeClipping_ClubAudioFiuba.tar.gz the same diode distortion, but with a clipping control to set the threshold when playing.

They liked these kind of prototyping features a lot, so probably we’re going to keep using it at the club.


, , , , , , ,

Posted in audio, effects, signal processing, programming, English, CLAM, plugins, ClubAudioFiuba | 1 Comment »

Mostrando un poco de CLAM como herramienta para prototipar en el Club de Audio de la FIUBA

Posted by hordia on 14th August 2009

Ayer estuve mostrando un poco de como usar el framework CLAM para prototipar aplicaciones de procesamiento en tiempo real de audio de forma rápida y sencilla.

Empezamos con una red de ejemplo para mostrar un poco el NetworkEditor: karaoke.clamnetwork
Karaoke

Luego seguimos con el plugin “distorsión de diodo”.

Especificamos y generamos el código base asi:
Especificación de distorsión tipo diodo

Escribimos este código:

bool Do()
        {
            bool result = Do( mEntrada.GetAudio(), mSalida.GetAudio() );
 
            mEntrada.Consume();
            mSalida.Produce();
 
            return result;
        }
   
        bool Do(const Audio& in, Audio& out)
        {
            int size = in.GetSize();
 
            const DataArray& inb = in.GetBuffer();
            DataArray& outb = out.GetBuffer();
 
            for (int i=0;i<size ;i++)
            {
                if ( fabs(inb[i])>0.8 )
                    outb[i] = inb[i]&lt;0.? -0.8:0.8;
                else
                    outb[i] = inb[i];
            }
            return true;
        }
</size>

Y armamos una red para probarlo:
Red para probar distorsión de diodo

El código del plugin listo para compilar esta aca: pluginDistorsiónDiodo_ClubAudioFiuba.tar.gz

Como extra, en pluginDistorsiónDiodoConControlDeClipping_ClubAudioFiuba.tar.gz dejo la misma distorsión de diodo pero con un control para poder manejar el umbral de clipping mientras se reproduce.


, , , , , , ,

Posted in audio, effects, signal processing, programming, Castellano, CLAM, plugins, ClubAudioFiuba | No Comments »

Idea simple: Delay ajustable para sincronizar transmisiones de radio y tv

Posted by hordia on 17th February 2009

Desde hace bastantes (meses? años?) que tengo ganas de ver los partidos de river pero con el relato de Atilio Costa Febre (que va vía radio AM[1]), pero nunca podía hacerlo de una forma satisfactoria ya que la transmisión de la tele siempre estaba retrasada unos cuantos segundos (gritaban gol en la radio y uno veia la pelota por la mitad de la cancha, insoportable).

También hace bastante que se me habia ocurrido la simple solución de retrasar la transmisión de radio unos segundos con la computadora hasta que se sincronizara todo. El tema es que los plugins de audio clásicos, están pensados para hacer música y generalmente soportan muy pocos segundos de delay (por ejemplo el delay común de los LADSPA), asi que dije bueno, lo armo en CLAM y sale con fritas… Pero no habia delay temporal disponible (sí uno espectral), asi que lo tuve que programar, sino en 5 minutos tenia todo listo.

El resto, armar la red de conexiones con el NetworkEditor[2], la interfaz[3] con el QtDesigner, y listo el prototipo dominguero:

Prototipo de delay ajustable. Delay en décimas de segundos.

 

Aparte de todo el poderio y posiblidades que tiene CLAM, como me gusta que también sirva para salir del paso y resolver estos pequeños problemas…

[1] Dado que ahora están en radio mitre y esta transmite por internet, hasta se puede prescindir de una radio externa y usar el streaming por ejemplo con mplayer que soporta jack como backend, lo que permite conectar su salida a la entrada de la red del NetworkEditor fácilmente. El comando:

mplayer -cache 32 mms://streammitre.uigc.net/mitrevivo -ao jack 

[2] atilioSimple.clamnetwork
[3] atilioSimple.ui

, , , , , ,

Posted in audio, hardware, Castellano, CLAM, sound, plugins, ideas | No Comments »

Interactive CLAM programming (with python)

Posted by hordia on 3rd August 2008

Recently I been playing with python bindings for the CLAM library. Here is a demo demonstrating how to interactively build a network and play a file using the IPython shell:


 
Related scripts: playfile.py fft_example.py.
 
PyCLAM source. INSTALL.


, , , , , , , , , , ,

Posted in audio, signal processing, free software, programming, GPL, c++, libraries, python, projects, English, CLAM, ideas | No Comments »

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 »

Radio de Last.fm, “recordando” las canciones nuevas que escucho y me gustan

Posted by hordia on 7th July 2008

Este post surge dado que recientemente redescubrí la radio de last.fm. Principalmente gracias a que me bajé el programa que proveen ellos (btw, multiplaforma y Software Libre). Digo que redescubrí porque antes la usaba desde el amarok, cosa que esta bien, ya que uno centraliza todo ahi, pero este programita tiene algunas cosas piolas y en algunas situaciones es mucho más cómodo de usar, sobre todo para cambiar de radios, por artistas o tags, etc y encima te tira algo de data (parecido a lo que tiene el amarok que busca en wikipedia, nada más que “propiedad” de last.fm). Pero lo que me hizo “engancharme” es el tema de poner un artista que me guste y que me empiece a tirar temas con la misma onda, cosa que me hace conocer canciones e interpretes nuevos. ¿Por qué cuento esto? Por que desencadeno en que comience a usar seguido el botón de “Love”/”Favorito” de la aplicación, que es una forma de decirle a last.fm que ese tema te gusta y que lo tenga en cuenta para volverlo a pasar en el futuro o para (supongo) que tengan más probabilidad de aparecer temas similares (si no te gusta para nada, también se puede “bannear”). Bueno, todo esto viene dado que de tanto presionar “love” (y descubrir/redescubrir varios artistas, sobre todo en blues y jazz) queria tener una forma de acceder a todo eso (nombre del tema + interprete). El programa en cuestión muestra una lista de las canciones recientemente maracadas como favoritas, pero no permite copy&paste y tampoco vía web hay forma de acceder a esa información, como si pasa con otras cosas, por ejemplo las canciones recientemente escuchadas… (con la nueva versión del sitio si se puede: Last.fm: The Next Generation)

Bueno, buscando un poco di con la API (versión 2.0), al parecer reciente, pero sin la capacidad de “recuperar” las últimas loved songs… asi que me remití a la versión 1.0 que si lo permite y además se puede usar sin api key. Entonces lo que hice fue armarme un script en python que descargara las últimas canciones “favoritas” y las vaya guardando en un xml (o .txt), es decir a medida que aparecen nuevas, las agrega y elimina los duplicados…

El script es este: recentLovedTracksList.py

Tip: si uno quiere estar seguro de no perderse ninguna canción, dado que las “canciones favoritas recientes” son solo 10, puede poner este script a correr en cron… (si es que va marcar muchas canciones como favoritas, pero a lo sumo y con mucha suerte uno marca como “loved” una por hora y la frecuencia por supuesto tiende bajar)

Ya que estaba jugando con la api, hice otro script para descargarme todo el historial de escucha (otra “feature” que no vi disponible vía web, pero por suerte con un poco de “hacking” se puede hacer con la API):

lastfmProfileBackup.py

No se para que me puede servir, pero es info mía y ya que la tiene otra persona, al menos me gusta poder tenerla yo :-P

Otras aplicaciones

Ya que escribo sobre last.fm aprovecho para comentar un par de “nuevos usos” que se me ocurrieron de este tipo de sistemas, ambos se aplican a un player haciendo scrobbling en una fiesta/reunión:

  • Con esto se tiene automáticamente trackeada y publicada la lista de canciones que se escucharon. ¿Cuantas veces uno quiere saber como se llama esa canción que le gustó el día anterior para poder volverla a escucharla?
  • Si uno no quiere estar eligiendo música, pero quiere asegurarse que va a escuchar algo de su agrado, puede poner su radio personalizada y listo… “satisfacción garantizada” :P . Esta feature ahora es paga, pero dado que cualquier usuario puede escuchar la radio del otro… no es difícil imaginarse como se puede salvaguardar este punto… de todas formas, la suscripción no es cara, alrededor de 3 euros por mes (creo).



, , , , , , ,

Posted in music, free software, python, Castellano, web, MIR, ideas | No Comments »

La historia de Horgand (conversación con holborn)

Posted by hordia on 28th June 2008

Hace bastante tiempo que tenia archivada esta conversación sobre síntesis por FM y Horgand que quería publicar.

Qué es Horgand? un sintetizador por soft capaz de realizar sonidos de órgano y otros tipos de sonido como pianos eléctricos (Rhodes , Wurlitzer, DX E.Piano ), Jazz Guitar, Strings, Brass, Fretless Bass, Accordion etc. Esta basado en síntesis por FM, según su web:

“Is based on a FM audio synthesizer with twenty carriers (20) without modulators in a plain based algorithm.
each carrier frequency can be modified for construct complex sounds. The synthesizer incorporate also a LFO (Low frequency oscillator) for generate tremolo effects and detune effects applying LFO Pitch and Amplitude to the carrier frequency’s. Some synthesizer parameters can be edited for each sound including two ADSR, (Normal and Percussion), Fine Frequency, Attenuation, Rotary Amplitude, Transpose, etc. Four DSP effects are available for obtain more complex sounds, Rotary, Chorus, Delay and Reverberation. Sounds are stored in banks of 32 organ sounds and can be changed externally with MIDI program change (1-32).”

También incorpora reconocimiento de acordes para producir acompañamiento automático (bajo y bateria) y con líneas de bajo editables para cada ritmo.

Ejemplo de como suena: Horgand_demo.ogg

No conozco mucho de síntesis por FM y tenía curiosidad de como lograba el sonido y terminó saliendo una especie de entrevista improvisada, creo que puede ser interesante para quienes quieran adentrarse en este tipo de programación.

La conversación:

<hordia> despues me tenes que contar en que te basaste para conseguir el sonido de horgand digitalmente…
<holborn> pues en el DX7 …. tiene 32 algoritmos de colocacion de los operadores … pero si usas el plano (todos en linea)… todo lo que hagas suena a organo … a partir de ahi … pues añadirle los efectos … y claro en vez de 6 “osciladores” hay 10 … que en realidad son 20 … con lo cual pues es mas rico que un emulador de dx7 tipo hexter o en el dx7 mismo … en realidad .. para usar 20 osciladores no chupa CPU nada … otros porgramas usan 3 y ch
<holborn> claro que para ahorrar cpu .. tuve que limitar algunos parametros de edicion … pero bueno … yo lo que queria era que sonara … si nadie se pone a editar sonidos … ni dios vaya …
<hordia> que es el DX7? :P me suena a un teclado legendario pero no estoy seguro…

<holborn> el DX7 fue el primer sintetizador FM … es de yamaha .. y fue una revolucion porque era el primero que mas o menos imitaba bien sonidos reales … algunos mejor que otros …
<holborn> los vendieron todos y mas …
<holborn> yo realmente era un experto … en aquella epoca ni dios sabia nada de musica electronica … yo me hice un curso que daba un loco de la musica electronica .. y sabia programar sintes cosa que nadie sabia .. te estoy hablando de hace mil años …
<holborn> cuando salio el DX7 pues me tuve que empapar toda la info porque realmente es muy diferente a un sinte analogico tradicional … y bueno .. le pedi a un amigo que trabajaba en un distribuidor de yamaha .. que me consiguiera info de verdad … de hecho todavia la conservo ..por ahi ..
<hordia> :O
<holborn> yo llegue a trabajar programando sintes en un estudio de grabacion …. vaya no todos los dias pero me llamaban de vez en cuando
<holborn> haciendo presets … me refiero .. claro
<hordia> veo que horgand es el resultado de muchos años de experiencia…
<holborn> si … a ese nivel si … pero todo fue gracias a un ejemplo de la web de alsa .. .se llama fmminisynth.c … o lago asi … 100 lineas de codigo … entonces se me ocurrio … y empece ..

<holborn> luego buscando … encuentras mil ejemplos de codigo … en HArmony Central … no esta el codigo pero explican como funcionan los efectos … en cristiano .. sin mucha matematica … esta muy bien .. luego ya el implementarlo es cosa de uno … pero el mismo Paul Nasca dice por ahi (el del zyn) que se basa en esa explicaciones … y yo tambien claro :)
<holborn> ya te aseguro que su implementacion es mejor que la mia :)
<hordia> jeje
<holborn> ahora …la mia consume un tercio de cpu que la suya :)
<hordia> entonces hay que ver que parametros se toman para definir cual es mejor ;-)
<holborn> pues es un sinte … lo que suena … sus efectos suenan mejor …. pero … el usa 3 o 4 osciladores por sonido … yo uso 20 … con lo cual en algun lado hay que recortar …

El ejemplo que se menciona: miniFMsynth.c


, , , , , , , , , , ,

Posted in audio, algorithms, effects, free software, programming, instruments, GNU/Linux, GPL, c++, alsa, Castellano, sound | No Comments »

Distortion rack prototype

Posted by hordia on 5th January 2008

A nice prototype:

CLAM distortion rack prototype

 
 

And the net behind:

CLAM distortion rack prototype


, , , , ,

Posted in effects, English, CLAM, GUI, sound | No Comments »

 
Cerrar
Enviar por Correo