Library to control and transfer data from NXP SGTL5000. As used on the Teensy Audio Shield. It uses DMA to transfer I2S FIFO data.

The Library now supports dual codecs. Allowing all 4 channels of the Teensy I2S interface to RX and TX data to separate SGTL5000 devices.

The ISR routines that handles pointer swaps for double buffering has been fully coded in assembler to reduce overhead and now takes < 800nS per FIFO transfer when using all 4 channels.

Support added for all typical sample rates and system Clock speeds of 96Mhz or 120Mhz.

Pause and Resume functions added to allow quick and simple suppression of IRQs and stream halting and restart. This required software triggered IRQ, in order to ensure accurate word sync control.

sgtl5000.h

Committer:
aidan1971
Date:
2017-09-27
Revision:
14:9043626add45
Parent:
13:83c2aaf4a338

File content as of revision 14:9043626add45:

/*!
@ author Aidan Walton, aidan.walton@gmail.com

@section LICENSE
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice, development funding notice, and this permission
 * notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.

@section DESCRIPTION
    Library for NXP SGTL5000 Codec
*/

#ifndef MBED_SGTL5000_H
#define MBED_SGTL5000_H

#include "mbed.h"
#include "platform.h"
#include "Callback.h"
#include "sgtl5000_defs.h"


