L`MP3 e il Music Information Retrieval (MIR)

Transcript

L`MP3 e il Music Information Retrieval (MIR)
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
L’MP3 e
il Music Information Retrieval (MIR)
Prof. Michele Scarpiniti
Dipartimento di Ingegneria dell’Informazione, Elettronica e Telecomunicazioni
“Sapienza” Università di Roma
http://ispac.diet.uniroma1.it/scarpiniti/index.htm
[email protected]
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
1 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
1
Introduzione
Introduzione
2
Il formato MP3
Introduzione
I principi dell’MP3
L’MP3 in Matlab
3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
2 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
Introduzione
Introduzione
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
3 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
Introduzione
L’obiettivo di queste slides è di introdurre ed illustrare brevemente il funzionamento della codifica MP3 dei file audio.
Successivamente, si passa a descrivere il funzionamento di software per il
Music Information Retreival (MIR), in particolare si illustrerà come reperire
il nome di un brano da un database di riferimento, ovvero svilupperemo un
R
software simile a Shazam .
Maggiori informazioni possono essere reperite al link http://labrosa.ee.
columbia.edu/matlab/fingerprint/ da cui è anche possibile scaricare
l’intero codice in Matlab.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
4 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Il formato MP3
Il formato MP3
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
5 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Introduzione
Il formato MP3 nasce dalla necessità di ridurre il bit/rate per lo streaming
di un segnale audio e l’occupazione di memoria del file che lo contiene.
Come esempio consideriamo un file audio stereofonico (2 canali), quantizzato a 16 bit e campionato con qualità CD a 44.1 kHz. Il bit/rate che si
ottiene è pari a:
2 × 16 × 44100 ≈ 1.41 Mb/s
Di conseguenza, per memorizzare un’ora di musica su un supporto fisico
quale un hard-disk, è necessario disporre di uno spazio pari a
60 × 60 ×
1.41 × 106
≈ 605 MB
8 × 220
ricordando che 1 byte è pari a 8 bit, e 1 kB = 1024 B.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
6 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Introduzione
In aggiunta può essere eventualmente considerato il problema di garantire
la sincronizzazione e di correggere gli errori commessi. Al fine di risolvere
tali problematiche, a valle della codifica viene introdotto un overhead. Si
può arrivare al caso in cui un campione di 16 bit sia rappresentato con 49
bit. Il bit/rate finale, per l’esempio precedente, diviene dunque:
2 × 49 × 44100 ≈ 4.32 Mb/s
Si capisce facilmente che è necessario introdurre un certo tipo di
compressione del segnale audio, al fine di ridurre il bit/rate.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
7 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Il CD-DA e il CD-ROM
L’audio è spesso memorizzato su supporto CD, che contiene solitamente 74
minuti di sonoro. Il CD è organizzato in settori la cui dimensione è tale per
cui ogni secondo sono letti 75 settori. Dunque un settore contiene:
1.41 × 106
= 2352 B
8 × 75
Un CD da 74 minuti contiene quindi:
74 × 60 × 75 = 330000 settori
Nel CD-DA (ovvero il CD Audio) tutti i bytes del settore vengono utilizzati
per i dati, lasciando all’interpolazione con i campioni vicini il compito di
correggere eventuali errori. Un CD-DA pieno, ovvero 74 minuti di musica,
occupano quindi:
333000 × 2352
= 749.9 MB
220
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
8 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Il CD-DA e il CD-ROM
Al contrario un CD-ROM che contiene “file” di natura eterogenea, deve
incorporare in se le informazioni necessarie per correggere eventuali errori. A
tal fine non tutti i 2352 bytes di un settore servono per memorizzare i dati,
ma una parte è utilizzata per la sincronizzazione e la correzione di errori.
Ho due soluzioni diverse. Precisamente:
1 Mode 1: si utilizzano 2048 bytes.
2 Mode 2: si utilizzano 2324 bytes, utilizzato nei video CD (VCD).
La capacità di un CD-ROM da 74 minuti è quindi
333000 × 2048
= 650.4 MB
220
per il Mode 1, e
333000 × 2324
= 738.0 MB
220
per il Mode 2.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
9 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Il CD-DA e il CD-ROM
In sintesi, i byte di un settore sono organizzati nel modo seguente.
Formato CD‐DA CD‐ROM Mode 1 CD‐ROM Mode 1 Struttura del settore: 2352 byte 2352 (Data) 12 (Sync) 3 (Address) 1 (Mode) 12 (Sync) 3 (Address) 1 (Mode) 2048 (Data) 4 (Error det) 8 (Riservati) 276 (Error corr) 2336 (Data) Entrambi i CD-ROM Mode 1 e Mode 2 hanno un header di 16 byte utilizzati
per la sincronizzazione e per descrivere la modalità di scrittura (Mode 1
oppure Mode 2).
Il CD-ROM Mode 1 utilizza 280 byte per la detection e la correzione degli
errori. 8 byte sono riservati per utilizzi personalizzati.
Al contrario, nel CD-ROM Mode 2 è presente il solo header di 16 byte.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
10 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
L’idea dell’MP3
Una eventuale compressione per il segnale audio deve ovviamente essere
molto efficiente, nel senso che idealmente deve diminuire molto il bit/rate,
mantenendo inalterata la qualità del segnale. La qualità del segnale, da
parte di un ascoltatore, dipende da caratteristiche percettive: si cercherà di
ridurre la ridondanza percettiva del segnale.
Dunque, si può pensare che:
1
le diverse componenti del segnale possono essere tanto più compresse
quanto più esse sono percettivamente trascurabili;
2
a frequenze diverse si possono utilizzare rate di compressioni diversi;
3
in presenza del fenomeno del mascheramento acustico, provocato da
più stimoli sovrapposti, è possibile aumentare la compressione.
Si vuole arrivare a codificare il segnale audio con 1 o 2 bit per campione.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
11 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
L’idea dell’MP3
Il gruppo di esperti di immagini in movimento (ovvero il Moving Picture Expert
Group) o MPEG ha messo a punto uno standard di compressione audio/video
molto efficente. Il successo di tale tecnica è dovuta a diversi fattori:
1
è uno standard aperto;
2
esiste molta documentazione libera;
3
la complessità algoritmica è sbilanciata verso il codificatore, facilitando lo
sviluppo e la diffusione di decodificatori molto veloci ed economici.
La prima versione è lo standard MPEG-1, creato all’inizio degli anni ’90. Esistono
tre schemi di codifica differenti, chiamati Layers (Layer I, Layer II e Layer III), a
cui corrispondono diversi bit-rate medi. Il formato MP3 corrisponde allo standard
MPEG-1 Layer III.
Standard
Layer I
Layer II
Layer III
M. Scarpiniti
bit-rate medio
384 Kb/s
192 Kb/s
128 Kb/s
L’MP3 e il Music Information Retrieval (MIR)
12 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
I principi alla base dell’MP3
I principi alla base dell’MP3 (ma anche degli altri Layers) sono di natura
percettiva. In particolare:
1 come già sappiamo, l’orecchio umano percepisce alla “stessa”
intensità due suoni a frequenza diversa con diversi livelli di intensità
(audiogramma normale). E’ quindi possibile determinare delle bande
che saranno compresse più di altre, in modo proporzionale alla
“sordità” dell’orecchio in quella banda.
2 In presenza di più toni in contemporanea (come nel caso musicale), la
presenza di un tono più forte aumenta la soglia di minima udibilità
alle frequenze adiacenti (effetto di mascheramento). Anche queste
componenti possono essere scartate o codificate con basso bit-rate.
3 Un suono più potente può inoltre mascherare un altro più debole che
si verifica in un breve intervallo temporale successivo (50 - 200 ms) o
precedente (< 5 ms).
L’idea è quindi di lavorare in sotto-bande con un banco filtri.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
13 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
I principi alla base dell’MP3
L’effetto del mascheramento è graficamente illustrato nella seguente figura.
Soglia di
udibilità
Spostamento della
soglia
Soglia di minima
udibilità
f
Segnali mascherati
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
14 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Funzionamento dell’MP3: il coder
Il funzionamento dell’MP3 è dunque descritto dalla seguente figura, in cui
il banco filtri è utilizzato per decomporre il segnale in 32 sotto-bande;
il modello percettivo utilizza il segnale sia nel dominio temporale che
in frequenza, al fine di valutare l’effetto del mascheramento;
la quantizzazione e codifica si occupa di quantizzare le componenti
spettrali e di codificarle in funzione della banda e del mascheramento;
la codifica del bitstream forma il bitstream finale insieme alle
informazioni aggiuntive di cui è composto il file MP3.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
15 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Funzionamento dell’MP3: il decoder
Al contrario, il decoder è illustrato nella seguente figura, in cui:
la decodifica del bitstream estrae le varie componenti quantizzate dal
file MP3;
la quantizzazione inversa si occupa di riottenere le varie componenti
spettrali;
il banco filtri di sintesi è utilizzato per ricomporre il segnale audio nel
tempo dalle 32 sotto-bande.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
16 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Il funzionamento dell’MP3
Lo standard MPEG-1 lavora con il segnale suddiviso in frame di lunghezza
pari a 384 campioni (per il Layer I) e 1152 campioni (per il Layer II e Layer
III). La grandezza in bit di tali frame è variabile, poiché dipende dal bit-rate
variabile. Si noti che 1152 = 3 × 384.
Per semplicità di ragionamento si consideri il caso di una frequenza di campionamento pari a 48 kHz. Allora ogni sotto-banda del segnale è pari
a
24 × 103
= 750 Hz
32
Il banco filtri utilizzato è a massima decimazione, pertanto ogni sequenza
in uscita da ogni sotto-banda è decimata di un fattore 32, e quindi è lunga:
1152
= 36 campioni
32
Inoltre il banco filtri è a ricostruzione perfetta, ovvero in assenza di compressione l’uscita è esattamente uguale all’ingresso.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
17 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Il funzionamento dell’MP3
I 36 campioni in uscita da ogni sotto-banda sono suddivisi in 3 blocchi da 12
campioni. Per ogni blocco viene valutato il valore massimo (definito fattore
di scala): per ogni sotto-banda vengono quindi trasmessi i 3 fattori di scala
associati.
Per il Layer I e II, i fattori di scala in uscita da ogni sotto-banda sono
quindi quantizzati, attraverso un processo di quantizzazione uniforme e poi
codificati utilizzando meno bit nelle sotto-bande più mascherate. L’entità
del mascheramento è calcolata attraverso un’analisi FFT.
Al contrario, nel Layer III le sequenze dei fattori di scala ottenute vengono
trasformate con la Trasformata del Coseno Discreto Modificata o Modified Discrete Cosine Transform (MDCT). Le sequenze trasformate vengono
quindi quantizzate, attraverso un processo di quantizzazione non uniforme
(più fitta per valori più piccoli) e poi codificate utilizzando meno bit nelle
sotto-bande più mascherate.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
18 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Il funzionamento dell’MP3
E’ comunque possibile sfruttare le correlazioni tra i 3 fattori di scala e tra i
due canali per ridurre il numero di bit.
Una illustrazione completa del codificatore MP3 è mostrata nella figura
sottostante.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
19 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Struttura del file MP3
Un file MP3 è una successione di frames costituiti ognuno da un header di
32 bit e in sequenza i dati. E’ possibile avere un blocco CRC di 16 bit, per
la gestione degli errori. Il dettaglio della struttura del file è illustrata nella
figura sottostante.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
20 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Un codificatore MP3: il LAME
Sono disponibili diversi codificatori MP3. E’ molto utile il codificatore
LAME (letteralmente LAME Ain’t an MP3 Encoder), che è reperibile al
seguente link: http://lame.sourceforge.net/
Il LAME è un insieme di librerie da includere in altro software ed eseguibili
con cui è possibile ottenere direttamente un file MP3.
La libreria LAME è rilasciata sotto licenza libera LGPL, ma in alcuni paesi
non tutti i componenti del software possono essere distribuiti senza ottenere
un’adeguata licenza.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
21 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Leggere e scrivere un file MP3
E’ possibile scaricare dal seguente link http://labrosa.ee.columbia.
edu/matlab/mp3read.html o dal sito di Matlab Central, due funzioni
Matlab per leggere e scrivere un file MP3.
Affinché queste due funzioni possano essere utilizzate correttamente è necessario utilizzare congiuntamente, ovvero avere nella stessa cartella di lavoro, altri tre file eseguibili ed un file di libreria dinamica dll. Precisamente:
1
mpg123.exe: è il decoder MP3 utilizzato in lettura;
2
mp3info.exe: serve in lettura per leggere tutte le proprietà e gli
attributi del file;
3
lame.exe: è il coder MP3 utilizzato in scrittura;
4
lame enc.dll: contiene metodi e funzioni utilizzate da lame.exe.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
22 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Leggere un file MP3
Per leggere un file MP3 in Matlab si utilizza il comando:
>> [x , Fs , Nb , opt ] = mp3read ( ’ nome_file . mp3 ’) ;
che restituisce i campioni del segnale nel vettore x, la frequenza di campionamento
Fs , il numero di bit Nb della quantizzazione e ulteriori informazioni sul file.
Alternativamente, si può utilizzare il comando con molti argomenti opzionali
>> [x , ...] = mp3read ( ’ nome_file . mp3 ’ , N , MONO , DOWNSAMP , DELAY ) ;
per leggere i primi N campioni (o dal campione N1 al campione N2 se N è un
vettore di tali due elementi), forzare a considerare il file come monofonico (con
MONO = 1), usare un fattore di decimazione pari a 2 o 4. Infine il parametro
DELAY consente di specificare quanti campioni saltare all’inizio del file per
allineare il file di lettura e di scrittura. Di default è 2257 e serve a “sanare” un
bug del programma mpg123.exe.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
23 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Scrivere un file MP3
La funzione mp3read() utilizza l’eseguibile mpg123.exe per ottenere un file
wav temporaneo, che viene quindi letto da wavread.
Per scrivere un file MP3 in Matlab si utilizza il comando:
>> mp3write (y , Fs , Nb , ’ nome_file ’[ , opt ]) ;
che scrive un file di nome “nome file.mp3” contenenti i dati del vettore y,
la frequenza di campionamento Fs , il numero di bit della quantizzazione
Nb ed eventuali ulteriori opzioni sul file.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
24 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi dell’MP3
L’MP3 in Matlab
Leggere e scrivere un file MP3 in Matlab
Nelle nuove versioni di Matlab è possibile leggere un file MP3 con la nuova
funzione
>> [x , Fs ] = audioread ( ’ nome_file . mp3 ’[ , opt ]) ;
E’ ovviamente importante specificare, in questo caso, sempre l’estensione
.mp3 del file.
Per scrivere il file MP3, si può quindi utilizzare
>> audiowrite ( ’ nome_file . mp3 ’ , y , Fs [ , opt ]) ;
specificando sempre l’estensione del file.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
25 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Il Music Information Retrieval (MIR)
Il Music Information Retrieval (MIR)
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
26 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Introduzione
Per Music Information Retrieval (MIR) si intende una tecnica per ottenere
informazioni da un file audio. In particolare, in questa sezione si è interessati
a rintracciare il nome del brano che si sta ascoltando da un database di
riferimento.
Si mostra un’implementazione Matlab del servizio commerciale per smartphone fornito da Shazam. Tale servizio fu sviluppato da Avery Wang e
iniziato nel 1999. Si utilizza il microfono incorporato nello smartphone per
catturare un breve spezzone di una canzone in riproduzione. Viene quindi
creata un’impronta digitale acustica e confrontata con un database centrale
alla ricerca di somiglianze. In caso positivo, sul display dello smartphone
vengono mostrate le informazioni sull’artista, il titolo e il testo della canzone.
L’obiettivo è quindi lo sviluppo di un algoritmo di ricerca audio. Maggiori
informazioni e il codice Matlab sono reperibili al link: http://www.ee.
columbia.edu/~dpwe/resources/matlab/fingerprint/.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
27 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Obiettivi della ricerca audio
Un ipotetico algoritmo di ricerca audio di un brano all’interno di un database di riferimento, deve soddisfare a diversi obiettivi. In particolare,
l’algoritmo deve:
funzionare con spezzoni brevi di un brano;
essere insensibile al rumore di fondo e al possibile riverbero
introdotto dall’ambiente in cui è utilizzato;
essere robusto alle distorsioni non lineari introdotte dallo
smartphone;
generare rapidamente la risposta, ricercando all’interno di un database
di riferimento generalmente molto grande (milioni di brani).
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
28 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
I principi di base
La ricerca audio è effettuata attraverso un’operazione di fingerprinting sul
segnale audio. Tale operazione è prima eseguita sul database di riferimento
generando un tabella di hash e quindi sul brano in ascolto estraendo le
stesse informazioni. Viene quindi effettuata una ricerca nella tabella per
trovare una possibile corrispondenza.
E’ importante ottenere dei fingerprints che siano:
temporalmente localizzati: in modo che eventi distanti non possano
influenzare la tabella di hash;
invarianti alle traslazioni: in modo tale che siano riproducibili
indipendentemente da quale “pezzo” di segnale è stato registrato;
robusti: in modo tale che siano riproducibili anche se registrati in
ambienti rumorosi;
sufficientemente entropici: in modo tale da minimizzare la
probabilità di falsi matching.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
29 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
L’architettura di base
L’architettura di base del sistema proposto è formata da tre blocchi fondamentali:
1
creazione della costellazione;
2
generazione della tabella di hash;
3
ricerca del brano.
Tale architettura, implementata da Shazam, garantisce ottime performace.
In particolare, l’algoritmo:
è molto robusto al rumore;
è molto veloce;
mostra un’alta specificità e un numero trascurabile di falsi matching.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
30 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Creazione della costellazione
Una caratteristica poco sensibile alla presenza di rumore, è rappresentata dai picchi
dello spettrogramma: un punto tempo-frequenza è un picco, se presenta una
energia elevata rispetto ai punti vicini. I probabili picchi sono poi selezionati con un
criterio di densità, in modo da averne sempre un certo numero per ogni frammento
di segnale registrato.
Uno spettrogramma complicato è quindi rappresentato con un insieme limitato
(sparso) di coordinate tempo-frequenza, senza più mantenere il valore in ampiezza
del picco. Quest’ultima è chiamata mappa della costellazione.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
31 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Creazione della costellazione
Tale rappresentazione è molto robusta alla presenza di rumore ed eventuale
equalizzazione sul segnale. Infatti, anche in presenza di rumore ed equalizzazione, un numero non trascurabile di picchi dello spettrogramma, si
troveranno ancora nelle stesse posizioni tempo-frequenza e possono essere
utilizzate per il matching.
Nella fase di matching, la costellazione estratta dal brano incognito, deve
essere la stessa del database. Se, ovviamente, si estrae solo uno spezzone corto di segnale, il matching viene effettuato traslando la costellazione estratta sull’intera costellazione ottenuta da tutto il segnale, fino a
raggiungere una buona sovrapposizione.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
32 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Generazione della tabella di hash
Sfortunatamente, la ricerca della posizione corretta a partire dall’intera mappa
di costellazione risulta computazionalmente molto onerosa e poco efficiente. Per
questo motivo, dalla costellazione vengono estratti degli hash, combinando insieme
due punti tempo-frequenza.
Si seleziona un punto tempo-frequenza come ancora a cui corrisponde una relativa
zona target. Il punto di ancora è successivamente accoppiato con ciascun punto
all’interno della zona target, generando ogni volta due componenti di frequenza e
la differenza temporale tra i punti. Ogni hash cosı̀ estratto è associato poi ad
un tempo di offset, ovvero il tempo del punto di ancora dall’inizio del brano. Ogni
hash può anche essere rappresentato con un unsigned integer a 32 bit.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
33 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Generazione della tabella di hash
Ripetendo l’operazione precedente per tutte le tracce in un database di riferimento,
si ottiene un database di indici che verrà utilizzato successivamente per l’eventuale
matching di un brano incognito.
Il numero di hash per secondo è pari al prodotto della densità della costellazione
d per il fan-out F , ovvero il numero di punti tempo-frequenza nella zona target:
numero di hash = d × F
Inoltre:
il fatto di concatenare due punti per ogni hash, accelera la procedura di
ricerca di 22×Nbit /F 2 ;
se p indica la probabilità che un picco dello spettrogramma di riferimento
sopravviva anche nel brano incognito registrato da un dispositivo mobile,
allora la probabilità di trovare almeno un hash per ogni punto di ancora è:
h
i
F
p 1 − (1 − p) ≈ p
se p > 0.1 e F > 10.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
34 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Ricerca di un brano musicale
Per eseguire una ricerca di un brano sconosciuto, viene eseguita la procedura precedente per generare un insieme di hash e relativi offset temporali. Ogni hash dal
campione è utilizzato per la ricerca nella tabella del database di riferimento. Per
ogni corrispondenza trovata, si prende la coppia di offset temporali dal campione
e dal brano del database. Tali coppie di offset temporali sono distribuite in bin
secondo l’identificativo della traccia del database di riferimento.
Dopo che si è eseguita la ricerca in tutto il database di riferimento, si fa la scansione
degli istogrammi ottenuti. Ogni bin genera un punto di uno scatterplot dei tempi
di offset. Nel caso di matching positivo, si osserva un picco in un istogramma
dei tempi di offset e una corrispondenza lineare del relativo scatterplot.
generally a peak in the spectrum
is still a e
peakil
withMusic
the
Yang
also considered the use of Retrieval
spectrogram peaks, but(MIR)
M. Scarpiniti
L’MP3
Information
same coordinates in a filtered spectrum (assuming that the
employed them in a different way [10].
aggregate 64-bit struct, 32 bits for the hash and 32 bits for
the time offset and track ID. To facilitate fast processing,
speedup is a factor of about 1000000/F2, or about 10000,
over token searches based on single constellation points.
35 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Ricerca di un brano musicale
La corrispondenza lineare dello scatterplot relativo ad un matching, si
manifesta sullo scatterplot come un allineamento dei punti lungo una retta
a pendenza unitaria. Infatti, il tempo tk0 della k-esima corrispondenza del
database di riferimento è legato al tempo tk del brano registrato tramite
tk0 = tk + offset
Per ogni punto (tk0 , tk ) dello scatterplot, si costruisce quindi l’istogramma
dei valori:
δtk = tk0 − tk
Quando dalla procedura di scanning del database viene fuori una corrispondenza significativa in termini di istogramma, l’identificativo della traccia è
utilizzato per richiamare il nome del brano e relative informazioni.
Si noti che durante la fase di matching, non si suppone nessun particolare
formato per gli hash.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
36 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Implementazione in Matlab
Dal seguente link http://www.ee.columbia.edu/~dpwe/resources/matla
fingerprint/ è possibile scaricare una versione Matlab del software che
implementa la procedura di fingerprinting descritta in precedenza.
Gli esempi mostrati utilizzano files in formato compresso MP3: a tal proposito si utilizzerà la funzione mp3read vista in precedenza per caricare i
campioni da tale file. E’ ovviamente possibile utilizzare anche file in fomato
wave o in qualsiasi altro formato se si ha a disposizione una funzione per
leggere il file specifico.
Il codice per il fingerprinting proposto al link precedente, è scritto per ambiente Linux. L’unica differenza è nella lettura di file da una cartella. Si è
modificata tale procedura, sostituendo la funzione myls del pacchetto con
una nuova funzione load files appositamente scritta.
Nel seguito si illustrerà il codice per il fingerprinting.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
37 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Lo script principale
Il main del programma di fingerprinting è organizzato nel modo seguente.
path = ’C :\ Users \ Michele Scarpiniti \ Desktop \ fingerprint \ Audio_DB \ ’;
ext = ’ *. mp3 ’;
tks = load_files ( path , ext ) ; % Carico i file
% tks = myls ( path ) ;
c le ar _h a shtable
% Inizializza la tabella di hash
add_tracks ( tks ) ; % Aggiunge le tracce del database alla tabella
[x , Fs ] = mp3read ( ’Q - full - circle . mp3 ’) ; % Carico il campione da trovare
R = match_query (x , Fs ) ; % Eseguo la query
disp ( ’ Premi un tasto per vedere il risultato ’) ;
pause ;
R (1 ,:)
% Vedo il risultato
>> 5 18 1 18
[ pth , nam , ext ] = fileparts ( tks { R (1 ,1) }) ;
nome_matching = [ nam ext ];
fprintf ( ’ Il brano cercato è : % s \ n \ n ’ , nome_matching ) ;
il l u s t r a t e_match (x , Fs , tks ) ; % plotto i matching
colormap (1 - gray )
Il risultato “5 18 1 18” significa che c’è stato un matching con 18 picchi per la
traccia 5, che la traccia di esempio inizia 1 frame dopo il brano di riferimento e
un totale di 18 hash del brano incognito coincidono con quelli del database di
riferimento. Nel seguito verranno analizzate le singole funzioni.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
38 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Caricare i segnali
La funzione che carica i segnali, è cosı̀ costituita:
function F = load_files (D , ext )
sources_dir = D ;
sour ces_pref ix = ext ;
sources_path = fullfile ( sources_dir , sourc es_pref ix ) ;
sources_list = dir ( sources_path ) ;
num_file = length ( sources_list ) ;
for s = 1: num_file ,
source_file = [ sources_dir sources_list ( s ) . name ];
F { s } = source_file ;
end
F è un insieme di celle che contiene i nomi dei file con il relativo percorso.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
39 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Inizializzazione della tabella di hash
Per inizializzare la tabella di hash, si procede come segue.
function c l ea r_ ha s ht ab le ()
global HashTable Ha sh T ab le Co u nt s
nhashes = 2^20; % 1 M hash x 32 bit ent x 100 ent = 400 MB
maxnentries = 100;
disp ([ ’ Max entries per hash = ’ , num2str ( maxnentries ) ]) ;
HashTable = zeros ( maxnentries , nhashes , ’ uint32 ’) ;
H as hT ab l eC ou nt s = zeros (1 , nhashes ) ;
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
40 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Aggiungere le tracce alla tabella di hash
Per aggiungere una traccia alla tabella di hash, si esegue la funzione add tracks(tks)
fatta nel modo seguente.
function [N , T ] = add_tracks (D , Fs , ID )
dens = 10;
% Numero di landmarks per secondo
if isnumeric ( D )
H = landmark2hash ( find_landmarks (D , Fs , dens ) , ID ) ;
record_hashes ( H ) ;
N = length ( H ) ;
T = length ( D ) / Fs ;
elseif ischar ( D )
if nargin < 3
ID = Fs ;
end
[D , Fs ] = readaudio ( D ) ;
[N , T ] = add_tracks (D , Fs , ID ) ;
elseif iscell ( D )
disp ([ ’ Target density = ’ , num2str ( dens ) , ’ hashes / sec ’ ]) ;
nd = length ( D ) ;
if nargin < 3
skip = 0;
else
skip = ID ;
end
if nargin < 2
Fs = [];
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
41 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Aggiungere le tracce alla tabella di hash
if length ( Fs ) == 0
ID = 1: nd ;
else
ID = Fs ;
end
N = 0;
T = 0;
for i = ( skip +1) : nd
disp ([ ’ Adding # ’ , num2str ( ID ( i ) ) , ’ ’ ,D { i } , ’ ... ’ ]) ;
[n , t ] = add_tracks ( D { i } , ID ( i ) ) ;
N = N + n;
T = T + t;
end
disp ([ ’ added ’ , num2str ( nd ) , ’ tracks ( ’ , num2str ( T ) , ’ secs , ’ , ...
num2str ( N ) , ’ hashes , ’ , num2str ( N / T ) , ’ hashes / sec ) ’ ]) ;
else
error ( ’I cant tell what D is ’) ;
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
42 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Leggere il file audio
Per leggere il file audio e caricare i campioni, si utilizza:
function [D , Fs ] = readaudio ( FN )
[ pth , nam , ext ] = fileparts ( FN ) ;
ext = lower ( ext ) ;
if strcmp ( ext , ’. mp3 ’)
[D , Fs ] = mp3read ( FN ) ; % Legge un MP3
elseif strcmp ( ext , ’. m4a ’) || strcmp ( ext , ’. aac ’)
[D , Fs ] = m4aread ( FN ) ; % Legge un M4A o AAC
else
[D , Fs ] = wavread ( FN ) ; % Legge un WAV
end
A secondo dell’estensione del file, viene letto un MP3, un M4A o AAC,
ovvero un file WAV.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
43 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Trovare i picchi dello spettrogramma (landmarks)
Per trovare i landmarks, ovvero i picchi dello spettrogramma, si utilizza
function [L ,S ,T , maxes ] = find_landmarks (D , Fs , N )
if nargin < 3; N = 7; end
f_sd = 30;
a_dec = 1 -0.01*( N /35) ;
maxp ksperframe = 5;
hpf_pole = 0.98;
targetdf = 31;
targetdt = 63;
[ nr , nc ] = size ( D ) ;
if nr > nc
D = D ’;
[ nr , nc ] = size ( D ) ;
end
if nr > 1
D = mean ( D ) ; % Si rende D monofonico
nr = 1;
end
targetFs = 8000;
if ( Fs ~= targetFs )
D = resample (D , targetFs , Fs ) ; % Ricampiono alla Fs target
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
44 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Trovare i picchi dello spettrogramma (landmarks)
% Calcolo dello spettrogramma
fft_ms = 64;
fft_hop = 32;
nfft = round ( targetFs /1000* fft_ms ) ;
S = abs ( specgram (D , nfft , targetFs , nfft , nfft - round ( targetFs /1000* fft_hop ) ) ) ;
Smax = max ( S (:) ) ;
S = log ( max ( Smax /1 e6 , S ) ) ;
S = S - mean ( S (:) ) ;
S = ( filter ([1 -1] ,[1 - hpf_pole ] ,S ’) ’) ;
maxespersec = 30;
ddur = length ( D ) / targetFs ;
nmaxkeep = round ( maxespersec * ddur ) ;
maxes = zeros (3 , nmaxkeep ) ;
nmaxes = 0;
maxix = 0;
s_sup = 1.0;
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
45 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Trovare i picchi dello spettrogramma (landmarks)
% Stima dei picchi
sthresh = s_sup * spread ( max ( S (: ,1: min (10 , size (S ,2) ) ) ,[] ,2) , f_sd ) ’;
T = 0* S ; % Decay treshold
for i = 1: size (S ,2) -1
s_this = S (: , i ) ;
sdiff = max (0 ,( s_this - sthresh ) ) ’;
sdiff = locmax ( sdiff ) ;
sdiff ( end ) = 0; % i . e . bin 257 from the sgram
[ vv , xx ] = sort ( sdiff , ’ descend ’) ;
xx = xx ( vv >0) ;
nmaxthistime = 0;
for j = 1: length ( xx )
p = xx ( j ) ;
if nmaxthistime < maxpksperframe
if s_this ( p ) > sthresh ( p )
nmaxthistime = nmaxthistime + 1;
nmaxes = nmaxes + 1;
maxes (2 , nmaxes ) = p ;
maxes (1 , nmaxes ) = i ;
maxes (3 , nmaxes ) = s_this ( p ) ;
eww = exp ( -0.5*(([1: length ( sthresh ) ] ’ - p ) / f_sd ) .^2) ;
sthresh = max ( sthresh , s_this ( p ) * s_sup * eww ) ;
end
end
end
T (: , i ) = sthresh ;
sthresh = a_dec * sthresh ;
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
46 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Trovare i picchi dello spettrogramma (landmarks)
% Backwards pruning of maxes
maxes2 = [];
nmaxes2 = 0;
whichmax = nmaxes ;
sthresh = s_sup * spread ( S (: , end ) , f_sd ) ’;
for i = ( size (S ,2) -1) : -1:1
while whichmax > 0 && maxes (1 , whichmax ) == i
p = maxes (2 , whichmax ) ;
v = maxes (3 , whichmax ) ;
if v >= sthresh ( p )
nmaxes2 = nmaxes2 + 1;
maxes2 (: , nmaxes2 ) = [ i ; p ];
eww = exp ( -0.5*(([1: length ( sthresh ) ] ’ - p ) / f_sd ) .^2) ;
sthresh = max ( sthresh , v * s_sup * eww ) ;
end
whichmax = whichmax - 1;
end
sthresh = a_dec * sthresh ;
end
maxes2 = fliplr ( maxes2 ) ;
max pa ir s perpeak =3; % Numero massimo di coppie per picco
L = zeros ( nmaxes2 * maxpairsperpeak ,4) ;
% matrice dei landmark
nlmarks = 0;
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
47 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Trovare i picchi dello spettrogramma (landmarks)
for i =1: nmaxes2
startt = maxes2 (1 , i ) ;
F1 = maxes2 (2 , i ) ;
maxt = startt + targetdt ;
minf = F1 - targetdf ;
maxf = F1 + targetdf ;
matchmaxs = find (( maxes2 (1 ,:) > startt ) & ( maxes2 (1 ,:) < maxt ) & ( maxes2 (2 ,:) > minf ) & (
maxes2 (2 ,:) < maxf ) ) ;
if length ( matchmaxs ) > maxpairsperpeak
matchmaxs = matchmaxs (1: maxpairsperpeak ) ;
end
for match = matchmaxs
nlmarks = nlmarks + 1;
L ( nlmarks ,1) = startt ;
L ( nlmarks ,2) = F1 ;
L ( nlmarks ,3) = maxes2 (2 , match ) ;
L ( nlmarks ,4) = maxes2 (1 , match ) - startt ;
end
end
L = L (1: nlmarks ,:) ;
if verbose
disp ([ ’ find_landmarks : ’ , num2str ( length ( D ) / targetSR ) , ’ secs , ’ ,...
num2str ( size (S ,2) ) , ’ cols , ’ , ...
num2str ( nmaxes ) , ’ maxes , ’ , ...
num2str ( nmaxes2 ) , ’ bwd - pruned maxes , ’ , ...
num2str ( nlmarks ) , ’ lmarks ’ ]) ;
end
maxes = maxes2 ;
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
48 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Trovare i picchi dello spettrogramma (landmarks)
La funzione precedente utilizza le seguenti due funzioni per la ricerca dei picchi:
function Y = locmax ( X )
X = X (:) ’;
nbr = [X , X ( end ) ] >= [ X (1) ,X ];
Y = X .* nbr (1: end -1) .* (1 - nbr (2: end ) ) ;
function Y = spread (X , E )
if nargin < 2; E = 4; end
if length ( E ) == 1
W = 4* E ;
E = exp ( -0.5*[( - W : W ) / E ].^2) ;
end
X = locmax ( X ) ;
Y = 0* X ;
lenx = length ( X ) ;
maxi = length ( X ) + length ( E ) ;
spos = 1 + round (( length ( E ) -1) /2) ;
for i = find (X >0)
EE = [ zeros (1 , i ) ,E ];
EE ( maxi ) = 0;
EE = EE ( spos +(1: lenx ) ) ;
Y = max (Y , X ( i ) * EE ) ;
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
49 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Aggiungere i landmark nella tabella di hash
La seguente funzione aggiunge i landmark trovati alla tabella di hash precedentemente creata.
function H = landmark2hash (L , S )
if nargin < 2
S = 0;
end
if length ( S ) == 1
S = repmat (S , size (L ,1) , 1) ;
end
H = uint32 ( L (: ,1) ) ;
F1 = rem ( round ( L (: ,2) -1) ,2^8) ; % F \ è tra 0 e 255 ( non 1 - 256)
DF = round ( L (: ,3) -L (: ,2) ) ;
if DF < 0
DF = DF + 2^8;
end
DF = rem ( DF ,2^6) ;
DT = rem ( abs ( round ( L (: ,4) ) ) , 2^6) ;
H = [S ,H , uint32 ( F1 *(2^12) + DF *(2^6) + DT ) ];
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
50 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Salvare la tabella di hash
Dopo aver aggiunto i landmark alla tabella di hash, si salva quest’ultima in memoria.
function N = record_hashes ( H )
global HashTable HashTableCounts
maxnentries = size ( HashTable ,1) ;
nhash = size (H ,1) ;
N = 0;
TIMESIZE = 16384;
for i =1: nhash
song = H (i ,1) ;
toffs = mod ( round ( H (i ,2) ) , TIMESIZE ) ;
hash = 1 + H (i ,3) ; % evita problemi per hash == 0
htcol = HashTable (: , hash ) ;
nentries = HashTableCounts ( hash ) + 1;
if nentries <= maxnentries
r = nentries ;
else
r = ceil ( nentries * rand (1) ) ;
end
if r <= maxnentries
hashval = int32 ( song * TIMESIZE + toffs ) ;
HashTable (r , hash ) = hashval ;
N = N +1;
end
H as hT ab leCounts ( hash ) = nentries ;
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
51 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Salvare la tabella di hash
La funzione precedente ritorna il numero N di hash salvati in memoria.
La tabella di hash H è quindi costituita da N righe, ognuna delle quali è di
tre elementi, precisamente:
<song id> <start time index> <hash>
Ogni riga è codificata con 52 bit: nello specifico
Campo
song ID
start time index
hash
M. Scarpiniti
Numero di bit
24
8
20
L’MP3 e il Music Information Retrieval (MIR)
Note
16M brani
risoluzione di 256 s
1M slots
52 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Effettuare una query
Per effettuare la query di un brano incognito nel database di riferimento, si inviano i
campioni e la frequenza di campionamento del brano alla seguente funzione.
function [R , L ] = match_query (D , Fs , IX )
if nargin < 3
IX = 1;
end
if ischar ( D )
if nargin > 1
IX = Fs ;
end
[D , Fs ] = readaudio ( D ) ;
end
dens = 20; % Densità dei landmark
if size (D ,2) == 2
D = mean (D ,2) ;
end
Lq = find _landmarks (D , Fs , dens ) ;
land marks_hopt = 0.032;
% Ricalcolo i landamrks su finestre diverse
Lq = [ Lq ; find_landmarks ( D ( round ( landmarks_hopt /4* Fs ) : end ) ,Fs , dens ) ];
Lq = [ Lq ; find_landmarks ( D ( round ( landmarks_hopt /2* Fs ) : end ) ,Fs , dens ) ];
Lq = [ Lq ; find_landmarks ( D ( round (3* landmarks_hopt /4* Fs ) : end ) ,Fs , dens ) ];
Hq = unique ( landmark2hash ( Lq ) , ’ rows ’) ;
disp ([ ’ landmarks ’ , num2str ( size ( Lq ,1) ) , ’ -> ’ , num2str ( size ( Hq ,1) ) , ’ hashes ’ ]) ;
Rt = get_hash_hits ( Hq ) ;
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
53 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Effettuare una query
nr = size ( Rt ,1) ;
if nr > 0
[ utrks , xx ] = unique ( sort ( Rt (: ,1) ) , ’ first ’) ;
utrkcounts = diff ([ xx ’ , nr ]) ;
[ utcvv , utcxx ] = sort ( utrkcounts , ’ descend ’) ;
utcxx = utcxx (1: min (20 , length ( utcxx ) ) ) ; % Massimo 20
utrkcounts = utrkcounts ( utcxx ) ;
utrks = utrks ( utcxx ) ;
nutrks = length ( utrks ) ;
R = zeros ( nutrks ,4) ;
for i = 1: nutrks
tkR = Rt ( Rt (: ,1) == utrks ( i ) ,:) ;
[ dts , xx ] = unique ( sort ( tkR (: ,2) ) , ’ first ’) ;
dtcounts = 1 + diff ([ xx ’ , size ( tkR ,1) ]) ;
[ vv , xx ] = max ( dtcounts ) ;
R (i ,:) = [ utrks ( i ) , sum ( abs ( tkR (: ,2) - dts ( xx (1) ) ) <=1) , dts ( xx (1) ) , size ( tkR ,1) ];
end
[ vv , xx ] = sort ( R (: ,2) , ’ descend ’) ;
R = R ( xx ,:) ;
Hix = find ( Rt (: ,1) == R ( IX ,1) ) ;
for i = 1: length ( Hix )
L (i ,:) = [ hash2landmark ( Rt ( Hix ( i ) ,:) ) , Rt ( Hix ( i ) ,2) ];
hqix = find ( Hq (: ,3) == Rt ( Hix ( i ) ,3) ) ;
hqix = hqix (1) ;
L (i ,1) = L (i ,1) + Hq ( hqix ,2) ;
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
54 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Effettuare una query
maxrtns = 100; % Non più di 100 risultati
if size (R ,1) > maxrtns
R = R (1: maxrtns ,:) ;
end
maxhits = R (1 ,2) ;
nuffhits = R (: ,2) >(0.1* maxhits ) ;
else
R = zeros (0 ,4) ;
disp ( ’ *** NO HITS FOUND *** ’) ;
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
55 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Ottenere i matching
Per ottenere i matching dalla query si utilizza la seguente funzione.
function R = get_hash_hits ( H )
global HashTable HashTableCounts
if size (H ,2) == 3 H = H (: ,[2 3]) ; end
if min ( size ( H ) ) ==1
H = [ zeros ( length ( H ) ,1) ,H (:) ];
end
nhtcols = size ( HashTable ,1) ;
TIMESIZE =16384;
Rsize = 1000; % preallocata
R = zeros ( Rsize ,3) ;
Rmax = 0;
for i = 1: length ( H )
hash = H (i ,2) ;
htime = double ( H (i ,1) ) ;
nentries = min ( nhtcols , HashTableCounts ( hash +1) ) ;
htcol = double ( HashTable (1: nentries , hash +1) ) ;
songs = floor ( htcol / TIMESIZE ) ;
times = round ( htcol - songs * TIMESIZE ) ;
if Rmax + nentries > Rsize
R = [ R ; zeros ( Rsize ,3) ];
Rsize = size (R ,1) ;
end
dtimes = times - htime ;
R ( Rmax +[1: nentries ] ,:) = [ songs , dtimes , repmat ( double ( hash ) , nentries ,1) ];
Rmax = Rmax + nentries ;
end
R = R (1: Rmax ,:) ;
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
56 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Illustrare i matching
I risultati vengono mostrati per via grafica attraverso la funzione seguente.
function [ DM , SRO , TK , T ] = illustrate_match ( DQ , Fs , FL , IX )
if nargin < 4; IX = 1; end
if isstr ( DQ )
[ DQ , Fs ] = readaudio ( DQ ) ;
end
[R , Lm ] = match_query ( DQ , Fs , IX ) ;
Lm = Lm ( abs ( Lm (: ,5) -R ( IX ,3) ) < 1 ,:) ;
dens = 7;
Lq = find _landmarks ( DQ , Fs , dens ) ;
subplot (211)
show _landmarks ( DQ , Fs , Lq ) ;
tbase = 0.032; % time base of analysis
matchtrk = R ( IX ,1) ;
matchdt = R ( IX ,3) ;
[d , FsO ] = readaudio ( FL { matchtrk }) ;
Ld = find _landmarks (d , FsO , dens ) ;
subplot (212)
show _landmarks (d , FsO , Ld , matchdt * tbase + [0 length ( DQ ) / Fs ]) ;
mbase = 1 + round ( matchdt * tbase * FsO ) ;
mend = mbase - 1 + round ( length ( DQ ) * FsO / Fs ) ;
DM = [ zeros (1 , max (0 , -( mbase -1) ) ) , d ( max (1 , mbase ) : mend ) ];
[p , name , e ] = fileparts ( FL { matchtrk }) ;
name ( find ( name == ’_ ’) ) = ’ ’;
title ([ ’ Match : ’ , name , ’ at ’ , num2str ( matchdt * tbase ) , ’ sec ’ ]) ;
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
57 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Illustrare i matching
show _landmar ks ([] , FsO , Lm ,[] , ’o - g ’) ;
subplot (211)
show _landmar ks ([] , FsO , Lm - repmat ([ matchdt 0 0 0 0] , size ( Lm ,1) ,1)
,[] , ’o - g ’) ;
title ( ’ Query audio ’)
TK = matchtrk ;
T = matchdt ;
Tale procedura utilizza la funzione show landmark per sovraimporre i landmark
allo spettrogramma del segnale. Tale funzione è strutturata come mostrato nelle
prossime slide.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
58 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Illustrare i matching
function show_landmarks (D , SR ,L ,T , C )
if nargin < 4
if nargin < 5
T = [];
end
C = ’o - r ’; end
targetSR = 8000;
fft_ms = 64;
nfft = round ( targetSR /1000* fft_ms ) ;
win_overlap = 2;
my_w in_overlap = 4;
fbase = targetSR / nfft ;
tbase = fft_ms / win_overlap /1000;
my_tbase = fft_ms / my_win_overlap /1000;
if ( size (D ,1) <3) || ( size (D ,2) <3) % c ’ è un file audio
if length ( D ) > 0
if size (D ,1) > size (D ,2)
D = D ’;
end
if size (D ,1) == 2;
D = mean ( D ) ;
end
if ( SR ~= targetSR )
srgcd = gcd ( SR , targetSR ) ;
D = resample (D , targetSR / srgcd , SR / srgcd ) ;
end
S = abs ( specgram (D , nfft , targetSR , nfft , nfft - nfft / my_win_overlap ) ) ;
end
else
S = D;
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
59 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Illustrare i matching
if length ( D ) > 0
[ nr , nc ] = size ( S ) ;
tt = [1: nc ]* my_tbase ;
ff = [0: nr -1]* fbase ;
imagesc ( tt , ff ,20* log10 ( S ) ) ;
axis xy
ca = caxis ;
caxis ([ -80 0]+ ca (2) ) ;
end
hold on
for i = 1: size (L ,1) ;
lrow = L (i ,:) ;
t1q = lrow (1) ;
f1q = lrow (2) ;
f2q = lrow (3) ;
dtq = lrow (4) ;
t2q = t1q + dtq ;
t1 = t1q * tbase ;
t2 = t2q * tbase ;
f1 = f1q * fbase ;
f2 = f2q * fbase ;
plot ([ t1 t2 ] ,[ f1 f2 ] , C ) ;
end
hold off
if length ( T ) == 2
a = axis ;
axis ([ T (1) T (2) a (3) a (4) ]) ;
end
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
60 / 61
Introduzione
Il formato MP3
Il Music Information Retrieval (MIR)
Introduzione
I principi di base
Implementazione in Matlab
Bibliografia
K. Brandenburg.
MP3 and AAC explained.
AES 17-th International Conference on High Quality Audio Coding, August 1999.
P. Noll.
MPEG Digital Audio Coding.
IEEE Signal Processing Magazine, Vol. 14, N. 5, pp.59-81, September 1997.
D. Pan.
A tutorial on MPEG/Audio Compression.
IEEE Transaction on Multimedia, Vol. 12, N. 2, pp. 60-74, Summer 1995.
J. Stephen Downie.
Music information retrieval.
Annual Review of Information Science and Technology, Vol. 37, pp. 295-340, 2003.
Available from http://music-ir.org/downie_mir_arist37.pdf.
A. Li-Chun Wang.
An Industrial-Strength Audio Search Algorithm.
Proceedings of the 4-th International Conference on Music Information Retrieval, Baltimore, MD, October 2003.
D. Ellis.
Robust Landmark-Based Audio Fingerprinting.
Available from http://labrosa.ee.columbia.edu/matlab/fingerprint/.
M. Scarpiniti
L’MP3 e il Music Information Retrieval (MIR)
61 / 61