Edited version of the wave player class that uses the MODDMA library to handle transfers to the DAC.

Dependencies:   MODDMA

Dependents:   WavePlayer_MODDMA wave_player_DMA_mbed

wave_player.cpp

Committer:
ebradley6
Date:
2016-03-16
Revision:
1:11a670498598
Parent:
0:286582877314

File content as of revision 1:11a670498598:

//-----------------------------------------------------------------------------
// a sample mbed library to play back wave files using MODDMA 
// Based on the wave_player library by Steve Ravet and the 
// MODDMA library by Andy Kirkham. 
// 
// The wave_player library is located here:
// https://developer.mbed.org/users/sravet/code/wave_player/
// 
// The MODDMA library is located here:
// https://developer.mbed.org/users/AjK/code/MODDMA/
// A wiki page and example are located here:
// https://developer.mbed.org/cookbook/MODDMA
//
// explanation of wave file format.
// https://ccrma.stanford.edu/courses/422/projects/WaveFormat/

// if VERBOSE is uncommented then the wave player will enter a verbose
// mode that displays all data values as it reads them from the file
// and writes them to the DAC.  Very slow and unusable output on the DAC,
// but useful for debugging wave files that don't work.
//#define VERBOSE


#include <mbed.h>
#include <stdio.h>
#include <wave_player.h>

//-----------------------------------------------------------------------------
// constructor -- accepts an mbed pin to use for AnalogOut.  Only p18 will work
wave_player::wave_player(AnalogOut *_dac)
{
  wave_DAC=_dac;
  wave_DAC->write_u16(32768);        //DAC is 0-3.3V, so idles at ~1.6V
  verbosity=0;
}

//-----------------------------------------------------------------------------
// if verbosity is set then wave player enters a mode where the wave file
// is decoded and displayed to the screen, including sample values put into
// the DAC FIFO, and values read out of the DAC FIFO by the ISR.  The DAC output
// itself is so slow as to be unusable, but this might be handy for debugging
// wave files that don't play
//-----------------------------------------------------------------------------
void wave_player::set_verbosity(int v)
{
  verbosity=v;
}