/** SGTL5000 namespace
*/
namespace SGTL5000
{


/*! SGTL5000 codec driver class
*/
/*! Class for NXP SGTL5000 codec instance.
*   Supports dual codecs. One using I2S TX&RX channel_0 the other I2S TX&RX channel_1. The instance created for codec1 (I2S channel_0 CODEC CS = LOW) is the master, 
    all stream ctrl functions (start, stop, pause & resume) are synchronous to this master codec and must be initiated by the master codec object. 
*   @code
*   #include 'SGTL5000.h'
*
*   SGTL5000::SGTL5000 codec(I2C_SDA, I2C_SCL);
*
*   static q31_t *RX_AudioL = NULL;
*   static q31_t *RX_AudioR = NULL;
*   static q31_t *TX_AudioL = NULL;
*   static q31_t *TX_AudioR = NULL;
*
*   const uint32_t I2S_FIFO_BS = 4;
*
*
*   uint32_t main()
*   {
*       codec.init();    
*       codec.modify_i2c(SGTL5000_ANA_HP_CTRL, 0x18, SGTL5000_ANA_HP_CTRL_HP_VOL_RIGHT_MASK);   // Headphone volume control with 0.5 dB steps.0x00 = +12 dB, 0x01 = +11.5 dB, 0x18 = 0 dB,...0x7F = -51.5 dB
*       codec.modify_i2c(SGTL5000_ANA_HP_CTRL, 0x18, SGTL5000_ANA_HP_CTRL_HP_VOL_LEFT_MASK);
*
*       codec.attach_SYNC_NB((uint32_t)&I2S_SYNC_ISR);
*       codec.sample_rate(96);
*       codec.start_SYNC((uint32_t)&RX_AudioL, (uint32_t)&RX_AudioR, (uint32_t)&TX_AudioL, (uint32_t)&TX_AudioR, I2S_FIFO_BS)
*   }
*
*   void I2S_SYNC_ISR(void)
*   {
*       for(uint32_t i = 0; i < (I2S_FIFO_BS >> 1); ++i)
*       {
*           TX_AudioL[i] = RX_AudioL[i];
*           TX_AudioR[i] = RX_AudioR[i];
*       }
*   }
@endcode
*
*   To implement dual CODECs
*   @code
*   #include 'SGTL5000.h'
*
*   SGTL5000::SGTL5000 codec1_ctrl(I2C_SDA, I2C_SCL);
*   SGTL5000::SGTL5000 codec2(I2C_SDA, I2C_SCL);
*
*   static q31_t *RX_AudioL1 = NULL;
*   static q31_t *RX_AudioR1 = NULL;
*   static q31_t *TX_AudioL1 = NULL;
*   static q31_t *TX_AudioR1 = NULL;
*   static q31_t *RX_AudioL2 = NULL;
*   static q31_t *RX_AudioR2 = NULL;
*   static q31_t *TX_AudioL2 = NULL;
*   static q31_t *TX_AudioR2 = NULL;
*
*   const uint32_t I2S_FIFO_BS = 4;
*
*
*   uint32_t main()
*   {
*       codec1_ctrl.init();
*       codec2.init();
*       codec1_ctrl.modify_i2c(SGTL5000_ANA_HP_CTRL, 0x18, SGTL5000_ANA_HP_CTRL_HP_VOL_RIGHT_MASK);     // Headphone volume control with 0.5 dB steps.0x00 = +12 dB, 0x01 = +11.5 dB, 0x18 = 0 dB,...0x7F = -51.5 dB
*       codec1_ctrl.modify_i2c(SGTL5000_ANA_HP_CTRL, 0x18, SGTL5000_ANA_HP_CTRL_HP_VOL_LEFT_MASK);
*       codec2.modify_i2c(SGTL5000_ANA_HP_CTRL, 0x01, SGTL5000_ANA_HP_CTRL_HP_VOL_RIGHT_MASK);          // Headphone volume control with 0.5 dB steps.0x00 = +12 dB, 0x01 = +11.5 dB, 0x18 = 0 dB,...0x7F = -51.5 dB
*       codec2.modify_i2c(SGTL5000_ANA_HP_CTRL, 0x01, SGTL5000_ANA_HP_CTRL_HP_VOL_LEFT_MASK);           // Seperate codec settings.
*
*       codec1_ctrl.attach_SYNC_NB((uint32_t)&I2S_SYNC_ISR);
*       codec1_ctrl.sample_rate(96);
*       codec1_ctrl.start_SYNC((uint32_t)&RX_AudioL1, (uint32_t)&RX_AudioR1, (uint32_t)&TX_AudioL1, (uint32_t)&TX_AudioR1, I2S_FIFO_BS, true, true, false, false, 14, 15, 
*                              (uint32_t)&RX_AudioL2, (uint32_t)&RX_AudioR2, (uint32_t)&TX_AudioL2, (uint32_t)&TX_AudioR2)
*   }
*
*   void I2S_SYNC_ISR(void)
*   {
*       for(uint32_t i = 0; i < (I2S_FIFO_BS >> 1); ++i)
*       {
*           // CODEC 1
*           TX_AudioL1[i] = RX_AudioL1[i];
*           TX_AudioR1[i] = RX_AudioR1[i];
*
*           // CODEC 2
*           TX_AudioL2[i] = RX_AudioL2[i];
*           TX_AudioR2[i] = RX_AudioR2[i];
*       }
*   }
@endcode
*/
class SGTL5000

{
public:
    //Constructor
    /*!
    @brief  Create an SGTL5000 object defined on the I2C port using DMA transfers of I2S data. The class is not defined as a singleton, as future development may require
            multiple instances. However currently only a single object for each CODEC should only be instantiated. It is possible to instantiate more, but care must be taken. 
            After the init() function is called, state within the class becomes indpendent of the object that modified it.
            The class is wrapped in the SGTL5000 namespace to avoid collisions with statics needed by the ISRs. Only the CODEC using CTRL_ADR0_CS = 0 can be used to manage 
            the I2S setup and data flow, such as sample_rate, attach, start, stop etc. If a second CODEC is available then its data flow is locked to the 1st,
            TX & RX FIFO buffers of both CODECs will be synchronised and only one DMA channel is used to TX data to both codecs and one DMA channel to RX data from both codecs.
            
            In SYNC mode FIFO buffers depths are synchronised to bring DMA transfers as close as possible to each other. After both TX & RX DMA transfers are complete, user code is called. 
            Therefore, please note, there will always be a minimum delay of 1 I2S sample between TX & RX DMA transfers.  In most circumstances this is irrelevant, but needs to be considered.
            For example; if the codecs run at 48KHz, and a FIFO depth of 8 samples is implemented. User code will be called every 83.3uS. At the end of this 83.3uS period there will be a short period
            equal to the length of time needed to transfer 1 channel sample (@48Khz this will be (1/48000)/2 = 10.42uS + the time required to swap pointers ~ 800nS. Therefore ~ 11.3uS).
            During this period just before user code is called again, the data in the transfer buffers should not be read or written. It is suggested that upon entry into user code, all TX data is first written out
            followed by processing of RX data, which must complete in less than (83.3 - 11.3 = 72uS). If the sample rate changes this period changes, getting shorter as the sample rate increases.
            However the pointer swaps take a fixed time, dependent only on system core clock frequency.
            If this behaviour needs to ber avoided, run the TX & RX streams independently. However this then increases the overhead associated with IRQs and the user will need to 
            manage synchronisation between TX & RX streams.

    @param  i2c_sda             i2c Serial data pin (D18 Teensy 3.2 header / PTB3 MK20DX256)
    @param  i2c_scl             i2c Serial clock pin (D19 Teensy 3.2 header / PTB2 MK20DX256)
    @param  i2c_freq            Frequency in Hz at which the i2c codec interface clocks data
    @param  i2c_ctrl_adr0_cs    State on SGTL5000 CTRL_ADR0_CS pin   i2c addr = 0n01010(R/W) :R/W = 1 to write R/W = 0 to read, n = 0 pull down / n = 1 pull up on CTRL_ADR0_CS pin of SGTL5000)
    @param  _ctrl_IRQn          A system IRQ number used to control the codec. All time sensitive commands are elevated to highest IRQ priority using this IRQ number.
                                Note: This is only used by the master codec (which is the codec with CS pin LOW). All commands to control data flow must be issued through the master codec object.
                                This includes setting sample rate. Both codecs are linked by default at the same rate. Setting the master codecs rate also sets the same rate for the 2nd codec.
                                However each codec instance has fully independent access to all the other codec internal features, through its respective object.


    // Pin Configs for i2s hardcoded as follows to match Teensy Audio Shield
    i2s_mclk           i2s master clock (D11 Teensy 3.2 header / PTC6 MK20DX256)
    i2s_bclk           i2s bit clock (D9 Teensy 3.2 header / PTC3 MK20DX256)
    i2s_fs             i2s Frame Sync / L/R clock / WordSelect (D23 Teensy 3.2 header / PTC2 MK20DX256)
    i2s_rx             i2s tx_data (from bus master perspective) (D22 Teensy 3.2 header / PTC1 MK20DX256)
    i2s_tx             i2s rx_data (from bus master perspective) (D13 Teensy 3.2 header /PTC5 MK20DX256)

    */
    SGTL5000(PinName i2c_sda, PinName i2c_scl, int _i2c_freq = 100000, bool i2c_ctrl_adr0_cs = 0, IRQn _ctrl_IRQn = Reserved109_IRQn);

