Streams USB audio with sound effects applied. Sound effect selected by joystick and intensity altered by tilting the mbed. Output to the mbed-application-board phono jack.

Dependencies:   C12832_lcd MMA7660 USBDevice mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers buffer.cpp Source File

buffer.cpp

00001 /*******************************************************************************
00002  * Implements FIFO buffer for glitch-free audio playback.
00003  * Bryan Wade
00004  * 27 MAR 2014
00005  ******************************************************************************/
00006 #include "buffer.h"
00007 #include "string.h"
00008 
00009 struct buffer_t { // Implementation of opaque type.
00010     int16_t *base;
00011     int16_t *head;
00012     int16_t *tail;
00013     size_t len;
00014 };
00015 
00016 /*
00017  * Create a buffer object given a ptr and size of available RAM.
00018  * @return Ptr to the new buffer.
00019  */
00020 buffer_t *Buffer_Create(void *ram, size_t size)
00021 {
00022     buffer_t *buffer = (buffer_t *)malloc(sizeof(buffer_t));
00023     if (buffer) {
00024         buffer->base = (int16_t *)ram;
00025         buffer->len = size / sizeof(int16_t);
00026         memset(ram, 0, size);
00027         buffer->head = buffer->tail = buffer->base;
00028     }
00029     return buffer;
00030 }
00031 
00032 /*
00033  * Read a single sample from the buffer.
00034  * @return True if successful (no underflow).
00035  */
00036 bool Buffer_Read(buffer_t *buffer, int16_t *pDataOut)
00037 {
00038     if (buffer->head == buffer->tail)
00039         return false;
00040 
00041     *pDataOut = *buffer->tail;
00042 
00043     if (++buffer->tail >= buffer->base + buffer->len) {
00044         buffer->tail = buffer->base;
00045     }
00046 
00047     return true;
00048 }
00049 
00050 /*
00051  * Write a single sample to the buffer.
00052  */
00053 void Buffer_Write(buffer_t *buffer, int16_t dataIn)
00054 {
00055     if (Buffer_GetLevel(buffer) >= buffer->len - 1)
00056         return;
00057     
00058     *buffer->head = dataIn;
00059 
00060     if (++buffer->head >= buffer->base + buffer->len)
00061         buffer->head = buffer->base;
00062 }
00063 
00064 /*
00065  * Write a block of data to the buffer.
00066  */
00067 void Buffer_WriteBlock(buffer_t *buffer, const int16_t *pDataIn, uint32_t length)
00068 {
00069     int i;
00070     for (i = 0; i < length; i++) {
00071         Buffer_Write(buffer, pDataIn[i]);
00072     }
00073 }
00074 
00075 /*
00076  * Get buffer level
00077  */
00078 int32_t Buffer_GetLevel(buffer_t *buffer) 
00079 {
00080     __disable_irq(); /* Begin critical section */
00081     
00082     int32_t level = (buffer->head >= buffer->tail) ?
00083                     buffer->head - buffer->tail :
00084                     buffer->len + buffer->head - buffer->tail;
00085                     
00086     __enable_irq(); /* End critical section */
00087     
00088     return level;
00089 }