//-----------------------------------------------------------------------------
// player function.  Takes a pointer to an opened wave file.  The file needs
// to be stored in a filesystem with enough bandwidth to feed the wave data.
// LocalFileSystem isn't, but the SDcard is, at least for 22kHz files.  The
// SDcard filesystem can be hotrodded by increasing the SPI frequency it uses
// internally.
//-----------------------------------------------------------------------------
void wave_player::play(FILE *wavefile)
{
    unsigned chunk_id,chunk_size,channel;
    unsigned data,i;
    unsigned j,k;
    int dac_cntval;
    bool buf0_flag;
    long long slice_value;
    char *slice_buf;
    short *data_sptr;
    unsigned char *data_bptr;
    int *data_wptr;
    FMT_STRUCT wav_format;
    long num_slices;
  
    for(i=0; i<BUF_SIZE; i++){
        DAC_buf0[i]=0;
        DAC_buf1[i]=0;
    }   
  
    DAC_on=0;
  
    int time=0;

    fread(&chunk_id,4,1,wavefile);
    fread(&chunk_size,4,1,wavefile);
  
    while (!feof(wavefile)) {
        if (verbosity)
            printf("Read chunk ID 0x%x, size 0x%x\n",chunk_id,chunk_size);
        switch (chunk_id) {
            case 0x46464952:
                fread(&data,4,1,wavefile);
                if (verbosity) {
                    printf("RIFF chunk\n");
                    printf("  chunk size %d (0x%x)\n",chunk_size,chunk_size);
                    printf("  RIFF type 0x%x\n",data);
                }
                break;
            case 0x20746d66:
                fread(&wav_format,sizeof(wav_format),1,wavefile);
                if (verbosity) {
                    printf("FORMAT chunk\n");
                    printf("  chunk size %d (0x%x)\n",chunk_size,chunk_size);
                    printf("  compression code %d\n",wav_format.comp_code);
                    printf("  %d channels\n",wav_format.num_channels);
                    printf("  %d samples/sec\n",wav_format.sample_rate);
                    printf("  %d bytes/sec\n",wav_format.avg_Bps);
                    printf("  block align %d\n",wav_format.block_align);
                    printf("  %d bits per sample\n",wav_format.sig_bps);
                }
                if (chunk_size > sizeof(wav_format))
                    fseek(wavefile,chunk_size-sizeof(wav_format),SEEK_CUR);
                break;
            case 0x61746164:
                // Data chunk which contains the audio samples to send to the DAC
            
                // allocate a buffer big enough to hold a slice
                slice_buf=(char *)malloc(wav_format.block_align);
                if (!slice_buf) {
                    printf("Unable to malloc slice buffer");
                    exit(1);
                }
                num_slices=chunk_size/wav_format.block_align;
        
                // Calculating the transfer frequency:
                // By default, the Mbed library sets the PCLK_DAC clock value
                // to 24MHz. 
        
                dac_cntval=(24000000/wav_format.sample_rate);
       
                if (verbosity) {
                    printf("DATA chunk\n\r");
                    printf("  chunk size %d (0x%x)\n\r",chunk_size,chunk_size);
                    printf("  %d slices\n\r",num_slices);
                    printf("  sample rate is %d\r\n", wav_format.sample_rate);
                    printf("  Ideal sample interval=%d\n\r",(unsigned)(1000000.0/wav_format.sample_rate));
                    printf("  programmed interrupt tick interval=%d\n\r",dac_cntval);
                }
  
                // Prepare the GPDMA system for buffer0.
                conf0 = new MODDMA_Config;
                conf0
                ->channelNum    ( MODDMA::Channel_0 )
                ->srcMemAddr    ( (uint32_t) &DAC_buf0 )
                ->dstMemAddr    ( MODDMA::DAC )
                ->transferSize  ( BUF_SIZE )
                ->transferType  ( MODDMA::m2p )
                ->dstConn       ( MODDMA::DAC )
                ->attach_tc     ( this,&wave_player::TC0_callback )
                ->attach_err    ( this,&wave_player::ERR0_callback )     
                ; // config end
    
                // Prepare the GPDMA system for buffer1.
                conf1 = new MODDMA_Config;
                conf1
                ->channelNum    ( MODDMA::Channel_1 )
                ->srcMemAddr    ( (uint32_t) &DAC_buf1 )
                ->dstMemAddr    ( MODDMA::DAC )
                ->transferSize  ( BUF_SIZE )
                ->transferType  ( MODDMA::m2p )
                ->dstConn       ( MODDMA::DAC )
                ->attach_tc     ( this,&wave_player::TC1_callback )
                ->attach_err    ( this,&wave_player::ERR1_callback )     
                ; // config end
    
                // Set the DAC to the audio sample rate
                LPC_DAC->DACCNTVAL = dac_cntval;
    
                // Begin (enable DMA and counter). Note, don't enable
                // DBLBUF_ENA as we are using DMA double buffering.
                LPC_DAC->DACCTRL |= (3UL << 2);
  
                DAC_on=1; 

                // start reading slices, which contain one sample each for however many channels
                // are in the wave file.  one channel=mono, two channels=stereo, etc.  Since
                // mbed only has a single AnalogOut, all of the channels present are averaged
                // to produce a single sample value.  This summing and averaging happens in
                // a variable of type signed long long, to make sure that the data doesn't
                // overflow regardless of sample size (8 bits, 16 bits, 32 bits).
                //
                // note that from what I can find that 8 bit wave files use unsigned data,
                // while 16 and 32 bit wave files use signed data
                //
                
                // Fill buffer 0 first
                buf0_flag=1;
        
                // Separate slices into sections of BUF_SIZE samples        
                for (j=0; j<((num_slices/BUF_SIZE)+1); j++)
                {
                    for(k=0; k<BUF_SIZE; k++)
                    {
                        // The last buffer will likely not be exactly BUF_SIZE,
                        // so fill the remaining spots with 0
                        if((j*BUF_SIZE+k)>num_slices){
                            if(buf0_flag)
                                DAC_buf0[k]=0;
                            else
                                DAC_buf1[k]=0;
                        }
                        else{
                            // Read audio samples from sd card
                            fread(slice_buf,wav_format.block_align,1,wavefile);
                            if (feof(wavefile)) {
                                printf("Oops -- not enough slices in the wave file\n");
                                exit(1);
                            }
                            data_sptr=(short *)slice_buf;     // 16 bit samples
                            data_bptr=(unsigned char *)slice_buf;     // 8 bit samples
                            data_wptr=(int *)slice_buf;     // 32 bit samples
                            slice_value=0;
                            for (channel=0;channel<wav_format.num_channels;channel++) {
                                switch (wav_format.sig_bps) {
                                    case 16:
                                        if (verbosity)
                                            printf("16 bit channel %d data=%d ",channel,data_sptr[channel]);
                                        slice_value+=data_sptr[channel];
                                        break;
                                    case 32:
                                        if (verbosity)
                                            printf("32 bit channel %d data=%d ",channel,data_wptr[channel]);
                                        slice_value+=data_wptr[channel];
                                        break;
                                    case 8:
                                        if (verbosity)
                                            printf("8 bit channel %d data=%d ",channel,(int)data_bptr[channel]);
                                        slice_value+=data_bptr[channel];
                                        break;
                                }
                            }
                            slice_value/=wav_format.num_channels;
              
                            // slice_value is now averaged.  Next it needs to be scaled to an unsigned 16 bit value
                            // with DC offset so it can be written to the DAC.
                            switch (wav_format.sig_bps) {
                                case 8:     slice_value<<=8;
                                    break;
                                case 16:    slice_value+=32768;
                                    break;
                                case 32:    slice_value>>=16;
                                            slice_value+=32768;
                                    break;
                            }

                            if (verbosity)
                                printf("sample %d slice_value %d\n",(j*BUF_SIZE+k),(int)slice_value);
                            if(buf0_flag)
                                DAC_buf0[k]=(uint32_t)slice_value;
                            else
                                DAC_buf1[k]=(uint32_t)slice_value;
                        }
                    }
          
                    // Except for the first buffer, wait until the previous DMA transfer is
                    // complete before switching buffers
                    if(j>0)
                    {
                        while((dma0_fin_flag==0)&(dma1_fin_flag==0)&(time<500000000)){
                            wait_us(1);
                            time++;
                        }
                    }
                    
                    if (time>499999999)
                    {
                        printf("timeout, %d of %d\r\n", (j*BUF_SIZE), num_slices);
                        exit(1);
                    }
            
                    time=0;
                    dma0_fin_flag=0;
                    dma1_fin_flag=0; 
          
                    // If finished filling buffer 0, set flag to fill buffer 1
                    // and start the DMA transfer for buffer 0
                    if(buf0_flag==1)
                    {
                        buf0_flag=0;
                        dma.Setup(conf0);
                        dma.Enable( conf0 );
                    }
                    else // Similarly for buffer 1
                    {
                        buf0_flag=1;
                        dma.Setup(conf1);
                        dma.Enable( conf1 );
                    }

                }
                DAC_on=0;
                delete conf0;
                delete conf1;
                free(slice_buf);
                break;
            case 0x5453494c:
                if (verbosity)
                    printf("INFO chunk, size %d\n",chunk_size);
                fseek(wavefile,chunk_size,SEEK_CUR);
                break;
            default:
                printf("unknown chunk type 0x%x, size %d\n",chunk_id,chunk_size);
                data=fseek(wavefile,chunk_size,SEEK_CUR);
                break;
        }
        fread(&chunk_id,4,1,wavefile);
        fread(&chunk_size,4,1,wavefile);
    }
}