    /*!
    @brief  Read 16bit register of SGTL5000
    @param  reg_addr    16bit address of the codec control register
    @param  data        16bit data to read from the address
    @param  mask        16bit mask applied over the data read from the codec. The final returned value is the register data automatically shifted to the position of the first masked bit.
    @param  _i2c_addr   Default = 0. If none zero, overrides the address associated with the current object.
    @returns            0 = register data, -1 = fail
    */
    int32_t read_i2c(uint32_t reg_addr, uint32_t mask = 0xFFFF, int _i2c_addr = 0);

    /*!
    @brief  Write 16bit register of SGTL5000
    @param  reg_addr    16bit address of the codec control register
    @param  data        16bit data to write into the address
    @param  _i2c_addr   Default = 0. If none zero, overrides the address associated with the current object.
    @returns            0 = success, -1 = fail
    */
    int32_t write_i2c(uint32_t reg_addr, uint32_t data, int _i2c_addr = 0);

    /*!
    @brief  Modify masked bits within 16bit register of SGTL5000
    @param  reg_addr    16bit address of the codec control register
    @param  data        16bit data to write into the address
    @param  mask        16bit mask of the bits to modify.
                        The function automatically shifts the data to the position of the first masked bit.
    @param  _i2c_addr   Default = 0. If none zero, overrides the address associated with the current object.
    @returns            0 = success, -1 = fail
    */
    int32_t modify_i2c(uint32_t reg_addr, uint32_t data, uint32_t mask, int _i2c_addr = 0);

    /*!
    @brief Attach a callback function to TX
    @param func         Address of the user function to be called from the TX FIFO triggered ISR.
                        This is blocking. If the user function does not complete before the next DMA completes the system will likely crash,
                        however using this function avoids the latency of an IRQ stack push.
    @returns            0 = success, -1 = fail.
                        Fails if already attached, must detach first.
    */
    int32_t attach_TX(Callback<void()> func);

