]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/protocol/lufa/LUFA-git/Demos/Device/ClassDriver/AudioOutput/AudioOutput.c
allow overriding of TARGET
[qmk_firmware.git] / tmk_core / protocol / lufa / LUFA-git / Demos / Device / ClassDriver / AudioOutput / AudioOutput.c
1 /*
2              LUFA Library
3      Copyright (C) Dean Camera, 2014.
4
5   dean [at] fourwalledcubicle [dot] com
6            www.lufa-lib.org
7 */
8
9 /*
10   Copyright 2014  Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12   Permission to use, copy, modify, distribute, and sell this
13   software and its documentation for any purpose is hereby granted
14   without fee, provided that the above copyright notice appear in
15   all copies and that both that the copyright notice and this
16   permission notice and warranty disclaimer appear in supporting
17   documentation, and that the name of the author not be used in
18   advertising or publicity pertaining to distribution of the
19   software without specific, written prior permission.
20
21   The author disclaims all warranties with regard to this
22   software, including all implied warranties of merchantability
23   and fitness.  In no event shall the author be liable for any
24   special, indirect or consequential damages or any damages
25   whatsoever resulting from loss of use, data or profits, whether
26   in an action of contract, negligence or other tortious action,
27   arising out of or in connection with the use or performance of
28   this software.
29 */
30
31 /** \file
32  *
33  *  Main source file for the AudioOutput demo. This file contains the main tasks of
34  *  the demo and is responsible for the initial application hardware configuration.
35  */
36
37 #include "AudioOutput.h"
38
39 /** LUFA Audio Class driver interface configuration and state information. This structure is
40  *  passed to all Audio Class driver functions, so that multiple instances of the same class
41  *  within a device can be differentiated from one another.
42  */
43 USB_ClassInfo_Audio_Device_t Speaker_Audio_Interface =
44         {
45                 .Config =
46                         {
47                                 .ControlInterfaceNumber   = INTERFACE_ID_AudioControl,
48                                 .StreamingInterfaceNumber = INTERFACE_ID_AudioStream,
49                                 .DataOUTEndpoint          =
50                                         {
51                                                 .Address          = AUDIO_STREAM_EPADDR,
52                                                 .Size             = AUDIO_STREAM_EPSIZE,
53                                                 .Banks            = 2,
54                                         },
55                         },
56         };
57
58 /** Current audio sampling frequency of the streaming audio endpoint. */
59 static uint32_t CurrentAudioSampleFrequency = 48000;
60
61
62 /** Main program entry point. This routine contains the overall program flow, including initial
63  *  setup of all components and the main program loop.
64  */
65 int main(void)
66 {
67         SetupHardware();
68
69         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
70         GlobalInterruptEnable();
71
72         for (;;)
73         {
74                 Audio_Device_USBTask(&Speaker_Audio_Interface);
75                 USB_USBTask();
76         }
77 }
78
79 /** Configures the board hardware and chip peripherals for the demo's functionality. */
80 void SetupHardware(void)
81 {
82 #if (ARCH == ARCH_AVR8)
83         /* Disable watchdog if enabled by bootloader/fuses */
84         MCUSR &= ~(1 << WDRF);
85         wdt_disable();
86
87         /* Disable clock division */
88         clock_prescale_set(clock_div_1);
89 #endif
90
91         /* Hardware Initialization */
92         LEDs_Init();
93         USB_Init();
94 }
95
96 /** ISR to handle the reloading of the PWM timer with the next sample. */
97 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
98 {
99         uint8_t PrevEndpoint = Endpoint_GetCurrentEndpoint();
100
101         /* Check that the USB bus is ready for the next sample to read */
102         if (Audio_Device_IsSampleReceived(&Speaker_Audio_Interface))
103         {
104                 /* Retrieve the signed 16-bit left and right audio samples, convert to 8-bit */
105                 int8_t LeftSample_8Bit  = (Audio_Device_ReadSample16(&Speaker_Audio_Interface) >> 8);
106                 int8_t RightSample_8Bit = (Audio_Device_ReadSample16(&Speaker_Audio_Interface) >> 8);
107
108                 /* Mix the two channels together to produce a mono, 8-bit sample */
109                 int8_t MixedSample_8Bit = (((int16_t)LeftSample_8Bit + (int16_t)RightSample_8Bit) >> 1);
110
111                 #if defined(AUDIO_OUT_MONO)
112                 /* Load the sample into the PWM timer channel */
113                 OCR3A = (MixedSample_8Bit ^ (1 << 7));
114                 #elif defined(AUDIO_OUT_STEREO)
115                 /* Load the dual 8-bit samples into the PWM timer channels */
116                 OCR3A = (LeftSample_8Bit  ^ (1 << 7));
117                 OCR3B = (RightSample_8Bit ^ (1 << 7));
118                 #elif defined(AUDIO_OUT_PORTC)
119                 /* Load the 8-bit mixed sample into PORTC */
120                 PORTC = MixedSample_8Bit;
121                 #endif
122
123                 uint8_t LEDMask = LEDS_NO_LEDS;
124
125                 /* Turn on LEDs as the sample amplitude increases */
126                 if (MixedSample_8Bit > 16)
127                   LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3 | LEDS_LED4);
128                 else if (MixedSample_8Bit > 8)
129                   LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3);
130                 else if (MixedSample_8Bit > 4)
131                   LEDMask = (LEDS_LED1 | LEDS_LED2);
132                 else if (MixedSample_8Bit > 2)
133                   LEDMask = (LEDS_LED1);
134
135                 LEDs_SetAllLEDs(LEDMask);
136         }
137
138         Endpoint_SelectEndpoint(PrevEndpoint);
139 }
140
141 /** Event handler for the library USB Connection event. */
142 void EVENT_USB_Device_Connect(void)
143 {
144         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
145
146         /* Sample reload timer initialization */
147         TIMSK0  = (1 << OCIE0A);
148         OCR0A   = ((F_CPU / 8 / CurrentAudioSampleFrequency) - 1);
149         TCCR0A  = (1 << WGM01);  // CTC mode
150         TCCR0B  = (1 << CS01);   // Fcpu/8 speed
151
152         #if defined(AUDIO_OUT_MONO)
153         /* Set speaker as output */
154         DDRC   |= (1 << 6);
155         #elif defined(AUDIO_OUT_STEREO)
156         /* Set speakers as outputs */
157         DDRC   |= ((1 << 6) | (1 << 5));
158         #elif defined(AUDIO_OUT_PORTC)
159         /* Set PORTC as outputs */
160         DDRC   |= 0xFF;
161         #endif
162
163         #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO))
164         /* PWM speaker timer initialization */
165         TCCR3A  = ((1 << WGM30) | (1 << COM3A1) | (1 << COM3A0)
166                 | (1 << COM3B1) | (1 << COM3B0)); // Set on match, clear on TOP
167         TCCR3B  = ((1 << WGM32) | (1 << CS30));  // Fast 8-Bit PWM, F_CPU speed
168         #endif
169 }
170
171 /** Event handler for the library USB Disconnection event. */
172 void EVENT_USB_Device_Disconnect(void)
173 {
174         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
175
176         /* Stop the sample reload timer */
177         TCCR0B = 0;
178
179         #if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO))
180         /* Stop the PWM generation timer */
181         TCCR3B = 0;
182         #endif
183
184         #if defined(AUDIO_OUT_MONO)
185         /* Set speaker as input to reduce current draw */
186         DDRC  &= ~(1 << 6);
187         #elif defined(AUDIO_OUT_STEREO)
188         /* Set speakers as inputs to reduce current draw */
189         DDRC  &= ~((1 << 6) | (1 << 5));
190         #elif defined(AUDIO_OUT_PORTC)
191         /* Set PORTC low */
192         PORTC = 0x00;
193         #endif
194 }
195
196 /** Event handler for the library USB Configuration Changed event. */
197 void EVENT_USB_Device_ConfigurationChanged(void)
198 {
199         bool ConfigSuccess = true;
200
201         ConfigSuccess &= Audio_Device_ConfigureEndpoints(&Speaker_Audio_Interface);
202
203         LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
204 }
205
206 /** Event handler for the library USB Control Request reception event. */
207 void EVENT_USB_Device_ControlRequest(void)
208 {
209         Audio_Device_ProcessControlRequest(&Speaker_Audio_Interface);
210 }
211
212 /** Audio class driver callback for the setting and retrieval of streaming endpoint properties. This callback must be implemented
213  *  in the user application to handle property manipulations on streaming audio endpoints.
214  *
215  *  When the DataLength parameter is NULL, this callback should only indicate whether the specified operation is valid for
216  *  the given endpoint index, and should return as fast as possible. When non-NULL, this value may be altered for GET operations
217  *  to indicate the size of the retrieved data.
218  *
219  *  \note The length of the retrieved data stored into the Data buffer on GET operations should not exceed the initial value
220  *        of the \c DataLength parameter.
221  *
222  *  \param[in,out] AudioInterfaceInfo  Pointer to a structure containing an Audio Class configuration and state.
223  *  \param[in]     EndpointProperty    Property of the endpoint to get or set, a value from Audio_ClassRequests_t.
224  *  \param[in]     EndpointAddress     Address of the streaming endpoint whose property is being referenced.
225  *  \param[in]     EndpointControl     Parameter of the endpoint to get or set, a value from Audio_EndpointControls_t.
226  *  \param[in,out] DataLength          For SET operations, the length of the parameter data to set. For GET operations, the maximum
227  *                                     length of the retrieved data. When NULL, the function should return whether the given property
228  *                                     and parameter is valid for the requested endpoint without reading or modifying the Data buffer.
229  *  \param[in,out] Data                Pointer to a location where the parameter data is stored for SET operations, or where
230  *                                     the retrieved data is to be stored for GET operations.
231  *
232  *  \return Boolean \c true if the property get/set was successful, \c false otherwise
233  */
234 bool CALLBACK_Audio_Device_GetSetEndpointProperty(USB_ClassInfo_Audio_Device_t* const AudioInterfaceInfo,
235                                                   const uint8_t EndpointProperty,
236                                                   const uint8_t EndpointAddress,
237                                                   const uint8_t EndpointControl,
238                                                   uint16_t* const DataLength,
239                                                   uint8_t* Data)
240 {
241         /* Check the requested endpoint to see if a supported endpoint is being manipulated */
242         if (EndpointAddress == Speaker_Audio_Interface.Config.DataOUTEndpoint.Address)
243         {
244                 /* Check the requested control to see if a supported control is being manipulated */
245                 if (EndpointControl == AUDIO_EPCONTROL_SamplingFreq)
246                 {
247                         switch (EndpointProperty)
248                         {
249                                 case AUDIO_REQ_SetCurrent:
250                                         /* Check if we are just testing for a valid property, or actually adjusting it */
251                                         if (DataLength != NULL)
252                                         {
253                                                 /* Set the new sampling frequency to the value given by the host */
254                                                 CurrentAudioSampleFrequency = (((uint32_t)Data[2] << 16) | ((uint32_t)Data[1] << 8) | (uint32_t)Data[0]);
255
256                                                 /* Adjust sample reload timer to the new frequency */
257                                                 OCR0A = ((F_CPU / 8 / CurrentAudioSampleFrequency) - 1);
258                                         }
259
260                                         return true;
261                                 case AUDIO_REQ_GetCurrent:
262                                         /* Check if we are just testing for a valid property, or actually reading it */
263                                         if (DataLength != NULL)
264                                         {
265                                                 *DataLength = 3;
266
267                                                 Data[2] = (CurrentAudioSampleFrequency >> 16);
268                                                 Data[1] = (CurrentAudioSampleFrequency >> 8);
269                                                 Data[0] = (CurrentAudioSampleFrequency &  0xFF);
270                                         }
271
272                                         return true;
273                         }
274                 }
275         }
276
277         return false;
278 }
279
280 /** Audio class driver callback for the setting and retrieval of streaming interface properties. This callback must be implemented
281  *  in the user application to handle property manipulations on streaming audio interfaces.
282  *
283  *  When the DataLength parameter is NULL, this callback should only indicate whether the specified operation is valid for
284  *  the given entity and should return as fast as possible. When non-NULL, this value may be altered for GET operations
285  *  to indicate the size of the retrieved data.
286  *
287  *  \note The length of the retrieved data stored into the Data buffer on GET operations should not exceed the initial value
288  *        of the \c DataLength parameter.
289  *
290  *  \param[in,out] AudioInterfaceInfo  Pointer to a structure containing an Audio Class configuration and state.
291  *  \param[in]     Property            Property of the interface to get or set, a value from Audio_ClassRequests_t.
292  *  \param[in]     EntityAddress       Address of the audio entity whose property is being referenced.
293  *  \param[in]     Parameter           Parameter of the entity to get or set, specific to each type of entity (see USB Audio specification).
294  *  \param[in,out] DataLength          For SET operations, the length of the parameter data to set. For GET operations, the maximum
295  *                                     length of the retrieved data. When NULL, the function should return whether the given property
296  *                                     and parameter is valid for the requested endpoint without reading or modifying the Data buffer.
297  *  \param[in,out] Data                Pointer to a location where the parameter data is stored for SET operations, or where
298  *                                     the retrieved data is to be stored for GET operations.
299  *
300  *  \return Boolean \c true if the property GET/SET was successful, \c false otherwise
301  */
302 bool CALLBACK_Audio_Device_GetSetInterfaceProperty(USB_ClassInfo_Audio_Device_t* const AudioInterfaceInfo,
303                                                    const uint8_t Property,
304                                                    const uint8_t EntityAddress,
305                                                    const uint16_t Parameter,
306                                                    uint16_t* const DataLength,
307                                                    uint8_t* Data)
308 {
309         /* No audio interface entities in the device descriptor, thus no properties to get or set. */
310         return false;
311 }