// Configuration callback on TC; runs when the DMA has finished transferring buffer 0 to the DAC
void wave_player::TC0_callback(void) {
        
    // Get configuration pointer.
    MODDMA_Config *config = dma.getConfig();
    
    // Only run once
    dma.haltAndWaitChannelComplete( (MODDMA::CHANNELS)config->channelNum());
    
    // Finish the DMA cycle by shutting down the channel.
    dma.Disable( (MODDMA::CHANNELS)config->channelNum() );

    // Clear DMA IRQ flags.
    if (dma.irqType() == MODDMA::TcIrq) dma.clearTcIrq();
    
    // Indicate that buffer 0 has finished transferring
    dma0_fin_flag=1; 
}

// Configuration callback on Error
void wave_player::ERR0_callback(void) {
    error("Oh no! My Mbed EXPLODED! :( Only kidding, go find the problem");
}

// Configuration callback on TC; runs when the DMA has finished transferring buffer 1 to the DAC
void wave_player::TC1_callback(void) {
        
    // Get configuration pointer.
    MODDMA_Config *config = dma.getConfig();
    
    // Only run once
    dma.haltAndWaitChannelComplete( (MODDMA::CHANNELS)config->channelNum());
    
    // Finish the DMA cycle by shutting down the channel.
    dma.Disable( (MODDMA::CHANNELS)config->channelNum() );
    
    // Clear DMA IRQ flags.
    if (dma.irqType() == MODDMA::TcIrq) dma.clearTcIrq(); 
    
    // Indicate that buffer 1 has finished transferring
    dma1_fin_flag=1;
}

// Configuration callback on Error
void wave_player::ERR1_callback(void) {
    error("Oh no! My Mbed EXPLODED! :( Only kidding, go find the problem");
}