    /*!
    @brief Attach an ISR function to DMA TX
    @param user_ISR     User function address pointer to be assigned as the NVIC vector for the DMA TX FIFO triggered user_ISR.
    @param irq_pri      Set the system wide priority of the user_ISR.
    @param sw_irq       The IRQ assigned. Default uses Reserved54_IRQn. See "MK20DX256.h" for available.
                        This is non-blocking provided the priority of the IRQ associated with user_ISR is lower than the priority of the DMA triggered ISR.
                        It can be useful to use a non-blocking call, however this involves the extra time needed to push the stack and manageing IRQ priorities
                        across the whole system needs consideration.
    */
    int32_t attach_TX_NB(void* user_ISR, uint32_t irq_pri = 1, IRQn sw_irq = Reserved54_IRQn);

    /*!
    @brief Stop TX channel and flag as detached.
                        During running stream, the callback based function can not be changed. It must therefore be deteched first. However changes to the NB IRQ based attachment can have the vector changed on-the-fly
    */
    int32_t detach_TX(void);

    /*!
    @brief Disables I2S TX function. This stops all DMA requests and supresses any IRQs from the driver and tristates the inbound CODEC I2S interface.
                            It also stops bit clocks and word sync clocks.
                            Note: Stopping the TX will also stop the RX stream because the RX is synchronous to the TX function. It is recommended that TX is the last enabled and first disabled.
    */
    int32_t stop_TX(void);

    /*!
    @brief Pauses I2S TX channels. Halts the TX stream(s) by masking all data words.
           This can be used to suspend the codec when a user wishes to run critical tasks where IRQs must be suppressed. To restart call the resume function.
    */
    int32_t pause_TX(void);

    /*!
    @brief Resumes a paused I2S TX channels. Resumes the TX stream(s) by un-masking all data words.
    */
    int32_t resume_TX(void);

    /*!
    @brief  Starts the codec I2S interface and begins transferring TX buffers. Transfers use DMA.
    @param  _BufTX_L_safe   A pointer address to the TX Left channel_0 data.
                            The address pointed to by the users pointer is managed by the library and changes to implement a double buffer.
                            It is suggested that a suitable declaration in the users code would be in the form: 'q31_t *TX_AudioL = NULL;'
                            To pass into the class, dereference this pointer and cast as uint32_t, as follows: 'codec.start_SYNC((uint32_t)&TX_AudioL .....'
    @param  _BufTX_R_safe   A pointer address to the TX Right channel_0 data.
    @param  _block_size     2 | 4 | 8 words of both Left and Right channels combined.
                            This defines the number of samples that are transferred to the TX FIFO each time a FIFO demand is detected.
    @param  _packed_TX      If true 2 * 16bit words for wire transmission are expected packed into a single 32bit word.
                            If False each 32bit word from the user should contain a single 16bit word for transmission.
    @param  _TX_shift       True = The MS16bits of TX buffer are sent to the TX FIFO.   Default = true.
                            False = The LS16bits of TX buffer are sent to the TX FIFO.
                            If packed is true, then shift has no relevance.
    @param  _tx_DMAch       Defines the system DMA channel to assign to the TX transfer. Default is 15.
                            15 is used as default to avoid using channels 0 - 3 which are the only channels available for gated triggers.
                            Gated triggering is not needed, so these 4 channels are avoided.
    @param  _DMA_irq_pri    Default = 0. Highest priority. This is the priority of the I2S TX DMA demands.
    @param  _BufTX_L_safe2  A pointer address to the TX Left channel_1 data.
    @param  _BufTX_R_safe2  A pointer address to the TX Right channel_1 data.
    @returns                0 = success, -1 = fail
                            Fails on variable sanity checks.
    */
    int32_t start_TX(uint32_t _BufTX_L_safe, uint32_t _BufTX_R_safe,
                     uint32_t _block_size = 4, bool _packed_TX = false, bool _TX_shift = true,  uint32_t _TX_DMAch = 15, uint32_t _DMA_irq_pri = 0, uint32_t _BufTX_L_safe2 = NULL, uint32_t _BufTX_R_safe2 = NULL);

    /*!
    @brief Attach a callback function to RX
    @param func         User function to be called from the RX FIFO triggered ISR.
                        This is blocking. If the user function does not complete before the next DMA completes the system will crash,
                        however using this function avoids the latency of a stack push.
    @returns            0 = success, -1 = fail.
                        Fails if already attached, must detach first.
    */
    int32_t attach_RX(Callback<void()> func);

    /*!
    @brief Attach an ISR function to DMA RX
    @param user_ISR     User function address pointer to be assigned as the NVIC vector for the DMA RX FIFO triggered user_ISR.
    @param irq_pri      Set the system wide priority of the user_ISR.
    @param sw_irq       The IRQ assigned. Default uses Reserved55_IRQn. See "MK20DX256.h" for available.
                        This is non-blocking provided the priority of the IRQ associated with user_ISR is lower than the priority of the DMA triggered ISR.
                        It can be useful to use a non-blocking call, however this involves the extra time needed to push the stack and manageing IRQ priorities
                        across the whole system needs consideration.
    */
    int32_t attach_RX_NB(void* user_ISR, uint32_t irq_pri = 1, IRQn sw_irq = Reserved55_IRQn);

    /*!
    @brief Stop RX channel and flag as detached.
           During running stream, the callback based function can not be changed. It must therefore be deteched first. However changes to the NB IRQ based attachment can have the vector changed on-the-fly
    */
    int32_t detach_RX(void);

    /*!
    @brief Disables I2S RX function. Stops all DMA requests and supresses any IRQs from the driver and tristates the outbound CODEC I2S interface(s).
                        Note: Bit clock and Word Sync clock will continue as long as TX is running (started).
    */
    int32_t stop_RX(void);

    /*!
    @brief Pauses I2S RX channels. Halts the RX stream(s) by masking all data words.
           This can be used to suspend the codec when a user wishes to run critical tasks where IRQs must be suppressed. To restart call the resume function.
    */
    int32_t pause_RX(void);

    /*!
    @brief Resumes a paused I2S RX channels. Resumes the RX stream(s) by un-masking all data words.
    */
    int32_t resume_RX(void);

    /*!
    @brief  Starts the codec I2S interface and begins transferring RX buffers. Transfers use DMA.
    @param  _BufRX_L_safe   A pointer address to the RX Left channel_0 data.
                            The address pointed to by the users pointer is managed by the library and changes to implement a double buffer.
                            It is suggested that a suitable declaration in the users code would be in the form: 'q31_t *RX_AudioL = NULL;'
                            To pass into the class, dereference this pointer and cast as uint32_t, as follows: 'codec.start_SYNC((uint32_t)&RX_AudioL .....'
    @param  _BufRX_R_safe   A pointer address to the RX Right channel_0 data.
    @param  _block_size     2 | 4 | 8 words of both Left and Right channels combined.
                            This defines the number of samples that are transferred to the RX FIFO each time a FIFO demand is detected.
    @param  _packed_RX      If true the 2 * 16bit words from the codec are packed into a single 32bit word towards the user. This allows user code to use SIMD operations on the data
                            If False a single 16bit word from the wire is placed into a single 32bit word towards the user.
    @param  _RX_shift       True = The 16bits of RX FIFO data are shifted to the MSBs of the RX buffer. Default = true
                            False = The 16bits of RX FIFO data are placed in the LSBs of the RX buffer
                            Note: If data is not shifted, the 32bit word delivered to the user will not be sign extended.
                            If packed is true, then shift has no relevance.
    @param  _rx_DMAch       Defines the system DMA channel to assign to the RX transfer. Default is 14.
                            14 is used as default to avoid using channels 0 - 3 which are the only channels available for gated triggers.
                            Gated triggering is not needed, so these 4 channels are avoided.
    @param  _DMA_irq_pri    Default = 0. Highest priority. This is the priority of the I2S RX DMA demands.
    @param  _BufRX_L_safe2  A pointer address to the RX Left channel_1 data.
    @param  _BufRX_R_safe2  A pointer address to the RX Right channel_1 data.
    @returns                0 = success, -1 = fail
                            Fails on variable sanity checks.
    */
    int32_t start_RX(uint32_t _BufRX_L_safe, uint32_t _BufRX_R_safe,
                     uint32_t _block_size = 4, bool _packed_RX = false, bool _RX_shift = true,  uint32_t _RX_DMAch = 14, uint32_t _DMA_irq_pri = 0, uint32_t _BufRX_L_safe2 = NULL, uint32_t _BufRX_R_safe2 = NULL);

    /*!
    @brief Attach a callback function to DMA SYNC
    @param func         User function to be called from the DMA SYNC FIFO triggered ISR.
                        This is blocking. If the user function does not complete before the next DMA triggered IRQ the system will crash,
                        however using this function avoids the latency of a stack push.
    @returns            0 = success, -1 = fail.
                        Fails if already attached, must detach first.
    */
    int32_t attach_SYNC(Callback<void()> func);


    /*!
    @brief Attach a ISR function to DMA SYNC
    @param user_ISR     User function address pointer to be assigned as the NVIC vector for the DMA SYNC FIFO triggered user_ISR.
    @param irq_pri      Set the system wide priority of the user_ISR.
    @param sw_irq       The IRQ assigned. Default uses Reserved53_IRQn. See "MK20DX256.h" for available.
                        This creates a non-blocking call, which tests to see if the users ISR has completed before calling again.
                        It requires that the priority of the IRQ associated with user_ISR is lower than the priority of the DMA triggered ISR.
                        It can be useful to use a non-blocking call, however this involves the extra time needed to push the stack and manageing IRQ priorities
                        across the whole system needs consideration.
    */
    int32_t attach_SYNC_NB(void* user_ISR, uint32_t irq_pri = 1, IRQn sw_irq = Reserved53_IRQn);

    /*!
    @brief Stop both TX & RX channels and flag as detached.
                        During running stream, the callback based function can not be changed. It must therefore be deteched first. However changes to the NB IRQ based attachment can have the vector changed on-the-fly
    */
    int32_t detach_SYNC(void);

    /**
    @brief  Starts the codec I2S interface and begins transferring RX and TX buffers. Transfers use DMA.
    @param  _BufRX_L_safe   A pointer address to the RX Left channel_0 data.
                            The address pointed to by the users pointer is managed by the library and changes to implement a double buffer.
                            It is suggested that a suitable declaration in the users code would be in the form: 'q31_t *RX_AudioL = NULL;'
                            To pass into the class, dereference this pointer and cast as uint32_t, as follows: 'codec.start_SYNC((uint32_t)&RX_AudioL .....'
    @param  _BufRX_R_safe   A pointer address to the RX Right channel_0 data.
    @param  _BufTX_L_safe   A pointer address to the TX Left channel_0 data.
    @param  _BufTX_R_safe   A pointer address to the TX Right channel_0 data.
    @param  _block_size     2 | 4 | 8 words of both Left and Right channels combined.
                            This defines the number of samples that are transferred to both FIFOs each time a FIFO demand is detected.
    @param  _packed_TX      If true the 2 * 16bit words for wire transmission are expected packed into a single 32bit word.
                            If False each 32bit word from the user should contain a single 16bit word for transmission.
    @param  _packed_RX      If true the 2 * 16bit words from the codec are packed into a single 32bit word towards the user. This allows user code to use SIMD operations on the data
                            If False a single 16bit word from the wire is placed into a single 32bit word towards the user.
    @param  _RX_shift       True = The 16bits of RX FIFO data are shifted to the MSBs of the RX buffer. Default = true
                            False = The 16bits of RX FIFO data are placed in the LSBs of the RX buffer.
                            Note: If data is not shifted, the 32bit word delivered to the user will not be sign extended.
                            If RX packed is true, then shift has no relevance.
    @param  _TX_shift       True = The MS16bits of TX buffer are sent to the TX FIFO.   Default = true.
                            False = The LS16bits of TX buffer are sent to the TX FIFO.
                            If TX packed is true, then shift has no relevance.
    @param  _RX_DMAch       Defines the system DMA channel to assign to the RX transfer. Default is 14.
    @param  _TX_DMAch       Defines the system DMA channel to assign to the TX transfer. Default is 15.
                            14 & 15 are used as default to avoid using channels 0 - 3 which are the only channels available for gated triggers.
                            Gated triggering is not needed, so these 4 channels are avoided.
    @param  _DMA_irq_pri    Default = 0. Highest priority. This is the priority of the I2S DMA demands.
    @param  _BufRX_L_safe2  A pointer address to the RX Left channel_1 data.
    @param  _BufRX_R_safe2  A pointer address to the RX Right channel_1 data.
    @param  _BufTX_L_safe2  A pointer address to the TX Left channel_1 data.
    @param  _BufTX_R_safe2  A pointer address to the TX Right channel_1 data.
    @returns                0 = success, -1 = fail
                            Fails on variable sanity checks.
    */
    int32_t start_SYNC(uint32_t _BufRX_L_safe, uint32_t _BufRX_R_safe, uint32_t _BufTX_L_safe, uint32_t _BufTX_R_safe,
                       uint32_t _block_size = 4, bool _packed_RX = false, bool _packed_TX = false, bool _RX_shift = true, bool _TX_shift = true, uint32_t _RX_DMAch = 14, uint32_t _TX_DMAch = 15, uint32_t _DMA_irq_pri = 0, uint32_t _BufRX_L_safe2 = NULL, uint32_t _BufRX_R_safe2 = NULL, uint32_t _BufTX_L_safe2 = NULL, uint32_t _BufTX_R_safe2 = NULL);

    /*!
    @brief Stops I2S TX & RX channels. Stops all DMA requests and supresses any IRQs from the driver and tristates the CODEC I2S interface.
    */
    int32_t stop_SYNC(void);

    /*!
    @brief Pauses I2S RX & TX channels. Halts the RX & TX stream(s) by masking all data words.
           This can be used to suspend the codec when a user wishes to run critical tasks where IRQs must be suppressed. To restart call the resume function.
    */
    int32_t pause_SYNC(void);

    /*!
    @brief Resumes a paused I2S RX & TX channels. Resumes the RX & TX stream(s) by un-masking all data words.
    */
    int32_t resume_SYNC(void);

    /*!
    @brief Set codec and I2S Sampling frequency
    @param  rate        8, 11, 12, 16, 22, 24, 32, 44, 48, 96, 192
                        Base sampling rate of the codec

                        In all cases the SGTL5000 is programmed to use MCLK 256 times faster than sampling freq.
                        MCU MCLK output = MCLK_Input((FRACT + 1)/(DIVIDE + 1))
                        MCU MCLK Divide Register ratio is therefore = (Fs * 256)/PLL Clk
                        The Teensy 3.1 & 3.2 have PLL freq @ 96MHz. However 120Mhz is supported dependent on the global 'SystemCoreClock' variable indicating this.

                        Note: To achieve some of these rates the codec SYS_FS is adjusted.
                        This needs to be considered for several internal codec processes such as filter co-efficients and AVC.
    @returns            0 = success, -1 = fail
    */
    int32_t sample_rate(uint32_t rate);

    /*!
    @brief  Initialise codec.
                        Resets the codec and sends initial default configuration data to the codec over I2C.
                        This function must be called after instantiation and before most other functions. It allows control over when I2C communications with the codec takes place.
                        Failure to initialize will prevent operation of the codec. However it possible to attach and detach functions before init.
    @returns            0 = success, -1 = fail
    */
    int32_t init(void);

    /*!
    @brief  Read debug data from the codec
    @param  index       0-15
    @param  finished    a simple semaphore, indicating that debug data should be aquired again. (Can be used in combination with the internal bool SGTL5000::debug_read, to gate data collection.) 
                        Just a simple way for user code to grab running variables if you need it.
    @returns            0 = success, -1 = fail
    */
    int32_t read_debug(uint32_t index, bool finished = false);
    static bool debug_read;


protected:
    static uint32_t debug[16];
    static void t_stamp_start(void);
    static void t_stamp_stop(void);
    static uint32_t t1;
    static uint32_t proc_time;
    static uint32_t SYST_CVAL;// = 0xE000E018;                                  // Address of SysTick current value register


private:

    static IRQn CODEC_CTRL_IRQ;                                                 // Default IRQ used to elevate priority of user commands.
    static uint32_t ctrl_command;                                               // Command translation
    #define STOP_SYNC   0x1
    #define STOP_TX     0x2
    #define STOP_RX     0x3
    #define PAUSE_TX    0x4
    #define PAUSE_RX    0x5
    #define PAUSE_SYNC  0x6
    #define RESUME_TX   0x7
    #define RESUME_RX   0x8
    #define RESUME_SYNC 0x9
    
    static void stream_ctrl_ISR(void);                                          // High priority control commands trigger by user through software ISR 


    I2C mI2C;                                                                   // Create I2C instance
    
    int i2c_addr;    

    int32_t init_i2s(void);                                                     // Configure I2S Default Settings

    int32_t init_codec(void);                                                   // Configure codec Default Settings

    void init_DMA(void);                                                        // Configure SYNC DMA settings on MK20DX256

    static void SYNC_TX_dma_ISR(void);

    static void SYNC_RX_dma_ISR(void);

    static void SYNC_pointer_swap(void);

    static void TX_dma_ISR(void);                                               // Handle TX DMA transfers complete.

    static void RX_dma_ISR(void);                                               // Handle RX DMA transfers complete using Callback

    static void tx_I2S_WS_ISR(void);                                            // Handle TX word start allignment

    static void rx_I2S_WS_ISR(void);                                            // Handle RX word start allignment

    static void sync_I2S_WS_ISR(void);                                          // Handle SYNC word start allignment


    //const uint32_t DMA_INT_ADDR = 0x40008024;        // Hard code the DMA->INT address its faster when inline assembler optimises


    static volatile uint32_t * volatile BufRX_L_safe;                                              // Define statics for ISRs
    static volatile uint32_t * volatile BufRX_R_safe;
    static volatile uint32_t * volatile BufTX_L_safe;
    static volatile uint32_t * volatile BufTX_R_safe;
    static volatile uint32_t * volatile BufRX_L_safe2;                                              // Define statics for ISRs
    static volatile uint32_t * volatile BufRX_R_safe2;
    static volatile uint32_t * volatile BufTX_L_safe2;
    static volatile uint32_t * volatile BufTX_R_safe2;
    static uint32_t BufRX_L_safeA;                                                  // Precalculated double buffer addresses
    static uint32_t BufRX_R_safeA;
    static uint32_t BufTX_L_safeA;
    static uint32_t BufTX_R_safeA;
    static uint32_t BufRX_L_safeB;                                                  // Precalculated double buffer addresses
    static uint32_t BufRX_R_safeB;
    static uint32_t BufTX_L_safeB;
    static uint32_t BufTX_R_safeB;
    static uint32_t BufRX_L_safeA2;                                                  // Precalculated double buffer addresses
    static uint32_t BufRX_R_safeA2;
    static uint32_t BufTX_L_safeA2;
    static uint32_t BufTX_R_safeA2;
    static uint32_t BufRX_L_safeB2;                                                  // Precalculated double buffer addresses
    static uint32_t BufRX_R_safeB2;
    static uint32_t BufTX_L_safeB2;
    static uint32_t BufTX_R_safeB2;
    static uint32_t I2S_RX_Buffer[16];
    static uint32_t I2S_TX_Buffer[16];
    static uint32_t I2S_RX_Buffer2[16];
    static uint32_t I2S_TX_Buffer2[16];
    static uint32_t active_RX_DMAch_bm;
    static uint32_t active_TX_DMAch_bm;
    static uint32_t sync_dma_irq_acks;
    static IRQn SYNC_swIRQ;
    static IRQn TX_swIRQ;
    static IRQn RX_swIRQ;
    static Callback<void()> TX_user_func;
    static Callback<void()> RX_user_func;
    static Callback<void()> SYNC_user_func;
    static uint32_t db_phase_sync;
    static uint32_t db_phase_tx;
    static uint32_t db_phase_rx;
    static uint32_t SYNC_attach_type;
    static uint32_t TX_attach_type;
    static uint32_t RX_attach_type;
    static bool i2s_configured;
    static bool codec2_active;
    static bool codec1_active;
    static uint32_t dump;
    static uint32_t NULL_DMA_TX;
    static uint32_t NULL_DMA_RX;
    static uint32_t RX_DMAch;
    static uint32_t TX_DMAch;
    static bool SYNC_run;
    static bool TX_run;
    static bool RX_run;

    int i2c_freq;
    uint32_t TX_block_size;
    uint32_t RX_block_size;
    uint32_t TX_bs_bytes;
    uint32_t RX_bs_bytes;
    bool ctrl_codec;
    bool codec_configured;
    bool codec_I2S_active;
    
    bool SYNC_attached;
    bool TX_attached;
    bool RX_attached;
    bool TX_shift;
    bool RX_shift;
    bool packed_RX;
    bool packed_TX;


};
}
#endif