code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "esp_log.h" #include "driver/gpio.h" #include <string.h> #include "board.h" #include "audio_error.h" #include "audio_mem.h" static const char *TAG = "LYRATD_MSC_V2_1"; esp_err_t get_i2c_pins(i2c_port_t port, i2c_config_t *i2c_config) { AUDIO_NULL_CHECK(TAG, i2c_config, return ESP_FAIL); if (port == I2C_NUM_0 || port == I2C_NUM_1) { i2c_config->sda_io_num = GPIO_NUM_18; i2c_config->scl_io_num = GPIO_NUM_23; } else { i2c_config->sda_io_num = -1; i2c_config->scl_io_num = -1; ESP_LOGE(TAG, "i2c port %d is not supported", port); return ESP_FAIL; } return ESP_OK; } esp_err_t get_i2s_pins(i2s_port_t port, i2s_pin_config_t *i2s_config) { AUDIO_NULL_CHECK(TAG, i2s_config, return ESP_FAIL); if (port == I2S_NUM_0 || port == I2S_NUM_1) { i2s_config->bck_io_num = GPIO_NUM_5; i2s_config->ws_io_num = GPIO_NUM_25; i2s_config->data_out_num = GPIO_NUM_26; i2s_config->data_in_num = GPIO_NUM_35; } else { memset(i2s_config, -1, sizeof(i2s_pin_config_t)); ESP_LOGE(TAG, "i2s port %d is not supported", port); return ESP_FAIL; } return ESP_OK; } esp_err_t get_spi_pins(spi_bus_config_t *spi_config, spi_device_interface_config_t *spi_device_interface_config) { AUDIO_NULL_CHECK(TAG, spi_config, return ESP_FAIL); AUDIO_NULL_CHECK(TAG, spi_config, return ESP_FAIL); spi_config->mosi_io_num = GPIO_NUM_33; spi_config->miso_io_num = GPIO_NUM_27; spi_config->sclk_io_num = GPIO_NUM_32; spi_config->quadwp_io_num = -1; spi_config->quadhd_io_num = -1; spi_device_interface_config->spics_io_num = GPIO_NUM_0; return ESP_OK; } esp_err_t i2s_mclk_gpio_select(i2s_port_t i2s_num, gpio_num_t gpio_num) { return ESP_ERR_ADF_NOT_SUPPORT; } // sdcard int8_t get_sdcard_intr_gpio(void) { return SDCARD_INTR_GPIO; } int8_t get_sdcard_open_file_num_max(void) { return SDCARD_OPEN_FILE_NUM_MAX; } // input-output pins int8_t get_pa_enable_gpio(void) { return PA_ENABLE_GPIO; } // adc button int8_t get_adc_detect_gpio(void) { return ADC_DETECT_GPIO; } int8_t get_input_rec_id(void) { return BUTTON_REC_ID; } int8_t get_input_mode_id(void) { return BUTTON_MODE_ID; } int8_t get_input_play_id(void) { return BUTTON_PLAY_ID; } int8_t get_input_set_id(void) { return BUTTON_SET_ID; } int8_t get_input_volup_id(void) { return BUTTON_VOLUP_ID; } int8_t get_input_voldown_id(void) { return BUTTON_VOLDOWN_ID; } // board related int8_t get_reset_codec_gpio(void) { return CODEC_RESET_GPIO; } int8_t get_reset_board_gpio(void) { return DSP_RESET_GPIO; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_board/lyratd_msc_v2_1/board_pins_config.c
C
apache-2.0
3,920
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "esp_log.h" #include "board.h" #include "audio_mem.h" #include "periph_sdcard.h" #include "periph_adc_button.h" #include "led_bar_is31x.h" static const char *TAG = "AUDIO_BOARD"; static audio_board_handle_t board_handle = 0; audio_board_handle_t audio_board_init(void) { if (board_handle) { ESP_LOGW(TAG, "The board has already been initialized!"); return board_handle; } board_handle = (audio_board_handle_t) audio_calloc(1, sizeof(struct audio_board_handle)); AUDIO_MEM_CHECK(TAG, board_handle, return NULL); board_handle->audio_hal = audio_board_codec_init(); return board_handle; } audio_hal_handle_t audio_board_codec_init(void) { audio_hal_codec_config_t audio_codec_cfg = AUDIO_CODEC_DEFAULT_CONFIG(); audio_hal_handle_t codec_hal = audio_hal_init(&audio_codec_cfg, &AUDIO_CODEC_ZL38063_DEFAULT_HANDLE); AUDIO_NULL_CHECK(TAG, codec_hal, return NULL); return codec_hal; } display_service_handle_t audio_board_led_init(void) { esp_periph_handle_t led = led_bar_is31x_init(); AUDIO_NULL_CHECK(TAG, led, return NULL); display_service_config_t display = { .based_cfg = { .task_stack = 0, .task_prio = 0, .task_core = 0, .task_func = NULL, .service_start = NULL, .service_stop = NULL, .service_destroy = NULL, .service_ioctl = led_bar_is31x_pattern, .service_name = "DISPLAY_serv", .user_data = NULL, }, .instance = led, }; return display_service_create(&display); } esp_err_t audio_board_key_init(esp_periph_set_handle_t set) { periph_adc_button_cfg_t adc_btn_cfg = PERIPH_ADC_BUTTON_DEFAULT_CONFIG(); adc_arr_t adc_btn_tag = ADC_DEFAULT_ARR(); adc_btn_cfg.arr = &adc_btn_tag; adc_btn_cfg.arr_size = 1; esp_periph_handle_t adc_btn_handle = periph_adc_button_init(&adc_btn_cfg); AUDIO_NULL_CHECK(TAG, adc_btn_handle, return ESP_ERR_ADF_MEMORY_LACK); return esp_periph_start(set, adc_btn_handle); } esp_err_t audio_board_sdcard_init(esp_periph_set_handle_t set, periph_sdcard_mode_t mode) { if (mode != SD_MODE_1_LINE) { ESP_LOGE(TAG, "current board only support 1-line SD mode!"); return ESP_FAIL; } periph_sdcard_cfg_t sdcard_cfg = { .root = "/sdcard", .card_detect_pin = get_sdcard_intr_gpio(), // GPIO_NUM_34 .mode = mode }; esp_periph_handle_t sdcard_handle = periph_sdcard_init(&sdcard_cfg); esp_err_t ret = esp_periph_start(set, sdcard_handle); int retry_time = 5; bool mount_flag = false; while (retry_time --) { if (periph_sdcard_is_mounted(sdcard_handle)) { mount_flag = true; break; } else { vTaskDelay(500 / portTICK_PERIOD_MS); } } if (mount_flag == false) { ESP_LOGE(TAG, "Sdcard mount failed"); return ESP_FAIL; } return ret; } audio_board_handle_t audio_board_get_handle(void) { return board_handle; } esp_err_t audio_board_deinit(audio_board_handle_t audio_board) { esp_err_t ret = ESP_OK; ret = audio_hal_deinit(audio_board->audio_hal); audio_free(audio_board); board_handle = NULL; return ret; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_board/lyratd_msc_v2_2/board.c
C
apache-2.0
4,515
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_BOARD_H_ #define _AUDIO_BOARD_H_ #include "audio_hal.h" #include "board_def.h" #include "board_pins_config.h" #include "esp_peripherals.h" #include "display_service.h" #include "periph_sdcard.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Audio board handle */ struct audio_board_handle { audio_hal_handle_t audio_hal; /*!< audio hardware abstract layer handle */ }; typedef struct audio_board_handle *audio_board_handle_t; /** * @brief Initialize audio board * * @return The audio board handle */ audio_board_handle_t audio_board_init(void); /** * @brief Initialize codec chip * * @return The audio hal handle */ audio_hal_handle_t audio_board_codec_init(void); /** * @brief Initialize led peripheral and display service * * @return The audio display service handle */ display_service_handle_t audio_board_led_init(void); /** * @brief Initialize key peripheral * * @param set The handle of esp_periph_set_handle_t * * @return * - ESP_OK, success * - Others, fail */ esp_err_t audio_board_key_init(esp_periph_set_handle_t set); /** * @brief Initialize sdcard peripheral * * @param set The handle of esp_periph_set_handle_t * * @return * - ESP_OK, success * - Others, fail */ esp_err_t audio_board_sdcard_init(esp_periph_set_handle_t set, periph_sdcard_mode_t mode); /** * @brief Query audio_board_handle * * @return The audio board handle */ audio_board_handle_t audio_board_get_handle(void); /** * @brief Uninitialize the audio board * * @param audio_board The handle of audio board * * @return 0 success, * others fail */ esp_err_t audio_board_deinit(audio_board_handle_t audio_board); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_board/lyratd_msc_v2_2/board.h
C
apache-2.0
2,973
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_BOARD_DEFINITION_H_ #define _AUDIO_BOARD_DEFINITION_H_ #define SDCARD_OPEN_FILE_NUM_MAX 5 #define SDCARD_INTR_GPIO GPIO_NUM_34 #define HEADPHONE_GPIO GPIO_NUM_36 #define PA_ENABLE_GPIO GPIO_NUM_22 #define ADC_DETECT_GPIO GPIO_NUM_39 #define BUTTON_SET_ID 0 #define BUTTON_PLAY_ID 1 #define BUTTON_REC_ID 2 #define BUTTON_MODE_ID 3 #define BUTTON_VOLDOWN_ID 4 #define BUTTON_VOLUP_ID 5 #define CODEC_RESET_GPIO GPIO_NUM_19 #define DSP_RESET_GPIO GPIO_NUM_21 extern audio_hal_func_t AUDIO_CODEC_ZL38063_DEFAULT_HANDLE; #define AUDIO_CODEC_DEFAULT_CONFIG(){ \ .adc_input = AUDIO_HAL_ADC_INPUT_LINE1, \ .dac_output = AUDIO_HAL_DAC_OUTPUT_ALL, \ .codec_mode = AUDIO_HAL_CODEC_MODE_BOTH, \ .i2s_iface = { \ .mode = AUDIO_HAL_MODE_SLAVE, \ .fmt = AUDIO_HAL_I2S_NORMAL, \ .samples = AUDIO_HAL_48K_SAMPLES, \ .bits = AUDIO_HAL_BIT_LENGTH_16BITS, \ }, \ }; #define INPUT_KEY_NUM 6 #define INPUT_KEY_DEFAULT_INFO() { \ { \ .type = PERIPH_ID_ADC_BTN, \ .user_id = INPUT_KEY_USER_ID_REC, \ .act_id = BUTTON_REC_ID, \ }, \ { \ .type = PERIPH_ID_ADC_BTN, \ .user_id = INPUT_KEY_USER_ID_MODE, \ .act_id = BUTTON_MODE_ID, \ }, \ { \ .type = PERIPH_ID_ADC_BTN, \ .user_id = INPUT_KEY_USER_ID_SET, \ .act_id = BUTTON_SET_ID, \ }, \ { \ .type = PERIPH_ID_ADC_BTN, \ .user_id = INPUT_KEY_USER_ID_PLAY, \ .act_id = BUTTON_PLAY_ID, \ }, \ { \ .type = PERIPH_ID_ADC_BTN, \ .user_id = INPUT_KEY_USER_ID_VOLUP, \ .act_id = BUTTON_VOLUP_ID, \ }, \ { \ .type = PERIPH_ID_ADC_BTN, \ .user_id = INPUT_KEY_USER_ID_VOLDOWN, \ .act_id = BUTTON_VOLDOWN_ID, \ } \ } #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_board/lyratd_msc_v2_2/board_def.h
C
apache-2.0
4,198
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "esp_log.h" #include "driver/gpio.h" #include <string.h> #include "board.h" #include "audio_error.h" #include "audio_mem.h" static const char *TAG = "LYRAT_V4_2"; esp_err_t get_i2c_pins(i2c_port_t port, i2c_config_t *i2c_config) { AUDIO_NULL_CHECK(TAG, i2c_config, return ESP_FAIL); if (port == I2C_NUM_0 || port == I2C_NUM_1) { i2c_config->sda_io_num = GPIO_NUM_18; i2c_config->scl_io_num = GPIO_NUM_23; } else { i2c_config->sda_io_num = -1; i2c_config->scl_io_num = -1; ESP_LOGE(TAG, "i2c port %d is not supported", port); return ESP_FAIL; } return ESP_OK; } esp_err_t get_i2s_pins(i2s_port_t port, i2s_pin_config_t *i2s_config) { AUDIO_NULL_CHECK(TAG, i2s_config, return ESP_FAIL); if (port == I2S_NUM_0 || port == I2S_NUM_1) { i2s_config->bck_io_num = GPIO_NUM_5; i2s_config->ws_io_num = GPIO_NUM_25; i2s_config->data_out_num = GPIO_NUM_26; i2s_config->data_in_num = GPIO_NUM_35; } else { memset(i2s_config, -1, sizeof(i2s_pin_config_t)); ESP_LOGE(TAG, "i2s port %d is not supported", port); return ESP_FAIL; } return ESP_OK; } esp_err_t get_spi_pins(spi_bus_config_t *spi_config, spi_device_interface_config_t *spi_device_interface_config) { AUDIO_NULL_CHECK(TAG, spi_config, return ESP_FAIL); spi_config->mosi_io_num = GPIO_NUM_33; spi_config->miso_io_num = GPIO_NUM_27; spi_config->sclk_io_num = GPIO_NUM_32; spi_config->quadwp_io_num = -1; spi_config->quadhd_io_num = -1; spi_device_interface_config->spics_io_num = GPIO_NUM_0; return ESP_OK; } esp_err_t i2s_mclk_gpio_select(i2s_port_t i2s_num, gpio_num_t gpio_num) { return ESP_ERR_ADF_NOT_SUPPORT; } // sdcard int8_t get_sdcard_intr_gpio(void) { return SDCARD_INTR_GPIO; } int8_t get_sdcard_open_file_num_max(void) { return SDCARD_OPEN_FILE_NUM_MAX; } // input-output pins int8_t get_headphone_detect_gpio(void) { return HEADPHONE_GPIO; } int8_t get_pa_enable_gpio(void) { return PA_ENABLE_GPIO; } // adc button int8_t get_adc_detect_gpio(void) { return ADC_DETECT_GPIO; } int8_t get_input_rec_id(void) { return BUTTON_REC_ID; } int8_t get_input_mode_id(void) { return BUTTON_MODE_ID; } int8_t get_input_play_id(void) { return BUTTON_PLAY_ID; } int8_t get_input_set_id(void) { return BUTTON_SET_ID; } int8_t get_input_volup_id(void) { return BUTTON_VOLUP_ID; } int8_t get_input_voldown_id(void) { return BUTTON_VOLDOWN_ID; } // board related int8_t get_reset_codec_gpio(void) { return CODEC_RESET_GPIO; } int8_t get_reset_board_gpio(void) { return DSP_RESET_GPIO; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_board/lyratd_msc_v2_2/board_pins_config.c
C
apache-2.0
3,928
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "esp_log.h" #include "board.h" #include "audio_mem.h" static const char *TAG = "AUDIO_BOARD"; static audio_board_handle_t board_handle = 0; audio_board_handle_t audio_board_init(void) { if (board_handle) { ESP_LOGW(TAG, "The board has already been initialized!"); return board_handle; } board_handle = (audio_board_handle_t) audio_calloc(1, sizeof(struct audio_board_handle)); AUDIO_MEM_CHECK(TAG, board_handle, return NULL); board_handle->audio_hal = audio_board_codec_init(); board_handle->adc_hal = audio_board_adc_init(); return board_handle; } audio_hal_handle_t audio_board_adc_init(void) { audio_hal_codec_config_t audio_codec_cfg = AUDIO_CODEC_DEFAULT_CONFIG(); audio_hal_handle_t adc_hal = audio_hal_init(&audio_codec_cfg, &AUDIO_CODEC_NS4168_DEFAULT_HANDLE); AUDIO_NULL_CHECK(TAG, adc_hal, return NULL); return adc_hal; } audio_hal_handle_t audio_board_codec_init(void) { audio_hal_codec_config_t audio_codec_cfg = AUDIO_CODEC_DEFAULT_CONFIG(); audio_hal_handle_t codec_hal = audio_hal_init(&audio_codec_cfg, &AUDIO_CODEC_NS4168_DEFAULT_HANDLE); AUDIO_NULL_CHECK(TAG, codec_hal, return NULL); return codec_hal; } audio_board_handle_t audio_board_get_handle(void) { return board_handle; } esp_err_t audio_board_deinit(audio_board_handle_t audio_board) { esp_err_t ret = ESP_OK; ret |= audio_hal_deinit(audio_board->audio_hal); ret |= audio_hal_deinit(audio_board->adc_hal); audio_free(audio_board); board_handle = NULL; return ret; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_board/m5stack_core2/board.c
C
apache-2.0
2,799
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_BOARD_H_ #define _AUDIO_BOARD_H_ #include "audio_hal.h" #include "board_def.h" #include "board_pins_config.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Audio board handle */ struct audio_board_handle { audio_hal_handle_t audio_hal; /*!< audio hardware abstract layer handle */ audio_hal_handle_t adc_hal; /*!< adc hardware abstract layer handle */ }; typedef struct audio_board_handle *audio_board_handle_t; /** * @brief Initialize audio board * * @return The audio board handle */ audio_board_handle_t audio_board_init(void); /** * @brief Initialize codec chip * * @return The audio hal handle */ audio_hal_handle_t audio_board_codec_init(void); /** * @brief Initialize adc * * @return The adc hal handle */ audio_hal_handle_t audio_board_adc_init(void); /** * @brief Query audio_board_handle * * @return The audio board handle */ audio_board_handle_t audio_board_get_handle(void); /** * @brief Uninitialize the audio board * * @param audio_board The handle of audio board * * @return 0 success, * others fail */ esp_err_t audio_board_deinit(audio_board_handle_t audio_board); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_board/m5stack_core2/board.h
C
apache-2.0
2,437
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_BOARD_DEFINITION_H_ #define _AUDIO_BOARD_DEFINITION_H_ extern audio_hal_func_t AUDIO_CODEC_NS4168_DEFAULT_HANDLE; #define AUDIO_CODEC_DEFAULT_CONFIG(){ \ .adc_input = AUDIO_HAL_ADC_INPUT_LINE1, \ .dac_output = AUDIO_HAL_DAC_OUTPUT_ALL, \ .codec_mode = AUDIO_HAL_CODEC_MODE_BOTH, \ .i2s_iface = { \ .mode = AUDIO_HAL_MODE_SLAVE, \ .fmt = AUDIO_HAL_I2S_NORMAL, \ .samples = AUDIO_HAL_48K_SAMPLES, \ .bits = AUDIO_HAL_BIT_LENGTH_16BITS, \ }, \ }; #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_board/m5stack_core2/board_def.h
C
apache-2.0
1,958
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "audio_error.h" #include "audio_mem.h" #include "board.h" #include "driver/gpio.h" #include "esp_log.h" static const char *TAG = "M5STACK_CORE2"; esp_err_t get_i2s_pins(i2s_port_t port, i2s_pin_config_t *i2s_config) { AUDIO_NULL_CHECK(TAG, i2s_config, return ESP_FAIL); if (port == I2S_NUM_0) { i2s_config->bck_io_num = GPIO_NUM_12; i2s_config->ws_io_num = GPIO_NUM_0; i2s_config->data_out_num = GPIO_NUM_2; i2s_config->data_in_num = GPIO_NUM_34; } else { memset(i2s_config, -1, sizeof(i2s_pin_config_t)); ESP_LOGE(TAG, "i2s port %d is not supported", port); return ESP_FAIL; } return ESP_OK; } esp_err_t i2s_mclk_gpio_select(i2s_port_t i2s_num, gpio_num_t gpio_num) { if (i2s_num >= I2S_NUM_MAX) { ESP_LOGE(TAG, "Does not support i2s number(%d)", i2s_num); return ESP_ERR_INVALID_ARG; } ESP_LOGI(TAG, "I2S%d, MCLK output by GPIO%d", i2s_num, gpio_num); return ESP_OK; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_board/m5stack_core2/board_pins_config.c
C
apache-2.0
2,249
set(COMPONENT_ADD_INCLUDEDIRS ./include ./driver/es8388 ./driver/es8374 ./driver/es8311 ./driver/es7243 ./driver/es7148 ./driver/es7210 ./driver/tas5805m ./driver/zl38063 ./driver/zl38063/api_lib ./driver/zl38063/example_apps ./driver/zl38063/firmware ./driver/include) # Edit following two lines to set component requirements (see docs) set(COMPONENT_REQUIRES ) set(COMPONENT_PRIV_REQUIRES audio_sal audio_board mbedtls esp_peripherals display_service esp_dispatcher) set(COMPONENT_SRCS ./audio_hal.c ./driver/es8388/es8388.c ./driver/es8388/headphone_detect.c ./driver/es8374/es8374.c ./driver/es8311/es8311.c ./driver/es7243/es7243.c ./driver/es7148/es7148.c ./driver/es7210/es7210.c ./driver/tas5805m/tas5805m.c ./driver/zl38063/zl38063.c ./driver/zl38063/api_lib/vprocTwolf_access.c ./driver/zl38063/api_lib/vproc_common.c ./driver/zl38063/example_apps/tw_hal_verify.c ./driver/zl38063/example_apps/tw_ldcfg.c ./driver/zl38063/example_apps/tw_ldfw.c ./driver/zl38063/example_apps/tw_ldfwcfg.c ./driver/zl38063/example_apps/tw_spi_access.c) register_component() IF (NOT (CONFIG_IDF_TARGET STREQUAL "esp32c3")) target_link_libraries(${COMPONENT_TARGET} INTERFACE "-L${CMAKE_CURRENT_LIST_DIR}/driver/zl38063/firmware") target_link_libraries(${COMPONENT_TARGET} INTERFACE firmware) ENDIF()
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/CMakeLists.txt
CMake
apache-2.0
1,950
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "driver/gpio.h" #include "esp_log.h" #include "audio_hal.h" #include "audio_mem.h" #include "audio_mutex.h" static const char *TAG = "AUDIO_HAL"; #define AUDIO_HAL_CHECK_NULL(a, format, b, ...) \ if ((a) == 0) { \ ESP_LOGE(TAG, format, ##__VA_ARGS__); \ return b;\ } audio_hal_handle_t audio_hal_init(audio_hal_codec_config_t *audio_hal_conf, audio_hal_func_t *audio_hal_func) { esp_err_t ret = 0; audio_hal_handle_t audio_hal = (audio_hal_handle_t) audio_calloc(1, sizeof(audio_hal_func_t)); AUDIO_MEM_CHECK(TAG, audio_hal, return NULL); memcpy(audio_hal, audio_hal_func, sizeof(audio_hal_func_t)); audio_hal->audio_hal_lock = mutex_create(); AUDIO_MEM_CHECK(TAG, audio_hal->audio_hal_lock, { audio_free(audio_hal); return NULL; }); mutex_lock(audio_hal->audio_hal_lock); ret = audio_hal->audio_codec_initialize(audio_hal_conf); if (ret == ESP_FAIL) { audio_free(audio_hal); if (audio_hal_func->handle) { return audio_hal_func->handle; } else { ESP_LOGE(TAG, "codec init failed!"); return NULL; } } ret |= audio_hal->audio_codec_config_iface(audio_hal_conf->codec_mode, &audio_hal_conf->i2s_iface); ret |= audio_hal->audio_codec_set_volume(AUDIO_HAL_VOL_DEFAULT); audio_hal->handle = audio_hal; audio_hal_func->handle = audio_hal; mutex_unlock(audio_hal->audio_hal_lock); return audio_hal; } esp_err_t audio_hal_deinit(audio_hal_handle_t audio_hal) { esp_err_t ret; AUDIO_HAL_CHECK_NULL(audio_hal, "audio_hal handle is null", -1); mutex_destroy(audio_hal->audio_hal_lock); ret = audio_hal->audio_codec_deinitialize(); audio_hal->audio_hal_lock = NULL; audio_hal->handle = NULL; audio_free(audio_hal); audio_hal = NULL; return ret; } esp_err_t audio_hal_ctrl_codec(audio_hal_handle_t audio_hal, audio_hal_codec_mode_t mode, audio_hal_ctrl_t audio_hal_state) { esp_err_t ret; AUDIO_HAL_CHECK_NULL(audio_hal, "audio_hal handle is null", -1); mutex_lock(audio_hal->audio_hal_lock); ESP_LOGI(TAG, "Codec mode is %d, Ctrl:%d", mode, audio_hal_state); ret = audio_hal->audio_codec_ctrl(mode, audio_hal_state); mutex_unlock(audio_hal->audio_hal_lock); return ret; } esp_err_t audio_hal_codec_iface_config(audio_hal_handle_t audio_hal, audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { esp_err_t ret = 0; AUDIO_HAL_CHECK_NULL(audio_hal, "audio_hal handle is null", -1); AUDIO_HAL_CHECK_NULL(iface, "Get volume para is null", -1); mutex_lock(audio_hal->audio_hal_lock); ret = audio_hal->audio_codec_config_iface(mode, iface); mutex_unlock(audio_hal->audio_hal_lock); return ret; } esp_err_t audio_hal_set_mute(audio_hal_handle_t audio_hal, bool mute) { esp_err_t ret; AUDIO_HAL_CHECK_NULL(audio_hal, "audio_hal handle is null", -1); mutex_lock(audio_hal->audio_hal_lock); ret = audio_hal->audio_codec_set_mute(mute); mutex_unlock(audio_hal->audio_hal_lock); return ret; } esp_err_t audio_hal_set_volume(audio_hal_handle_t audio_hal, int volume) { esp_err_t ret; AUDIO_HAL_CHECK_NULL(audio_hal, "audio_hal handle is null", -1); mutex_lock(audio_hal->audio_hal_lock); ret = audio_hal->audio_codec_set_volume(volume); mutex_unlock(audio_hal->audio_hal_lock); return ret; } esp_err_t audio_hal_get_volume(audio_hal_handle_t audio_hal, int *volume) { esp_err_t ret; AUDIO_HAL_CHECK_NULL(audio_hal, "audio_hal handle is null", -1); AUDIO_HAL_CHECK_NULL(volume, "Get volume para is null", -1); mutex_lock(audio_hal->audio_hal_lock); ret = audio_hal->audio_codec_get_volume(volume); mutex_unlock(audio_hal->audio_hal_lock); return ret; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/audio_hal.c
C
apache-2.0
5,058
# # "main" pseudo-component makefile. # # (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) COMPONENT_ADD_INCLUDEDIRS := ./include ./driver/include COMPONENT_SRCDIRS := . COMPONENT_PRIV_INCLUDEDIRS := ./driver/include COMPONENT_ADD_INCLUDEDIRS += ./driver/es8388 ./driver/es8374 COMPONENT_SRCDIRS += ./driver/es8388 ./driver/es8374 COMPONENT_ADD_INCLUDEDIRS += ./driver/es8311 ./driver/es7243 COMPONENT_SRCDIRS += ./driver/es8311 ./driver/es7243 COMPONENT_ADD_INCLUDEDIRS += ./driver/zl38063 ./driver/zl38063/api_lib ./driver/zl38063/example_apps ./driver/zl38063/firmware COMPONENT_SRCDIRS += ./driver/zl38063 ./driver/zl38063/api_lib ./driver/zl38063/example_apps ./driver/zl38063/firmware COMPONENT_ADD_LDFLAGS += -L$(COMPONENT_PATH)/driver/zl38063/firmware -lfirmware COMPONENT_ADD_INCLUDEDIRS += ./driver/tas5805m ./driver/es7148 COMPONENT_SRCDIRS += ./driver/tas5805m ./driver/es7148 COMPONENT_ADD_INCLUDEDIRS += ./driver/es7210 COMPONENT_SRCDIRS += ./driver/es7210
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/component.mk
Makefile
apache-2.0
1,031
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "esp_log.h" #include "es7148.h" #include "driver/gpio.h" #include "board.h" static const char *TAG = "es7148"; static bool codec_init_flag = 0; audio_hal_func_t AUDIO_CODEC_ES7148_DEFAULT_HANDLE = { .audio_codec_initialize = es7148_codec_init, .audio_codec_deinitialize = es7148_codec_deinit, .audio_codec_ctrl = es7148_codec_ctrl_state, .audio_codec_config_iface = es7148_codec_config_i2s, .audio_codec_set_mute = es7148_codec_set_voice_mute, .audio_codec_set_volume = es7148_codec_set_voice_volume, .audio_codec_get_volume = es7148_codec_get_voice_volume, .audio_hal_lock = NULL, .handle = NULL, }; static bool es7148_codec_initialized() { return codec_init_flag; } esp_err_t es7148_codec_init(audio_hal_codec_config_t *cfg) { if (es7148_codec_initialized()) { ESP_LOGW(TAG, "The es7148 codec has been already initialized"); return ESP_OK; } codec_init_flag = true; return ESP_OK; } esp_err_t es7148_codec_deinit(void) { codec_init_flag = false; return ESP_OK; } esp_err_t es7148_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { return ESP_OK; } esp_err_t es7148_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { return ESP_OK; } esp_err_t es7148_codec_set_voice_mute(bool mute) { return ESP_OK; } esp_err_t es7148_codec_set_voice_volume(int volume) { int ret = 0; return ret; } esp_err_t es7148_codec_get_voice_volume(int *volume) { int ret = 0; return ret; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es7148/es7148.c
C
apache-2.0
2,791
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __ES7148_H__ #define __ES7148_H__ #include "audio_hal.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize es7148 chip * * @param cfg configuration of es7148 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7148_codec_init(audio_hal_codec_config_t *cfg); /** * @brief Deinitialize es7148 chip * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7148_codec_deinit(void); /** * The functions es7148_ctrl_state and es7148_config_i2s are not used by this driver. * They are kept here to maintain the uniformity and convenience of the interface * of the ADF project. * These settings for es7148 are burned in firmware and configuration files. * Default i2s configuration: 48000Hz, 16bit, Left-Right channels. * Use resampling to be compatible with different file types. * * @brief Control es7148 chip * * @param mode codec mode * @param ctrl_state start or stop decode or encode progress * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es7148_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); /** * @brief Configure es7148 codec mode and I2S interface * * @param mode codec mode * @param iface I2S config * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es7148_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /** * @brief mute or unmute the codec * * @param mute: true, false * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7148_codec_set_voice_mute(bool mute); /** * @brief Set voice volume * * @param volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7148_codec_set_voice_volume(int volume); /** * @brief Get voice volume * * @param[out] *volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7148_codec_get_voice_volume(int *volume); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es7148/es7148.h
C
apache-2.0
3,229
/* * ESPRESSIF MIT License * * Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "esp_log.h" #include "board.h" #include "i2c_bus.h" #include "es7210.h" #define I2S_DSP_MODE 0 #define MCLK_DIV_FRE 256 /* ES7210 address*/ #define ES7210_ADDR ES7210_AD1_AD0_00 #define ES7210_MCLK_SOURCE FROM_CLOCK_DOUBLE_PIN /* In master mode, 0 : MCLK from pad 1 : MCLK from clock doubler */ #define FROM_PAD_PIN 0 #define FROM_CLOCK_DOUBLE_PIN 1 /* * Operate function of ADC */ audio_hal_func_t AUDIO_CODEC_ES7210_DEFAULT_HANDLE = { .audio_codec_initialize = es7210_adc_init, .audio_codec_deinitialize = es7210_adc_deinit, .audio_codec_ctrl = es7210_adc_ctrl_state, .audio_codec_config_iface = es7210_adc_config_i2s, .audio_codec_set_mute = es7210_set_mute, .audio_codec_set_volume = es7210_adc_set_volume, .audio_hal_lock = NULL, .handle = NULL, }; /* * Clock coefficient structer */ struct _coeff_div { uint32_t mclk; /* mclk frequency */ uint32_t lrck; /* lrck */ uint8_t ss_ds; uint8_t adc_div; /* adcclk divider */ uint8_t dll; /* dll_bypass */ uint8_t doubler; /* doubler enable */ uint8_t osr; /* adc osr */ uint8_t mclk_src; /* select mclk source */ uint32_t lrck_h; /* The high 4 bits of lrck */ uint32_t lrck_l; /* The low 8 bits of lrck */ }; static char *TAG = "ES7210"; static i2c_bus_handle_t i2c_handle; static es7210_input_mics_t mic_select = ES7210_INPUT_MIC1 | ES7210_INPUT_MIC2; /* Number of microphones */ /* Codec hifi mclk clock divider coefficients * MEMBER REG * mclk: 0x03 * lrck: standard * ss_ds: -- * adc_div: 0x02 * dll: 0x06 * doubler: 0x02 * osr: 0x07 * mclk_src: 0x03 * lrckh: 0x04 * lrckl: 0x05 */ static const struct _coeff_div coeff_div[] = { //mclk lrck ss_ds adc_div dll doubler osr mclk_src lrckh lrckl /* 8k */ {12288000, 8000 , 0x00, 0x03, 0x01, 0x00, 0x20, 0x00, 0x06, 0x00}, {16384000, 8000 , 0x00, 0x04, 0x01, 0x00, 0x20, 0x00, 0x08, 0x00}, {19200000, 8000 , 0x00, 0x1e, 0x00, 0x01, 0x28, 0x00, 0x09, 0x60}, {4096000, 8000 , 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00}, /* 11.025k */ {11289600, 11025, 0x00, 0x02, 0x01, 0x00, 0x20, 0x00, 0x01, 0x00}, /* 12k */ {12288000, 12000, 0x00, 0x02, 0x01, 0x00, 0x20, 0x00, 0x04, 0x00}, {19200000, 12000, 0x00, 0x14, 0x00, 0x01, 0x28, 0x00, 0x06, 0x40}, /* 16k */ {4096000, 16000, 0x00, 0x01, 0x01, 0x01, 0x20, 0x00, 0x01, 0x00}, {19200000, 16000, 0x00, 0x0a, 0x00, 0x00, 0x1e, 0x00, 0x04, 0x80}, {16384000, 16000, 0x00, 0x02, 0x01, 0x00, 0x20, 0x00, 0x04, 0x00}, {12288000, 16000, 0x00, 0x03, 0x01, 0x01, 0x20, 0x00, 0x03, 0x00}, /* 22.05k */ {11289600, 22050, 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00}, /* 24k */ {12288000, 24000, 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00}, {19200000, 24000, 0x00, 0x0a, 0x00, 0x01, 0x28, 0x00, 0x03, 0x20}, /* 32k */ {12288000, 32000, 0x00, 0x03, 0x00, 0x00, 0x20, 0x00, 0x01, 0x80}, {16384000, 32000, 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00}, {19200000, 32000, 0x00, 0x05, 0x00, 0x00, 0x1e, 0x00, 0x02, 0x58}, /* 44.1k */ {11289600, 44100, 0x00, 0x01, 0x01, 0x01, 0x20, 0x00, 0x01, 0x00}, /* 48k */ {12288000, 48000, 0x00, 0x01, 0x01, 0x01, 0x20, 0x00, 0x01, 0x00}, {19200000, 48000, 0x00, 0x05, 0x00, 0x01, 0x28, 0x00, 0x01, 0x90}, /* 64k */ {16384000, 64000, 0x01, 0x01, 0x01, 0x00, 0x20, 0x00, 0x01, 0x00}, {19200000, 64000, 0x00, 0x05, 0x00, 0x01, 0x1e, 0x00, 0x01, 0x2c}, /* 88.2k */ {11289600, 88200, 0x01, 0x01, 0x01, 0x01, 0x20, 0x00, 0x00, 0x80}, /* 96k */ {12288000, 96000, 0x01, 0x01, 0x01, 0x01, 0x20, 0x00, 0x00, 0x80}, {19200000, 96000, 0x01, 0x05, 0x00, 0x01, 0x28, 0x00, 0x00, 0xc8}, }; static esp_err_t es7210_write_reg(uint8_t reg_addr, uint8_t data) { return i2c_bus_write_bytes(i2c_handle, ES7210_ADDR, &reg_addr, sizeof(reg_addr), &data, sizeof(data)); } static esp_err_t es7210_update_reg_bit(uint8_t reg_addr, uint8_t update_bits, uint8_t data) { uint8_t regv; regv = es7210_read_reg(reg_addr); regv = (regv & (~update_bits)) | (update_bits & data); return es7210_write_reg(reg_addr, regv); } static int i2c_init() { int ret = 0; i2c_config_t es_i2c_cfg = { .mode = I2C_MODE_MASTER, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_pullup_en = GPIO_PULLUP_ENABLE, .master.clk_speed = 100000, }; ret = get_i2c_pins(I2C_NUM_0, &es_i2c_cfg); AUDIO_CHECK(TAG, !ret, return ESP_FAIL;, "getting i2c pins error"); i2c_handle = i2c_bus_create(I2C_NUM_0, &es_i2c_cfg); return ret; } static int get_coeff(uint32_t mclk, uint32_t lrck) { for (int i = 0; i < (sizeof(coeff_div) / sizeof(coeff_div[0])); i++) { if (coeff_div[i].lrck == lrck && coeff_div[i].mclk == mclk) return i; } return -1; } int8_t get_es7210_mclk_src(void) { return ES7210_MCLK_SOURCE; } int es7210_read_reg(uint8_t reg_addr) { uint8_t data; i2c_bus_read_bytes(i2c_handle, ES7210_ADDR, &reg_addr, sizeof(reg_addr), &data, sizeof(data)); return (int)data; } esp_err_t es7210_config_sample(audio_hal_iface_samples_t sample) { uint8_t regv; int coeff; int sample_fre = 0; int mclk_fre = 0; esp_err_t ret = ESP_OK; switch (sample) { case AUDIO_HAL_08K_SAMPLES: sample_fre = 8000; break; case AUDIO_HAL_11K_SAMPLES: sample_fre = 11025; break; case AUDIO_HAL_16K_SAMPLES: sample_fre = 16000; break; case AUDIO_HAL_22K_SAMPLES: sample_fre = 22050; break; case AUDIO_HAL_24K_SAMPLES: sample_fre = 24000; break; case AUDIO_HAL_32K_SAMPLES: sample_fre = 32000; break; case AUDIO_HAL_44K_SAMPLES: sample_fre = 44100; break; case AUDIO_HAL_48K_SAMPLES: sample_fre = 48000; break; default: ESP_LOGE(TAG, "Unable to configure sample rate %dHz", sample_fre); break; } mclk_fre = sample_fre * MCLK_DIV_FRE; coeff = get_coeff(mclk_fre, sample_fre); if (coeff < 0) { ESP_LOGE(TAG, "Unable to configure sample rate %dHz with %dHz MCLK", sample_fre, mclk_fre); return ESP_FAIL; } /* Set clock parammeters */ if (coeff >= 0) { /* Set adc_div & doubler & dll */ regv = es7210_read_reg(ES7210_MAINCLK_REG02) & 0x00; regv |= coeff_div[coeff].adc_div; regv |= coeff_div[coeff].doubler << 6; regv |= coeff_div[coeff].dll << 7; ret |= es7210_write_reg(ES7210_MAINCLK_REG02, regv); /* Set osr */ regv = coeff_div[coeff].osr; ret |= es7210_write_reg(ES7210_OSR_REG07, regv); /* Set lrck */ regv = coeff_div[coeff].lrck_h; ret |= es7210_write_reg(ES7210_LRCK_DIVH_REG04, regv); regv = coeff_div[coeff].lrck_l; ret |= es7210_write_reg(ES7210_LRCK_DIVL_REG05, regv); } return ret; } esp_err_t es7210_mic_select(es7210_input_mics_t mic) { esp_err_t ret = ESP_OK; mic_select = mic; if (mic_select & (ES7210_INPUT_MIC1 | ES7210_INPUT_MIC2 | ES7210_INPUT_MIC3 | ES7210_INPUT_MIC4)) { for (int i = 0; i < 4; i++) { ret |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43 + i, 0x10, 0x00); } ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B, 0xff); ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0xff); if (mic_select & ES7210_INPUT_MIC1) { ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC1"); ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x0b, 0x00); ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B, 0x00); ret |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43, 0x10, 0x10); } if (mic_select & ES7210_INPUT_MIC2) { ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC2"); ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x0b, 0x00); ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B, 0x00); ret |= es7210_update_reg_bit(ES7210_MIC2_GAIN_REG44, 0x10, 0x10); } if (mic_select & ES7210_INPUT_MIC3) { ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC3"); ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x15, 0x00); ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0x00); ret |= es7210_update_reg_bit(ES7210_MIC3_GAIN_REG45, 0x10, 0x10); } if (mic_select & ES7210_INPUT_MIC4) { ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC4"); ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x15, 0x00); ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0x00); ret |= es7210_update_reg_bit(ES7210_MIC4_GAIN_REG46, 0x10, 0x10); } } else { ESP_LOGE(TAG, "Microphone selection error"); return ESP_FAIL; } return ret; } esp_err_t es7210_adc_init(audio_hal_codec_config_t *codec_cfg) { esp_err_t ret = ESP_OK; i2c_init(); ret |= es7210_write_reg(ES7210_RESET_REG00, 0xff); ret |= es7210_write_reg(ES7210_RESET_REG00, 0x41); ret |= es7210_write_reg(ES7210_CLOCK_OFF_REG01, 0x1f); ret |= es7210_write_reg(ES7210_TIME_CONTROL0_REG09, 0x30); /* Set chip state cycle */ ret |= es7210_write_reg(ES7210_TIME_CONTROL1_REG0A, 0x30); /* Set power on state cycle */ ret |= es7210_write_reg(ES7210_ADC12_HPF2_REG23, 0x2a); /* Quick setup */ ret |= es7210_write_reg(ES7210_ADC12_HPF1_REG22, 0x0a); ret |= es7210_write_reg(ES7210_ADC34_HPF2_REG20, 0x0a); ret |= es7210_write_reg(ES7210_ADC34_HPF1_REG21, 0x2a); /* Set master/slave audio interface */ audio_hal_codec_i2s_iface_t *i2s_cfg = & (codec_cfg->i2s_iface); switch (i2s_cfg->mode) { case AUDIO_HAL_MODE_MASTER: /* MASTER MODE */ ESP_LOGI(TAG, "ES7210 in Master mode"); ret |= es7210_update_reg_bit(ES7210_MODE_CONFIG_REG08, 0x01, 0x01); /* Select clock source for internal mclk */ switch (get_es7210_mclk_src()) { case FROM_PAD_PIN: ret |= es7210_update_reg_bit(ES7210_MASTER_CLK_REG03, 0x80, 0x00); break; case FROM_CLOCK_DOUBLE_PIN: ret |= es7210_update_reg_bit(ES7210_MASTER_CLK_REG03, 0x80, 0x80); break; default: ret |= es7210_update_reg_bit(ES7210_MASTER_CLK_REG03, 0x80, 0x00); break; } break; case AUDIO_HAL_MODE_SLAVE: /* SLAVE MODE */ ESP_LOGI(TAG, "ES7210 in Slave mode"); ret |= es7210_update_reg_bit(ES7210_MODE_CONFIG_REG08, 0x01, 0x00); break; default: ret |= es7210_update_reg_bit(ES7210_MODE_CONFIG_REG08, 0x01, 0x00); } ret |= es7210_write_reg(ES7210_ANALOG_REG40, 0x43); /* Select power off analog, vdda = 3.3V, close vx20ff, VMID select 5KΩ start */ ret |= es7210_write_reg(ES7210_MIC12_BIAS_REG41, 0x70); /* Select 2.87v */ ret |= es7210_write_reg(ES7210_MIC34_BIAS_REG42, 0x70); /* Select 2.87v */ ret |= es7210_write_reg(ES7210_OSR_REG07, 0x20); ret |= es7210_write_reg(ES7210_MAINCLK_REG02, 0xc1); /* Set the frequency division coefficient and use dll except clock doubler, and need to set 0xc1 to clear the state */ ret |= es7210_config_sample(i2s_cfg->samples); ret |= es7210_mic_select(mic_select); ret |= es7210_adc_set_gain(GAIN_30DB); return ESP_OK; } esp_err_t es7210_adc_deinit() { i2c_bus_delete(i2c_handle); return ESP_OK; } esp_err_t es7210_config_fmt(audio_hal_iface_format_t fmt) { esp_err_t ret = ESP_OK; uint8_t adc_iface = 0; adc_iface = es7210_read_reg(ES7210_SDP_INTERFACE1_REG11); adc_iface &= 0xfc; switch (fmt) { case AUDIO_HAL_I2S_NORMAL: ESP_LOGD(TAG, "ES7210 in I2S Format"); adc_iface |= 0x00; break; case AUDIO_HAL_I2S_LEFT: case AUDIO_HAL_I2S_RIGHT: ESP_LOGD(TAG, "ES7210 in LJ Format"); adc_iface |= 0x01; break; case AUDIO_HAL_I2S_DSP: if (I2S_DSP_MODE) { ESP_LOGD(TAG, "ES7210 in DSP-A Format"); adc_iface |= 0x13; } else { ESP_LOGD(TAG, "ES7210 in DSP-B Format"); adc_iface |= 0x03; } break; default: adc_iface &= 0xfc; break; } ret |= es7210_write_reg(ES7210_SDP_INTERFACE1_REG11, adc_iface); return ret; } esp_err_t es7210_set_bits(audio_hal_iface_bits_t bits) { esp_err_t ret = ESP_OK; uint8_t adc_iface = 0; adc_iface = es7210_read_reg(ES7210_SDP_INTERFACE1_REG11); adc_iface &= 0x1f; switch (bits) { case AUDIO_HAL_BIT_LENGTH_16BITS: adc_iface |= 0x60; break; case AUDIO_HAL_BIT_LENGTH_24BITS: adc_iface |= 0x00; break; case AUDIO_HAL_BIT_LENGTH_32BITS: adc_iface |= 0x80; break; default: adc_iface |= 0x60; break; } ret |= es7210_write_reg(ES7210_SDP_INTERFACE1_REG11, adc_iface); return ret; } esp_err_t es7210_adc_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { esp_err_t ret = ESP_OK; ret |= es7210_set_bits(iface->bits); ret |= es7210_config_fmt(iface->fmt); ret |= es7210_config_sample(iface->samples); return ret; } esp_err_t es7210_start(uint8_t clock_reg_value) { esp_err_t ret = ESP_OK; ret |= es7210_write_reg(ES7210_CLOCK_OFF_REG01, clock_reg_value); ret |= es7210_write_reg(ES7210_POWER_DOWN_REG06, 0x00); ret |= es7210_write_reg(ES7210_ANALOG_REG40, 0x43); ret |= es7210_write_reg(ES7210_MIC1_POWER_REG47, 0x00); ret |= es7210_write_reg(ES7210_MIC2_POWER_REG48, 0x00); ret |= es7210_write_reg(ES7210_MIC3_POWER_REG49, 0x00); ret |= es7210_write_reg(ES7210_MIC4_POWER_REG4A, 0x00); ret |= es7210_mic_select(mic_select); return ret; } esp_err_t es7210_stop(void) { esp_err_t ret = ESP_OK; ret |= es7210_write_reg(ES7210_MIC1_POWER_REG47, 0xff); ret |= es7210_write_reg(ES7210_MIC2_POWER_REG48, 0xff); ret |= es7210_write_reg(ES7210_MIC3_POWER_REG49, 0xff); ret |= es7210_write_reg(ES7210_MIC4_POWER_REG4A, 0xff); ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B,0xff); ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0xff); ret |= es7210_write_reg(ES7210_ANALOG_REG40, 0xc0); ret |= es7210_write_reg(ES7210_CLOCK_OFF_REG01, 0x7f); ret |= es7210_write_reg(ES7210_POWER_DOWN_REG06, 0x07); return ret; } esp_err_t es7210_adc_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { static uint8_t regv; esp_err_t ret = ESP_OK; ESP_LOGW(TAG, "ES7210 only supports ADC mode"); ret = es7210_read_reg(ES7210_CLOCK_OFF_REG01); if ((ret != 0x7f) && (ret != 0xff)) { regv = es7210_read_reg(ES7210_CLOCK_OFF_REG01); } if (ctrl_state == AUDIO_HAL_CTRL_START) { ESP_LOGI(TAG, "The ES7210_CLOCK_OFF_REG01 value before stop is %x",regv); ret |= es7210_start(regv); } else { ESP_LOGW(TAG, "The codec is about to stop"); regv = es7210_read_reg(ES7210_CLOCK_OFF_REG01); ret |= es7210_stop(); } return ret; } esp_err_t es7210_adc_set_gain(es7210_gain_value_t gain) { esp_err_t ret = ESP_OK; uint32_t max_gain_vaule = 14; if (gain < 0) { gain = 0; } else if (gain > max_gain_vaule) { gain = max_gain_vaule; } ESP_LOGD(TAG, "SET: gain:%d", gain); if (mic_select & ES7210_INPUT_MIC1) { ret |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43, 0x0f, gain); } if (mic_select & ES7210_INPUT_MIC2) { ret |= es7210_update_reg_bit(ES7210_MIC2_GAIN_REG44, 0x0f, gain); } if (mic_select & ES7210_INPUT_MIC3) { ret |= es7210_update_reg_bit(ES7210_MIC3_GAIN_REG45, 0x0f, gain); } if (mic_select & ES7210_INPUT_MIC4) { ret |= es7210_update_reg_bit(ES7210_MIC4_GAIN_REG46, 0x0f, gain); } return ret; } esp_err_t es7210_adc_get_gain(void) { int regv = 0; uint8_t gain_value; if (mic_select & ES7210_INPUT_MIC1) { regv = es7210_read_reg(ES7210_MIC1_GAIN_REG43); } else if (mic_select & ES7210_INPUT_MIC2) { regv = es7210_read_reg(ES7210_MIC2_GAIN_REG44); } else if (mic_select & ES7210_INPUT_MIC3) { regv = es7210_read_reg(ES7210_MIC3_GAIN_REG45); } else if (mic_select & ES7210_INPUT_MIC4) { regv = es7210_read_reg(ES7210_MIC4_GAIN_REG46); } else { ESP_LOGE(TAG, "No MIC selected"); return ESP_FAIL; } if (regv == ESP_FAIL) { return regv; } gain_value = (regv & 0x0f); /* Retain the last four bits for gain */ ESP_LOGI(TAG, "GET: gain_value:%d", gain_value); return gain_value; } esp_err_t es7210_adc_set_volume(int volume) { esp_err_t ret = ESP_OK; ESP_LOGD(TAG, "ADC can adjust gain"); return ret; } esp_err_t es7210_set_mute(bool enable) { ESP_LOGD(TAG, "ES7210 SetMute :%d", enable); return ESP_OK; } void es7210_read_all(void) { for (int i = 0; i <= 0x4E; i++) { uint8_t reg = es7210_read_reg(i); ets_printf("REG:%02x, %02x\n", reg, i); } }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es7210/es7210.c
C
apache-2.0
19,427
/* * ESPRESSIF MIT License * * Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _ES7210_H #define _ES7210_H #include "audio_hal.h" #ifdef __cplusplus extern "C" { #endif #define ES7210_RESET_REG00 0x00 /* Reset control */ #define ES7210_CLOCK_OFF_REG01 0x01 /* Used to turn off the ADC clock */ #define ES7210_MAINCLK_REG02 0x02 /* Set ADC clock frequency division */ #define ES7210_MASTER_CLK_REG03 0x03 /* MCLK source $ SCLK division */ #define ES7210_LRCK_DIVH_REG04 0x04 /* lrck_divh */ #define ES7210_LRCK_DIVL_REG05 0x05 /* lrck_divl */ #define ES7210_POWER_DOWN_REG06 0x06 /* power down */ #define ES7210_OSR_REG07 0x07 #define ES7210_MODE_CONFIG_REG08 0x08 /* Set master/slave & channels */ #define ES7210_TIME_CONTROL0_REG09 0x09 /* Set Chip intial state period*/ #define ES7210_TIME_CONTROL1_REG0A 0x0A /* Set Power up state period */ #define ES7210_SDP_INTERFACE1_REG11 0x11 /* Set sample & fmt */ #define ES7210_SDP_INTERFACE2_REG12 0x12 /* Pins state */ #define ES7210_ADC_AUTOMUTE_REG13 0x13 /* Set mute */ #define ES7210_ADC34_MUTERANGE_REG14 0x14 /* Set mute range */ #define ES7210_ADC34_HPF2_REG20 0x20 /* HPF */ #define ES7210_ADC34_HPF1_REG21 0x21 #define ES7210_ADC12_HPF1_REG22 0x22 #define ES7210_ADC12_HPF2_REG23 0x23 #define ES7210_ANALOG_REG40 0x40 /* ANALOG Power */ #define ES7210_MIC12_BIAS_REG41 0x41 #define ES7210_MIC34_BIAS_REG42 0x42 #define ES7210_MIC1_GAIN_REG43 0x43 #define ES7210_MIC2_GAIN_REG44 0x44 #define ES7210_MIC3_GAIN_REG45 0x45 #define ES7210_MIC4_GAIN_REG46 0x46 #define ES7210_MIC1_POWER_REG47 0x47 #define ES7210_MIC2_POWER_REG48 0x48 #define ES7210_MIC3_POWER_REG49 0x49 #define ES7210_MIC4_POWER_REG4A 0x4A #define ES7210_MIC12_POWER_REG4B 0x4B /* MICBias & ADC & PGA Power */ #define ES7210_MIC34_POWER_REG4C 0x4C typedef enum { ES7210_AD1_AD0_00 = 0x80, ES7210_AD1_AD0_01 = 0x82, ES7210_AD1_AD0_10 = 0x84, ES7210_AD1_AD0_11 = 0x86 } es7210_address_t; typedef enum { ES7210_INPUT_MIC1 = 0x01, ES7210_INPUT_MIC2 = 0x02, ES7210_INPUT_MIC3 = 0x04, ES7210_INPUT_MIC4 = 0x08 } es7210_input_mics_t; typedef enum gain_value{ GAIN_0DB = 0, GAIN_3DB, GAIN_6DB, GAIN_9DB, GAIN_12DB, GAIN_15DB, GAIN_18DB, GAIN_21DB, GAIN_24DB, GAIN_27DB, GAIN_30DB, GAIN_33DB, GAIN_34_5DB, GAIN_36DB, GAIN_37_5DB, } es7210_gain_value_t; /* * @brief Initialize ES7210 ADC chip * * @param[in] codec_cfg: configuration of ES7210 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7210_adc_init(audio_hal_codec_config_t *codec_cfg); /** * @brief Deinitialize ES7210 ADC chip * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7210_adc_deinit(); /** * @brief Configure ES7210 ADC mode and I2S interface * * @param[in] mode: codec mode * @param[in] iface: I2S config * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es7210_adc_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /** * @brief Control ES7210 ADC chip * * @param[in] mode: codec mode * @param[in] ctrl_state: start or stop progress * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es7210_adc_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); /** * @brief Set gain (Note: the enabled microphone sets the same gain) * * @param[in] gain: gain * * gain : value * GAIN_0DB : 1 * GAIN_3DB : 2 * GAIN_6DB : 3 * · * · * · * GAIN_30DB : 10 * GAIN_33DB : 11 * GAIN_34_5DB : 12 * GAIN_36DB : 13 * GAIN_37_5DB : 14 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7210_adc_set_gain(es7210_gain_value_t gain); /** * @brief Get gain * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7210_adc_get_gain(void); /** * @brief Set volume * * @param[in] volume: volume * * @return * - ESP_OK */ esp_err_t es7210_adc_set_volume(int volume); /** * @brief Set ES7210 ADC mute status * * @return * - ESP_FAIL * - ESP_OK */ esp_err_t es7210_set_mute(bool enable); /** * @brief Select ES7210 mic * * @param[in] mic: mics * * @return * - ESP_FAIL * - ESP_OK */ esp_err_t es7210_mic_select(es7210_input_mics_t mic); /** * @brief Read regs of ES7210 * * @param[in] reg_addr: reg_addr * * @return * - ESP_FAIL * - ESP_OK */ int es7210_read_reg(uint8_t reg_addr); /** * @brief Read all regs of ES7210 */ void es7210_read_all(void); #ifdef __cplusplus } #endif #endif /* _ES7210_H_ */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es7210/es7210.h
C
apache-2.0
6,281
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "es7243.h" #include "i2c_bus.h" #include "board.h" #include "esp_log.h" #define MCLK_PULSES_NUMBER (20) #define ES_ASSERT(a, format, b, ...) \ if ((a) != 0) { \ ESP_LOGE(TAG, format, ##__VA_ARGS__); \ return b;\ } static char *TAG = "DRV7243"; static i2c_bus_handle_t i2c_handle; static int es7243_addr = 0x26; audio_hal_func_t AUDIO_CODEC_ES7243_DEFAULT_HANDLE = { .audio_codec_initialize = es7243_adc_init, .audio_codec_deinitialize = es7243_adc_deinit, .audio_codec_ctrl = es7243_adc_ctrl_state, .audio_codec_config_iface = es7243_adc_config_i2s, .audio_codec_set_mute = es7243_adc_set_voice_mute, .audio_codec_set_volume = es7243_adc_set_voice_volume, .audio_codec_get_volume = es7243_adc_get_voice_volume, .audio_hal_lock = NULL, .handle = NULL, }; static esp_err_t es7243_write_reg(uint8_t reg_add, uint8_t data) { return i2c_bus_write_bytes(i2c_handle, es7243_addr, &reg_add, sizeof(reg_add), &data, sizeof(data)); } static int i2c_init() { int res = 0; i2c_config_t es_i2c_cfg = { .mode = I2C_MODE_MASTER, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_pullup_en = GPIO_PULLUP_ENABLE, .master.clk_speed = 100000, }; res = get_i2c_pins(I2C_NUM_0, &es_i2c_cfg); ES_ASSERT(res, "getting i2c pins error", -1); i2c_handle = i2c_bus_create(I2C_NUM_0, &es_i2c_cfg); return res; } esp_err_t es7243_adc_set_addr(int addr) { es7243_addr = addr; return ESP_OK; } static esp_err_t es7243_mclk_active(uint8_t mclk_gpio) { gpio_pad_select_gpio(mclk_gpio); gpio_set_direction(mclk_gpio, GPIO_MODE_OUTPUT); /* Before initializing es7243, it is necessary to output mclk to es7243 to activate the I2C configuration. So give some clocks to active es7243. */ for (int i = 0; i < MCLK_PULSES_NUMBER; ++i) { gpio_set_level(mclk_gpio, 0); vTaskDelay(1 / portTICK_PERIOD_MS); gpio_set_level(mclk_gpio, 1); vTaskDelay(1 / portTICK_PERIOD_MS); } return ESP_OK; } esp_err_t es7243_adc_init(audio_hal_codec_config_t *codec_cfg) { esp_err_t ret = ESP_OK; es7243_mclk_active(get_es7243_mclk_gpio()); i2c_init(); ret |= es7243_write_reg(0x00, 0x01); ret |= es7243_write_reg(0x06, 0x00); ret |= es7243_write_reg(0x05, 0x1B); ret |= es7243_write_reg(0x01, 0x0C); ret |= es7243_write_reg(0x08, 0x43); ret |= es7243_write_reg(0x05, 0x13); if (ret) { ESP_LOGE(TAG, "Es7243 initialize failed!"); return ESP_FAIL; } return ret; } esp_err_t es7243_adc_deinit(void) { return ESP_OK; } esp_err_t es7243_adc_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { return ESP_OK; } esp_err_t es7243_adc_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { return ESP_OK; } esp_err_t es7243_adc_set_voice_mute(bool mute) { ESP_LOGI(TAG, "Enter into es7243_mute(), mute = %d\n", mute); if (mute) { es7243_write_reg(0x05, 0x1B); } else { es7243_write_reg(0x05, 0x13); } return ESP_OK; } esp_err_t es7243_adc_set_voice_volume(int volume) { esp_err_t ret = ESP_OK; if (volume > 100) { volume = 100; } if (volume < 0) { volume = 0; } switch (volume) { case 0 ... 12: ret |= es7243_write_reg(0x08, 0x11); // 1db break; case 13 ... 25: ret |= es7243_write_reg(0x08, 0x13); //3.5db break; case 26 ... 38: ret |= es7243_write_reg(0x08, 0x21); //18db break; case 39 ... 51: ret |= es7243_write_reg(0x08, 0x23); //20.5db break; case 52 ... 65: ret |= es7243_write_reg(0x08, 0x06); //22.5db break; case 66 ... 80: ret |= es7243_write_reg(0x08, 0x41); //24.5db break; case 81 ... 90: ret |= es7243_write_reg(0x08, 0x07); //25db break; case 91 ... 100: ret |= es7243_write_reg(0x08, 0x43); //27db break; default: break; } return ESP_OK; } esp_err_t es7243_adc_get_voice_volume(int *volume) { return ESP_OK; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es7243/es7243.c
C
apache-2.0
5,532
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _ES7243_H_ #define _ES7243_H_ #include "esp_err.h" #include "audio_hal.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize ES7243 adc chip * * @param codec_cfg configuration of ES7243 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7243_adc_init(audio_hal_codec_config_t *codec_cfg); /** * @brief Deinitialize ES7243 adc chip * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7243_adc_deinit(void); /** * @brief Control ES7243 adc chip * * @param mode adc mode * @param ctrl_state start or stop decode or encode progress * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es7243_adc_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); /** * @brief Configure ES7243 adc mode and I2S interface * * @param mode codec mode * @param iface I2S config * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es7243_adc_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /** * @brief Set mute * * @param mute true, false * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7243_adc_set_voice_mute(bool mute); /** * @brief Set adc gain * * @param volume value of gain (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7243_adc_set_voice_volume(int volume); /** * @brief Get adc gain * * @param[out] *volume: value of gain (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7243_adc_get_voice_volume(int *volume); /** * @brief Set adc I2C address * * @param[in] addr: value of I2C address * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es7243_adc_set_addr(int addr); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es7243/es7243.h
C
apache-2.0
3,005
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "i2c_bus.h" #include "board.h" #include "esp_log.h" #include "es8311.h" /* ES8311 address * 0x32:CE=1;0x30:CE=0 */ #define ES8311_ADDR 0x30 /* * to define the clock soure of MCLK */ #define FROM_MCLK_PIN 0 #define FROM_SCLK_PIN 1 /* * to define whether to reverse the clock */ #define INVERT_MCLK 0 // do not invert #define INVERT_SCLK 0 #define IS_DMIC 0 // Is it a digital microphone #define MCLK_DIV_FRE 256 static i2c_bus_handle_t i2c_handle; /* * operate function of codec */ audio_hal_func_t AUDIO_CODEC_ES8311_DEFAULT_HANDLE = { .audio_codec_initialize = es8311_codec_init, .audio_codec_deinitialize = es8311_codec_deinit, .audio_codec_ctrl = es8311_codec_ctrl_state, .audio_codec_config_iface = es8311_codec_config_i2s, .audio_codec_set_mute = es8311_set_voice_mute, .audio_codec_set_volume = es8311_codec_set_voice_volume, .audio_codec_get_volume = es8311_codec_get_voice_volume, .audio_hal_lock = NULL, .handle = NULL, }; /* * Clock coefficient structer */ struct _coeff_div { uint32_t mclk; /* mclk frequency */ uint32_t rate; /* sample rate */ uint8_t pre_div; /* the pre divider with range from 1 to 8 */ uint8_t pre_multi; /* the pre multiplier with x1, x2, x4 and x8 selection */ uint8_t adc_div; /* adcclk divider */ uint8_t dac_div; /* dacclk divider */ uint8_t fs_mode; /* double speed or single speed, =0, ss, =1, ds */ uint8_t lrck_h; /* adclrck divider and daclrck divider */ uint8_t lrck_l; uint8_t bclk_div; /* sclk divider */ uint8_t adc_osr; /* adc osr */ uint8_t dac_osr; /* dac osr */ }; /* codec hifi mclk clock divider coefficients */ static const struct _coeff_div coeff_div[] = { //mclk rate pre_div mult adc_div dac_div fs_mode lrch lrcl bckdiv osr /* 8k */ {12288000, 8000 , 0x06, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {18432000, 8000 , 0x03, 0x02, 0x03, 0x03, 0x00, 0x05, 0xff, 0x18, 0x10, 0x10}, {16384000, 8000 , 0x08, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {8192000 , 8000 , 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {6144000 , 8000 , 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {4096000 , 8000 , 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {3072000 , 8000 , 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {2048000 , 8000 , 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1536000 , 8000 , 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1024000 , 8000 , 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, /* 11.025k */ {11289600, 11025, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {5644800 , 11025, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {2822400 , 11025, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1411200 , 11025, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, /* 12k */ {12288000, 12000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {6144000 , 12000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {3072000 , 12000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1536000 , 12000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, /* 16k */ {12288000, 16000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {18432000, 16000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10}, {16384000, 16000, 0x04, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {8192000 , 16000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {6144000 , 16000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {4096000 , 16000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {3072000 , 16000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {2048000 , 16000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1536000 , 16000, 0x03, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1024000 , 16000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, /* 22.05k */ {11289600, 22050, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {5644800 , 22050, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {2822400 , 22050, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1411200 , 22050, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, /* 24k */ {12288000, 24000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {18432000, 24000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {6144000 , 24000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {3072000 , 24000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1536000 , 24000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, /* 32k */ {12288000, 32000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {18432000, 32000, 0x03, 0x04, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10}, {16384000, 32000, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {8192000 , 32000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {6144000 , 32000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {4096000 , 32000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {3072000 , 32000, 0x03, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {2048000 , 32000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1536000 , 32000, 0x03, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10}, {1024000 , 32000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, /* 44.1k */ {11289600, 44100, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {5644800 , 44100, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {2822400 , 44100, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1411200 , 44100, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, /* 48k */ {12288000, 48000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {18432000, 48000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {6144000 , 48000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {3072000 , 48000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1536000 , 48000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, /* 64k */ {12288000, 64000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {18432000, 64000, 0x03, 0x04, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10}, {16384000, 64000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {8192000 , 64000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {6144000 , 64000, 0x01, 0x04, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10}, {4096000 , 64000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {3072000 , 64000, 0x01, 0x08, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10}, {2048000 , 64000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1536000 , 64000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0xbf, 0x03, 0x18, 0x18}, {1024000 , 64000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10}, /* 88.2k */ {11289600, 88200, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {5644800 , 88200, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {2822400 , 88200, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1411200 , 88200, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10}, /* 96k */ {12288000, 96000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {18432000, 96000, 0x03, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {6144000 , 96000, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {3072000 , 96000, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10}, {1536000 , 96000, 0x01, 0x08, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10}, }; static char *TAG = "DRV8311"; #define ES_ASSERT(a, format, b, ...) \ if ((a) != 0) { \ ESP_LOGE(TAG, format, ##__VA_ARGS__); \ return b;\ } int8_t get_es8311_mclk_src(void); static esp_err_t es8311_write_reg(uint8_t reg_addr, uint8_t data) { return i2c_bus_write_bytes(i2c_handle, ES8311_ADDR, &reg_addr, sizeof(reg_addr), &data, sizeof(data)); } static int es8311_read_reg(uint8_t reg_addr) { uint8_t data; i2c_bus_read_bytes(i2c_handle, ES8311_ADDR, &reg_addr, sizeof(reg_addr), &data, sizeof(data)); return (int)data; } static int i2c_init() { int res = 0; i2c_config_t es_i2c_cfg = { .mode = I2C_MODE_MASTER, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_pullup_en = GPIO_PULLUP_ENABLE, .master.clk_speed = 100000, }; res = get_i2c_pins(I2C_NUM_0, &es_i2c_cfg); ES_ASSERT(res, "getting i2c pins error", -1); i2c_handle = i2c_bus_create(I2C_NUM_0, &es_i2c_cfg); return res; } /* * look for the coefficient in coeff_div[] table */ static int get_coeff(uint32_t mclk, uint32_t rate) { for (int i = 0; i < (sizeof(coeff_div) / sizeof(coeff_div[0])); i++) { if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk) return i; } return -1; } /* * set es8311 dac mute or not * if mute = 0, dac un-mute * if mute = 1, dac mute */ static void es8311_mute(int mute) { uint8_t regv; ESP_LOGI(TAG, "Enter into es8311_mute(), mute = %d\n", mute); regv = es8311_read_reg(ES8311_DAC_REG31) & 0x9f; if (mute) { es8311_write_reg(ES8311_SYSTEM_REG12, 0x02); es8311_write_reg(ES8311_DAC_REG31, regv | 0x60); es8311_write_reg(ES8311_DAC_REG32, 0x00); es8311_write_reg(ES8311_DAC_REG37, 0x08); } else { es8311_write_reg(ES8311_DAC_REG31, regv); es8311_write_reg(ES8311_SYSTEM_REG12, 0x00); } } /* * set es8311 into suspend mode */ static void es8311_suspend(void) { ESP_LOGI(TAG, "Enter into es8311_suspend()"); es8311_write_reg(ES8311_DAC_REG32, 0x00); es8311_write_reg(ES8311_ADC_REG17, 0x00); es8311_write_reg(ES8311_SYSTEM_REG0E, 0xFF); es8311_write_reg(ES8311_SYSTEM_REG12, 0x02); es8311_write_reg(ES8311_SYSTEM_REG14, 0x00); es8311_write_reg(ES8311_SYSTEM_REG0D, 0xFA); es8311_write_reg(ES8311_ADC_REG15, 0x00); es8311_write_reg(ES8311_DAC_REG37, 0x08); es8311_write_reg(ES8311_GP_REG45, 0x01); } /* * enable pa power */ void es8311_pa_power(bool enable) { gpio_config_t io_conf; memset(&io_conf, 0, sizeof(io_conf)); io_conf.mode = GPIO_MODE_OUTPUT; io_conf.pin_bit_mask = BIT64(get_pa_enable_gpio()); io_conf.pull_down_en = 0; io_conf.pull_up_en = 0; gpio_config(&io_conf); if (enable) { gpio_set_level(get_pa_enable_gpio(), 1); } else { gpio_set_level(get_pa_enable_gpio(), 0); } } esp_err_t es8311_codec_init(audio_hal_codec_config_t *codec_cfg) { uint8_t datmp, regv; int coeff; esp_err_t ret = ESP_OK; i2c_init(); // ESP32 in master mode ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG01, 0x30); ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG02, 0x00); ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG03, 0x10); ret |= es8311_write_reg(ES8311_ADC_REG16, 0x24); ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG04, 0x10); ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG05, 0x00); ret |= es8311_write_reg(ES8311_SYSTEM_REG0B, 0x00); ret |= es8311_write_reg(ES8311_SYSTEM_REG0C, 0x00); ret |= es8311_write_reg(ES8311_SYSTEM_REG10, 0x1F); ret |= es8311_write_reg(ES8311_SYSTEM_REG11, 0x7F); ret |= es8311_write_reg(ES8311_RESET_REG00, 0x80); /* * Set Codec into Master or Slave mode */ regv = es8311_read_reg(ES8311_RESET_REG00); /* * Set master/slave audio interface */ audio_hal_codec_i2s_iface_t *i2s_cfg = &(codec_cfg->i2s_iface); switch (i2s_cfg->mode) { case AUDIO_HAL_MODE_MASTER: /* MASTER MODE */ ESP_LOGI(TAG, "ES8311 in Master mode"); regv |= 0x40; break; case AUDIO_HAL_MODE_SLAVE: /* SLAVE MODE */ ESP_LOGI(TAG, "ES8311 in Slave mode"); regv &= 0xBF; break; default: regv &= 0xBF; } ret |= es8311_write_reg(ES8311_RESET_REG00, regv); ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG01, 0x3F); /* * Select clock source for internal mclk */ switch (get_es8311_mclk_src()) { case FROM_MCLK_PIN: regv = es8311_read_reg(ES8311_CLK_MANAGER_REG01); regv &= 0x7F; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG01, regv); break; case FROM_SCLK_PIN: regv = es8311_read_reg(ES8311_CLK_MANAGER_REG01); regv |= 0x80; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG01, regv); break; default: regv = es8311_read_reg(ES8311_CLK_MANAGER_REG01); regv &= 0x7F; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG01, regv); break; } int sample_fre = 0; int mclk_fre = 0; switch (i2s_cfg->samples) { case AUDIO_HAL_08K_SAMPLES: sample_fre = 8000; break; case AUDIO_HAL_11K_SAMPLES: sample_fre = 11025; break; case AUDIO_HAL_16K_SAMPLES: sample_fre = 16000; break; case AUDIO_HAL_22K_SAMPLES: sample_fre = 22050; break; case AUDIO_HAL_24K_SAMPLES: sample_fre = 24000; break; case AUDIO_HAL_32K_SAMPLES: sample_fre = 32000; break; case AUDIO_HAL_44K_SAMPLES: sample_fre = 44100; break; case AUDIO_HAL_48K_SAMPLES: sample_fre = 48000; break; default: ESP_LOGE(TAG, "Unable to configure sample rate %dHz", sample_fre); break; } mclk_fre = sample_fre * MCLK_DIV_FRE; coeff = get_coeff(mclk_fre, sample_fre); if (coeff < 0) { ESP_LOGE(TAG, "Unable to configure sample rate %dHz with %dHz MCLK", sample_fre, mclk_fre); return ESP_FAIL; } /* * Set clock parammeters */ if (coeff >= 0) { regv = es8311_read_reg(ES8311_CLK_MANAGER_REG02) & 0x07; regv |= (coeff_div[coeff].pre_div - 1) << 5; datmp = 0; switch (coeff_div[coeff].pre_multi) { case 1: datmp = 0; break; case 2: datmp = 1; break; case 4: datmp = 2; break; case 8: datmp = 3; break; default: break; } if (get_es8311_mclk_src() == FROM_SCLK_PIN) { datmp = 3; /* DIG_MCLK = LRCK * 256 = BCLK * 8 */ } regv |= (datmp) << 3; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG02, regv); regv = es8311_read_reg(ES8311_CLK_MANAGER_REG05) & 0x00; regv |= (coeff_div[coeff].adc_div - 1) << 4; regv |= (coeff_div[coeff].dac_div - 1) << 0; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG05, regv); regv = es8311_read_reg(ES8311_CLK_MANAGER_REG03) & 0x80; regv |= coeff_div[coeff].fs_mode << 6; regv |= coeff_div[coeff].adc_osr << 0; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG03, regv); regv = es8311_read_reg(ES8311_CLK_MANAGER_REG04) & 0x80; regv |= coeff_div[coeff].dac_osr << 0; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG04, regv); regv = es8311_read_reg(ES8311_CLK_MANAGER_REG07) & 0xC0; regv |= coeff_div[coeff].lrck_h << 0; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG07, regv); regv = es8311_read_reg(ES8311_CLK_MANAGER_REG08) & 0x00; regv |= coeff_div[coeff].lrck_l << 0; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG08, regv); regv = es8311_read_reg(ES8311_CLK_MANAGER_REG06) & 0xE0; if (coeff_div[coeff].bclk_div < 19) { regv |= (coeff_div[coeff].bclk_div - 1) << 0; } else { regv |= (coeff_div[coeff].bclk_div) << 0; } ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG06, regv); } /* * mclk inverted or not */ if (INVERT_MCLK) { regv = es8311_read_reg(ES8311_CLK_MANAGER_REG01); regv |= 0x40; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG01, regv); } else { regv = es8311_read_reg(ES8311_CLK_MANAGER_REG01); regv &= ~(0x40); ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG01, regv); } /* * sclk inverted or not */ if (INVERT_SCLK) { regv = es8311_read_reg(ES8311_CLK_MANAGER_REG06); regv |= 0x20; ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG06, regv); } else { regv = es8311_read_reg(ES8311_CLK_MANAGER_REG06); regv &= ~(0x20); ret |= es8311_write_reg(ES8311_CLK_MANAGER_REG06, regv); } ret |= es8311_write_reg(ES8311_SYSTEM_REG13, 0x10); ret |= es8311_write_reg(ES8311_ADC_REG1B, 0x0A); ret |= es8311_write_reg(ES8311_ADC_REG1C, 0x6A); es8311_pa_power(true); return ESP_OK; } esp_err_t es8311_codec_deinit() { i2c_bus_delete(i2c_handle); return ESP_OK; } esp_err_t es8311_config_fmt(es_i2s_fmt_t fmt) { esp_err_t ret = ESP_OK; uint8_t adc_iface = 0, dac_iface = 0; dac_iface = es8311_read_reg(ES8311_SDPIN_REG09); adc_iface = es8311_read_reg(ES8311_SDPOUT_REG0A); switch (fmt) { case AUDIO_HAL_I2S_NORMAL: ESP_LOGD(TAG, "ES8311 in I2S Format"); dac_iface &= 0xFC; adc_iface &= 0xFC; break; case AUDIO_HAL_I2S_LEFT: case AUDIO_HAL_I2S_RIGHT: ESP_LOGD(TAG, "ES8311 in LJ Format"); adc_iface &= 0xFC; dac_iface &= 0xFC; adc_iface |= 0x01; dac_iface |= 0x01; break; case AUDIO_HAL_I2S_DSP: ESP_LOGD(TAG, "ES8311 in DSP-A Format"); adc_iface &= 0xDC; dac_iface &= 0xDC; adc_iface |= 0x03; dac_iface |= 0x03; break; default: dac_iface &= 0xFC; adc_iface &= 0xFC; break; } ret |= es8311_write_reg(ES8311_SDPIN_REG09, dac_iface); ret |= es8311_write_reg(ES8311_SDPOUT_REG0A, adc_iface); return ret; } esp_err_t es8311_set_bits_per_sample(audio_hal_iface_bits_t bits) { esp_err_t ret = ESP_OK; uint8_t adc_iface = 0, dac_iface = 0; dac_iface = es8311_read_reg(ES8311_SDPIN_REG09); adc_iface = es8311_read_reg(ES8311_SDPOUT_REG0A); switch (bits) { case AUDIO_HAL_BIT_LENGTH_16BITS: dac_iface |= 0x0c; adc_iface |= 0x0c; break; case AUDIO_HAL_BIT_LENGTH_24BITS: break; case AUDIO_HAL_BIT_LENGTH_32BITS: dac_iface |= 0x10; adc_iface |= 0x10; break; default: dac_iface |= 0x0c; adc_iface |= 0x0c; break; } ret |= es8311_write_reg(ES8311_SDPIN_REG09, dac_iface); ret |= es8311_write_reg(ES8311_SDPOUT_REG0A, adc_iface); return ret; } esp_err_t es8311_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { int ret = ESP_OK; ret |= es8311_set_bits_per_sample(iface->bits); ret |= es8311_config_fmt(iface->fmt); return ret; } esp_err_t es8311_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { esp_err_t ret = ESP_OK; es_module_t es_mode = ES_MODULE_MIN; switch (mode) { case AUDIO_HAL_CODEC_MODE_ENCODE: es_mode = ES_MODULE_ADC; break; case AUDIO_HAL_CODEC_MODE_LINE_IN: es_mode = ES_MODULE_LINE; break; case AUDIO_HAL_CODEC_MODE_DECODE: es_mode = ES_MODULE_DAC; break; case AUDIO_HAL_CODEC_MODE_BOTH: es_mode = ES_MODULE_ADC_DAC; break; default: es_mode = ES_MODULE_DAC; ESP_LOGW(TAG, "Codec mode not support, default is decode mode"); break; } if (ctrl_state == AUDIO_HAL_CTRL_START) { ret |= es8311_start(es_mode); } else { ESP_LOGW(TAG, "The codec is about to stop"); ret |= es8311_stop(es_mode); } return ret; } esp_err_t es8311_start(es_module_t mode) { esp_err_t ret = ESP_OK; uint8_t adc_iface = 0, dac_iface = 0; dac_iface = es8311_read_reg(ES8311_SDPIN_REG09) & 0xBF; adc_iface = es8311_read_reg(ES8311_SDPOUT_REG0A) & 0xBF; adc_iface |= BIT(6); dac_iface |= BIT(6); if (mode == ES_MODULE_LINE) { ESP_LOGE(TAG, "The codec es8311 doesn't support ES_MODULE_LINE mode"); return ESP_FAIL; } if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC) { adc_iface &= ~(BIT(6)); } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC) { dac_iface &= ~(BIT(6)); } ret |= es8311_write_reg(ES8311_SDPIN_REG09, dac_iface); ret |= es8311_write_reg(ES8311_SDPOUT_REG0A, adc_iface); ret |= es8311_write_reg(ES8311_ADC_REG17, 0xBF); ret |= es8311_write_reg(ES8311_SYSTEM_REG0E, 0x02); ret |= es8311_write_reg(ES8311_SYSTEM_REG12, 0x00); ret |= es8311_write_reg(ES8311_SYSTEM_REG14, 0x1A); /* * pdm dmic enable or disable */ int regv = 0; if (IS_DMIC) { regv = es8311_read_reg(ES8311_SYSTEM_REG14); regv |= 0x40; ret |= es8311_write_reg(ES8311_SYSTEM_REG14, regv); } else { regv = es8311_read_reg(ES8311_SYSTEM_REG14); regv &= ~(0x40); ret |= es8311_write_reg(ES8311_SYSTEM_REG14, regv); } ret |= es8311_write_reg(ES8311_SYSTEM_REG0D, 0x01); ret |= es8311_write_reg(ES8311_ADC_REG15, 0x40); ret |= es8311_write_reg(ES8311_DAC_REG37, 0x48); ret |= es8311_write_reg(ES8311_GP_REG45, 0x00); return ret; } esp_err_t es8311_stop(es_module_t mode) { esp_err_t ret = ESP_OK; es8311_suspend(); return ret; } esp_err_t es8311_codec_set_voice_volume(int volume) { esp_err_t res = ESP_OK; if (volume < 0) { volume = 0; } else if (volume > 100) { volume = 100; } int vol = (volume) * 2550 / 1000; ESP_LOGD(TAG, "SET: volume:%d", vol); es8311_write_reg(ES8311_DAC_REG32, vol); return res; } esp_err_t es8311_codec_get_voice_volume(int *volume) { esp_err_t res = ESP_OK; int regv = 0; regv = es8311_read_reg(ES8311_DAC_REG32); if (regv == ESP_FAIL) { *volume = 0; res = ESP_FAIL; } else { *volume = regv * 100 / 256; } ESP_LOGD(TAG, "GET: res:%d, volume:%d", regv, *volume); return res; } esp_err_t es8311_set_voice_mute(bool enable) { ESP_LOGD(TAG, "Es8311SetVoiceMute volume:%d", enable); es8311_mute(enable); return ESP_OK; } esp_err_t es8311_get_voice_mute(int *mute) { esp_err_t res = ESP_OK; uint8_t reg = 0; res = es8311_read_reg(ES8311_DAC_REG31); if (res != ESP_FAIL) { reg = (res & 0x20) >> 5; } *mute = reg; return res; } esp_err_t es8311_set_mic_gain(es8311_mic_gain_t gain_db) { esp_err_t res = ESP_OK; res = es8311_write_reg(ES8311_ADC_REG16, gain_db); // MIC gain scale return res; } void es8311_read_all() { for (int i = 0; i < 0x4A; i++) { uint8_t reg = es8311_read_reg(i); ets_printf("REG:%02x, %02x\n", reg, i); } }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es8311/es8311.c
C
apache-2.0
25,302
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _ES8311_H #define _ES8311_H #include "audio_hal.h" #include "esp_types.h" #include "esxxx_common.h" #ifdef __cplusplus extern "C" { #endif /* * ES8311_REGISTER NAME_REG_REGISTER ADDRESS */ #define ES8311_RESET_REG00 0x00 /*reset digital,csm,clock manager etc.*/ /* * Clock Scheme Register definition */ #define ES8311_CLK_MANAGER_REG01 0x01 /* select clk src for mclk, enable clock for codec */ #define ES8311_CLK_MANAGER_REG02 0x02 /* clk divider and clk multiplier */ #define ES8311_CLK_MANAGER_REG03 0x03 /* adc fsmode and osr */ #define ES8311_CLK_MANAGER_REG04 0x04 /* dac osr */ #define ES8311_CLK_MANAGER_REG05 0x05 /* clk divier for adc and dac */ #define ES8311_CLK_MANAGER_REG06 0x06 /* bclk inverter and divider */ #define ES8311_CLK_MANAGER_REG07 0x07 /* tri-state, lrck divider */ #define ES8311_CLK_MANAGER_REG08 0x08 /* lrck divider */ /* * SDP */ #define ES8311_SDPIN_REG09 0x09 /* dac serial digital port */ #define ES8311_SDPOUT_REG0A 0x0A /* adc serial digital port */ /* * SYSTEM */ #define ES8311_SYSTEM_REG0B 0x0B /* system */ #define ES8311_SYSTEM_REG0C 0x0C /* system */ #define ES8311_SYSTEM_REG0D 0x0D /* system, power up/down */ #define ES8311_SYSTEM_REG0E 0x0E /* system, power up/down */ #define ES8311_SYSTEM_REG0F 0x0F /* system, low power */ #define ES8311_SYSTEM_REG10 0x10 /* system */ #define ES8311_SYSTEM_REG11 0x11 /* system */ #define ES8311_SYSTEM_REG12 0x12 /* system, Enable DAC */ #define ES8311_SYSTEM_REG13 0x13 /* system */ #define ES8311_SYSTEM_REG14 0x14 /* system, select DMIC, select analog pga gain */ /* * ADC */ #define ES8311_ADC_REG15 0x15 /* ADC, adc ramp rate, dmic sense */ #define ES8311_ADC_REG16 0x16 /* ADC */ #define ES8311_ADC_REG17 0x17 /* ADC, volume */ #define ES8311_ADC_REG18 0x18 /* ADC, alc enable and winsize */ #define ES8311_ADC_REG19 0x19 /* ADC, alc maxlevel */ #define ES8311_ADC_REG1A 0x1A /* ADC, alc automute */ #define ES8311_ADC_REG1B 0x1B /* ADC, alc automute, adc hpf s1 */ #define ES8311_ADC_REG1C 0x1C /* ADC, equalizer, hpf s2 */ /* * DAC */ #define ES8311_DAC_REG31 0x31 /* DAC, mute */ #define ES8311_DAC_REG32 0x32 /* DAC, volume */ #define ES8311_DAC_REG33 0x33 /* DAC, offset */ #define ES8311_DAC_REG34 0x34 /* DAC, drc enable, drc winsize */ #define ES8311_DAC_REG35 0x35 /* DAC, drc maxlevel, minilevel */ #define ES8311_DAC_REG37 0x37 /* DAC, ramprate */ /* *GPIO */ #define ES8311_GPIO_REG44 0x44 /* GPIO, dac2adc for test */ #define ES8311_GP_REG45 0x45 /* GP CONTROL */ /* * CHIP */ #define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */ #define ES8311_CHD2_REGFE 0xFE /* CHIP ID2 */ #define ES8311_CHVER_REGFF 0xFF /* VERSION */ #define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */ #define ES8311_MAX_REGISTER 0xFF typedef enum { ES8311_MIC_GAIN_MIN = -1, ES8311_MIC_GAIN_0DB, ES8311_MIC_GAIN_6DB, ES8311_MIC_GAIN_12DB, ES8311_MIC_GAIN_18DB, ES8311_MIC_GAIN_24DB, ES8311_MIC_GAIN_30DB, ES8311_MIC_GAIN_36DB, ES8311_MIC_GAIN_42DB, ES8311_MIC_GAIN_MAX } es8311_mic_gain_t; /* * @brief Initialize ES8311 codec chip * * @param codec_cfg configuration of ES8311 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8311_codec_init(audio_hal_codec_config_t *codec_cfg); /** * @brief Deinitialize ES8311 codec chip * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8311_codec_deinit(void); /** * @brief Control ES8311 codec chip * * @param mode codec mode * @param ctrl_state start or stop decode or encode progress * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8311_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); /** * @brief Configure ES8311 codec mode and I2S interface * * @param mode codec mode * @param iface I2S config * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8311_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /** * @brief Configure ES8311 DAC mute or not. Basically you can use this function to mute the output or unmute * * @param enable enable(1) or disable(0) * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8311_set_voice_mute(bool enable); /** * @brief Set voice volume * * @param volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8311_codec_set_voice_volume(int volume); /** * @brief Get voice volume * * @param[out] *volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8311_codec_get_voice_volume(int *volume); /** * @brief Configure ES8311 I2S format * * @param mod: set ADC or DAC or both * @param cfg: ES8388 I2S format * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8311_config_fmt(es_i2s_fmt_t fmt); /** * @brief Configure ES8311 data sample bits * * @param mode: set ADC or DAC or both * @param bit_per_sample: bit number of per sample * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8311_set_bits_per_sample(audio_hal_iface_bits_t bits); /** * @brief Start ES8311 codec chip * * @param mode: set ADC or DAC or both * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8311_start(es_module_t mode); /** * @brief Stop ES8311 codec chip * * @param mode: set ADC or DAC or both * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8311_stop(es_module_t mode); /** * @brief Get ES8311 DAC mute status * * @return * - ESP_FAIL * - ESP_OK */ esp_err_t es8311_get_voice_mute(int *mute); /** * @brief Set ES8311 mic gain * * @param gain db of mic gain * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8311_set_mic_gain(es8311_mic_gain_t gain_db); /** * @brief Print all ES8311 registers * * @return * - void */ void es8311_read_all(); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es8311/es8311.h
C
apache-2.0
7,690
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "esp_system.h" #include "esp_log.h" #include "i2c_bus.h" #include "es8374.h" #include "board_pins_config.h" #define ES8374_TAG "ES8374_DRIVER" #define ES_ASSERT(a, format, b, ...) \ if ((a) != 0) { \ ESP_LOGE(ES8374_TAG, format, ##__VA_ARGS__); \ return b;\ } #define LOG_8374(fmt, ...) ESP_LOGW(ES8374_TAG, fmt, ##__VA_ARGS__) static int codec_init_flag = 0; static i2c_bus_handle_t i2c_handle; audio_hal_func_t AUDIO_CODEC_ES8374_DEFAULT_HANDLE = { .audio_codec_initialize = es8374_codec_init, .audio_codec_deinitialize = es8374_codec_deinit, .audio_codec_ctrl = es8374_codec_ctrl_state, .audio_codec_config_iface = es8374_codec_config_i2s, .audio_codec_set_mute = es8374_set_voice_mute, .audio_codec_set_volume = es8374_codec_set_voice_volume, .audio_codec_get_volume = es8374_codec_get_voice_volume, .audio_hal_lock = NULL, .handle = NULL, }; static bool es8374_codec_initialized() { return codec_init_flag; } static esp_err_t es_write_reg(uint8_t slave_addr, uint8_t reg_add, uint8_t data) { return i2c_bus_write_bytes(i2c_handle, slave_addr, &reg_add, sizeof(reg_add), &data, sizeof(data)); } static esp_err_t es_read_reg(uint8_t slave_addr, uint8_t reg_add, uint8_t *p_data) { return i2c_bus_read_bytes(i2c_handle, slave_addr, &reg_add, sizeof(reg_add), p_data, 1); } static int i2c_init() { int res; i2c_config_t es_i2c_cfg = { .mode = I2C_MODE_MASTER, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_pullup_en = GPIO_PULLUP_ENABLE, .master.clk_speed = 100000 }; res = get_i2c_pins(I2C_NUM_0, &es_i2c_cfg); ES_ASSERT(res, "getting i2c pins error", -1); i2c_handle = i2c_bus_create(I2C_NUM_0, &es_i2c_cfg); return res; } esp_err_t es8374_write_reg(uint8_t reg_add, uint8_t data) { return es_write_reg(ES8374_ADDR, reg_add, data); } int es8374_read_reg(uint8_t reg_add, uint8_t *regv) { uint8_t regdata = 0xFF; uint8_t res = 0; if (es_read_reg(ES8374_ADDR, reg_add, &regdata) == 0) { *regv = regdata; return res; } else { LOG_8374("Read Audio Codec Register Failed!"); res = -1; return res; } } void es8374_read_all() { for (int i = 0; i < 50; i++) { uint8_t reg = 0; es8374_read_reg(i, &reg); ESP_LOGI(ES8374_TAG, "%x: %x", i, reg); } } esp_err_t es8374_set_voice_mute(bool enable) { esp_err_t res = ESP_OK; uint8_t reg = 0; res |= es8374_read_reg(0x36, &reg); if (res == 0) { reg = reg & 0xdf; res |= es8374_write_reg(0x36, reg | (((int)enable) << 5)); } return res; } esp_err_t es8374_get_voice_mute(void) { esp_err_t res = ESP_OK; uint8_t reg = 0; res |= es8374_read_reg(0x36, &reg); if (res == ESP_OK) { reg = reg & 0x40; } return res == ESP_OK ? reg : res; } esp_err_t es8374_set_bits_per_sample(es_module_t mode, es_bits_length_t bit_per_sample) { esp_err_t res = ESP_OK; uint8_t reg = 0; int bits = (int)bit_per_sample & 0x0f; if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC) { res |= es8374_read_reg(0x10, &reg); if (res == 0) { reg = reg & 0xe3; res |= es8374_write_reg(0x10, reg | (bits << 2)); } } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC) { res |= es8374_read_reg(0x11, &reg); if (res == 0) { reg = reg & 0xe3; res |= es8374_write_reg(0x11, reg | (bits << 2)); } } return res; } esp_err_t es8374_config_fmt(es_module_t mode, es_i2s_fmt_t fmt) { esp_err_t res = ESP_OK; uint8_t reg = 0; int fmt_tmp, fmt_i2s; fmt_tmp = ((fmt & 0xf0) >> 4); fmt_i2s = fmt & 0x0f; if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC) { res |= es8374_read_reg(0x10, &reg); if (res == 0) { reg = reg & 0xfc; res |= es8374_write_reg(0x10, reg | fmt_i2s); res |= es8374_set_bits_per_sample(mode, fmt_tmp); } } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC) { res |= es8374_read_reg(0x11, &reg); if (res == 0) { reg = reg & 0xfc; res |= es8374_write_reg(0x11, reg | (fmt_i2s)); res |= es8374_set_bits_per_sample(mode, fmt_tmp); } } return res; } esp_err_t es8374_start(es_module_t mode) { esp_err_t res = ESP_OK; uint8_t reg = 0; if (mode == ES_MODULE_LINE) { res |= es8374_read_reg(0x1a, &reg); //set monomixer reg |= 0x60; reg |= 0x20; reg &= 0xf7; res |= es8374_write_reg( 0x1a, reg); res |= es8374_read_reg(0x1c, &reg); // set spk mixer reg |= 0x40; res |= es8374_write_reg( 0x1c, reg); res |= es8374_write_reg(0x1D, 0x02); // spk set res |= es8374_write_reg(0x1F, 0x00); // spk set res |= es8374_write_reg(0x1E, 0xA0); // spk on } if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC || mode == ES_MODULE_LINE) { res |= es8374_read_reg(0x21, &reg); //power up adc and input reg &= 0x3f; res |= es8374_write_reg(0x21, reg); res |= es8374_read_reg(0x10, &reg); //power up adc and input reg &= 0x3f; res |= es8374_write_reg(0x10, reg); } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC || mode == ES_MODULE_LINE) { res |= es8374_read_reg(0x1a, &reg); //disable lout reg |= 0x08; res |= es8374_write_reg( 0x1a, reg); reg &= 0xdf; res |= es8374_write_reg( 0x1a, reg); res |= es8374_write_reg(0x1D, 0x12); // mute speaker res |= es8374_write_reg(0x1E, 0x20); // disable class d res |= es8374_read_reg(0x15, &reg); //power up dac reg &= 0xdf; res |= es8374_write_reg(0x15, reg); res |= es8374_read_reg(0x1a, &reg); //disable lout reg |= 0x20; res |= es8374_write_reg( 0x1a, reg); reg &= 0xf7; res |= es8374_write_reg( 0x1a, reg); res |= es8374_write_reg(0x1D, 0x02); // mute speaker res |= es8374_write_reg(0x1E, 0xa0); // disable class d res |= es8374_set_voice_mute(false); } return res; } esp_err_t es8374_stop(es_module_t mode) { esp_err_t res = ESP_OK; uint8_t reg = 0; if (mode == ES_MODULE_LINE) { res |= es8374_read_reg(0x1a, &reg); //disable lout reg |= 0x08; res |= es8374_write_reg( 0x1a, reg); reg &= 0x9f; res |= es8374_write_reg( 0x1a, reg); res |= es8374_write_reg(0x1D, 0x12); // mute speaker res |= es8374_write_reg(0x1E, 0x20); // disable class d res |= es8374_read_reg(0x1c, &reg); // disable spkmixer reg &= 0xbf; res |= es8374_write_reg( 0x1c, reg); res |= es8374_write_reg(0x1F, 0x00); // spk set } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC) { res |= es8374_set_voice_mute(true); res |= es8374_read_reg(0x1a, &reg); //disable lout reg |= 0x08; res |= es8374_write_reg( 0x1a, reg); reg &= 0xdf; res |= es8374_write_reg( 0x1a, reg); res |= es8374_write_reg(0x1D, 0x12); // mute speaker res |= es8374_write_reg(0x1E, 0x20); // disable class d res |= es8374_read_reg(0x15, &reg); //power up dac reg |= 0x20; res |= es8374_write_reg(0x15, reg); } if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC) { res |= es8374_read_reg(0x10, &reg); //power up adc and input reg |= 0xc0; res |= es8374_write_reg(0x10, reg); res |= es8374_read_reg(0x21, &reg); //power up adc and input reg |= 0xc0; res |= es8374_write_reg(0x21, reg); } return res; } esp_err_t es8374_i2s_config_clock(es_i2s_clock_t cfg) { esp_err_t res = ESP_OK; uint8_t reg = 0; res |= es8374_read_reg(0x0f, &reg); //power up adc and input reg &= 0xe0; int divratio = 0; switch (cfg.sclk_div) { case MCLK_DIV_1: divratio = 1; break; case MCLK_DIV_2: // = 2, divratio = 2; break; case MCLK_DIV_3: // = 3, divratio = 3; break; case MCLK_DIV_4: // = 4, divratio = 4; break; case MCLK_DIV_5: // = 20, divratio = 5; break; case MCLK_DIV_6: // = 5, divratio = 6; break; case MCLK_DIV_7: // = 29, divratio = 7; break; case MCLK_DIV_8: // = 6, divratio = 8; break; case MCLK_DIV_9: // = 7, divratio = 9; break; case MCLK_DIV_10: // = 21, divratio = 10; break; case MCLK_DIV_11: // = 8, divratio = 11; break; case MCLK_DIV_12: // = 9, divratio = 12; break; case MCLK_DIV_13: // = 30, divratio = 13; break; case MCLK_DIV_14: // = 31 divratio = 14; break; case MCLK_DIV_15: // = 22, divratio = 15; break; case MCLK_DIV_16: // = 10, divratio = 16; break; case MCLK_DIV_17: // = 23, divratio = 17; break; case MCLK_DIV_18: // = 11, divratio = 18; break; case MCLK_DIV_20: // = 24, divratio = 19; break; case MCLK_DIV_22: // = 12, divratio = 20; break; case MCLK_DIV_24: // = 13, divratio = 21; break; case MCLK_DIV_25: // = 25, divratio = 22; break; case MCLK_DIV_30: // = 26, divratio = 23; break; case MCLK_DIV_32: // = 27, divratio = 24; break; case MCLK_DIV_33: // = 14, divratio = 25; break; case MCLK_DIV_34: // = 28, divratio = 26; break; case MCLK_DIV_36: // = 15, divratio = 27; break; case MCLK_DIV_44: // = 16, divratio = 28; break; case MCLK_DIV_48: // = 17, divratio = 29; break; case MCLK_DIV_66: // = 18, divratio = 30; break; case MCLK_DIV_72: // = 19, divratio = 31; break; default: break; } reg |= divratio; res |= es8374_write_reg(0x0f, reg); int dacratio_l = 0; int dacratio_h = 0; switch (cfg.lclk_div) { case LCLK_DIV_128: dacratio_l = 128 % 256; dacratio_h = 128 / 256; break; case LCLK_DIV_192: dacratio_l = 192 % 256; dacratio_h = 192 / 256; break; case LCLK_DIV_256: dacratio_l = 256 % 256; dacratio_h = 256 / 256; break; case LCLK_DIV_384: dacratio_l = 384 % 256; dacratio_h = 384 / 256; break; case LCLK_DIV_512: dacratio_l = 512 % 256; dacratio_h = 512 / 256; break; case LCLK_DIV_576: dacratio_l = 576 % 256; dacratio_h = 576 / 256; break; case LCLK_DIV_768: dacratio_l = 768 % 256; dacratio_h = 768 / 256; break; case LCLK_DIV_1024: dacratio_l = 1024 % 256; dacratio_h = 1024 / 256; break; case LCLK_DIV_1152: dacratio_l = 1152 % 256; dacratio_h = 1152 / 256; break; case LCLK_DIV_1408: dacratio_l = 1408 % 256; dacratio_h = 1408 / 256; break; case LCLK_DIV_1536: dacratio_l = 1536 % 256; dacratio_h = 1536 / 256; break; case LCLK_DIV_2112: dacratio_l = 2112 % 256; dacratio_h = 2112 / 256; break; case LCLK_DIV_2304: dacratio_l = 2304 % 256; dacratio_h = 2304 / 256; break; case LCLK_DIV_125: dacratio_l = 125 % 256; dacratio_h = 125 / 256; break; case LCLK_DIV_136: dacratio_l = 136 % 256; dacratio_h = 136 / 256; break; case LCLK_DIV_250: dacratio_l = 250 % 256; dacratio_h = 250 / 256; break; case LCLK_DIV_272: dacratio_l = 272 % 256; dacratio_h = 272 / 256; break; case LCLK_DIV_375: dacratio_l = 375 % 256; dacratio_h = 375 / 256; break; case LCLK_DIV_500: dacratio_l = 500 % 256; dacratio_h = 500 / 256; break; case LCLK_DIV_544: dacratio_l = 544 % 256; dacratio_h = 544 / 256; break; case LCLK_DIV_750: dacratio_l = 750 % 256; dacratio_h = 750 / 256; break; case LCLK_DIV_1000: dacratio_l = 1000 % 256; dacratio_h = 1000 / 256; break; case LCLK_DIV_1088: dacratio_l = 1088 % 256; dacratio_h = 1088 / 256; break; case LCLK_DIV_1496: dacratio_l = 1496 % 256; dacratio_h = 1496 / 256; break; case LCLK_DIV_1500: dacratio_l = 1500 % 256; dacratio_h = 1500 / 256; break; default: break; } res |= es8374_write_reg( 0x06, dacratio_h); //ADCFsMode,singel SPEED,RATIO=256 res |= es8374_write_reg( 0x07, dacratio_l); //ADCFsMode,singel SPEED,RATIO=256 return res; } esp_err_t es8374_config_dac_output(es_dac_output_t output) { esp_err_t res = ESP_OK; uint8_t reg = 0; reg = 0x1d; res = es8374_write_reg(reg, 0x02); res |= es8374_read_reg(0x1c, &reg); // set spk mixer reg |= 0x80; res |= es8374_write_reg(0x1c, reg); res |= es8374_write_reg(0x1D, 0x02); // spk set res |= es8374_write_reg(0x1F, 0x00); // spk set res |= es8374_write_reg(0x1E, 0xA0); // spk on return res; } esp_err_t es8374_config_adc_input(es_adc_input_t input) { esp_err_t res = ESP_OK; uint8_t reg = 0; res |= es8374_read_reg(0x21, &reg); if (res == 0) { reg = (reg & 0xcf) | 0x14; res |= es8374_write_reg( 0x21, reg); } return res; } esp_err_t es8374_set_mic_gain(es_mic_gain_t gain) { esp_err_t res = ESP_OK; if (gain > MIC_GAIN_MIN && gain < MIC_GAIN_24DB) { int gain_n = 0; gain_n = (int)gain / 3; res = es8374_write_reg(0x22, gain_n | (gain_n << 4)); //MIC PGA } else { res = -1; LOG_8374("invalid microphone gain!"); } return res; } esp_err_t es8374_codec_set_voice_volume(int volume) { esp_err_t res = ESP_OK; if (volume < 0) { volume = 192; } else if (volume > 96) { volume = 0; } else { volume = 192 - volume * 2; } res = es8374_write_reg(0x38, volume); return res; } esp_err_t es8374_codec_get_voice_volume(int *volume) { esp_err_t res = 0; uint8_t reg = 0; res = es8374_read_reg(0x38, &reg); if (res == ESP_FAIL) { *volume = 0; } else { *volume = (192 - reg) / 2; if (*volume > 96) { *volume = 100; } } return res; } static int es8374_set_adc_dac_volume(int mode, int volume, int dot) { int res = 0; if ( volume < -96 || volume > 0 ) { LOG_8374("Warning: volume < -96! or > 0!"); if (volume < -96) { volume = -96; } else { volume = 0; } } dot = (dot >= 5 ? 1 : 0); volume = (-volume << 1) + dot; if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC) { res |= es8374_write_reg(0x25, volume); } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC) { res |= es8374_write_reg(0x38, volume); } return res; } static int es8374_set_d2se_pga(es_d2se_pga_t gain) { int res = 0; uint8_t reg = 0; if (gain > D2SE_PGA_GAIN_MIN && gain < D2SE_PGA_GAIN_MAX) { res = es8374_read_reg(0x21, &reg); reg &= 0xfb; reg |= gain << 2; res = es8374_write_reg(0x21, reg); //MIC PGA } else { res = 0xff; LOG_8374("invalid microphone gain!"); } return res; } static int es8374_init_reg(audio_hal_codec_mode_t ms_mode, es_i2s_fmt_t fmt, es_i2s_clock_t cfg, es_dac_output_t out_channel, es_adc_input_t in_channel) { int res = 0; uint8_t reg; res |= es8374_write_reg(0x00, 0x3F); //IC Rst start res |= es8374_write_reg(0x00, 0x03); //IC Rst stop res |= es8374_write_reg(0x01, 0x7F); //IC clk on res |= es8374_read_reg(0x0F, &reg); reg &= 0x7f; reg |= (ms_mode << 7); res |= es8374_write_reg( 0x0f, reg); //CODEC IN I2S SLAVE MODE res |= es8374_write_reg(0x6F, 0xA0); //pll set:mode enable res |= es8374_write_reg(0x72, 0x41); //pll set:mode set res |= es8374_write_reg(0x09, 0x01); //pll set:reset on ,set start res |= es8374_write_reg(0x0C, 0x22); //pll set:k res |= es8374_write_reg(0x0D, 0x2E); //pll set:k res |= es8374_write_reg(0x0E, 0xC6); //pll set:k res |= es8374_write_reg(0x0A, 0x3A); //pll set: res |= es8374_write_reg(0x0B, 0x07); //pll set:n res |= es8374_write_reg(0x09, 0x41); //pll set:reset off ,set stop res |= es8374_i2s_config_clock(cfg); res |= es8374_write_reg(0x24, 0x08); //adc set res |= es8374_write_reg(0x36, 0x00); //dac set res |= es8374_write_reg(0x12, 0x30); //timming set res |= es8374_write_reg(0x13, 0x20); //timming set res |= es8374_config_fmt(ES_MODULE_ADC, fmt); res |= es8374_config_fmt(ES_MODULE_DAC, fmt); res |= es8374_write_reg(0x21, 0x50); //adc set: SEL LIN1 CH+PGAGAIN=0DB res |= es8374_write_reg(0x22, 0xFF); //adc set: PGA GAIN=0DB res |= es8374_write_reg(0x21, 0x14); //adc set: SEL LIN1 CH+PGAGAIN=18DB res |= es8374_write_reg(0x22, 0x55); //pga = +15db res |= es8374_write_reg(0x08, 0x21); //set class d divider = 33, to avoid the high frequency tone on laudspeaker res |= es8374_write_reg(0x00, 0x80); // IC START res |= es8374_set_adc_dac_volume(ES_MODULE_ADC, 0, 0); // 0db res |= es8374_set_adc_dac_volume(ES_MODULE_DAC, 0, 0); // 0db res |= es8374_write_reg(0x14, 0x8A); // IC START res |= es8374_write_reg(0x15, 0x40); // IC START res |= es8374_write_reg(0x1A, 0xA0); // monoout set res |= es8374_write_reg(0x1B, 0x19); // monoout set res |= es8374_write_reg(0x1C, 0x90); // spk set res |= es8374_write_reg(0x1D, 0x01); // spk set res |= es8374_write_reg(0x1F, 0x00); // spk set res |= es8374_write_reg(0x1E, 0x20); // spk on res |= es8374_write_reg(0x28, 0x00); // alc set res |= es8374_write_reg(0x25, 0x00); // ADCVOLUME on res |= es8374_write_reg(0x38, 0x00); // DACVOLUME on res |= es8374_write_reg(0x37, 0x30); // dac set res |= es8374_write_reg(0x6D, 0x60); //SEL:GPIO1=DMIC CLK OUT+SEL:GPIO2=PLL CLK OUT res |= es8374_write_reg(0x71, 0x05); //for automute setting res |= es8374_write_reg(0x73, 0x70); res |= es8374_config_dac_output(out_channel); //0x3c Enable DAC and Enable Lout/Rout/1/2 res |= es8374_config_adc_input(in_channel); //0x00 LINSEL & RINSEL, LIN1/RIN1 as ADC Input; DSSEL,use one DS Reg11; DSR, LINPUT1-RINPUT1 res |= es8374_codec_set_voice_volume(0); res |= es8374_write_reg(0x37, 0x00); // dac set return res; } esp_err_t es8374_codec_init(audio_hal_codec_config_t *cfg) { if (es8374_codec_initialized()) { ESP_LOGW(ES8374_TAG, "The es8374 codec has already been initialized!"); return ESP_FAIL; } esp_err_t res = ESP_OK; es_i2s_clock_t clkdiv; clkdiv.lclk_div = LCLK_DIV_256; clkdiv.sclk_div = MCLK_DIV_4; i2c_init(); // ESP32 in master mode res |= es8374_stop(cfg->codec_mode); res |= es8374_init_reg(cfg->i2s_iface.mode, (BIT_LENGTH_16BITS << 4) | cfg->i2s_iface.fmt, clkdiv, cfg->dac_output, cfg->adc_input); res |= es8374_set_mic_gain(MIC_GAIN_15DB); res |= es8374_set_d2se_pga(D2SE_PGA_GAIN_EN); res |= es8374_config_fmt(cfg->codec_mode, cfg->i2s_iface.fmt); res |= es8374_codec_config_i2s(cfg->codec_mode, &(cfg->i2s_iface)); codec_init_flag = 1; return res; } esp_err_t es8374_codec_deinit(void) { codec_init_flag = 0; i2c_bus_delete(i2c_handle); return es8374_write_reg(0x00, 0x7F); // IC Reset and STOP } esp_err_t es8374_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { esp_err_t res = ESP_OK; int tmp = 0; res |= es8374_config_fmt(ES_MODULE_ADC_DAC, iface->fmt); if (iface->bits == AUDIO_HAL_BIT_LENGTH_16BITS) { tmp = BIT_LENGTH_16BITS; } else if (iface->bits == AUDIO_HAL_BIT_LENGTH_24BITS) { tmp = BIT_LENGTH_24BITS; } else { tmp = BIT_LENGTH_32BITS; } res |= es8374_set_bits_per_sample(ES_MODULE_ADC_DAC, tmp); return res; } esp_err_t es8374_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { esp_err_t res = ESP_OK; int es_mode_t = 0; switch (mode) { case AUDIO_HAL_CODEC_MODE_ENCODE: es_mode_t = ES_MODULE_ADC; break; case AUDIO_HAL_CODEC_MODE_LINE_IN: es_mode_t = ES_MODULE_LINE; break; case AUDIO_HAL_CODEC_MODE_DECODE: es_mode_t = ES_MODULE_DAC; break; case AUDIO_HAL_CODEC_MODE_BOTH: es_mode_t = ES_MODULE_ADC_DAC; break; default: es_mode_t = ES_MODULE_DAC; ESP_LOGW(ES8374_TAG, "Codec mode not support, default is decode mode"); break; } if (AUDIO_HAL_CTRL_STOP == ctrl_state) { res = es8374_stop(es_mode_t); } else { res = es8374_start(es_mode_t); ESP_LOGD(ES8374_TAG, "start default is decode mode:%d", es_mode_t); } return res; } void es8374_pa_power(bool enable) { gpio_config_t io_conf; memset(&io_conf, 0, sizeof(io_conf)); io_conf.mode = GPIO_MODE_OUTPUT; io_conf.pin_bit_mask = BIT64(get_pa_enable_gpio()); io_conf.pull_down_en = 0; io_conf.pull_up_en = 0; gpio_config(&io_conf); if (enable) { gpio_set_level(get_pa_enable_gpio(), 1); } else { gpio_set_level(get_pa_enable_gpio(), 0); } }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es8374/es8374.c
C
apache-2.0
24,162
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __ES8374_H__ #define __ES8374_H__ #include "esp_types.h" #include "audio_hal.h" #include "esxxx_common.h" #ifdef __cplusplus extern "C" { #endif /* ES8374 address */ #define ES8374_ADDR 0x20 // 0x22:CE=1;0x20:CE=0 /** * @brief Initialize ES8374 codec chip * * @param cfg configuration of ES8374 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8374_codec_init(audio_hal_codec_config_t *cfg); /** * @brief Deinitialize ES8374 codec chip * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8374_codec_deinit(void); /** * @brief Configure ES8374 I2S format * * @param mode: set ADC or DAC or both * @param fmt: ES8374 I2S format * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8374_config_fmt(es_module_t mode, es_i2s_fmt_t fmt); /** * @brief Configure I2S clock in MSATER mode * * @param cfg: set bits clock and WS clock * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8374_i2s_config_clock(es_i2s_clock_t cfg); /** * @brief Configure ES8374 data sample bits * * @param mode: set ADC or DAC or both * @param bit_per_sample: bit number of per sample * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8374_set_bits_per_sample(es_module_t mode, es_bits_length_t bit_per_sample); /** * @brief Start ES8374 codec chip * * @param mode: set ADC or DAC or both * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8374_start(es_module_t mode); /** * @brief Stop ES8374 codec chip * * @param mode: set ADC or DAC or both * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8374_stop(es_module_t mode); /** * @brief Set voice volume * * @param volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8374_codec_set_voice_volume(int volume); /** * @brief Get voice volume * * @param[out] *volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8374_codec_get_voice_volume(int *volume); /** * @brief Mute or unmute ES8374 DAC. Basically you can use this function to mute or unmute the output * * @param enable mute(1) or unmute(0) * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8374_set_voice_mute(bool enable); /** * @brief Get ES8374 DAC mute status * * @return * - ESP_FAIL * - ESP_OK */ esp_err_t es8374_get_voice_mute(void); /** * @brief Set ES8374 mic gain * * @param gain db of mic gain * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8374_set_mic_gain(es_mic_gain_t gain); /** * @brief Set ES8374 ADC input mode * * @param input adc input mode * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8374_config_adc_input(es_adc_input_t input); /** * @brief Set ES8374 DAC output mode * * @param output dac output mode * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8374_config_dac_output(es_dac_output_t output); /** * @brief Write ES8374 register * * @param reg_add address of register * @param data data of register * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8374_write_reg(uint8_t reg_add, uint8_t data); /** * @brief Print all ES8374 registers * * @return * - void */ void es8374_read_all(); /** * @brief Configure ES8374 codec mode and I2S interface * * @param mode codec mode * @param iface I2S config * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8374_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /** * @brief Control ES8374 codec chip * * @param mode codec mode * @param ctrl_state start or stop decode or encode progress * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8374_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); /** * @brief Set ES8374 PA power * * @param enable true for enable PA power, false for disable PA power * * @return * - void */ void es8374_pa_power(bool enable); #ifdef __cplusplus } #endif #endif //__ES8374_H__
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es8374/es8374.h
C
apache-2.0
5,687
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "esp_log.h" #include "i2c_bus.h" #include "es8388.h" #include "board_pins_config.h" #ifdef CONFIG_ESP_LYRAT_V4_3_BOARD #include "headphone_detect.h" #endif static const char *ES_TAG = "ES8388_DRIVER"; static i2c_bus_handle_t i2c_handle; #define ES_ASSERT(a, format, b, ...) \ if ((a) != 0) { \ ESP_LOGE(ES_TAG, format, ##__VA_ARGS__); \ return b;\ } audio_hal_func_t AUDIO_CODEC_ES8388_DEFAULT_HANDLE = { .audio_codec_initialize = es8388_init, .audio_codec_deinitialize = es8388_deinit, .audio_codec_ctrl = es8388_ctrl_state, .audio_codec_config_iface = es8388_config_i2s, .audio_codec_set_mute = es8388_set_voice_mute, .audio_codec_set_volume = es8388_set_voice_volume, .audio_codec_get_volume = es8388_get_voice_volume, .audio_hal_lock = NULL, .handle = NULL, }; static esp_err_t es_write_reg(uint8_t slave_addr, uint8_t reg_add, uint8_t data) { return i2c_bus_write_bytes(i2c_handle, slave_addr, &reg_add, sizeof(reg_add), &data, sizeof(data)); } static esp_err_t es_read_reg(uint8_t reg_add, uint8_t *p_data) { return i2c_bus_read_bytes(i2c_handle, ES8388_ADDR, &reg_add, sizeof(reg_add), p_data, 1); } static int i2c_init() { int res; i2c_config_t es_i2c_cfg = { .mode = I2C_MODE_MASTER, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_pullup_en = GPIO_PULLUP_ENABLE, .master.clk_speed = 100000 }; res = get_i2c_pins(I2C_NUM_0, &es_i2c_cfg); ES_ASSERT(res, "getting i2c pins error", -1); i2c_handle = i2c_bus_create(I2C_NUM_0, &es_i2c_cfg); return res; } void es8388_read_all() { for (int i = 0; i < 50; i++) { uint8_t reg = 0; es_read_reg(i, &reg); ets_printf("%x: %x\n", i, reg); } } esp_err_t es8388_write_reg(uint8_t reg_add, uint8_t data) { return es_write_reg(ES8388_ADDR, reg_add, data); } /** * @brief Configure ES8388 ADC and DAC volume. Basicly you can consider this as ADC and DAC gain * * @param mode: set ADC or DAC or all * @param volume: -96 ~ 0 for example Es8388SetAdcDacVolume(ES_MODULE_ADC, 30, 6); means set ADC volume -30.5db * @param dot: whether include 0.5. for example Es8388SetAdcDacVolume(ES_MODULE_ADC, 30, 4); means set ADC volume -30db * * @return * - (-1) Parameter error * - (0) Success */ static int es8388_set_adc_dac_volume(int mode, int volume, int dot) { int res = 0; if ( volume < -96 || volume > 0 ) { ESP_LOGW(ES_TAG, "Warning: volume < -96! or > 0!\n"); if (volume < -96) volume = -96; else volume = 0; } dot = (dot >= 5 ? 1 : 0); volume = (-volume << 1) + dot; if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC) { res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL8, volume); res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL9, volume); //ADC Right Volume=0db } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC) { res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL5, volume); res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL4, volume); } return res; } /** * @brief Power Management * * @param mod: if ES_POWER_CHIP, the whole chip including ADC and DAC is enabled * @param enable: false to disable true to enable * * @return * - (-1) Error * - (0) Success */ esp_err_t es8388_start(es_module_t mode) { esp_err_t res = ESP_OK; uint8_t prev_data = 0, data = 0; es_read_reg(ES8388_DACCONTROL21, &prev_data); if (mode == ES_MODULE_LINE) { res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL16, 0x09); // 0x00 audio on LIN1&RIN1, 0x09 LIN2&RIN2 by pass enable res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL17, 0x50); // left DAC to left mixer enable and LIN signal to left mixer enable 0db : bupass enable res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL20, 0x50); // right DAC to right mixer enable and LIN signal to right mixer enable 0db : bupass enable res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL21, 0xC0); //enable adc } else { res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL21, 0x80); //enable dac } es_read_reg(ES8388_DACCONTROL21, &data); if (prev_data != data) { res |= es_write_reg(ES8388_ADDR, ES8388_CHIPPOWER, 0xF0); //start state machine // res |= es_write_reg(ES8388_ADDR, ES8388_CONTROL1, 0x16); // res |= es_write_reg(ES8388_ADDR, ES8388_CONTROL2, 0x50); res |= es_write_reg(ES8388_ADDR, ES8388_CHIPPOWER, 0x00); //start state machine } if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC || mode == ES_MODULE_LINE) { res |= es_write_reg(ES8388_ADDR, ES8388_ADCPOWER, 0x00); //power up adc and line in } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC || mode == ES_MODULE_LINE) { res |= es_write_reg(ES8388_ADDR, ES8388_DACPOWER, 0x3c); //power up dac and line out res |= es8388_set_voice_mute(false); ESP_LOGD(ES_TAG, "es8388_start default is mode:%d", mode); } return res; } /** * @brief Power Management * * @param mod: if ES_POWER_CHIP, the whole chip including ADC and DAC is enabled * @param enable: false to disable true to enable * * @return * - (-1) Error * - (0) Success */ esp_err_t es8388_stop(es_module_t mode) { esp_err_t res = ESP_OK; if (mode == ES_MODULE_LINE) { res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL21, 0x80); //enable dac res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL16, 0x00); // 0x00 audio on LIN1&RIN1, 0x09 LIN2&RIN2 res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL17, 0x90); // only left DAC to left mixer enable 0db res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL20, 0x90); // only right DAC to right mixer enable 0db return res; } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC) { res |= es_write_reg(ES8388_ADDR, ES8388_DACPOWER, 0x00); res |= es8388_set_voice_mute(true); //res |= Es8388SetAdcDacVolume(ES_MODULE_DAC, -96, 5); // 0db //res |= es_write_reg(ES8388_ADDR, ES8388_DACPOWER, 0xC0); //power down dac and line out } if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC) { //res |= Es8388SetAdcDacVolume(ES_MODULE_ADC, -96, 5); // 0db res |= es_write_reg(ES8388_ADDR, ES8388_ADCPOWER, 0xFF); //power down adc and line in } if (mode == ES_MODULE_ADC_DAC) { res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL21, 0x9C); //disable mclk // res |= es_write_reg(ES8388_ADDR, ES8388_CONTROL1, 0x00); // res |= es_write_reg(ES8388_ADDR, ES8388_CONTROL2, 0x58); // res |= es_write_reg(ES8388_ADDR, ES8388_CHIPPOWER, 0xF3); //stop state machine } return res; } /** * @brief Config I2s clock in MSATER mode * * @param cfg.sclkDiv: generate SCLK by dividing MCLK in MSATER mode * @param cfg.lclkDiv: generate LCLK by dividing MCLK in MSATER mode * * @return * - (-1) Error * - (0) Success */ esp_err_t es8388_i2s_config_clock(es_i2s_clock_t cfg) { esp_err_t res = ESP_OK; res |= es_write_reg(ES8388_ADDR, ES8388_MASTERMODE, cfg.sclk_div); res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL5, cfg.lclk_div); //ADCFsMode,singel SPEED,RATIO=256 res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL2, cfg.lclk_div); //ADCFsMode,singel SPEED,RATIO=256 return res; } esp_err_t es8388_deinit(void) { int res = 0; res = es_write_reg(ES8388_ADDR, ES8388_CHIPPOWER, 0xFF); //reset and stop es8388 i2c_bus_delete(i2c_handle); #ifdef CONFIG_ESP_LYRAT_V4_3_BOARD headphone_detect_deinit(); #endif return res; } /** * @return * - (-1) Error * - (0) Success */ esp_err_t es8388_init(audio_hal_codec_config_t *cfg) { int res = 0; #ifdef CONFIG_ESP_LYRAT_V4_3_BOARD headphone_detect_init(get_headphone_detect_gpio()); #endif res = i2c_init(); // ESP32 in master mode res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL3, 0x04); // 0x04 mute/0x00 unmute&ramp;DAC unmute and disabled digital volume control soft ramp /* Chip Control and Power Management */ res |= es_write_reg(ES8388_ADDR, ES8388_CONTROL2, 0x50); res |= es_write_reg(ES8388_ADDR, ES8388_CHIPPOWER, 0x00); //normal all and power up all // Disable the internal DLL to improve 8K sample rate res |= es_write_reg(ES8388_ADDR, 0x35, 0xA0); res |= es_write_reg(ES8388_ADDR, 0x37, 0xD0); res |= es_write_reg(ES8388_ADDR, 0x39, 0xD0); res |= es_write_reg(ES8388_ADDR, ES8388_MASTERMODE, cfg->i2s_iface.mode); //CODEC IN I2S SLAVE MODE /* dac */ res |= es_write_reg(ES8388_ADDR, ES8388_DACPOWER, 0xC0); //disable DAC and disable Lout/Rout/1/2 res |= es_write_reg(ES8388_ADDR, ES8388_CONTROL1, 0x12); //Enfr=0,Play&Record Mode,(0x17-both of mic&paly) // res |= es_write_reg(ES8388_ADDR, ES8388_CONTROL2, 0); //LPVrefBuf=0,Pdn_ana=0 res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL1, 0x18);//1a 0x18:16bit iis , 0x00:24 res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL2, 0x02); //DACFsMode,SINGLE SPEED; DACFsRatio,256 res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL16, 0x00); // 0x00 audio on LIN1&RIN1, 0x09 LIN2&RIN2 res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL17, 0x90); // only left DAC to left mixer enable 0db res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL20, 0x90); // only right DAC to right mixer enable 0db res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL21, 0x80); //set internal ADC and DAC use the same LRCK clock, ADC LRCK as internal LRCK res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL23, 0x00); //vroi=0 res |= es8388_set_adc_dac_volume(ES_MODULE_DAC, 0, 0); // 0db int tmp = 0; if (AUDIO_HAL_DAC_OUTPUT_LINE2 == cfg->dac_output) { tmp = DAC_OUTPUT_LOUT1 | DAC_OUTPUT_ROUT1; } else if (AUDIO_HAL_DAC_OUTPUT_LINE1 == cfg->dac_output) { tmp = DAC_OUTPUT_LOUT2 | DAC_OUTPUT_ROUT2; } else { tmp = DAC_OUTPUT_LOUT1 | DAC_OUTPUT_LOUT2 | DAC_OUTPUT_ROUT1 | DAC_OUTPUT_ROUT2; } res |= es_write_reg(ES8388_ADDR, ES8388_DACPOWER, tmp); //0x3c Enable DAC and Enable Lout/Rout/1/2 /* adc */ res |= es_write_reg(ES8388_ADDR, ES8388_ADCPOWER, 0xFF); res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL1, 0xbb); // MIC Left and Right channel PGA gain tmp = 0; if (AUDIO_HAL_ADC_INPUT_LINE1 == cfg->adc_input) { tmp = ADC_INPUT_LINPUT1_RINPUT1; } else if (AUDIO_HAL_ADC_INPUT_LINE2 == cfg->adc_input) { tmp = ADC_INPUT_LINPUT2_RINPUT2; } else { tmp = ADC_INPUT_DIFFERENCE; } res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL2, tmp); //0x00 LINSEL & RINSEL, LIN1/RIN1 as ADC Input; DSSEL,use one DS Reg11; DSR, LINPUT1-RINPUT1 res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL3, 0x02); res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL4, 0x0d); // Left/Right data, Left/Right justified mode, Bits length, I2S format res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL5, 0x02); //ADCFsMode,singel SPEED,RATIO=256 //ALC for Microphone res |= es8388_set_adc_dac_volume(ES_MODULE_ADC, 0, 0); // 0db res |= es_write_reg(ES8388_ADDR, ES8388_ADCPOWER, 0x09); //Power on ADC, Enable LIN&RIN, Power off MICBIAS, set int1lp to low power mode /* enable es8388 PA */ es8388_pa_power(true); ESP_LOGI(ES_TAG, "init,out:%02x, in:%02x", cfg->dac_output, cfg->adc_input); return res; } /** * @brief Configure ES8388 I2S format * * @param mode: set ADC or DAC or all * @param bitPerSample: see Es8388I2sFmt * * @return * - (-1) Error * - (0) Success */ esp_err_t es8388_config_fmt(es_module_t mode, es_i2s_fmt_t fmt) { esp_err_t res = ESP_OK; uint8_t reg = 0; if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC) { res = es_read_reg(ES8388_ADCCONTROL4, &reg); reg = reg & 0xfc; res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL4, reg | fmt); } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC) { res = es_read_reg(ES8388_DACCONTROL1, &reg); reg = reg & 0xf9; res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL1, reg | (fmt << 1)); } return res; } /** * @param volume: 0 ~ 100 * * @return * - (-1) Error * - (0) Success */ esp_err_t es8388_set_voice_volume(int volume) { esp_err_t res = ESP_OK; if (volume < 0) volume = 0; else if (volume > 100) volume = 100; volume /= 3; res = es_write_reg(ES8388_ADDR, ES8388_DACCONTROL24, volume); res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL25, volume); res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL26, 0); res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL27, 0); return res; } /** * * @return * volume */ esp_err_t es8388_get_voice_volume(int *volume) { esp_err_t res = ESP_OK; uint8_t reg = 0; res = es_read_reg(ES8388_DACCONTROL24, &reg); if (res == ESP_FAIL) { *volume = 0; } else { *volume = reg; *volume *= 3; if (*volume == 99) *volume = 100; } return res; } /** * @brief Configure ES8388 data sample bits * * @param mode: set ADC or DAC or all * @param bitPerSample: see BitsLength * * @return * - (-1) Parameter error * - (0) Success */ esp_err_t es8388_set_bits_per_sample(es_module_t mode, es_bits_length_t bits_length) { esp_err_t res = ESP_OK; uint8_t reg = 0; int bits = (int)bits_length; if (mode == ES_MODULE_ADC || mode == ES_MODULE_ADC_DAC) { res = es_read_reg(ES8388_ADCCONTROL4, &reg); reg = reg & 0xe3; res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL4, reg | (bits << 2)); } if (mode == ES_MODULE_DAC || mode == ES_MODULE_ADC_DAC) { res = es_read_reg(ES8388_DACCONTROL1, &reg); reg = reg & 0xc7; res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL1, reg | (bits << 3)); } return res; } /** * @brief Configure ES8388 DAC mute or not. Basically you can use this function to mute the output or unmute * * @param enable: enable or disable * * @return * - (-1) Parameter error * - (0) Success */ esp_err_t es8388_set_voice_mute(bool enable) { esp_err_t res = ESP_OK; uint8_t reg = 0; res = es_read_reg(ES8388_DACCONTROL3, &reg); reg = reg & 0xFB; res |= es_write_reg(ES8388_ADDR, ES8388_DACCONTROL3, reg | (((int)enable) << 2)); return res; } esp_err_t es8388_get_voice_mute(void) { esp_err_t res = ESP_OK; uint8_t reg = 0; res = es_read_reg(ES8388_DACCONTROL3, &reg); if (res == ESP_OK) { reg = (reg & 0x04) >> 2; } return res == ESP_OK ? reg : res; } /** * @param gain: Config DAC Output * * @return * - (-1) Parameter error * - (0) Success */ esp_err_t es8388_config_dac_output(int output) { esp_err_t res; uint8_t reg = 0; res = es_read_reg(ES8388_DACPOWER, &reg); reg = reg & 0xc3; res |= es_write_reg(ES8388_ADDR, ES8388_DACPOWER, reg | output); return res; } /** * @param gain: Config ADC input * * @return * - (-1) Parameter error * - (0) Success */ esp_err_t es8388_config_adc_input(es_adc_input_t input) { esp_err_t res; uint8_t reg = 0; res = es_read_reg(ES8388_ADCCONTROL2, &reg); reg = reg & 0x0f; res |= es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL2, reg | input); return res; } /** * @param gain: see es_mic_gain_t * * @return * - (-1) Parameter error * - (0) Success */ esp_err_t es8388_set_mic_gain(es_mic_gain_t gain) { esp_err_t res, gain_n; gain_n = (int)gain / 3; gain_n = (gain_n << 4) + gain_n; res = es_write_reg(ES8388_ADDR, ES8388_ADCCONTROL1, gain_n); //MIC PGA return res; } int es8388_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { int res = 0; int es_mode_t = 0; switch (mode) { case AUDIO_HAL_CODEC_MODE_ENCODE: es_mode_t = ES_MODULE_ADC; break; case AUDIO_HAL_CODEC_MODE_LINE_IN: es_mode_t = ES_MODULE_LINE; break; case AUDIO_HAL_CODEC_MODE_DECODE: es_mode_t = ES_MODULE_DAC; break; case AUDIO_HAL_CODEC_MODE_BOTH: es_mode_t = ES_MODULE_ADC_DAC; break; default: es_mode_t = ES_MODULE_DAC; ESP_LOGW(ES_TAG, "Codec mode not support, default is decode mode"); break; } if (AUDIO_HAL_CTRL_STOP == ctrl_state) { res = es8388_stop(es_mode_t); } else { res = es8388_start(es_mode_t); ESP_LOGD(ES_TAG, "start default is decode mode:%d", es_mode_t); } return res; } esp_err_t es8388_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { esp_err_t res = ESP_OK; int tmp = 0; res |= es8388_config_fmt(ES_MODULE_ADC_DAC, iface->fmt); if (iface->bits == AUDIO_HAL_BIT_LENGTH_16BITS) { tmp = BIT_LENGTH_16BITS; } else if (iface->bits == AUDIO_HAL_BIT_LENGTH_24BITS) { tmp = BIT_LENGTH_24BITS; } else { tmp = BIT_LENGTH_32BITS; } res |= es8388_set_bits_per_sample(ES_MODULE_ADC_DAC, tmp); return res; } void es8388_pa_power(bool enable) { gpio_config_t io_conf; memset(&io_conf, 0, sizeof(io_conf)); io_conf.mode = GPIO_MODE_OUTPUT; io_conf.pin_bit_mask = BIT64(get_pa_enable_gpio()); io_conf.pull_down_en = 0; io_conf.pull_up_en = 0; gpio_config(&io_conf); if (enable) { gpio_set_level(get_pa_enable_gpio(), 1); } else { gpio_set_level(get_pa_enable_gpio(), 0); } }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es8388/es8388.c
C
apache-2.0
19,117
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __ES8388_H__ #define __ES8388_H__ #include "esp_types.h" #include "audio_hal.h" #include "driver/i2c.h" #include "esxxx_common.h" #ifdef __cplusplus extern "C" { #endif /* ES8388 address */ #define ES8388_ADDR 0x20 /*!< 0x22:CE=1;0x20:CE=0*/ /* ES8388 register */ #define ES8388_CONTROL1 0x00 #define ES8388_CONTROL2 0x01 #define ES8388_CHIPPOWER 0x02 #define ES8388_ADCPOWER 0x03 #define ES8388_DACPOWER 0x04 #define ES8388_CHIPLOPOW1 0x05 #define ES8388_CHIPLOPOW2 0x06 #define ES8388_ANAVOLMANAG 0x07 #define ES8388_MASTERMODE 0x08 /* ADC */ #define ES8388_ADCCONTROL1 0x09 #define ES8388_ADCCONTROL2 0x0a #define ES8388_ADCCONTROL3 0x0b #define ES8388_ADCCONTROL4 0x0c #define ES8388_ADCCONTROL5 0x0d #define ES8388_ADCCONTROL6 0x0e #define ES8388_ADCCONTROL7 0x0f #define ES8388_ADCCONTROL8 0x10 #define ES8388_ADCCONTROL9 0x11 #define ES8388_ADCCONTROL10 0x12 #define ES8388_ADCCONTROL11 0x13 #define ES8388_ADCCONTROL12 0x14 #define ES8388_ADCCONTROL13 0x15 #define ES8388_ADCCONTROL14 0x16 /* DAC */ #define ES8388_DACCONTROL1 0x17 #define ES8388_DACCONTROL2 0x18 #define ES8388_DACCONTROL3 0x19 #define ES8388_DACCONTROL4 0x1a #define ES8388_DACCONTROL5 0x1b #define ES8388_DACCONTROL6 0x1c #define ES8388_DACCONTROL7 0x1d #define ES8388_DACCONTROL8 0x1e #define ES8388_DACCONTROL9 0x1f #define ES8388_DACCONTROL10 0x20 #define ES8388_DACCONTROL11 0x21 #define ES8388_DACCONTROL12 0x22 #define ES8388_DACCONTROL13 0x23 #define ES8388_DACCONTROL14 0x24 #define ES8388_DACCONTROL15 0x25 #define ES8388_DACCONTROL16 0x26 #define ES8388_DACCONTROL17 0x27 #define ES8388_DACCONTROL18 0x28 #define ES8388_DACCONTROL19 0x29 #define ES8388_DACCONTROL20 0x2a #define ES8388_DACCONTROL21 0x2b #define ES8388_DACCONTROL22 0x2c #define ES8388_DACCONTROL23 0x2d #define ES8388_DACCONTROL24 0x2e #define ES8388_DACCONTROL25 0x2f #define ES8388_DACCONTROL26 0x30 #define ES8388_DACCONTROL27 0x31 #define ES8388_DACCONTROL28 0x32 #define ES8388_DACCONTROL29 0x33 #define ES8388_DACCONTROL30 0x34 /** * @brief Initialize ES8388 codec chip * * @param cfg configuration of ES8388 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8388_init(audio_hal_codec_config_t *cfg); /** * @brief Deinitialize ES8388 codec chip * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8388_deinit(void); /** * @brief Configure ES8388 I2S format * * @param mod: set ADC or DAC or both * @param cfg: ES8388 I2S format * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8388_config_fmt(es_module_t mod, es_i2s_fmt_t cfg); /** * @brief Configure I2s clock in MSATER mode * * @param cfg: set bits clock and WS clock * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8388_i2s_config_clock(es_i2s_clock_t cfg); /** * @brief Configure ES8388 data sample bits * * @param mode: set ADC or DAC or both * @param bit_per_sample: bit number of per sample * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8388_set_bits_per_sample(es_module_t mode, es_bits_length_t bit_per_sample); /** * @brief Start ES8388 codec chip * * @param mode: set ADC or DAC or both * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8388_start(es_module_t mode); /** * @brief Stop ES8388 codec chip * * @param mode: set ADC or DAC or both * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8388_stop(es_module_t mode); /** * @brief Set voice volume * * @param volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8388_set_voice_volume(int volume); /** * @brief Get voice volume * * @param[out] *volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t es8388_get_voice_volume(int *volume); /** * @brief Configure ES8388 DAC mute or not. Basically you can use this function to mute the output or unmute * * @param enable enable(1) or disable(0) * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8388_set_voice_mute(bool enable); /** * @brief Get ES8388 DAC mute status * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8388_get_voice_mute(void); /** * @brief Set ES8388 mic gain * * @param gain db of mic gain * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8388_set_mic_gain(es_mic_gain_t gain); /** * @brief Set ES8388 adc input mode * * @param input adc input mode * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8388_config_adc_input(es_adc_input_t input); /** * @brief Set ES8388 dac output mode * * @param output dac output mode * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8388_config_dac_output(es_dac_output_t output); /** * @brief Write ES8388 register * * @param reg_add address of register * @param data data of register * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8388_write_reg(uint8_t reg_add, uint8_t data); /** * @brief Print all ES8388 registers * * @return * - void */ void es8388_read_all(); /** * @brief Configure ES8388 codec mode and I2S interface * * @param mode codec mode * @param iface I2S config * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8388_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /** * @brief Control ES8388 codec chip * * @param mode codec mode * @param ctrl_state start or stop decode or encode progress * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t es8388_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); /** * @brief Set ES8388 PA power * * @param enable true for enable PA power, false for disable PA power * * @return * - void */ void es8388_pa_power(bool enable); #ifdef __cplusplus } #endif #endif //__ES8388_H__
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es8388/es8388.h
C
apache-2.0
7,474
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <stdio.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "freertos/timers.h" #include "driver/gpio.h" #include "esp_log.h" #include "es8388.h" #include "board.h" #ifdef CONFIG_ESP_LYRAT_V4_3_BOARD #define HP_DELAY_TIME_MS 1000 static char *TAG = "HEADPHONE"; static xTimerHandle timer_headphone; static void hp_timer_cb(TimerHandle_t xTimer) { int num = (int)pvTimerGetTimerID(xTimer); int res = gpio_get_level(num); es8388_pa_power(res); ESP_LOGW(TAG, "Headphone jack %s", res ? "removed" : "inserted"); } static int hp_timer_init(int num) { timer_headphone = xTimerCreate("hp_timer0", HP_DELAY_TIME_MS / portTICK_RATE_MS, pdFALSE, (void *) num, hp_timer_cb); if (timer_headphone == NULL) { ESP_LOGE(TAG, "hp_timer create err"); return ESP_FAIL; } return ESP_OK; } static void IRAM_ATTR headphone_gpio_intr_handler(void *arg) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerResetFromISR(timer_headphone, &xHigherPriorityTaskWoken); if ( xHigherPriorityTaskWoken != pdFALSE ) { portYIELD_FROM_ISR(); } } void headphone_detect_deinit() { xTimerDelete(timer_headphone, HP_DELAY_TIME_MS / portTICK_RATE_MS); gpio_uninstall_isr_service(); timer_headphone = NULL; } int headphone_status_get() { return gpio_get_level(0); } void headphone_detect_init(int num) { hp_timer_init(num); gpio_config_t io_conf; memset(&io_conf, 0, sizeof(io_conf)); io_conf.intr_type = GPIO_INTR_ANYEDGE; io_conf.mode = GPIO_MODE_INPUT; io_conf.pin_bit_mask = BIT64(num); io_conf.pull_down_en = 0; io_conf.pull_up_en = 1; gpio_config(&io_conf); gpio_install_isr_service(0); gpio_isr_handler_add(num, headphone_gpio_intr_handler, (void *)num); } #endif /* CONFIG_ESP_LYRAT_V4_3_BOARD */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es8388/headphone_detect.c
C
apache-2.0
3,126
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_HEADPHONE_DETEC_H_ #define _AUDIO_HEADPHONE_DETEC_H_ #ifdef __cplusplus extern "C" { #endif /** * @brief Get headphone insertion status * * @param None. * * @return int, 0:headphone inserted, 1:headphone not inserted. */ int headphone_status_get(); /** * @brief Initialize headphone detect gpio. * * @param None. * * @return None. */ void headphone_detect_init(int num); /** * @brief Delete headphone detect timer. * * @param None. * * @return None. */ void headphone_detect_deinit(); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/es8388/headphone_detect.h
C
apache-2.0
1,796
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _ESXXX_COMMON_H_ #define _ESXXX_COMMON_H_ #ifdef __cplusplus extern "C" { #endif typedef enum { BIT_LENGTH_MIN = -1, BIT_LENGTH_16BITS = 0x03, BIT_LENGTH_18BITS = 0x02, BIT_LENGTH_20BITS = 0x01, BIT_LENGTH_24BITS = 0x00, BIT_LENGTH_32BITS = 0x04, BIT_LENGTH_MAX, } es_bits_length_t; typedef enum { MCLK_DIV_MIN = -1, MCLK_DIV_1 = 1, MCLK_DIV_2 = 2, MCLK_DIV_3 = 3, MCLK_DIV_4 = 4, MCLK_DIV_6 = 5, MCLK_DIV_8 = 6, MCLK_DIV_9 = 7, MCLK_DIV_11 = 8, MCLK_DIV_12 = 9, MCLK_DIV_16 = 10, MCLK_DIV_18 = 11, MCLK_DIV_22 = 12, MCLK_DIV_24 = 13, MCLK_DIV_33 = 14, MCLK_DIV_36 = 15, MCLK_DIV_44 = 16, MCLK_DIV_48 = 17, MCLK_DIV_66 = 18, MCLK_DIV_72 = 19, MCLK_DIV_5 = 20, MCLK_DIV_10 = 21, MCLK_DIV_15 = 22, MCLK_DIV_17 = 23, MCLK_DIV_20 = 24, MCLK_DIV_25 = 25, MCLK_DIV_30 = 26, MCLK_DIV_32 = 27, MCLK_DIV_34 = 28, MCLK_DIV_7 = 29, MCLK_DIV_13 = 30, MCLK_DIV_14 = 31, MCLK_DIV_MAX, } es_sclk_div_t; typedef enum { LCLK_DIV_MIN = -1, LCLK_DIV_128 = 0, LCLK_DIV_192 = 1, LCLK_DIV_256 = 2, LCLK_DIV_384 = 3, LCLK_DIV_512 = 4, LCLK_DIV_576 = 5, LCLK_DIV_768 = 6, LCLK_DIV_1024 = 7, LCLK_DIV_1152 = 8, LCLK_DIV_1408 = 9, LCLK_DIV_1536 = 10, LCLK_DIV_2112 = 11, LCLK_DIV_2304 = 12, LCLK_DIV_125 = 16, LCLK_DIV_136 = 17, LCLK_DIV_250 = 18, LCLK_DIV_272 = 19, LCLK_DIV_375 = 20, LCLK_DIV_500 = 21, LCLK_DIV_544 = 22, LCLK_DIV_750 = 23, LCLK_DIV_1000 = 24, LCLK_DIV_1088 = 25, LCLK_DIV_1496 = 26, LCLK_DIV_1500 = 27, LCLK_DIV_MAX, } es_lclk_div_t; typedef enum { D2SE_PGA_GAIN_MIN = -1, D2SE_PGA_GAIN_DIS = 0, D2SE_PGA_GAIN_EN = 1, D2SE_PGA_GAIN_MAX = 2, } es_d2se_pga_t; typedef enum { ADC_INPUT_MIN = -1, ADC_INPUT_LINPUT1_RINPUT1 = 0x00, ADC_INPUT_MIC1 = 0x05, ADC_INPUT_MIC2 = 0x06, ADC_INPUT_LINPUT2_RINPUT2 = 0x50, ADC_INPUT_DIFFERENCE = 0xf0, ADC_INPUT_MAX, } es_adc_input_t; typedef enum { DAC_OUTPUT_MIN = -1, DAC_OUTPUT_LOUT1 = 0x04, DAC_OUTPUT_LOUT2 = 0x08, DAC_OUTPUT_SPK = 0x09, DAC_OUTPUT_ROUT1 = 0x10, DAC_OUTPUT_ROUT2 = 0x20, DAC_OUTPUT_ALL = 0x3c, DAC_OUTPUT_MAX, } es_dac_output_t; typedef enum { MIC_GAIN_MIN = -1, MIC_GAIN_0DB = 0, MIC_GAIN_3DB = 3, MIC_GAIN_6DB = 6, MIC_GAIN_9DB = 9, MIC_GAIN_12DB = 12, MIC_GAIN_15DB = 15, MIC_GAIN_18DB = 18, MIC_GAIN_21DB = 21, MIC_GAIN_24DB = 24, MIC_GAIN_MAX, } es_mic_gain_t; typedef enum { ES_MODULE_MIN = -1, ES_MODULE_ADC = 0x01, ES_MODULE_DAC = 0x02, ES_MODULE_ADC_DAC = 0x03, ES_MODULE_LINE = 0x04, ES_MODULE_MAX } es_module_t; typedef enum { ES_MODE_MIN = -1, ES_MODE_SLAVE = 0x00, ES_MODE_MASTER = 0x01, ES_MODE_MAX, } es_mode_t; typedef enum { ES_I2S_MIN = -1, ES_I2S_NORMAL = 0, ES_I2S_LEFT = 1, ES_I2S_RIGHT = 2, ES_I2S_DSP = 3, ES_I2S_MAX } es_i2s_fmt_t; /** * @brief Configure ES8388 clock */ typedef struct { es_sclk_div_t sclk_div; /*!< bits clock divide */ es_lclk_div_t lclk_div; /*!< WS clock divide */ } es_i2s_clock_t; #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/include/esxxx_common.h
C
apache-2.0
4,546
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "esp_log.h" #include "ns4168.h" #include "driver/gpio.h" #include "board.h" static const char *TAG = "ns4168"; static bool codec_init_flag = 0; audio_hal_func_t AUDIO_CODEC_NS4168_DEFAULT_HANDLE = { .audio_codec_initialize = ns4168_codec_init, .audio_codec_deinitialize = ns4168_codec_deinit, .audio_codec_ctrl = ns4168_codec_ctrl_state, .audio_codec_config_iface = ns4168_codec_config_i2s, .audio_codec_set_mute = ns4168_codec_set_voice_mute, .audio_codec_set_volume = ns4168_codec_set_voice_volume, .audio_codec_get_volume = ns4168_codec_get_voice_volume, .audio_hal_lock = NULL, .handle = NULL, }; static bool ns4168_codec_initialized() { return codec_init_flag; } esp_err_t ns4168_codec_init(audio_hal_codec_config_t *cfg) { if (ns4168_codec_initialized()) { ESP_LOGW(TAG, "The ns4168 codec has been already initialized"); return ESP_OK; } codec_init_flag = true; return ESP_OK; } esp_err_t ns4168_codec_deinit(void) { codec_init_flag = false; return ESP_OK; } esp_err_t ns4168_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { return ESP_OK; } esp_err_t ns4168_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { return ESP_OK; } esp_err_t ns4168_codec_set_voice_mute(bool mute) { return ESP_OK; } esp_err_t ns4168_codec_set_voice_volume(int volume) { int ret = 0; return ret; } esp_err_t ns4168_codec_get_voice_volume(int *volume) { int ret = 0; return ret; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/ns4168/ns4168.c
C
apache-2.0
2,791
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __NS4168_H__ #define __NS4168_H__ #include "audio_hal.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize ns4168 chip * * @param cfg configuration of ns4168 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t ns4168_codec_init(audio_hal_codec_config_t *cfg); /** * @brief Deinitialize ns4168 chip * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t ns4168_codec_deinit(void); /** * The functions ns4168_ctrl_state and ns4168_config_i2s are not used by this driver. * They are kept here to maintain the uniformity and convenience of the interface * of the ADF project. * These settings for ns4168 are burned in firmware and configuration files. * Default i2s configuration: 48000Hz, 16bit, Left-Right channels. * Use resampling to be compatible with different file types. * * @brief Control ns4168 chip * * @param mode codec mode * @param ctrl_state start or stop decode or encode progress * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t ns4168_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); /** * @brief Configure ns4168 codec mode and I2S interface * * @param mode codec mode * @param iface I2S config * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t ns4168_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /** * @brief mute or unmute the codec * * @param mute: true, false * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t ns4168_codec_set_voice_mute(bool mute); /** * @brief Set voice volume * * @param volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t ns4168_codec_set_voice_volume(int volume); /** * @brief Get voice volume * * @param[out] *volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t ns4168_codec_get_voice_volume(int *volume); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/ns4168/ns4168.h
C
apache-2.0
3,229
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "i2c_bus.h" #include "board.h" #include "esp_log.h" #include "tas5805m.h" #include "tas5805m_reg_cfg.h" static const char *TAG = "TAS5805M"; #define TAS5805M_ADDR 0x5c #define TAS5805M_RST_GPIO get_pa_enable_gpio() #define TAS5805M_VOLUME_MAX 100 #define TAS5805M_VOLUME_MIN 0 #define TAS5805M_ASSERT(a, format, b, ...) \ if ((a) != 0) { \ ESP_LOGE(TAG, format, ##__VA_ARGS__); \ return b;\ } esp_err_t tas5805m_ctrl(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); esp_err_t tas5805m_conig_iface(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); static i2c_bus_handle_t i2c_handler; /* * i2c default configuration */ static i2c_config_t i2c_cfg = { .mode = I2C_MODE_MASTER, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_pullup_en = GPIO_PULLUP_ENABLE, .master.clk_speed = 100000, }; /* * Operate fuction of PA */ audio_hal_func_t AUDIO_CODEC_TAS5805M_DEFAULT_HANDLE = { .audio_codec_initialize = tas5805m_init, .audio_codec_deinitialize = tas5805m_deinit, .audio_codec_ctrl = tas5805m_ctrl, .audio_codec_config_iface = tas5805m_conig_iface, .audio_codec_set_mute = tas5805m_set_mute, .audio_codec_set_volume = tas5805m_set_volume, .audio_codec_get_volume = tas5805m_get_volume, .audio_hal_lock = NULL, .handle = NULL, }; static esp_err_t tas5805m_transmit_registers(const tas5805m_cfg_reg_t *conf_buf, int size) { int i = 0; esp_err_t ret = ESP_OK; while (i < size) { switch (conf_buf[i].offset) { case CFG_META_SWITCH: // Used in legacy applications. Ignored here. break; case CFG_META_DELAY: vTaskDelay(conf_buf[i].value / portTICK_RATE_MS); break; case CFG_META_BURST: ret = i2c_bus_write_bytes(i2c_handler, TAS5805M_ADDR, (unsigned char *)(&conf_buf[i + 1].offset), 1, (unsigned char *)(&conf_buf[i + 1].value), conf_buf[i].value); i += (conf_buf[i].value / 2) + 1; break; case CFG_END_1: if (CFG_END_2 == conf_buf[i + 1].offset && CFG_END_3 == conf_buf[i + 2].offset) { ESP_LOGI(TAG, "End of tms5805m reg: %d\n", i); } break; default: ret = i2c_bus_write_bytes(i2c_handler, TAS5805M_ADDR, (unsigned char *)(&conf_buf[i].offset), 1, (unsigned char *)(&conf_buf[i].value), 1); break; } i++; } if (ret != ESP_OK) { ESP_LOGE(TAG, "Fail to load configuration to tas5805m"); return ESP_FAIL; } ESP_LOGI(TAG, "%s: write %d reg done", __FUNCTION__, i); return ret; } esp_err_t tas5805m_init(audio_hal_codec_config_t *codec_cfg) { esp_err_t ret = ESP_OK; ESP_LOGI(TAG, "Power ON CODEC with GPIO %d", TAS5805M_RST_GPIO); gpio_config_t io_conf; io_conf.pin_bit_mask = BIT64(TAS5805M_RST_GPIO); io_conf.mode = GPIO_MODE_OUTPUT; io_conf.intr_type = GPIO_INTR_DISABLE; gpio_config(&io_conf); gpio_set_level(TAS5805M_RST_GPIO, 0); vTaskDelay(20 / portTICK_RATE_MS); gpio_set_level(TAS5805M_RST_GPIO, 1); vTaskDelay(200 / portTICK_RATE_MS); ret = get_i2c_pins(I2C_NUM_0, &i2c_cfg); i2c_handler = i2c_bus_create(I2C_NUM_0, &i2c_cfg); if (i2c_handler == NULL) { ESP_LOGW(TAG, "failed to create i2c bus handler\n"); return ESP_FAIL; } ret |= tas5805m_transmit_registers(tas5805m_registers, sizeof(tas5805m_registers) / sizeof(tas5805m_registers[0])); TAS5805M_ASSERT(ret, "Fail to iniitialize tas5805m PA", ESP_FAIL); return ret; } esp_err_t tas5805m_set_volume(int vol) { int vol_idx = 0; if (vol < TAS5805M_VOLUME_MIN) { vol = TAS5805M_VOLUME_MIN; } if (vol > TAS5805M_VOLUME_MAX) { vol = TAS5805M_VOLUME_MAX; } vol_idx = vol / 5; uint8_t cmd[2] = {0, 0}; esp_err_t ret = ESP_OK; cmd[0] = MASTER_VOL_REG_ADDR; cmd[1] = tas5805m_volume[vol_idx]; ret = i2c_bus_write_bytes(i2c_handler, TAS5805M_ADDR, &cmd[0], 1, &cmd[1], 1); ESP_LOGW(TAG, "volume = 0x%x", cmd[1]); return ret; } esp_err_t tas5805m_get_volume(int *value) { /// FIXME: Got the digit volume is not right. uint8_t cmd[2] = {MASTER_VOL_REG_ADDR, 0x00}; esp_err_t ret = i2c_bus_read_bytes(i2c_handler, TAS5805M_ADDR, &cmd[0], 1, &cmd[1], 1); TAS5805M_ASSERT(ret, "Fail to get volume", ESP_FAIL); int i; for (i = 0; i < sizeof(tas5805m_volume); i++) { if (cmd[1] >= tas5805m_volume[i]) break; } ESP_LOGI(TAG, "Volume is %d", i * 5); *value = 5 * i; return ret; } esp_err_t tas5805m_set_mute(bool enable) { esp_err_t ret = ESP_OK; uint8_t cmd[2] = {TAS5805M_REG_03, 0x00}; ret |= i2c_bus_read_bytes(i2c_handler, TAS5805M_ADDR, &cmd[0], 1, &cmd[1], 1); if (enable) { cmd[1] |= 0x8; } else { cmd[1] &= (~0x08); } ret |= i2c_bus_write_bytes(i2c_handler, TAS5805M_ADDR, &cmd[0], 1, &cmd[1], 1); TAS5805M_ASSERT(ret, "Fail to set mute", ESP_FAIL); return ret; } esp_err_t tas5805m_get_mute(int *value) { esp_err_t ret = ESP_OK; uint8_t cmd[2] = {TAS5805M_REG_03, 0x00}; ret |= i2c_bus_read_bytes(i2c_handler, TAS5805M_ADDR, &cmd[0], 1, &cmd[1], 1); TAS5805M_ASSERT(ret, "Fail to get mute", ESP_FAIL); *value = (cmd[1] & 0x08) >> 4; ESP_LOGI(TAG, "Get mute value: 0x%x", *value); return ret; } esp_err_t tas5805m_set_mute_fade(int value) { esp_err_t ret = 0; unsigned char cmd[2] = {MUTE_TIME_REG_ADDR, 0x00}; /* Time for register value * 000: 11.5 ms * 001: 53 ms * 010: 106.5 ms * 011: 266.5 ms * 100: 0.535 sec * 101: 1.065 sec * 110: 2.665 sec * 111: 5.33 sec */ if (value <= 12) { cmd[1] = 0; } else if (value <= 53) { cmd[1] = 1; } else if (value <= 107) { cmd[1] = 2; } else if (value <= 267) { cmd[1] = 3; } else if (value <= 535) { cmd[1] = 4; } else if (value <= 1065) { cmd[1] = 5; } else if (value <= 2665) { cmd[1] = 6; } else { cmd[1] = 7; } cmd[1] |= (cmd[1] << 4); ret |= i2c_bus_write_bytes(i2c_handler, TAS5805M_ADDR, &cmd[0], 1, &cmd[1], 1); TAS5805M_ASSERT(ret, "Fail to set mute fade", ESP_FAIL); ESP_LOGI(TAG, "Set mute fade, value:%d, 0x%x", value, cmd[1]); return ret; } esp_err_t tas5805m_set_damp_mode(int value) { unsigned char cmd[2] = {0}; cmd[0] = TAS5805M_REG_02; cmd[1] = 0x10 | value; return i2c_bus_write_bytes(i2c_handler, TAS5805M_ADDR, &cmd[0], 1, &cmd[1], 1); } esp_err_t tas5805m_deinit(void) { // TODO return ESP_OK; } esp_err_t tas5805m_ctrl(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { // TODO return ESP_OK; } esp_err_t tas5805m_conig_iface(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { //TODO return ESP_OK; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/tas5805m/tas5805m.c
C
apache-2.0
8,296
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _TAS5805M_H_ #define _TAS5805M_H_ #include "audio_hal.h" #include "esp_err.h" #ifdef __cplusplus extern "C" { #endif #define TAS5805M_REG_00 0x00 #define TAS5805M_REG_02 0x02 #define TAS5805M_REG_03 0x03 #define TAS5805M_REG_24 0x24 #define TAS5805M_REG_25 0x25 #define TAS5805M_REG_26 0x26 #define TAS5805M_REG_27 0x27 #define TAS5805M_REG_28 0x28 #define TAS5805M_REG_29 0x29 #define TAS5805M_REG_2A 0x2a #define TAS5805M_REG_2B 0x2b #define TAS5805M_REG_35 0x35 #define TAS5805M_REG_7E 0x7e #define TAS5805M_REG_7F 0x7f #define TAS5805M_PAGE_00 0x00 #define TAS5805M_PAGE_2A 0x2a #define TAS5805M_BOOK_00 0x00 #define TAS5805M_BOOK_8C 0x8c #define MASTER_VOL_REG_ADDR 0X4C #define MUTE_TIME_REG_ADDR 0X51 #define TAS5805M_DAMP_MODE_BTL 0x0 #define TAS5805M_DAMP_MODE_PBTL 0x04 /** * @brief Initialize TAS5805 codec chip * * @param cfg configuration of TAS5805 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t tas5805m_init(audio_hal_codec_config_t *codec_cfg); /** * @brief Deinitialize TAS5805 codec chip * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t tas5805m_deinit(void); /** * @brief Set voice volume * * @param volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t tas5805m_set_volume(int vol); /** * @brief Get voice volume * * @param[out] *volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t tas5805m_get_volume(int *value); /** * @brief Set TAS5805 mute or not * Continuously call should have an interval time determined by tas5805m_set_mute_fade() * * @param enable enable(1) or disable(0) * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t tas5805m_set_mute(bool enable); /** * @brief Mute gradually by (value)ms * * @param value Time for mute with millisecond. * @return * - ESP_FAIL Parameter error * - ESP_OK Success * */ esp_err_t tas5805m_set_mute_fade(int value); /** * @brief Get TAS5805 mute status * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t tas5805m_get_mute(int *value); /** * @brief Set DAMP mode * * @param value TAS5805M_DAMP_MODE_BTL or TAS5805M_DAMP_MODE_PBTL * @return * - ESP_FAIL Parameter error * - ESP_OK Success * */ esp_err_t tas5805m_set_damp_mode(int value); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/tas5805m/tas5805m.h
C
apache-2.0
3,748
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _TAS5805M_REG_CFG_ #define _TAS5805M_REG_CFG_ #ifdef __cplusplus extern "C" { #endif #define CFG_META_SWITCH (255) #define CFG_META_DELAY (254) #define CFG_META_BURST (253) #define CFG_END_1 (0Xaa) #define CFG_END_2 (0Xcc) #define CFG_END_3 (0Xee) typedef struct { uint8_t offset; uint8_t value; } tas5805m_cfg_reg_t; static const uint8_t tas5805m_volume[] = { 0xff, 0x9f, 0x8f, 0x7f, 0x6f, 0x5f, 0x5c, 0x5a, 0x58, 0x54, 0x50, 0x4c, 0x4a, 0x48, 0x44, 0x40, 0x3d, 0x3b, 0x39, 0x37, 0x35 }; static const tas5805m_cfg_reg_t tas5805m_registers[] = { //RESET { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x03, 0x02 }, { 0x01, 0x11 }, { 0x00, 0x00 }, { 0x00, 0x00 }, { 0x00, 0x00 }, { 0x00, 0x00 }, { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x03, 0x02 }, { CFG_META_DELAY, 5 }, { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x03, 0x00 }, { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x46, 0x11 }, { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x03, 0x02 }, { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x78, 0x80 }, { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x61, 0x0b }, { 0x60, 0x01 }, { 0x7d, 0x11 }, { 0x7e, 0xff }, { 0x00, 0x01 }, { 0x51, 0x05 }, { 0x00, 0x00 }, #if CONFIG_ESP32_KORVO_DU1906_BOARD { 0x02, 0x10 }, #else { 0x02, 0x14 }, #endif { 0x53, 0x00 }, { 0x54, 0x13 }, { 0x00, 0x00 }, { 0x00, 0x00 }, { 0x00, 0x00 }, { 0x00, 0x00 }, { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x66, 0x86 }, { 0x7f, 0x8c }, { 0x00, 0x29 }, { 0x18, 0x00 }, { 0x19, 0x40 }, { 0x1a, 0x26 }, { 0x1b, 0xe7 }, { 0x1c, 0x00 }, { 0x1d, 0x40 }, { 0x1e, 0x26 }, { 0x1f, 0xe7 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x00, 0x2a }, { 0x24, 0x00 }, { 0x25, 0x65 }, { 0x26, 0xac }, { 0x27, 0x8c }, { 0x28, 0x00 }, { 0x29, 0x65 }, { 0x2a, 0xac }, { 0x2b, 0x8c }, { 0x30, 0x00 }, { 0x31, 0xe2 }, { 0x32, 0xc4 }, { 0x33, 0x6b }, { 0x00, 0x2c }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x80 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x18, 0x00 }, { 0x19, 0x00 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0x00 }, { 0x1d, 0x80 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x80 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x00 }, { 0x2d, 0x00 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x34, 0x00 }, { 0x35, 0x80 }, { 0x36, 0x00 }, { 0x37, 0x00 }, { 0x38, 0x00 }, { 0x39, 0x00 }, { 0x3a, 0x00 }, { 0x3b, 0x00 }, { 0x48, 0x00 }, { 0x49, 0x80 }, { 0x4a, 0x00 }, { 0x4b, 0x00 }, { 0x4c, 0x00 }, { 0x4d, 0x00 }, { 0x4e, 0x00 }, { 0x4f, 0x00 }, { 0x5c, 0x00 }, { 0x5d, 0x00 }, { 0x5e, 0xae }, { 0x5f, 0xc3 }, { 0x60, 0x00 }, { 0x61, 0x45 }, { 0x62, 0xa1 }, { 0x63, 0xcb }, { 0x64, 0x04 }, { 0x65, 0x0c }, { 0x66, 0x37 }, { 0x67, 0x14 }, { 0x68, 0xc0 }, { 0x69, 0x00 }, { 0x6a, 0x00 }, { 0x6b, 0x00 }, { 0x6c, 0x04 }, { 0x6d, 0xc1 }, { 0x6e, 0xff }, { 0x6f, 0x93 }, { 0x74, 0x00 }, { 0x75, 0x80 }, { 0x76, 0x00 }, { 0x77, 0x00 }, { 0x00, 0x2d }, { 0x18, 0x7b }, { 0x19, 0x3e }, { 0x1a, 0x00 }, { 0x1b, 0x6d }, { 0x1c, 0x00 }, { 0x1d, 0x00 }, { 0x1e, 0xae }, { 0x1f, 0xc3 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x00 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x00 }, { 0x2d, 0x80 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x00, 0x2e }, { 0x24, 0x20 }, { 0x25, 0x29 }, { 0x26, 0x00 }, { 0x27, 0x94 }, { 0x00, 0x31 }, { 0x48, 0x40 }, { 0x49, 0x00 }, { 0x4a, 0x00 }, { 0x4b, 0x00 }, { 0x4c, 0x00 }, { 0x4d, 0x00 }, { 0x4e, 0x00 }, { 0x4f, 0x00 }, { 0x50, 0x00 }, { 0x51, 0x00 }, { 0x52, 0x00 }, { 0x53, 0x00 }, { 0x54, 0x00 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x58, 0x00 }, { 0x59, 0x00 }, { 0x5a, 0x00 }, { 0x5b, 0x00 }, { 0x5c, 0x00 }, { 0x5d, 0x00 }, { 0x5e, 0x00 }, { 0x5f, 0x00 }, { 0x60, 0x00 }, { 0x61, 0x00 }, { 0x62, 0x00 }, { 0x63, 0x00 }, { 0x64, 0x00 }, { 0x65, 0x00 }, { 0x66, 0x00 }, { 0x67, 0x00 }, { 0x68, 0x00 }, { 0x69, 0x00 }, { 0x6a, 0x00 }, { 0x6b, 0x00 }, { 0x6c, 0x00 }, { 0x6d, 0x00 }, { 0x6e, 0x00 }, { 0x6f, 0x00 }, { 0x70, 0x00 }, { 0x71, 0x00 }, { 0x72, 0x00 }, { 0x73, 0x00 }, { 0x74, 0x00 }, { 0x75, 0x00 }, { 0x76, 0x00 }, { 0x77, 0x00 }, { 0x78, 0x00 }, { 0x79, 0x00 }, { 0x7a, 0x00 }, { 0x7b, 0x00 }, { 0x7c, 0x00 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x32 }, { 0x08, 0x00 }, { 0x09, 0x00 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x18, 0x00 }, { 0x19, 0x00 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0x00 }, { 0x1d, 0x00 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x00 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x00 }, { 0x2d, 0x00 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x30, 0x00 }, { 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 }, { 0x34, 0x00 }, { 0x35, 0x00 }, { 0x36, 0x00 }, { 0x37, 0x00 }, { 0x38, 0x00 }, { 0x39, 0x00 }, { 0x3a, 0x00 }, { 0x3b, 0x00 }, { 0x3c, 0x00 }, { 0x3d, 0x00 }, { 0x3e, 0x00 }, { 0x3f, 0x00 }, { 0x40, 0x00 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0x00 }, { 0x45, 0x00 }, { 0x46, 0x00 }, { 0x47, 0x00 }, { 0x48, 0x00 }, { 0x49, 0x00 }, { 0x4a, 0x00 }, { 0x4b, 0x00 }, { 0x4c, 0x00 }, { 0x4d, 0x00 }, { 0x4e, 0x00 }, { 0x4f, 0x00 }, { 0x50, 0x00 }, { 0x51, 0x00 }, { 0x52, 0x00 }, { 0x53, 0x00 }, { 0x54, 0x00 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x58, 0x00 }, { 0x59, 0x00 }, { 0x5a, 0x00 }, { 0x5b, 0x00 }, { 0x5c, 0x00 }, { 0x5d, 0x00 }, { 0x5e, 0x00 }, { 0x5f, 0x00 }, { 0x60, 0x00 }, { 0x61, 0x00 }, { 0x62, 0x00 }, { 0x63, 0x00 }, { 0x64, 0x00 }, { 0x65, 0x00 }, { 0x66, 0x00 }, { 0x67, 0x00 }, { 0x68, 0x00 }, { 0x69, 0x00 }, { 0x6a, 0x00 }, { 0x6b, 0x00 }, { 0x6c, 0x00 }, { 0x6d, 0x00 }, { 0x6e, 0x00 }, { 0x6f, 0x00 }, { 0x70, 0x00 }, { 0x71, 0x00 }, { 0x72, 0x00 }, { 0x73, 0x00 }, { 0x74, 0x00 }, { 0x75, 0x00 }, { 0x76, 0x00 }, { 0x77, 0x00 }, { 0x78, 0x00 }, { 0x79, 0x00 }, { 0x7a, 0x00 }, { 0x7b, 0x00 }, { 0x7c, 0x00 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x33 }, { 0x08, 0x00 }, { 0x09, 0x00 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x18, 0x00 }, { 0x19, 0x00 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0x00 }, { 0x1d, 0x00 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x00 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x00 }, { 0x2d, 0x00 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x30, 0x00 }, { 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 }, { 0x34, 0x00 }, { 0x35, 0x00 }, { 0x36, 0x00 }, { 0x37, 0x00 }, { 0x38, 0x00 }, { 0x39, 0x00 }, { 0x3a, 0x00 }, { 0x3b, 0x00 }, { 0x3c, 0x00 }, { 0x3d, 0x00 }, { 0x3e, 0x00 }, { 0x3f, 0x00 }, { 0x40, 0x00 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0x00 }, { 0x45, 0x00 }, { 0x46, 0x00 }, { 0x47, 0x00 }, { 0x48, 0x00 }, { 0x49, 0x00 }, { 0x4a, 0x00 }, { 0x4b, 0x00 }, { 0x4c, 0x00 }, { 0x4d, 0x00 }, { 0x4e, 0x00 }, { 0x4f, 0x00 }, { 0x50, 0x00 }, { 0x51, 0x00 }, { 0x52, 0x00 }, { 0x53, 0x00 }, { 0x54, 0x00 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x58, 0x00 }, { 0x59, 0x00 }, { 0x5a, 0x00 }, { 0x5b, 0x00 }, { 0x5c, 0x00 }, { 0x5d, 0x00 }, { 0x5e, 0x00 }, { 0x5f, 0x00 }, { 0x60, 0x00 }, { 0x61, 0x00 }, { 0x62, 0x00 }, { 0x63, 0x00 }, { 0x64, 0x00 }, { 0x65, 0x00 }, { 0x66, 0x00 }, { 0x67, 0x00 }, { 0x68, 0x00 }, { 0x69, 0x00 }, { 0x6a, 0x00 }, { 0x6b, 0x00 }, { 0x6c, 0x00 }, { 0x6d, 0x00 }, { 0x6e, 0x00 }, { 0x6f, 0x00 }, { 0x70, 0x00 }, { 0x71, 0x00 }, { 0x72, 0x00 }, { 0x73, 0x00 }, { 0x74, 0x00 }, { 0x75, 0x00 }, { 0x76, 0x00 }, { 0x77, 0x00 }, { 0x78, 0x00 }, { 0x79, 0x00 }, { 0x7a, 0x00 }, { 0x7b, 0x00 }, { 0x7c, 0x00 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x34 }, { 0x08, 0x00 }, { 0x09, 0x00 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x18, 0x00 }, { 0x19, 0x00 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0x00 }, { 0x1d, 0x00 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x00 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x00 }, { 0x2d, 0x00 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x30, 0x00 }, { 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 }, { 0x34, 0x00 }, { 0x35, 0x00 }, { 0x36, 0x00 }, { 0x37, 0x00 }, { 0x38, 0x00 }, { 0x39, 0x00 }, { 0x3a, 0x00 }, { 0x3b, 0x00 }, { 0x3c, 0x00 }, { 0x3d, 0x00 }, { 0x3e, 0x00 }, { 0x3f, 0x00 }, { 0x40, 0x00 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0x00 }, { 0x45, 0x00 }, { 0x46, 0x00 }, { 0x47, 0x00 }, { 0x48, 0x00 }, { 0x49, 0x00 }, { 0x4a, 0x00 }, { 0x4b, 0x00 }, { 0x4c, 0x00 }, { 0x4d, 0x00 }, { 0x4e, 0x00 }, { 0x4f, 0x00 }, { 0x50, 0x00 }, { 0x51, 0x00 }, { 0x52, 0x00 }, { 0x53, 0x00 }, { 0x54, 0x00 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x58, 0x00 }, { 0x59, 0x00 }, { 0x5a, 0x00 }, { 0x5b, 0x00 }, { 0x5c, 0x00 }, { 0x5d, 0x00 }, { 0x5e, 0x00 }, { 0x5f, 0x00 }, { 0x60, 0x00 }, { 0x61, 0x00 }, { 0x62, 0x00 }, { 0x63, 0x00 }, { 0x64, 0x00 }, { 0x65, 0x00 }, { 0x66, 0x00 }, { 0x67, 0x00 }, { 0x68, 0x00 }, { 0x69, 0x00 }, { 0x6a, 0x00 }, { 0x6b, 0x00 }, { 0x6c, 0x00 }, { 0x6d, 0x00 }, { 0x6e, 0x00 }, { 0x6f, 0x00 }, { 0x70, 0x00 }, { 0x71, 0x00 }, { 0x72, 0x00 }, { 0x73, 0x00 }, { 0x74, 0x00 }, { 0x75, 0x00 }, { 0x76, 0x00 }, { 0x77, 0x00 }, { 0x78, 0x00 }, { 0x79, 0x00 }, { 0x7a, 0x00 }, { 0x7b, 0x00 }, { 0x7c, 0x00 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x35 }, { 0x08, 0x00 }, { 0x09, 0x00 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x18, 0x00 }, { 0x19, 0x00 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0x00 }, { 0x1d, 0x00 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x00 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x00 }, { 0x2d, 0x00 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x30, 0x00 }, { 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 }, { 0x34, 0x00 }, { 0x35, 0x00 }, { 0x36, 0x00 }, { 0x37, 0x00 }, { 0x38, 0x00 }, { 0x39, 0x00 }, { 0x3a, 0x00 }, { 0x3b, 0x00 }, { 0x3c, 0x00 }, { 0x3d, 0x00 }, { 0x3e, 0x00 }, { 0x3f, 0x00 }, { 0x40, 0x00 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0x00 }, { 0x45, 0x00 }, { 0x46, 0x00 }, { 0x47, 0x00 }, { 0x48, 0x00 }, { 0x49, 0x00 }, { 0x4a, 0x00 }, { 0x4b, 0x00 }, { 0x4c, 0x00 }, { 0x4d, 0x00 }, { 0x4e, 0x00 }, { 0x4f, 0x00 }, { 0x50, 0x00 }, { 0x51, 0x00 }, { 0x52, 0x00 }, { 0x53, 0x00 }, { 0x54, 0x00 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x58, 0x00 }, { 0x59, 0x00 }, { 0x5a, 0x00 }, { 0x5b, 0x00 }, { 0x5c, 0x00 }, { 0x5d, 0x00 }, { 0x5e, 0x00 }, { 0x5f, 0x00 }, { 0x60, 0x00 }, { 0x61, 0x00 }, { 0x62, 0x00 }, { 0x63, 0x00 }, { 0x64, 0x00 }, { 0x65, 0x00 }, { 0x66, 0x00 }, { 0x67, 0x00 }, { 0x00, 0x00 }, { 0x7f, 0xaa }, { 0x00, 0x24 }, { 0x18, 0x07 }, { 0x19, 0xf0 }, { 0x1a, 0xe4 }, { 0x1b, 0x16 }, { 0x1c, 0xf0 }, { 0x1d, 0x1e }, { 0x1e, 0x37 }, { 0x1f, 0xd3 }, { 0x20, 0x07 }, { 0x21, 0xf0 }, { 0x22, 0xe4 }, { 0x23, 0x16 }, { 0x24, 0x0f }, { 0x25, 0xe1 }, { 0x26, 0xab }, { 0x27, 0xa4 }, { 0x28, 0xf8 }, { 0x29, 0x1e }, { 0x2a, 0x1b }, { 0x2b, 0x4a }, { 0x2c, 0x07 }, { 0x2d, 0xf2 }, { 0x2e, 0xc6 }, { 0x2f, 0x03 }, { 0x30, 0xf0 }, { 0x31, 0x1a }, { 0x32, 0x73 }, { 0x33, 0xfa }, { 0x34, 0x07 }, { 0x35, 0xf2 }, { 0x36, 0xc6 }, { 0x37, 0x03 }, { 0x38, 0x0f }, { 0x39, 0xe5 }, { 0x3a, 0x76 }, { 0x3b, 0x28 }, { 0x3c, 0xf8 }, { 0x3d, 0x1a }, { 0x3e, 0x5e }, { 0x3f, 0x1c }, { 0x40, 0x08 }, { 0x41, 0x28 }, { 0x42, 0x01 }, { 0x43, 0xe1 }, { 0x44, 0xf0 }, { 0x45, 0x35 }, { 0x46, 0x45 }, { 0x47, 0x27 }, { 0x48, 0x07 }, { 0x49, 0xa3 }, { 0x4a, 0x11 }, { 0x4b, 0xa4 }, { 0x4c, 0x0f }, { 0x4d, 0xca }, { 0x4e, 0xba }, { 0x4f, 0xd9 }, { 0x50, 0xf8 }, { 0x51, 0x34 }, { 0x52, 0xec }, { 0x53, 0x7b }, { 0x54, 0x07 }, { 0x55, 0xfd }, { 0x56, 0x56 }, { 0x57, 0xbd }, { 0x58, 0xf0 }, { 0x59, 0x0d }, { 0x5a, 0x69 }, { 0x5b, 0xed }, { 0x5c, 0x07 }, { 0x5d, 0xf7 }, { 0x5e, 0xfd }, { 0x5f, 0xbb }, { 0x60, 0x0f }, { 0x61, 0xf2 }, { 0x62, 0x96 }, { 0x63, 0x13 }, { 0x64, 0xf8 }, { 0x65, 0x0a }, { 0x66, 0xab }, { 0x67, 0x87 }, { 0x68, 0x07 }, { 0x69, 0xe1 }, { 0x6a, 0xc2 }, { 0x6b, 0x69 }, { 0x6c, 0xf0 }, { 0x6d, 0xac }, { 0x6e, 0x0d }, { 0x6f, 0x58 }, { 0x70, 0x07 }, { 0x71, 0x94 }, { 0x72, 0x0c }, { 0x73, 0x4d }, { 0x74, 0x0f }, { 0x75, 0x53 }, { 0x76, 0xf2 }, { 0x77, 0xa8 }, { 0x78, 0xf8 }, { 0x79, 0x8a }, { 0x7a, 0x31 }, { 0x7b, 0x49 }, { 0x7c, 0x08 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x25 }, { 0x08, 0x00 }, { 0x09, 0x00 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x18, 0x08 }, { 0x19, 0x00 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0xf1 }, { 0x1d, 0x79 }, { 0x1e, 0xcb }, { 0x1f, 0xec }, { 0x20, 0x06 }, { 0x21, 0xa6 }, { 0x22, 0x49 }, { 0x23, 0xa5 }, { 0x24, 0x0e }, { 0x25, 0x86 }, { 0x26, 0x34 }, { 0x27, 0x14 }, { 0x28, 0xf9 }, { 0x29, 0x59 }, { 0x2a, 0xb6 }, { 0x2b, 0x5b }, { 0x2c, 0x09 }, { 0x2d, 0x63 }, { 0x2e, 0x61 }, { 0x2f, 0x75 }, { 0x30, 0xf8 }, { 0x31, 0x28 }, { 0x32, 0x33 }, { 0x33, 0x32 }, { 0x34, 0x02 }, { 0x35, 0xcb }, { 0x36, 0xa2 }, { 0x37, 0x07 }, { 0x38, 0x05 }, { 0x39, 0xc8 }, { 0x3a, 0x94 }, { 0x3b, 0x61 }, { 0x3c, 0xfd }, { 0x3d, 0xe0 }, { 0x3e, 0x34 }, { 0x3f, 0xf0 }, { 0x40, 0x08 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0xf1 }, { 0x45, 0x79 }, { 0x46, 0xcb }, { 0x47, 0xec }, { 0x48, 0x06 }, { 0x49, 0xa6 }, { 0x4a, 0x49 }, { 0x4b, 0xa5 }, { 0x4c, 0x0e }, { 0x4d, 0x86 }, { 0x4e, 0x34 }, { 0x4f, 0x14 }, { 0x50, 0xf9 }, { 0x51, 0x59 }, { 0x52, 0xb6 }, { 0x53, 0x5b }, { 0x54, 0x07 }, { 0x55, 0xd8 }, { 0x56, 0xc2 }, { 0x57, 0x5c }, { 0x58, 0xf1 }, { 0x59, 0x09 }, { 0x5a, 0x84 }, { 0x5b, 0x20 }, { 0x5c, 0x07 }, { 0x5d, 0xa4 }, { 0x5e, 0xd9 }, { 0x5f, 0x7a }, { 0x60, 0x0e }, { 0x61, 0xf6 }, { 0x62, 0x7b }, { 0x63, 0xe0 }, { 0x64, 0xf8 }, { 0x65, 0x82 }, { 0x66, 0x64 }, { 0x67, 0x2a }, { 0x68, 0x07 }, { 0x69, 0xc6 }, { 0x6a, 0x16 }, { 0x6b, 0x0b }, { 0x6c, 0xf3 }, { 0x6d, 0x04 }, { 0x6e, 0x30 }, { 0x6f, 0xd8 }, { 0x70, 0x07 }, { 0x71, 0x00 }, { 0x72, 0x0d }, { 0x73, 0xc1 }, { 0x74, 0x0c }, { 0x75, 0xfb }, { 0x76, 0xcf }, { 0x77, 0x28 }, { 0x78, 0xf9 }, { 0x79, 0x39 }, { 0x7a, 0xdc }, { 0x7b, 0x34 }, { 0x7c, 0x07 }, { 0x7d, 0xfc }, { 0x7e, 0x8e }, { 0x7f, 0xc5 }, { 0x00, 0x26 }, { 0x08, 0xf0 }, { 0x09, 0x91 }, { 0x0a, 0xb8 }, { 0x0b, 0xc2 }, { 0x0c, 0x07 }, { 0x0d, 0xe1 }, { 0x0e, 0xf7 }, { 0x0f, 0xf1 }, { 0x10, 0x0f }, { 0x11, 0x6e }, { 0x12, 0x47 }, { 0x13, 0x3e }, { 0x14, 0xf8 }, { 0x15, 0x21 }, { 0x16, 0x79 }, { 0x17, 0x4a }, { 0x18, 0x08 }, { 0x19, 0x00 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0x00 }, { 0x1d, 0x00 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x00 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x08 }, { 0x2d, 0x00 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x30, 0x00 }, { 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 }, { 0x34, 0x00 }, { 0x35, 0x00 }, { 0x36, 0x00 }, { 0x37, 0x00 }, { 0x38, 0x00 }, { 0x39, 0x00 }, { 0x3a, 0x00 }, { 0x3b, 0x00 }, { 0x3c, 0x00 }, { 0x3d, 0x00 }, { 0x3e, 0x00 }, { 0x3f, 0x00 }, { 0x40, 0x08 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0x00 }, { 0x45, 0x00 }, { 0x46, 0x00 }, { 0x47, 0x00 }, { 0x48, 0x00 }, { 0x49, 0x00 }, { 0x4a, 0x00 }, { 0x4b, 0x00 }, { 0x4c, 0x00 }, { 0x4d, 0x00 }, { 0x4e, 0x00 }, { 0x4f, 0x00 }, { 0x50, 0x00 }, { 0x51, 0x00 }, { 0x52, 0x00 }, { 0x53, 0x00 }, { 0x54, 0x08 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x58, 0x00 }, { 0x59, 0x00 }, { 0x5a, 0x00 }, { 0x5b, 0x00 }, { 0x5c, 0x00 }, { 0x5d, 0x00 }, { 0x5e, 0x00 }, { 0x5f, 0x00 }, { 0x60, 0x00 }, { 0x61, 0x00 }, { 0x62, 0x00 }, { 0x63, 0x00 }, { 0x64, 0x00 }, { 0x65, 0x00 }, { 0x66, 0x00 }, { 0x67, 0x00 }, { 0x68, 0x08 }, { 0x69, 0x00 }, { 0x6a, 0x00 }, { 0x6b, 0x00 }, { 0x6c, 0x00 }, { 0x6d, 0x00 }, { 0x6e, 0x00 }, { 0x6f, 0x00 }, { 0x70, 0x00 }, { 0x71, 0x00 }, { 0x72, 0x00 }, { 0x73, 0x00 }, { 0x74, 0x00 }, { 0x75, 0x00 }, { 0x76, 0x00 }, { 0x77, 0x00 }, { 0x78, 0x00 }, { 0x79, 0x00 }, { 0x7a, 0x00 }, { 0x7b, 0x00 }, { 0x7c, 0x08 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x27 }, { 0x08, 0x00 }, { 0x09, 0x00 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x18, 0x08 }, { 0x19, 0x00 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0x00 }, { 0x1d, 0x00 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x00 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x08 }, { 0x2d, 0x00 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x30, 0x00 }, { 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 }, { 0x34, 0x00 }, { 0x35, 0x00 }, { 0x36, 0x00 }, { 0x37, 0x00 }, { 0x38, 0x00 }, { 0x39, 0x00 }, { 0x3a, 0x00 }, { 0x3b, 0x00 }, { 0x3c, 0x00 }, { 0x3d, 0x00 }, { 0x3e, 0x00 }, { 0x3f, 0x00 }, { 0x40, 0x08 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0x00 }, { 0x45, 0x00 }, { 0x46, 0x00 }, { 0x47, 0x00 }, { 0x48, 0x00 }, { 0x49, 0x00 }, { 0x4a, 0x00 }, { 0x4b, 0x00 }, { 0x4c, 0x00 }, { 0x4d, 0x00 }, { 0x4e, 0x00 }, { 0x4f, 0x00 }, { 0x50, 0x00 }, { 0x51, 0x00 }, { 0x52, 0x00 }, { 0x53, 0x00 }, { 0x54, 0x08 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x58, 0x00 }, { 0x59, 0x00 }, { 0x5a, 0x00 }, { 0x5b, 0x00 }, { 0x5c, 0x00 }, { 0x5d, 0x00 }, { 0x5e, 0x00 }, { 0x5f, 0x00 }, { 0x60, 0x00 }, { 0x61, 0x00 }, { 0x62, 0x00 }, { 0x63, 0x00 }, { 0x64, 0x00 }, { 0x65, 0x00 }, { 0x66, 0x00 }, { 0x67, 0x00 }, { 0x68, 0x08 }, { 0x69, 0x00 }, { 0x6a, 0x00 }, { 0x6b, 0x00 }, { 0x6c, 0x00 }, { 0x6d, 0x00 }, { 0x6e, 0x00 }, { 0x6f, 0x00 }, { 0x70, 0x00 }, { 0x71, 0x00 }, { 0x72, 0x00 }, { 0x73, 0x00 }, { 0x74, 0x00 }, { 0x75, 0x00 }, { 0x76, 0x00 }, { 0x77, 0x00 }, { 0x78, 0x00 }, { 0x79, 0x00 }, { 0x7a, 0x00 }, { 0x7b, 0x00 }, { 0x7c, 0x08 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x28 }, { 0x08, 0x00 }, { 0x09, 0x00 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x18, 0x08 }, { 0x19, 0x00 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0x00 }, { 0x1d, 0x00 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x00 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x08 }, { 0x2d, 0x00 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x30, 0x00 }, { 0x31, 0x00 }, { 0x32, 0x00 }, { 0x33, 0x00 }, { 0x34, 0x00 }, { 0x35, 0x00 }, { 0x36, 0x00 }, { 0x37, 0x00 }, { 0x38, 0x00 }, { 0x39, 0x00 }, { 0x3a, 0x00 }, { 0x3b, 0x00 }, { 0x3c, 0x00 }, { 0x3d, 0x00 }, { 0x3e, 0x00 }, { 0x3f, 0x00 }, { 0x40, 0x08 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0x00 }, { 0x45, 0x00 }, { 0x46, 0x00 }, { 0x47, 0x00 }, { 0x48, 0x00 }, { 0x49, 0x00 }, { 0x4a, 0x00 }, { 0x4b, 0x00 }, { 0x4c, 0x00 }, { 0x4d, 0x00 }, { 0x4e, 0x00 }, { 0x4f, 0x00 }, { 0x50, 0x00 }, { 0x51, 0x00 }, { 0x52, 0x00 }, { 0x53, 0x00 }, { 0x54, 0x08 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x58, 0x00 }, { 0x59, 0x00 }, { 0x5a, 0x00 }, { 0x5b, 0x00 }, { 0x5c, 0x00 }, { 0x5d, 0x00 }, { 0x5e, 0x00 }, { 0x5f, 0x00 }, { 0x60, 0x00 }, { 0x61, 0x00 }, { 0x62, 0x00 }, { 0x63, 0x00 }, { 0x64, 0x00 }, { 0x65, 0x00 }, { 0x66, 0x00 }, { 0x67, 0x00 }, { 0x68, 0x08 }, { 0x69, 0x00 }, { 0x6a, 0x00 }, { 0x6b, 0x00 }, { 0x6c, 0x00 }, { 0x6d, 0x00 }, { 0x6e, 0x00 }, { 0x6f, 0x00 }, { 0x70, 0x00 }, { 0x71, 0x00 }, { 0x72, 0x00 }, { 0x73, 0x00 }, { 0x74, 0x00 }, { 0x75, 0x00 }, { 0x76, 0x00 }, { 0x77, 0x00 }, { 0x78, 0x00 }, { 0x79, 0x00 }, { 0x7a, 0x00 }, { 0x7b, 0x00 }, { 0x7c, 0x08 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x29 }, { 0x08, 0x00 }, { 0x09, 0x00 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x00, 0x2e }, { 0x7c, 0x08 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x2f }, { 0x08, 0x00 }, { 0x09, 0x00 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 }, { 0x17, 0x00 }, { 0x1c, 0x08 }, { 0x1d, 0x00 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x00 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, { 0x24, 0x00 }, { 0x25, 0x00 }, { 0x26, 0x00 }, { 0x27, 0x00 }, { 0x28, 0x00 }, { 0x29, 0x00 }, { 0x2a, 0x00 }, { 0x2b, 0x00 }, { 0x2c, 0x00 }, { 0x2d, 0x00 }, { 0x2e, 0x00 }, { 0x2f, 0x00 }, { 0x00, 0x2a }, { 0x48, 0x00 }, { 0x49, 0x15 }, { 0x4a, 0xa7 }, { 0x4b, 0x04 }, { 0x4c, 0x00 }, { 0x4d, 0x15 }, { 0x4e, 0xa7 }, { 0x4f, 0x04 }, { 0x50, 0x00 }, { 0x51, 0x15 }, { 0x52, 0xa7 }, { 0x53, 0x04 }, { 0x54, 0x7b }, { 0x55, 0x43 }, { 0x56, 0x52 }, { 0x57, 0x44 }, { 0x58, 0x89 }, { 0x59, 0x22 }, { 0x5a, 0xbf }, { 0x5b, 0x66 }, { 0x00, 0x00 }, { 0x7f, 0x8c }, { 0x00, 0x2b }, { 0x34, 0x00 }, { 0x35, 0x22 }, { 0x36, 0x1d }, { 0x37, 0x95 }, { 0x38, 0x02 }, { 0x39, 0xa3 }, { 0x3a, 0x9a }, { 0x3b, 0xcc }, { 0x3c, 0x00 }, { 0x3d, 0x06 }, { 0x3e, 0xd3 }, { 0x3f, 0x72 }, { 0x40, 0x00 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0x00 }, { 0x45, 0x00 }, { 0x46, 0x4e }, { 0x47, 0xa5 }, { 0x48, 0xff }, { 0x49, 0x81 }, { 0x4a, 0x47 }, { 0x4b, 0xae }, { 0x4c, 0xf9 }, { 0x4d, 0x06 }, { 0x4e, 0x21 }, { 0x4f, 0xa9 }, { 0x50, 0xfc }, { 0x51, 0xc2 }, { 0x52, 0xd8 }, { 0x53, 0xc5 }, { 0x54, 0x00 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x58, 0x00 }, { 0x59, 0x02 }, { 0x5a, 0x4b }, { 0x5b, 0xce }, { 0x00, 0x2d }, { 0x58, 0x02 }, { 0x59, 0xa3 }, { 0x5a, 0x9a }, { 0x5b, 0xcc }, { 0x5c, 0x02 }, { 0x5d, 0xa3 }, { 0x5e, 0x9a }, { 0x5f, 0xcc }, { 0x60, 0x00 }, { 0x61, 0x44 }, { 0x62, 0x32 }, { 0x63, 0x13 }, { 0x64, 0x00 }, { 0x65, 0x00 }, { 0x66, 0x00 }, { 0x67, 0x00 }, { 0x68, 0x00 }, { 0x69, 0x00 }, { 0x6a, 0x00 }, { 0x6b, 0x00 }, { 0x6c, 0xff }, { 0x6d, 0x81 }, { 0x6e, 0x47 }, { 0x6f, 0xae }, { 0x70, 0xf9 }, { 0x71, 0x06 }, { 0x72, 0x21 }, { 0x73, 0xa9 }, { 0x74, 0xfc }, { 0x75, 0xad }, { 0x76, 0x96 }, { 0x77, 0x20 }, { 0x78, 0x00 }, { 0x79, 0x00 }, { 0x7a, 0x00 }, { 0x7b, 0x00 }, { 0x7c, 0x00 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 }, { 0x00, 0x00 }, { 0x7f, 0xaa }, { 0x00, 0x2e }, { 0x40, 0x58 }, { 0x41, 0x3b }, { 0x42, 0x2f }, { 0x43, 0x3d }, { 0x44, 0x58 }, { 0x45, 0x3b }, { 0x46, 0x2f }, { 0x47, 0x3d }, { 0x48, 0x58 }, { 0x49, 0x3b }, { 0x4a, 0x2f }, { 0x4b, 0x3d }, { 0x4c, 0xae }, { 0x4d, 0x1a }, { 0x4e, 0x80 }, { 0x4f, 0x9b }, { 0x50, 0xc2 }, { 0x51, 0xde }, { 0x52, 0x41 }, { 0x53, 0xd5 }, { 0x00, 0x2b }, { 0x20, 0x06 }, { 0x21, 0x55 }, { 0x22, 0xaf }, { 0x23, 0xd8 }, { 0x24, 0xf9 }, { 0x25, 0xaa }, { 0x26, 0x50 }, { 0x27, 0x28 }, { 0x28, 0x06 }, { 0x29, 0x55 }, { 0x2a, 0xaf }, { 0x2b, 0xd8 }, { 0x2c, 0xae }, { 0x2d, 0x1a }, { 0x2e, 0x80 }, { 0x2f, 0x9b }, { 0x30, 0xc2 }, { 0x31, 0xde }, { 0x32, 0x41 }, { 0x33, 0xd5 }, { 0x0c, 0x06 }, { 0x0d, 0x55 }, { 0x0e, 0xaf }, { 0x0f, 0xd8 }, { 0x10, 0xf9 }, { 0x11, 0xaa }, { 0x12, 0x50 }, { 0x13, 0x28 }, { 0x14, 0x06 }, { 0x15, 0x55 }, { 0x16, 0xaf }, { 0x17, 0xd8 }, { 0x18, 0xae }, { 0x19, 0x1a }, { 0x1a, 0x80 }, { 0x1b, 0x9b }, { 0x1c, 0xc2 }, { 0x1d, 0xde }, { 0x1e, 0x41 }, { 0x1f, 0xd5 }, { 0x00, 0x2a }, { 0x34, 0x00 }, { 0x35, 0x15 }, { 0x36, 0xa7 }, { 0x37, 0x04 }, { 0x38, 0x00 }, { 0x39, 0x15 }, { 0x3a, 0xa7 }, { 0x3b, 0x04 }, { 0x3c, 0x00 }, { 0x3d, 0x15 }, { 0x3e, 0xa7 }, { 0x3f, 0x04 }, { 0x40, 0x7b }, { 0x41, 0x43 }, { 0x42, 0x52 }, { 0x43, 0x44 }, { 0x44, 0x89 }, { 0x45, 0x22 }, { 0x46, 0xbf }, { 0x47, 0x66 }, { 0x00, 0x00 }, { 0x7f, 0x8c }, { 0x00, 0x2d }, { 0x30, 0x02 }, { 0x31, 0xa3 }, { 0x32, 0x9a }, { 0x33, 0xcc }, { 0x34, 0x02 }, { 0x35, 0xa3 }, { 0x36, 0x9a }, { 0x37, 0xcc }, { 0x38, 0x00 }, { 0x39, 0x06 }, { 0x3a, 0xd3 }, { 0x3b, 0x72 }, { 0x3c, 0x00 }, { 0x3d, 0x00 }, { 0x3e, 0x00 }, { 0x3f, 0x00 }, { 0x40, 0x00 }, { 0x41, 0x00 }, { 0x42, 0x00 }, { 0x43, 0x00 }, { 0x44, 0xff }, { 0x45, 0x81 }, { 0x46, 0x47 }, { 0x47, 0xae }, { 0x48, 0xf9 }, { 0x49, 0x06 }, { 0x4a, 0x21 }, { 0x4b, 0xa9 }, { 0x4c, 0xfc }, { 0x4d, 0xc2 }, { 0x4e, 0xd8 }, { 0x4f, 0xc5 }, { 0x50, 0x00 }, { 0x51, 0x00 }, { 0x52, 0x00 }, { 0x53, 0x00 }, { 0x54, 0x00 }, { 0x55, 0x00 }, { 0x56, 0x00 }, { 0x57, 0x00 }, { 0x00, 0x00 }, { 0x7f, 0xaa }, { 0x00, 0x2a }, { 0x5c, 0x7b }, { 0x5d, 0x58 }, { 0x5e, 0xf9 }, { 0x5f, 0x48 }, { 0x60, 0x84 }, { 0x61, 0xa7 }, { 0x62, 0x06 }, { 0x63, 0xb8 }, { 0x64, 0x7b }, { 0x65, 0x58 }, { 0x66, 0xf9 }, { 0x67, 0x48 }, { 0x68, 0x7b }, { 0x69, 0x43 }, { 0x6a, 0x52 }, { 0x6b, 0x44 }, { 0x6c, 0x89 }, { 0x6d, 0x22 }, { 0x6e, 0xbf }, { 0x6f, 0x66 }, { 0x70, 0x7b }, { 0x71, 0x58 }, { 0x72, 0xf9 }, { 0x73, 0x48 }, { 0x74, 0x84 }, { 0x75, 0xa7 }, { 0x76, 0x06 }, { 0x77, 0xb8 }, { 0x78, 0x7b }, { 0x79, 0x58 }, { 0x7a, 0xf9 }, { 0x7b, 0x48 }, { 0x7c, 0x7b }, { 0x7d, 0x43 }, { 0x7e, 0x52 }, { 0x7f, 0x44 }, { 0x00, 0x2b }, { 0x08, 0x89 }, { 0x09, 0x22 }, { 0x0a, 0xbf }, { 0x0b, 0x66 }, { 0x00, 0x2e }, { 0x54, 0x58 }, { 0x55, 0x3b }, { 0x56, 0x2f }, { 0x57, 0x3d }, { 0x58, 0x58 }, { 0x59, 0x3b }, { 0x5a, 0x2f }, { 0x5b, 0x3d }, { 0x5c, 0x58 }, { 0x5d, 0x3b }, { 0x5e, 0x2f }, { 0x5f, 0x3d }, { 0x60, 0xae }, { 0x61, 0x1a }, { 0x62, 0x80 }, { 0x63, 0x9b }, { 0x64, 0xc2 }, { 0x65, 0xde }, { 0x66, 0x41 }, { 0x67, 0xd5 }, { 0x00, 0x00 }, { 0x7f, 0x8c }, { 0x00, 0x2e }, { 0x10, 0x00 }, { 0x11, 0x80 }, { 0x12, 0x00 }, { 0x13, 0x00 }, { 0x0c, 0x00 }, { 0x0d, 0x80 }, { 0x0e, 0x00 }, { 0x0f, 0x00 }, { 0x08, 0x00 }, { 0x09, 0x80 }, { 0x0a, 0x00 }, { 0x0b, 0x00 }, { 0x18, 0x00 }, { 0x19, 0x80 }, { 0x1a, 0x00 }, { 0x1b, 0x00 }, { 0x1c, 0x40 }, { 0x1d, 0x00 }, { 0x1e, 0x00 }, { 0x1f, 0x00 }, { 0x20, 0x40 }, { 0x21, 0x00 }, { 0x22, 0x00 }, { 0x23, 0x00 }, //Register Tuning { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x30, 0x00 }, { 0x4c, 0x30 }, { 0x03, 0x03 }, { 0x00, 0x00 }, { 0x7f, 0x00 }, { 0x78, 0x80 }, }; #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/tas5805m/tas5805m_reg_cfg.h
C
apache-2.0
35,533
/* * User Space API wrapper for the "/dev/microsemi_spis_tw" linux kernel driver * if USING_MICROSEMI_LINUX_KERNEL_DRIVER is defined * or else this code is Operating System independent. * A host can use these functions to access the the microsemi Z * L38040/050/051/060/080 Voice Processing devices over a spi interface. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * Microsemi Inc. 2014, Jean Bony */ #include "vprocTwolf_access.h" /*------------------------------------------------------*/ /*TWOLF MACROS-------------------------------*/ #define HBI_PAGED_READ(offset,length) \ ((uint16)(((uint16)(offset) << 8) | (length))) #define HBI_DIRECT_READ(offset,length) \ ((uint16)(0x8000 | ((uint16)(offset) << 8) | (length))) #define HBI_PAGED_WRITE(offset,length) \ ((uint16)(HBI_PAGED_READ(offset,length) | 0x0080)) #define HBI_DIRECT_WRITE(offset,length) \ ((uint16)(HBI_DIRECT_READ(offset,length) | 0x0080)) #define HBI_GLOBAL_DIRECT_WRITE(offset,length) \ ((uint16)(0xFC00 | ((offset) << 4) | (length))) #define HBI_CONFIGURE(pinConfig) \ ((uint16)(0xFD00 | (pinConfig))) #define HBI_SELECT_PAGE(page) \ ((uint16)(0xFE00 | (page))) #define HBI_SELECT_CL_PAGE() \ ((uint16)(0xFE80) #define HBI_CL_BROADCAST \ ((uint16)0xFEFF) #define HBI_NO_OP \ ((uint16)0xFFFF) #ifndef USING_MICROSEMI_LINUX_KERNEL_DRIVER /*TWOLF REGisters*/ #define HOST_CMD_REG 0x0032 /*Host Command register*/ #define HOST_CMD_IDLE 0x0000 /*idle/ operation complete*/ #define HOST_CMD_NO_OP 0x0001 /*no-op*/ #define HOST_CMD_IMG_CFG_LOAD 0x0002 /*load firmware and CR from flash*/ #define HOST_CMD_IMG_LOAD 0x0003 /*load firmware only from flash*/ #define HOST_CMD_IMG_CFG_SAVE 0x0004 /*save a firmware and CR to flash*/ #define HOST_CMD_IMG_CFG_ERASE 0x0005 /*erase a firmware and CR in flash*/ #define HOST_CMD_CFG_LOAD 0x0006 /*Load CR from flash*/ #define HOST_CMD_CFG_SAVE 0x0007 /*save CR to flash*/ #define HOST_CMD_FWR_GO 0x0008 /*start/restart firmware (GO)*/ #define HOST_CMD_HOST_LOAD_CMP 0x000D /*Host Application Load Complete*/ #define HOST_CMD_HOST_FLASH_INIT 0x000B /*Host Application flash discovery*/ #define HOST_CMD_FWR_STOP 0x8000 /*stop firmware */ #define HOST_CMD_CMD_IN_PROGRESS 0xFFFF /*wait command is in progress */ #define PAGE_255_CHKSUM_LO_REG 0x000A #define PAGE_255_CHKSUM_HI_REG 0x0008 #define CLK_STATUS_REG 0x014 /*Clock status register*/ #define PAGE_255_BASE_LO_REG 0x000E #define PAGE_255_BASE_HI_REG 0x000C #define HOST_SW_FLAGS_REG 0x0006 #define HOST_SW_FLAGS_CMD 0x0001 #define HOST_SW_FLAGS_CMD_NORST 0x0004 #define TWOLF_CLK_STATUS_HBI_BOOT 0x0001 #define HBI_CONFIG_REG 0xFD00 #define HBI_CONFIG_ENDIANNESS 0x0000 #define HBI_CONFIG_DIVEMODE 0x0000 #define HBI_CONFIG_WAKE 0x0080 #define HBI_CONFIG_VAL (HBI_CONFIG_ENDIANNESS | \ HBI_CONFIG_DIVEMODE | HBI_CONFIG_WAKE) #define HOST_CMD_PARAM_RESULT_REG 0x034 /*Host Command Param/Result register*/ #endif /*USING_MICROSEMI_LINUX_KERNEL_DRIVER*/ #define TOTAL_FWR_DATA_WORD_PER_LINE 24 #define TOTAL_FWR_DATA_BYTE_PER_LINE 128 #define TWOLF_STATUS_NEED_MORE_DATA 22 #define TWOLF_STATUS_BOOT_COMPLETE 23 #define TWOLF_MBCMDREG_SPINWAIT 10000 #define TWOLF_MAILBOX_SPINWAIT 1000 /*--------------------------------------------------------------------*/ /* VprocTwolfMailboxAcquire(): use this function to * check for the availability of the mailbox * * Input Argument: None * Return: (VprocStatusType) type error code (0 = success, else= fail) */ static VprocStatusType VprocTwolfMailboxAcquire(uint16 flag, uint16 timeout) { VprocStatusType status = VPROC_STATUS_SUCCESS; /*Check whether the host owns the command register*/ uint16 i = 0, temp = 0x0BAD; for (i = 0; i < timeout; i++) { status = VprocTwolfHbiRead(HOST_SW_FLAGS_REG, 1, &temp); if ((status != VPROC_STATUS_SUCCESS)) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } if (!(temp & flag)) {break;} Vproc_msDelay(10); /*wait for reset to complete*/ } DEBUG_LOGD(TAG_SPI, "timeout count = %d: \n", i); if ((i >= timeout) && (temp & flag)) { return VPROC_STATUS_MAILBOX_BUSY; } /*read the Host Command register*/ return VPROC_STATUS_SUCCESS; } /* VprocTwolfcmdRegAcquire(): use this function to * check whether the last command completed sucsesfully * * Input Argument: None * Return: (VprocStatusType) type error code (0 = success, else= fail) */ static VprocStatusType VprocTwolfcmdRegAcquire(uint16 flag, uint16 timeout) { VprocStatusType status = VPROC_STATUS_SUCCESS; /*Check whether the host owns the command register*/ uint16 i = 0, temp = 0x0BAD; for (i = 0; i < timeout; i++) { status = VprocTwolfHbiRead(HOST_CMD_REG, 1, &temp); if ((status != VPROC_STATUS_SUCCESS)) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } if (temp == flag) {break;} Vproc_msDelay(10); /*wait*/ } DEBUG_LOGD(TAG_SPI, "timeout count = %d, cmdReg = 0x%04x: \n", i, temp); if ((i >= timeout) && (temp != flag)) { return VPROC_STATUS_CMDREG_BUSY; } /*read the Host Command register*/ return VPROC_STATUS_SUCCESS; } /* VprocTwolfcmdRegWr(): use this function to * access the host command register * * Input Argument: cmd - the command to send * Return: (VprocStatusType) type error code (0 = success, else= fail) */ static VprocStatusType VprocTwolfcmdRegWr(unsigned short cmd) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short flag = 0x0BAD; /*Check whether the host owns the command register*/ status = VprocTwolfMailboxAcquire(HOST_SW_FLAGS_CMD, TWOLF_MAILBOX_SPINWAIT); if ((status != VPROC_STATUS_SUCCESS)) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } /*write the command into the Host Command register*/ status = VprocTwolfHbiWrite(HOST_CMD_REG, 1, &cmd); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } /*Release the command reg*/ /*read the Host Command register*/ flag = HOST_SW_FLAGS_CMD; status = VprocTwolfHbiWrite(HOST_SW_FLAGS_REG, 1, &flag); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } /*Wait for the command to complete*/ status = VprocTwolfcmdRegAcquire(HOST_CMD_IDLE, TWOLF_MAILBOX_SPINWAIT); if ((status != VPROC_STATUS_SUCCESS)) { DEBUG_LOGE(TAG_SPI, "ERROR %d: CMD_REG - Operation is not complete\n", status); return status; } return VPROC_STATUS_SUCCESS; } static VprocStatusType VprocTwolfCheckCmdResult(void) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short buf; status = VprocTwolfHbiRead(HOST_CMD_PARAM_RESULT_REG, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } if (buf != 0) { DEBUG_LOGE(TAG_SPI, "Command failed...Resultcode = 0x%04x\n", buf); return VPROC_STATUS_ERR_VERIFY; } return VPROC_STATUS_SUCCESS; } /* spis_tw_hbi_rd16()- Decode the 16-bit T-WOLF Regs Host address into * page, offset and build the 16-bit command acordingly to the access type. * then read the 16-bit word data and store it in pdata * \param[in] * .addr the 16-bit HBI address * * return ::status */ static int spis_tw_hbi_rd16(uint16* pdata) { /*perform the HBI access*/ if (VprocHALRead(pdata) != 0) { return VPROC_STATUS_ERR_HBI; } return 0; } /* spis_tw_hbi_wr16_cmd()- this function is used for single word access * It decodes the 16-bit T-WOLF Regs Host address into * page, offset and build the 16-bit command acordingly to the access type. * then write the command to the device * \param[in] * .addr the 16-bit HBI address * * return ::status */ static int spis_tw_hbi_wr16_cmd(uint16 addr, uint8 numwords) { uint16 cmd; int status = 0; uint8 page; uint8 offset; page = addr >> 8; offset = (addr & 0xFF) / 2; if (page == 0) { /*Direct page access*/ cmd = HBI_DIRECT_WRITE(offset, numwords - 1); /*build the cmd*/ } else { /*indirect page access*/ if (page != 0xFF) { page -= 1; } cmd = HBI_SELECT_PAGE(page); /*select the page*/ if (VprocHALWrite(cmd) != 0) { return status; } cmd = HBI_PAGED_WRITE(offset, numwords - 1); /*build the cmd*/ } /*perform the HBI access*/ if (VprocHALWrite(cmd) != 0) { /*write the register address*/ return status; } return 0; } /* spis_tw_hbi_rd16()- Decode the 16-bit T-WOLF Regs Host address into * page, offset and build the 16-bit command acordingly to the access type. * then read the 16-bit word data and store it in pdata * \param[in] * .addr the 16-bit HBI address * * return ::status */ static int spis_tw_hbi_rd16_cmd(uint16 addr, uint8 numwords) { uint16 cmd; int status = 0; uint8 page; uint8 offset; page = addr >> 8; offset = (addr & 0xFF) / 2; if (page == 0) { /*Direct page access*/ cmd = HBI_DIRECT_READ(offset, numwords - 1); /*build the cmd*/ } else { /*Indirect page access*/ if (page != 0xFF) { page -= 1; } cmd = HBI_SELECT_PAGE(page); /*select the page*/ if (VprocHALWrite(cmd) != 0) { return status; } cmd = HBI_PAGED_READ(offset, numwords - 1); /*build the cmd*/ } /*perform the HBI access*/ if (VprocHALWrite(cmd) != 0) { /*write the register address*/ return status; } return 0; } /* spis_tw_hbi_wr16()- this function is used for single word access by the * ioctl read. It decodes the 16-bit T-WOLF Regs Host address into * page, offset and build the 16-bit command acordingly to the access type. * then write the command and data to the device * \param[in] * .addr the 16-bit HBI address * * return ::status */ static int spis_tw_hbi_wr16_data(uint16 data) { if (VprocHALWrite(data) != 0) { return VPROC_STATUS_ERR_HBI; } return 0; } /****************************************************************************** * TwolfPagedWrite() * This function selects the specified page, writes the number of specified * words, starting at the specified offset from a source buffer. * * \param[in] page Page to select * \param[in] offset Offset of the requested Page to read from * \param[in] numWords Number of words to read starting from the offset * \param[in] pSrc Pointer to the date to write * * \retval ::VP_STATUS_SUCCESS * \retval ::VP_STATUS_ERR_HBI ******************************************************************************/ static VprocStatusType TwolfHbiPage255Write( unsigned char page, unsigned char offset, unsigned char numWords, unsigned short* pDdata) { uint16 cmdWrd = (uint16)(page << 8) | (uint16)offset; if (VprocTwolfHbiWrite(cmdWrd, numWords, pDdata) != VPROC_STATUS_SUCCESS) { return VPROC_STATUS_ERR_HBI; } return VPROC_STATUS_SUCCESS; } /* TwolfHbiPagedWrite() */ /*------------------------------------------------------ * Higher level functions - Can be called by a host application *------------------------------------------------------*/ /*VprocTwolfHbiInit - use this function to initialize the device HBI * This function can be called at startup during the system init * Configure the HBI_CONFIG_VAL as per the host system. But default * config is good for most cases. See HBI section in device datasheet for * details * * \retval ::VPROC_STATUS_SUCCESS * \retval ::VPROC_STATUS_ERR_HBI */ VprocStatusType VprocTwolfHbiInit(void) { unsigned short buf = HBI_CONFIG_REG | HBI_CONFIG_VAL; if (VprocHALInit() != 0) { return VPROC_STATUS_INIT_FAILED; } return VprocHALWrite(buf); } /*VprocTwolfHbiCleanup - To close any open communication path to * to the device * * \retval ::VPROC_STATUS_SUCCESS * \retval ::VPROC_STATUS_ERR_HBI */ VprocStatusType VprocTwolfHbiCleanup(void) { VprocHALcleanup(); return VPROC_STATUS_SUCCESS; } /*VprocTwolfHbiRead - use this function to read up to 254 words from the device * \param[in] cmd of the requested device register to read from * \param[in] numWords Number of words to read starting from the offset * \param[in] pData Pointer to the data read * * \retval ::VPROC_STATUS_SUCCESS * \retval ::VPROC_STATUS_ERR_HBI */ VprocStatusType VprocTwolfHbiRead( unsigned short cmd, /*register to read from*/ unsigned char numwords, unsigned short* pData) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short tempBuf = 0x0BAD; unsigned char i = 0; // DEBUG_LOGE(TAG_SPI, "cmd = 0x%04x\n", cmd); status = spis_tw_hbi_rd16_cmd(cmd, numwords); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR: VPROC_STATUS_RD_FAILED,CMD:0x%04x\n", cmd); return VPROC_STATUS_WR_FAILED; } for (i = 0; i < numwords; i++) { status = spis_tw_hbi_rd16(&tempBuf); pData[i] = tempBuf; // DEBUG_LOGE(TAG_SPI, "pData[%d] = 0x%04x\n", i, pData[i]); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR: VPROC_STATUS_RD_FAILED,CMD:0x%04x\n", cmd); return VPROC_STATUS_RD_FAILED; } } return status; } /*VprocTwolfHbiWrite - use this function to write up to 252 words to the device * \param[in] cmd of the requested device register to write to * \param[in] numWords Number of words to write starting from the offset * \param[in] pData Pointer to the data to write * * \retval ::VPROC_STATUS_SUCCESS * \retval ::VPROC_STATUS_ERR_HBI */ VprocStatusType VprocTwolfHbiWrite( unsigned short cmd, /*register to read from*/ unsigned char numwords, unsigned short* pData) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned char i = 0; if ((numwords == 0) || (numwords > 126)) { DEBUG_LOGE(TAG_SPI, "number of words is out of range. Maximum is 126\n"); return VPROC_STATUS_INVALID_ARG; } /*16-bit SPI access mode - Send only 1 word within the same CS*/ status = spis_tw_hbi_wr16_cmd(cmd, numwords); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR: VPROC_STATUS_WR_FAILED\n"); return VPROC_STATUS_WR_FAILED; } for (i = 0; i < numwords; i++) { status = spis_tw_hbi_wr16_data(pData[i]); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR: VPROC_STATUS_WR_FAILED\n"); return VPROC_STATUS_WR_FAILED; } } return VPROC_STATUS_SUCCESS; } /*VprocTwolfLoadConfig() - use this function to load a custom or new config * record into the device RAM to override the default config * \retval ::VPROC_STATUS_SUCCESS * \retval ::VPROC_STATUS_ERR_HBI */ VprocStatusType VprocTwolfLoadConfig(dataArr* pCr2Buf, unsigned short numElements) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short i, buf; /*stop the current firmware but do not reset the device and do not go to boot mode*/ /*send the config to the device RAM*/ for (i = 0; i < numElements; i++) { buf = pCr2Buf[i].value; status = VprocTwolfHbiWrite(pCr2Buf[i].reg, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { return VPROC_STATUS_ERR_HBI; } } return status; } /* HbiSrecBoot_alt() Use this alternate method to load the st_twFirmware.c *(converted *.s3 to c code) to the device */ static VprocStatusType HbiSrecBoot_alt(twFirmware* st_firmware) { uint16 index = 0; uint16 gTargetAddr[2] = {0, 0}; VprocStatusType status = VPROC_STATUS_SUCCESS; while (index < st_firmware->twFirmwareStreamLen) { /* put the address into our global target addr */ gTargetAddr[0] = (uint16)((st_firmware->st_Fwr[index].targetAddr & 0xFFFF0000) >> 16); gTargetAddr[1] = (uint16)(st_firmware->st_Fwr[index].targetAddr & 0x0000FFFF); //DEBUG_LOGE(TAG_SPI, "gTargetAddr[0] = 0x%04x, gTargetAddr[1] = 0x%04x: \n", // gTargetAddr[0], gTargetAddr[1]); //DEBUG_LOGE(TAG_SPI, "numWords = %d: \n", // st_firmware->st_Fwr[index].numWords); /* write the data to the device */ if (st_firmware->st_Fwr[index].numWords != 0) { if (st_firmware->st_Fwr[index].useTargetAddr) { status = VprocTwolfHbiWrite(PAGE_255_BASE_HI_REG, 2, gTargetAddr); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Unable to set gTargetAddr[0] = 0x%04x," " gTargetAddr[1] = 0x%04x: \n", gTargetAddr[0], gTargetAddr[1]); return VPROC_STATUS_ERR_HBI; } } status = TwolfHbiPage255Write(0xFF, (uint8)((gTargetAddr[1] & 0x00FF)), st_firmware->st_Fwr[index].numWords, st_firmware->st_Fwr[index].buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "status = %d, numWords = %d: \n", status, st_firmware->st_Fwr[index].numWords); return status; } } // DEBUG_LOGE(TAG_SPI, "index %d\n", index); if (index == 9) { // break; } index++; } /* * convert the number of bytes to two 16 bit * values and write them to the requested page register */ /* even number of bytes required */ /* program the program's execution start register */ gTargetAddr[0] = (uint16)((st_firmware->execAddr & 0xFFFF0000) >> 16); gTargetAddr[1] = (uint16)(st_firmware->execAddr & 0x0000FFFF); status = VprocTwolfHbiWrite(0x12C, 2, gTargetAddr); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, " unable to program page 1 execution address\n"); return status; } /* print out the srecord program info */ DEBUG_LOGI(TAG_SPI, "prgmBase 0x%08x\n", st_firmware->prgmBase); DEBUG_LOGI(TAG_SPI, "execAddr 0x%08x\n", st_firmware->execAddr); DEBUG_LOGI(TAG_SPI, "DONE\n"); return VPROC_STATUS_SUCCESS; } /*VprocTwolfHbiBoot_alt - use this function to bootload the firmware * into the device * \param[in] pointer to image data structure * * \retval ::VPROC_STATUS_SUCCESS * \retval ::VPROC_STATUS_ERR_HBI * \retval ::VPROC_STATUS_MAILBOX_BUSY */ VprocStatusType VprocTwolfHbiBoot_alt(twFirmware* st_firmware) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short buf[2] = {0, 0}; /* write a value of 1 to address 0x14 (direct page offset 0x0A). * to stop current firmware, reset the device into the Boot Rom mode. */ buf[0] = 1;//TWOLF_CLK_STATUS_HBI_BOOT; status = VprocTwolfHbiWrite(CLK_STATUS_REG, 1, buf); if (status != VPROC_STATUS_SUCCESS) { return VPROC_STATUS_ERR_HBI; } Vproc_msDelay(300); /*wait for reset to complete*/ buf[0] = buf[1] = 0; status = VprocTwolfHbiRead(HOST_CMD_PARAM_RESULT_REG, 1, buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } /*Check if the device is accessible for command*/ if ((buf[0] != 0xD3D3)) { DEBUG_LOGE(TAG_SPI, "ERROR: HBI is not accessible\n"); return VPROC_STATUS_ERR_HBI; } /*Transfer the image*/ status = HbiSrecBoot_alt(st_firmware); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } /*tell Twolf that the firmware loading is complete*/ buf[0] = HOST_CMD_HOST_LOAD_CMP; status = VprocTwolfcmdRegWr(buf[0]); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } /*Verify whether the boot loading is successful*/ if (VprocTwolfCheckCmdResult() != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR: Failed to load the Firmware...\n"); return VPROC_STATUS_FW_LOAD_FAILED; } return VPROC_STATUS_SUCCESS; } /*The following 3 functions provide a mean to loading the *.s3 firmare into * the device * - Call sequence: * 1- Call VprocTwolfHbiBootPrepare() * 2- Call VprocTwolfHbiBootMoreData() in a loop by passing one line at a time * from the *.S3 image file until the whole file is transferred * to the device. or until a TWOLF_STATUS_BOOT_COMPLETE status * is reported * 3- Call VprocTwolfHbiBootConclude() once the whole data is transferred suc- * cessfully */ VprocStatusType VprocTwolfHbiBootPrepare(void) { unsigned short buf[2] = {0, 0}; VprocStatusType status = VPROC_STATUS_SUCCESS; /* write a value of 1 to address 0x14 (direct page offset 0x0A). * to stop current firmware, reset the device into the Boot Rom mode. */ buf[0] = 1;//TWOLF_CLK_STATUS_HBI_BOOT; status = VprocTwolfHbiWrite(CLK_STATUS_REG, 1, buf); if (status != VPROC_STATUS_SUCCESS) { return VPROC_STATUS_ERR_HBI; } Vproc_msDelay(300); /*wait for reset to complete*/ buf[0] = buf[1] = 0; status = VprocTwolfHbiRead(HOST_CMD_PARAM_RESULT_REG, 1, buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } /*Check if the device is accessible for command*/ if ((buf[0] != 0xD3D3)) { DEBUG_LOGE(TAG_SPI, "ERROR: HBI is not accessible\n"); return VPROC_STATUS_ERR_HBI; } return status; } /*AsciiHexToHex() - to convert ascii char hex to integer hex * pram[in] - str - pointer to the char to convert. * pram[in] - len - the number of character to convert (2:u8, 4:u16, 8:u32). */ static unsigned int AsciiHexToHex(const char* str, unsigned char len) { unsigned int val = 0; char c; unsigned char i = 0; for (i = 0; i < len; i++) { c = *str++; val <<= 4; if (c >= '0' && c <= '9') { val += c & 0x0F; continue; } c &= 0xDF; if (c >= 'A' && c <= 'F') { val += (c & 0x07) + 9; continue; } return 0; } return val; } static int spisTwBootWrite(char* blockOfFwrData) /*0: HBI; 1:FLASH*/ { /*Use this method to load the actual *.s3 file line by line*/ int status = 0; int rec_type, i = 0, j = 0; uint8 numbytesPerLine = 0; uint8 numdataWordPerLine = 0; uint16 dataBuf[64]; unsigned long address = 0; uint8 page255Offset = 0x00; uint16 cmd = 0; uint16 gTargetAddr[2] = {0, 0}; DEBUG_LOGI(TAG_SPI, "blockOfFwrData = %s\n", blockOfFwrData); if (blockOfFwrData == NULL) { DEBUG_LOGE(TAG_SPI, "blockOfFwrData[0] = %c\n", blockOfFwrData[0]); return VPROC_STATUS_INVALID_ARG; } /* if this line is not an srecord skip it */ if (blockOfFwrData[0] != 'S') { DEBUG_LOGE(TAG_SPI, "blockOfFwrData[0] = %c\n", blockOfFwrData[0]); return VPROC_STATUS_INVALID_ARG; } numbytesPerLine = AsciiHexToHex(&blockOfFwrData[2], 2); numdataWordPerLine = (numbytesPerLine - 5) / 2; DEBUG_LOGI(TAG_SPI, "numbytesPerLine = %d\n", numbytesPerLine); if (numbytesPerLine == 0) { DEBUG_LOGE(TAG_SPI, "blockOfFwrData[3] = %c\n", blockOfFwrData[3]); return VPROC_STATUS_INVALID_ARG; } /* get the srecord type */ rec_type = blockOfFwrData[1] - '0'; /* skip non-existent srecord types and block header */ if ((rec_type == 4) || (rec_type == 5) || (rec_type == 6) || (rec_type == 0)) { return TWOLF_STATUS_NEED_MORE_DATA; } /* get the info based on srecord type (skip checksum) */ address = AsciiHexToHex(&blockOfFwrData[4], 8); page255Offset = (uint8)(address & 0xFF); gTargetAddr[0] = (uint16)((address & 0xFFFF0000) >> 16); gTargetAddr[1] = (uint16)(address & 0x0000FFFF); /* store the execution address */ if ((rec_type == 7) || (rec_type == 8) || (rec_type == 9)) { /* the address is the execution address for the program */ DEBUG_LOGI(TAG_SPI, "execAddr = 0x%08lx\n", address); /* program the program's execution start register */ //status = spis_tw_hbi_multi_wr8(0x012C, 4, buf); status = VprocTwolfHbiWrite(0x12C, 2, gTargetAddr); if (status != 0) { DEBUG_LOGE(TAG_SPI, " unable to program page 1 execution address\n"); return status; } DEBUG_LOGI(TAG_SPI, "Loading firmware data complete...\n"); return TWOLF_STATUS_BOOT_COMPLETE; /*BOOT_COMPLETE Sucessfully*/ } /* put the address into our global target addr */ //DEBUG_LOGE(TAG_SPI, "gTargetAddr = 0x%08lx: \n", address); status = VprocTwolfHbiWrite(PAGE_255_BASE_HI_REG, 2, gTargetAddr); //status = spis_tw_hbi_multi_wr8(PAGE_255_BASE_HI_REG, 4, buf); if (status != 0) { DEBUG_LOGE(TAG_SPI, "gTargetAddr = 0x%08lx: \n", address); return VPROC_STATUS_FW_LOAD_FAILED; } /* get the data bytes */ j = 12; DEBUG_LOGI(TAG_SPI, "dataBuf[]=\n"); for (i = 0; i < numdataWordPerLine; i++) { dataBuf[i] = AsciiHexToHex(&blockOfFwrData[j], 4); j += 4; DEBUG_LOGI(TAG_SPI, "0x%04x, ", dataBuf[i]); } /* write the data to the device */ cmd = (uint16)(0xFF << 8) | (uint16)page255Offset; status = VprocTwolfHbiWrite(cmd, numdataWordPerLine, dataBuf); if (status != 0) { return status; } DEBUG_LOGI(TAG_SPI, "Provide next block of data...\n"); return TWOLF_STATUS_NEED_MORE_DATA; /*REQUEST STATUS_MORE_DATA*/ } VprocStatusType VprocTwolfHbiBootMoreData(char* dataBlock) { // return ioctl(twolf_fd, TWOLF_BOOT_SEND_MORE_DATA, dataBlock); return spisTwBootWrite(dataBlock); } VprocStatusType VprocTwolfHbiBootConclude(void) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short buf; /*tell Twolf that the firmware loading is complete*/ buf = HOST_CMD_HOST_LOAD_CMP; status = VprocTwolfcmdRegWr(buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } /*Verify whether the boot loading is successful*/ if (VprocTwolfCheckCmdResult() != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR: Failed to load the Firmware...\n"); return VPROC_STATUS_FW_LOAD_FAILED; } return status; //return status; } /*USe this function to erase a slave flash device controlled by the Twolf*/ VprocStatusType VprocTwolfEraseFlash(void) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short buf; /*Save firmware to flash*/ status = VprocTwolfReset(VPROC_RST_HARDWARE_RAM); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } buf = HOST_CMD_HOST_FLASH_INIT; /*if there is a flash on board initialize it*/ status = VprocTwolfcmdRegWr(buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } buf = 0xAA55; status = VprocTwolfHbiWrite(HOST_CMD_PARAM_RESULT_REG, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Unable to set command reg = 0x%04x: \n", buf); return VPROC_STATUS_ERR_HBI; } buf = 0x0009; /*delete all applications on flash*/ status = VprocTwolfcmdRegWr(buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } return VPROC_STATUS_SUCCESS; } /* VprocTwolfReset(): use this function to reset the device. * * * Input Argument: mode - the reset mode (VPROC_RST_HARDWARE_ROM, * VPROC_RST_HARDWARE_ROM, VPROC_RST_SOFT, VPROC_RST_AEC) * Return: (VprocStatusType) type error code (0 = success, else= fail) */ VprocStatusType VprocTwolfReset(VprocResetMode mode) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short buf; /*PLATFORM SPECIFIC code*/ if (mode == VPROC_RST_HARDWARE_RAM) { /*hard reset*/ /*hard reset*/ buf = 0x05; status = VprocTwolfHbiWrite(0x014, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } } else if (mode == VPROC_RST_HARDWARE_ROM) { /*power on reset*/ /*hard reset*/ buf = 0x09; status = VprocTwolfHbiWrite(0x014, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } } else if (mode == VPROC_RST_AEC) { /*AEC method*/ buf = 0x01; status = VprocTwolfHbiWrite(0x0300, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } } else if (mode == VPROC_RST_SOFTWARE) { /*soft reset*/ buf = 0x02; status = VprocTwolfHbiWrite(0x006, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } } else { DEBUG_LOGE(TAG_SPI, "Invalid reset type\n"); return VPROC_STATUS_INVALID_ARG; } Vproc_msDelay(200); return VPROC_STATUS_SUCCESS; } VprocStatusType VprocTwolfSetVolume(uint8 vol) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short buf = vol; // Gain A buf += (unsigned short )vol << 8; // Gain B VprocHALInit(); status = VprocTwolfHbiWrite(0x238, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } status = VprocTwolfHbiWrite(0x23A, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } return status; } VprocStatusType VprocTwolfGetVolume(int8_t* vol) { VprocStatusType status = VPROC_STATUS_SUCCESS; unsigned short buf = 0; VprocHALInit(); status = VprocTwolfHbiRead(0x238, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } *vol = (int8_t)buf; return status; } VprocStatusType VprocTwolfGetAppStatus(uint16 *status) { VprocStatusType ret = VPROC_STATUS_SUCCESS; unsigned short buf = 0; VprocHALInit(); ret = VprocTwolfHbiRead(0x030, 1, &buf); if (ret != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", ret); return ret; } *status = buf & 0x0F; return ret; } /* VprocTwolfSaveImgToFlash(): use this function to * save both the config record and the firmware to flash. It Sets the bit * which initiates a firmware save to flash when the device * moves from a STOPPED state to a RUNNING state (by using the GO bit) * * Input Argument: None * Return: (VprocStatusType) type error code (0 = success, else= fail) */ /* VprocTwolfSaveImgToFlash(): use this function to * save both the config record and the firmware to flash. It Sets the bit * which initiates a firmware save to flash when the device * moves from a STOPPED state to a RUNNING state (by using the GO bit) * * Input Argument: None * Return: (VprocStatusType) type error code (0 = success, else= fail) */ VprocStatusType VprocTwolfSaveImgToFlash(void) { unsigned short buf; VprocStatusType status = VPROC_STATUS_SUCCESS; /*Save firmware to flash*/ buf = HOST_CMD_HOST_FLASH_INIT; /*if there is a flash on board initialize it*/ status = VprocTwolfcmdRegWr(buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } buf = 0xAA55; status = VprocTwolfHbiWrite(HOST_CMD_PARAM_RESULT_REG, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Unable to set command reg = 0x%04x: \n", buf); return VPROC_STATUS_ERR_HBI; } buf = 0x0009; /*delete all applications on flash*/ status = VprocTwolfcmdRegWr(buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } buf = HOST_CMD_IMG_CFG_SAVE; /*save the image to flash*/ status = VprocTwolfcmdRegWr(buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Save firmware to flash failed... reg = 0x%04x: \n", buf); return VPROC_STATUS_ERR_HBI; } /*check whethe the actions above were performed successfully*/ return VprocTwolfCheckCmdResult(); } /* VprocTwolfSaveCfgToFlash(): use this function to * save the config record to flash. It Sets the bit * which initiates a config save to flash when the device * moves from a STOPPED state to a RUNNING state (by using the GO bit) * * Input Argument: None * Return: (VprocStatusType) type error code (0 = success, else= fail) * The firmware must be stopped first with VprocTwolfFirmwareStop() */ VprocStatusType VprocTwolfSaveCfgToFlash(void) { unsigned short buf; VprocStatusType status = VPROC_STATUS_SUCCESS; /*Save firmware to flash*/ /*if there is a flash on board initialize it*/ /* Clear the checksum register so that the fimrware can calculate a new chk value * If this register is not cleared first, then an invalid checksum will be calculated * which will cause this procedure to fail */ buf = HOST_CMD_HOST_FLASH_INIT; /*if there is a flash on the board initialize it*/ status = VprocTwolfcmdRegWr(buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } /*Check if there is a flash device and an image already saved to it - load it to RAM*/ status = VprocTwolfHbiRead(0x026, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } if ((buf > 0)) { /*load the corresponding image/cr from flash*/ buf = 0x0001; status = VprocTwolfHbiWrite(HOST_CMD_PARAM_RESULT_REG, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Unable to set command reg = 0x%04x: \n", buf); return VPROC_STATUS_ERR_HBI; } buf = 0x8002; status = VprocTwolfHbiWrite(HOST_CMD_REG, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Unable to set command reg = 0x%04x: \n", buf); return VPROC_STATUS_ERR_HBI; } /*Release the command reg*/ /*read the Host Command register*/ buf = 0x0004; status = VprocTwolfHbiWrite(HOST_SW_FLAGS_REG, 1, &buf); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "ERROR %d: \n", status); return status; } status = VprocTwolfcmdRegAcquire(HOST_CMD_IDLE, TWOLF_MAILBOX_SPINWAIT); if ((status != VPROC_STATUS_SUCCESS)) { DEBUG_LOGE(TAG_SPI, "ERROR %d: CMD_REG - Operation is not complete\n", status); return status; } /*Verify wheter the operation completed sucessfully*/ status = VprocTwolfCheckCmdResult(); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Error %d: Unable to verify result-param: \n", status); return status; } } return VPROC_STATUS_SUCCESS; } /*VprocTwolfFirmwareStart - use this function to start/restart the firmware * previously stopped with VprocTwolfFirmwareStop() * \param[in] none * * \retval ::VPROC_STATUS_SUCCESS * \retval ::VPROC_STATUS_ERR_HBI */ VprocStatusType VprocTwolfFirmwareStart(void) { unsigned short buf; /*Start firmware*/ buf = HOST_CMD_FWR_GO; return VprocTwolfcmdRegWr(buf); } /*VprocTwolfFirmwareStop - use this function to stop the firmware currently running * And set the device in boot mode * \param[in] none * * \retval ::VPROC_STATUS_SUCCESS * \retval ::VPROC_STATUS_ERR_HBI */ VprocStatusType VprocTwolfFirmwareStop(void) { unsigned short buf; /*Stop firmware*/ buf = HOST_CMD_FWR_STOP; return VprocTwolfcmdRegWr(buf); }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/api_lib/vprocTwolf_access.c
C
apache-2.0
38,239
/**************************************************************************** * Microsemi Semiconductor, Kanata, ON **************************************************************************** * * Description: Voice Processor devices high level access module function * definitions * * NOTE: The registers of the device are 16-bit wide. A 32-bit access * is not required. However, the 32-bit access functions are provided * only if the host wants to access two consecutives 16-bit registers * in one single access. * Author: Jean Bony **************************************************************************** * Copyright Microsemi Semiconductor Ltd., 2013. All rights reserved. This * copyrighted work constitutes an unpublished work created in 2013. The use * of the copyright notice is intended to provide notice that Microsemi * Semiconductor Ltd. owns a copyright in this unpublished work; the main * copyright notice is not an admission that publication has occurred. This * work contains confidential, proprietary information and trade secrets of * Microsemi Semiconductor Ltd.; it may not be used, reproduced or transmitted, * in whole or in part, in any form or by any means without the prior * written permission of Microsemi Semiconductor Ltd. This work is provided on * a right to use basis subject to additional restrictions set out in the * applicable license or other agreement. * ***************************************************************************/ #ifndef VPROC_TWOLFACCESS_H #define VPROC_TWOLFACCESS_H #include "vproc_common.h" #ifdef __cplusplus extern "C" { #endif #define TWOLF_MAILBOX_SPINWAIT 1000 /*at least a 1000 to avoid mailbox busy */ /*device HBI command structure*/ typedef struct hbiCmdInfo { unsigned char page; unsigned char offset; unsigned char numwords; } hbiCmdInfo; /* external function prototypes */ VprocStatusType VprocTwolfHbiInit(void); /*Use this function to initialize the HBI bus*/ VprocStatusType VprocTwolfHbiRead( unsigned short cmd, /*the 16-bit register to read from*/ unsigned char numwords, /* The number of 16-bit words to read*/ unsigned short *pData); /* Pointer to the read data buffer*/ VprocStatusType VprocTwolfHbiWrite( unsigned short cmd, /*the 16-bit register to write to*/ unsigned char numwords, /* The number of 16-bit words to write*/ unsigned short *pData); /*the words (0-255) to write*/ VprocStatusType TwolfHbiNoOp( /*send no-op command to the device*/ unsigned char numWords); /* The number of no-op (0-255) to write*/ /*An alternative method to loading the firmware into the device * USe this method if you have used the provided tool to convert the *.s3 into * c code that can be compiled with the application */ VprocStatusType VprocTwolfHbiBoot_alt( /*use this function to boot load the firmware (*.c) from the host to the device RAM*/ twFirmware *st_firmware); /*Pointer to the firmware image in host RAM*/ VprocStatusType VprocTwolfLoadConfig(dataArr *pCr2Buf, unsigned short numElements); VprocStatusType VprocTwolfHbiCleanup(void); VprocStatusType VprocTwolfHbiBootPrepare(void); VprocStatusType VprocTwolfHbiBootMoreData(char *dataBlock); VprocStatusType VprocTwolfHbiBootConclude(void); VprocStatusType VprocTwolfFirmwareStop(void); /*Use this function to halt the currently running firmware*/ VprocStatusType VprocTwolfFirmwareStart(void); /*Use this function to start/restart the firmware currently in RAM*/ VprocStatusType VprocTwolfSaveImgToFlash(void); /*Save current loaded firmware from device RAM to FLASH*/ VprocStatusType VprocTwolfSaveCfgToFlash(void); /*Save current device config from device RAM to FLASH*/ VprocStatusType VprocTwolfReset(VprocResetMode mode); VprocStatusType VprocTwolfEraseFlash(void); VprocStatusType VprocTwolfLoadFwrCfgFromFlash(uint16 image_number); VprocStatusType VprocTwolfSetVolume(uint8 vol); VprocStatusType VprocTwolfGetVolume(int8_t *vol); VprocStatusType VprocTwolfGetAppStatus(uint16 *status); #ifdef __cplusplus } #endif #endif /* VPROCTWOLFACCESS_H */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/api_lib/vprocTwolf_access.h
C
apache-2.0
4,200
/**************************************************************************** * vproc_common.c - Hal functions for the VPROC API * * **************************************************************************** * Copyright Microsemi Inc, 2018. All rights reserved. * Licensed under the MIT License. See LICENSE.txt in the project * root for license information. * ***************************************************************************/ #include "vproc_common.h" #include <stdio.h> #include "driver/spi_master.h" #include "soc/gpio_struct.h" #include "driver/gpio.h" #include "mbedtls/net.h" #include "lwip/def.h" #include "board.h" #include "audio_idf_version.h" static spi_device_handle_t g_spi = NULL; int VprocHALInit(void) { /*if the customer platform requires any init * then implement such init here. * Otherwise the implementation of this function is complete */ esp_err_t ret = ESP_OK; spi_bus_config_t buscfg = {0}; spi_device_interface_config_t devcfg = { .clock_speed_hz = 1000000, // Clock out at 10 MHz .mode = 0, // SPI mode 0 .queue_size = 6, //queue 7 transactions at a time }; get_spi_pins(&buscfg, &devcfg); //Initialize the SPI bus if (g_spi) { return ret; } #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 0, 0)) ret = spi_bus_initialize(HSPI_HOST, &buscfg, 0); assert(ret == ESP_OK); ret = spi_bus_add_device(HSPI_HOST, &devcfg, &g_spi); #else ret = spi_bus_initialize(SPI3_HOST, &buscfg, 0); assert(ret == ESP_OK); ret = spi_bus_add_device(SPI3_HOST, &devcfg, &g_spi); #endif assert(ret == ESP_OK); gpio_set_pull_mode(0, GPIO_FLOATING); return ret; } /*HAL clean up function - To close any open file connection * microsemi_spis_tw kernel char driver * * return: a positive integer value for success, a negative integer value for failure */ void VprocHALcleanup(void) { /*if the customer platform requires any cleanup function * then implement such function here. * Otherwise the implementation of this function is complete */ int ret = 0; ret = spi_bus_remove_device(g_spi); assert(ret == ESP_OK); #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 0, 0)) ret = spi_bus_free(HSPI_HOST); #else ret = spi_bus_free(SPI3_HOST); #endif assert(ret == ESP_OK); } /*Note - These functions are PLATFORM SPECIFIC- They must be modified * accordingly **********************************************************************/ /* Vproc_msDelay(): use this function to * force a delay of specified time in resolution of milli-second * * Input Argument: time in unsigned 16-bit * Return: none */ void Vproc_msDelay(unsigned short time) { ets_delay_us(time * 1000); } /* VprocWait(): use this function to * force a delay of specified time in resolution of 125 micro-Seconds * * Input Argument: time in unsigned 32-bit * Return: none */ void VprocWait(unsigned long int time) { ets_delay_us(time * 1000); } #define BIGENDIAN 1 /* This is the platform dependent low level spi * function to write 16-bit data to the ZL380xx device */ int VprocHALWrite(unsigned short val) { /*Note: Implement this as per your platform*/ esp_err_t ret; spi_transaction_t t; unsigned short data = 0; memset(&t, 0, sizeof(t)); //Zero out the transaction t.length = sizeof(unsigned short) * 8; //Len is in bytes, transaction length is in bits. #if BIGENDIAN data = htons(val); t.tx_buffer = &data; //Data #else t.tx_buffer = &val; #endif ret = spi_device_transmit(g_spi, &t); //Transmit assert(ret == ESP_OK); return 0; } /* This is the platform dependent low level spi * function to read 16-bit data from the ZL380xx device */ int VprocHALRead(unsigned short *pVal) { /*Note: Implement this as per your platform*/ esp_err_t ret; spi_transaction_t t; unsigned short data = 0; memset(&t, 0, sizeof(t)); //Zero out the transaction t.length = sizeof(unsigned short) * 8; t.rxlength = sizeof(unsigned short) * 8; //The unit of len is byte, and the unit of length is bit. t.rx_buffer = &data; ret = spi_device_transmit(g_spi, &t); //Transmit! #if BIGENDIAN *pVal = ntohs(data); #else *pVal = data; #endif assert(ret == ESP_OK); return 0; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/api_lib/vproc_common.c
C
apache-2.0
4,584
/**************************************************************************** * vproc_common.h - Hal functions prototypes, macros and variables for the VPROC API * * **************************************************************************** * Copyright Microsemi Inc, 2018. All rights reserved. * Licensed under the MIT License. See LICENSE.txt in the project * root for license information. * ***************************************************************************/ #ifndef VPROC_COMMON_H #define VPROC_COMMON_H #include <string.h> #include <stdio.h> #include <stdlib.h> #include "esp_log.h" #ifdef __cplusplus extern "C" { #endif #define DEBUG_LOGD ESP_LOGD #define DEBUG_LOGE ESP_LOGE #define DEBUG_LOGI ESP_LOGI /*This header includes some platform dependent data types*/ #include "vproc_data_types.h" //#define RETRY_COUNT 100 #define VPROC_TIMEOUT 500 #define TAG_SPI "SPI" /* external defines */ #undef VPROC_DEBUG /*create a 16-bit word out of two bytes*/ #define MAKE16(a, b) (unsigned short)(((unsigned short)(b) << 8) | \ (unsigned short)(a)) /*create a 32-bit word out of 4 bytes*/ #define MAKE32(a, b, c, d) (unsigned long)(((unsigned long)d << 24) | ((unsigned long)c << 16) | ((unsigned long)b << 8) | ((unsigned long)a)) /* * debug - print the function name and line number for the source of the error * the line number count start at 1 and not 0 */ /* *Define this macro to report mode debug info */ #undef VPROC_API_DBG_INFO #ifdef VPROC_API_DBG_INFO #define VPROG_DBG_INFO(s, args...) \ printf(""s, ##args); #else #define VPROG_DBG_INFO(s, args...) #endif #define VPROC_API_DBG_ERROR #ifdef VPROC_API_DBG_ERROR #define VPROG_DBG_ERROR(s, args...) \ printf("---%s %d: "s, __func__, __LINE__, ##args); #else #define VPROG_DBG_ERROR(s, args...) #endif /*unsigned char deviceType;*/ /*device/access Status codes*/ typedef enum VprocStatusType { VPROC_STATUS_SUCCESS = 0, VPROC_STATUS_FAILURE, VPROC_STATUS_INIT_FAILED, VPROC_STATUS_WR_FAILED, VPROC_STATUS_RD_FAILED, VPROC_STATUS_FW_LOAD_FAILED, VPROC_STATUS_CFG_LOAD_FAILED, VPROC_STATUS_CLOSE_FAILED, VPROC_STATUS_FW_SAVE_FAILED, VPROC_STATUS_GFG_SAVE_FAILED, VPROC_STATUS_MAU_NOT_READY, VPROC_STATUS_CHK_FAILED, VPROC_STATUS_FUNC_NOT_SUPPORTED, VPROC_STATUS_INVALID_ARG, VPROC_STATUS_ERR_VTD_CODE, VPROC_STATUS_ERR_VERIFY, VPROC_STATUS_DEVICE_BUSY, VPROC_STATUS_ERR_HBI, VPROC_STATUS_ERR_IMAGE, VPROC_STATUS_MAILBOX_BUSY, VPROC_STATUS_CMDREG_BUSY, VPROC_STATUS_IN_CRTCL_SECTN, VPROC_STATUS_BOOT_LOADING_MORE_DATA, VPROC_STATUS_BOOT_LOADING_CMP, VPROC_STATUS_DEV_NOT_INITIALIZED, } VprocStatusType; /* Device Reset modes*/ typedef enum VprocResetMode { VPROC_RST_HARDWARE_ROM = 0, /*hardware reset -reset the device and reload the firmware from flash*/ VPROC_RST_HARDWARE_RAM = 1, /*hardware reset -reset the device and reload the firmware from RAM*/ VPROC_RST_SOFTWARE = 2, VPROC_RST_AEC = 3, /*software reset -reset and runs the firmware from RAM*/ VPROC_RST_BOOT = 4 } VprocResetMode; typedef enum vProcDeviceType { VPROC_DEV_GALILEO = 1, /*Galileo devices: ZL38004, ZL38012, ZL38005*/ VPROC_DEV_TIMBERWOLF = 2 /*Timberwolf: ZL38040*/ } VprocDeviceType; extern void VprocHALcleanup(void); extern int VprocHALInit(void); extern void Vproc_msDelay(unsigned short time); extern void VprocWait(unsigned long int time); extern int VprocHALWrite(unsigned short val); extern int VprocHALRead(unsigned short* pVal); #ifdef __cplusplus } #endif #endif /* VPROC_COMMON_H */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/api_lib/vproc_common.h
C
apache-2.0
3,826
/** \file vproc_data_types.h * vproc_data_types.h * * This file is the header for all standard types used in the API code. * **************************************************************************** * Copyright Microsemi Inc, 2018. All rights reserved. * Licensed under the MIT License. See LICENSE.txt in the project * root for license information. * ***************************************************************************/ #ifndef VP_API_TYPES_H #define VP_API_TYPES_H /* For maximum that can be stored in an int - if file exists in library */ #include "limits.h" #include "esp_types.h" #ifdef __cplusplus extern "C" { #endif #ifndef NULL #define NULL (0) #endif #ifdef EXTERN #undef EXTERN #error EXTERN was redefined! #endif /* undef EXTERN */ #ifdef __cplusplus #define EXTERN extern "C" #else #define EXTERN extern #endif /* __cplusplus */ /********************* DECLARATIONS ***************************/ /* Constants */ #define FALSE (0) /* Boolean constant */ #define TRUE (1) /* Boolean constant */ #ifndef __cplusplus /* C++ language provides a boolean data type; So no need to define * one more data type; Make use of it * NOTE: The 'C' potions of the VP-API assume C++ "bool" to be of the * same size as that of "char". Please make sure this assumption is correct. */ //typedef unsigned char bool; #endif /* __cplusplus */ /****************** typedefs ***********************************/ /* These are the basic number types used */ /* for uint8, uint16, uint32, int8, int16, int32, bool */ // PLATFORM SPECIFIC DEFINITIONS typedef unsigned char uchar; typedef signed char int8; typedef unsigned char UCharT; // 8 bits unsigned - PLATFORM SPECIFIC typedef unsigned char UInt8T; // 8 bits unsigned - PLATFORM SPECIFIC typedef unsigned short UInt16T; // 16 bits unsigned - PLATFORM SPECIFIC typedef unsigned long UInt32T; // 32 bits unsigned - PLATFORM SPECIFIC typedef signed long Int32T; // 32 bits signed - PLATFORM SPECIFIC typedef unsigned char uint8; // 8 bits unsigned - PLATFORM SPECIFIC typedef unsigned short uint16; // 16 bits unsigned - PLATFORM SPECIFIC typedef uint8* uint8p; // pointer to 8 bits unsigned - PLATFORM SPECIFIC typedef uint16* uint16p; // pointer to 16 bits unsigned - PLATFORM SPECIFIC typedef uint32_t uint32; // 32 bits unsigned - PLATFORM SPECIFIC typedef signed short int16; // 32 bits unsigned - PLATFORM SPECIFIC typedef uint32* uint32p; typedef int8* int8p; typedef int16* int16p; typedef Int32T* int32p; /* external types */ /* Some compilers optimize the size of enumeration data types based on * the maximum data value assigned to the members of that data type. * 'Standard C' requires enumeration data types to be of the same size * as that of native 'int' implementation. * The VP-API from a portability persepective adds a 'dummy' member to * all enumeration data types that force the compilers to allocate the size * of enumeration data types to be equal to that of native 'int' * implementation */ #define FORCE_STANDARD_C_ENUM_SIZE (INT_MAX) /* Eliminate error messages that occur when comparing an enumeration constant < 0 */ #define FORCE_SIGNED_ENUM (INT_MIN) /* Define any API specific basic data type ranges (that are necessary) */ #define VP_INT16_MAX (SHRT_MAX) #define VP_INT16_MIN (SHRT_MIN) #define VP_INT32_MAX (LONG_MAX) #define VP_INT32_MIN (LONG_MIN) /*firmware data structures*/ typedef struct { uint16 buf[16]; /*the firmware data block to send to the device*/ uint16 numWords; /*the number of words within the block of data stored in buf[]*/ uint32 targetAddr; /*the target base address to write to register 0x00c of the device*/ uint8 useTargetAddr; /*this value is either 0 or 1. When 1 the tarGetAddr must be written to the device*/ } twFwr; typedef struct { twFwr* st_Fwr; uint32 byteCount; /*The total number of bytes within the firmware - NOT USED*/ uint8 havePrgmBase; uint32 prgmBase; uint32 execAddr; /*The execution start address of the firmware in RAM*/ uint16 twFirmwareStreamLen; /*The number of blocks within the firmware*/ } twFirmware; /*config record structures*/ typedef struct { uint16 reg; /*the register */ uint16 value; /*the value to write into reg */ } dataArr; #ifdef __cplusplus } #endif #endif /* VP_API_TYPES_H */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/api_lib/vproc_data_types.h
C
apache-2.0
4,481
/**************************************************************************** * tw_hal_verify.c - Read/write registers of the device and verify whether the * device is accessed properly * * **************************************************************************** * Copyright Microsemi Inc, 2018. All rights reserved. * Licensed under the MIT License. See LICENSE.txt in the project * root for license information. * ***************************************************************************/ #include <stdio.h> #include <stdlib.h> /* malloc, free, rand */ #include "esp_log.h" #include "vproc_common.h" #include "zl38063_config.h" #include "vprocTwolf_access.h" #include "zl38063_firmware.h" /*NOTE: notice that the *.c code are included in the apps- * This is because the compiler I'm using requires that * But if your makefile is such that compiler knows where to find these files * then remove the #include *.c below */ #undef SAVE_IMAGE_TO_FLASH /*define this macro to save the firmware from RAM to flash*/ #undef SAVE_CFG_TO_FLASH /*define this macro to save the cfg from RAM to flash*/ /*quick test*/ #define TW_HAL_VERIFY_DEBUG #define MAX_WORDS_FOR_MULTIWORD_ACCESS_TEST 125 static const char *TAG = "TW_HAL_VERIFY"; /*LoadFwrConfig_Alt - to load a converted *s3, *cr2 to c code into the device. * Basically instead of loading the *.s3, *cr2 directly, * use the tw_convert tool to convert the ascii hex fwr mage into code and compile * with the application * * input arg: mode: 0 - load both firmware and confing * 1 - load firmware only * 2 - load config only */ VprocStatusType LoadFwrConfig_Alt(uint8 mode) { VprocStatusType status = VPROC_STATUS_SUCCESS; if ((mode == 0) || (mode == 1)) { twFirmware st_Firmware; st_Firmware.st_Fwr = (twFwr*)st_twFirmware; st_Firmware.twFirmwareStreamLen = (uint16)firmwareStreamLen; st_Firmware.execAddr = (uint32)executionAddress; st_Firmware.havePrgmBase = (uint8)haveProgramBaseAddress; st_Firmware.prgmBase = (uint32)programBaseAddress; ESP_LOGD(TAG, "Firmware boot loading started ...."); status = VprocTwolfHbiBoot_alt(&st_Firmware); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiBoot()", status); return -1; } ESP_LOGD(TAG,"Loading the image to RAM....done"); #ifdef SAVE_IMAGE_TO_FLASH ESP_LOGD(TAG,"Saving firmware to flash...."); status = VprocTwolfSaveImgToFlash(); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfSaveImgToFlash()", status); return status; } ESP_LOGD(TAG,"Saving firmware to flash....done"); #endif status = VprocTwolfFirmwareStart(); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfFirmwareStart()", status); return status; } } if ((mode == 0) || (mode == 2)) { ESP_LOGD(TAG,"Loading the config file into the device RAM...."); status = VprocTwolfLoadConfig((dataArr*)st_twConfig, (uint16)configStreamLen); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfLoadConfig()", status); return status; } #ifdef SAVE_CFG_TO_FLASH ESP_LOGD(TAG,"Saving config to flash...."); status = VprocTwolfSaveCfgToFlash(); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfSaveCfgToFlash()", status); return status; } ESP_LOGD(TAG,"Saving config to flash....done"); #endif } { /*Verify that the boot loading PASS or Fail*/ uint16 val = 0; status = VprocTwolfHbiRead(0x0022, 1, &val); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiRead()", status); VprocTwolfHbiCleanup(); return -1; } if ((val == 38040) || (val == 38050) || (val == 38060) || (val == 38080) || (val == 38051) || (val == 38041)){ ESP_LOGD(TAG,"Device boot loading completed successfully..."); }else { ESP_LOGD(TAG,"Device boot loading failed!!!..."); return VPROC_STATUS_FAILURE; } } /*Firmware reset - in order for the configuration to take effect * NOTE: The ZL38040 needs a soft reset for the uploaded configuration * to take effect. This soft-reset is sent below * if the ZL38040 is an I2S slave, if the I2S master is not stable * at the time of this reset, then that reset will not take effect. * In that case the host has to to simply resend the reset * command once the I2S master * is up and running and is at a stable state. */ status = VprocTwolfReset(VPROC_RST_SOFTWARE); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfReset()", status); return status; } ESP_LOGD(TAG,"Device boot loading completed successfully..."); return status; } int test_zl38063(void* arg) { int status = 0; uint16 cmdword = 0; uint16 val[MAX_WORDS_FOR_MULTIWORD_ACCESS_TEST]; uint8 numwords = 0; uint16 tempbuf[MAX_WORDS_FOR_MULTIWORD_ACCESS_TEST]; uint16 i = 0; #ifdef TW_HAL_VERIFY_DEBUG uint16 j = 0; #endif status = VprocTwolfHbiInit(); if (status < 0) { perror("tw_spi_access open"); return -1; } if ((MAX_WORDS_FOR_MULTIWORD_ACCESS_TEST > 125) || (MAX_WORDS_FOR_MULTIWORD_ACCESS_TEST < 2)) { ESP_LOGD(TAG,"MAX_WORDS_FOR_MULTIWORD_ACCESS_TEST must between 2 and 126"); } memset(val, 0, sizeof(val)); memset(tempbuf, 0, sizeof(tempbuf)); ESP_LOGD(TAG,"Test 1 - Verifying that the device is present and working ...."); cmdword = 0x00C; numwords = 2; val[0] = 0x1234; val[1] = 0x5678; status = VprocTwolfHbiWrite(cmdword, numwords, val); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiWrite()\n", status); VprocHALcleanup(); return -1; } #ifdef TW_HAL_VERIFY_DEBUG j = 0; for (i = 0; i < numwords; i++) { ESP_LOGD(TAG,"wr: addr 0x%04x = 0x%04x", (cmdword + j), val[i]); j = j + 2; } #endif status = VprocTwolfHbiRead(cmdword, numwords, tempbuf); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiRead()", status); VprocTwolfHbiCleanup(); return -1; } #ifdef TW_HAL_VERIFY_DEBUG j = 0; for (i = 0; i < numwords; i++) { ESP_LOGD(TAG,"RD: addr 0x%04x = 0x%04x", (cmdword + j), tempbuf[i]); j = j + 2; } #endif if ((tempbuf[0] != 0x1234) && (tempbuf[1] != 0x5600)) { ESP_LOGD(TAG,"Test 1 - completed - FAIL!!!"); return -1; } ESP_LOGD(TAG,"Test 1 - completed - PASS\n\n"); status = VprocTwolfReset(0); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiRead()", status); VprocTwolfHbiCleanup(); return -1; } ESP_LOGD(TAG,"Device reset completed successfully..."); ESP_LOGD(TAG,"Test 2 - Verifying single word write/read access ...."); cmdword = 0x0300; val[0] = 0x4008; numwords = 1; status = VprocTwolfHbiWrite(cmdword, numwords, val); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiWrite()", status); VprocTwolfHbiCleanup(); return -1; } #ifdef TW_HAL_VERIFY_DEBUG j = 0; for (i = 0; i < numwords; i++) { ESP_LOGD(TAG,"wr: addr 0x%04x = 0x%04x", (cmdword + j), val[i]); j = j + 2; } #endif status = VprocTwolfHbiRead(cmdword, numwords, val); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiRead()", status); VprocTwolfHbiCleanup(); return -1; } #ifdef TW_HAL_VERIFY_DEBUG j = 0; for (i = 0; i < numwords; i++) { ESP_LOGD(TAG,"RD: addr 0x%04x = 0x%04x\n", (cmdword + j), val[i]); j = j + 2; } #endif if ((val[0] != 0x4008)) { ESP_LOGD(TAG,"Test 2 - completed - FAIL!!!"); return -1; } ESP_LOGD(TAG,"Test 2 - completed - PASS"); ESP_LOGD(TAG,"Test 3 - Verifying multiple words write/read access ...."); /* Fill the data buffer with unique data values. */ for ( i = 0 ; i < MAX_WORDS_FOR_MULTIWORD_ACCESS_TEST ; i++ ) { val[i] = i | ((0xFF - i) << 8); } cmdword = 0x0300; numwords = MAX_WORDS_FOR_MULTIWORD_ACCESS_TEST; status = VprocTwolfHbiWrite(cmdword, numwords, val); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiWrite()", status); VprocTwolfHbiCleanup(); return -1; } #ifdef TW_HAL_VERIFY_DEBUG j = 0; for (i = 0; i < numwords; i++) { ESP_LOGD(TAG,"twr: addr 0x%04x = 0x%04x", (cmdword + j), val[i]); j = j + 2; } #endif status = VprocTwolfHbiRead(cmdword, numwords, tempbuf); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiRead()", status); VprocTwolfHbiCleanup(); return -1; } #ifdef TW_HAL_VERIFY_DEBUG j = 0; for (i = 0; i < numwords; i++) { ESP_LOGD(TAG,"RD: addr 0x%04x = 0x%04x =? 0x%04x", (cmdword + j), tempbuf[i], val[i]); j = j + 2; } #endif j = 0; for ( i = 0 ; i < MAX_WORDS_FOR_MULTIWORD_ACCESS_TEST ; i++ ) { if (tempbuf[i] != val[i]) { ESP_LOGD(TAG,"RD: addr 0x%04x = 0x%04x =? 0x%04x", (cmdword + j), tempbuf[i], val[i]); ESP_LOGD(TAG,"Test 3 - completed - FAIL!!!"); return -1; } j = j + 2; } ESP_LOGD(TAG,"Test 3 - completed - PASS"); ESP_LOGD(TAG,"Test 4 - Verifying the firmware/config boot loading ...."); if (LoadFwrConfig_Alt(0) != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Device boot loading failed....."); ESP_LOGD(TAG,"Test 4 - completed - FAIL!!!"); } else ESP_LOGD(TAG,"Test 4 - completed - PASS"); VprocTwolfHbiCleanup(); return 0; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/example_apps/tw_hal_verify.c
C
apache-2.0
10,613
/**************************************************************************** * tw_ldfwcfg.c - To load a *.s3 firmware and/or a *.cr2 into the device * and optionally save the loaded image to flash * * **************************************************************************** * Copyright Microsemi Inc, 2018. All rights reserved. * Licensed under the MIT License. See LICENSE.txt in the project * root for license information. * ***************************************************************************/ #include <stdio.h> #include <stdlib.h> /* malloc, free, rand */ #include "esp_log.h" #include "vproc_common.h" #include "vprocTwolf_access.h" /*NOTE: notice that the *.c code are included in the apps- * This is because the compiler I'm using requires that * But if your makefile is such that compiler knows where to find these files * then remove the #include *.c below */ #undef SAVE_CFG_TO_FLASH /*define this macro to save the cfg from RAM to flash*/ static const char *TAG = "TW_LDCFG"; uint16 numElements; dataArr* pCr2Buf; /* fseekNunlines() -- The firmware file is an ascii text file. * the information from fseek will not be useful. * this is our own fseek equivalent */ static unsigned long fseekNunlines(FILE* BOOT_FD) { uint32 line_count = 0; int c; while ( (c = fgetc(BOOT_FD)) != EOF ) { if ( c == '\n' ) line_count++; } return line_count; } /* readCfgFile() use this function to * Read the Voice processing cr2 config file into RAM * filepath -- pointer to the location where to find the file * pCr2Buf -- the actual firmware data array will be pointed to this buffer */ static int readCfgFile(char* filepath) { unsigned int reg[2], val[2], len; uint8 done = 0; uint16 index = 0; FILE* BOOT_FD; char* s; char line[512] = ""; BOOT_FD = fopen(filepath, "rb"); if (BOOT_FD != NULL) { len = fseekNunlines(BOOT_FD); if (len <= 0) { ESP_LOGD(TAG,"Error: file is not of the correct format..."); return -1; } ESP_LOGD(TAG,"fileLength = %u", len); /*start at the beginning of the file*/ //fseek(BOOT_FD, 0, SEEK_SET); /* allocate memory to contain the reg and val:*/ pCr2Buf = (dataArr*) malloc(len * sizeof(dataArr)); if (pCr2Buf == NULL) { ESP_LOGD(TAG,"not enough memory to allocate %u bytes.. ", len * sizeof(dataArr)); return -1; } rewind(BOOT_FD); /*read and format the data accordingly*/ numElements = 0; do { s = fgets(line, 512, BOOT_FD); if (line[0] == ';') { continue; } else if (s != NULL) { numElements++; sscanf(line, "%x %c %x", reg, s, val); pCr2Buf[index].reg = reg[0]; pCr2Buf[index].value = val[0]; // ESP_LOGD(TAG,"pCr2Buf[%d].reg pCr2Buf[%d].value = 0x%04x\t0x%04x\n", index, index, pCr2Buf[index].reg, pCr2Buf[index].value); index++; } else { done = 1;} } while (done == 0); fclose(BOOT_FD); ESP_LOGD(TAG,"size of pCr2Buf = %u bytes.. ", sizeof(pCr2Buf)); } else { ESP_LOGD(TAG,"Error: can't open file"); } return 0; } /*This example host app load the *.s3 firmware to the device RAM. Optionally save it to flash * Then start the firmware from the execution address in RAM * It then stops the firmware - Load the cr2 file into RAM. Optionally save it to flash * Then restarts the firmware */ int main (int argc, char** argv) { VprocStatusType status = VPROC_STATUS_SUCCESS; if (argc != 2) { ESP_LOGD(TAG,"Error: argc = %d - missing %d arg(s)... ", argc, 3 - (argc - 1)); ESP_LOGD(TAG,"command Usage:%s ConfigPath", argv[0]); exit(1); } ESP_LOGD(TAG,":%s %s %s", argv[0], argv[1], argv[2]); /*global file handle*/ status = VprocTwolfHbiInit(); if (status < 0) { perror("tw_spi_access open"); return -1; } if (readCfgFile(argv[1]) < 0) { ESP_LOGD(TAG,"Error:read %s file", argv[1]); } ESP_LOGD(TAG,"a- Reading config file to host RAM - done...."); ESP_LOGD(TAG,"c- Loading the config file into the device RAM"); status = VprocTwolfLoadConfig(pCr2Buf, numElements); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfLoadConfig()", status); VprocTwolfHbiCleanup(); return -1; } #ifdef SAVE_CONFIG_TO_FLASH status = VprocTwolfSaveCfgToFlash(); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfSaveCfgToFlash()", status); VprocTwolfHbiCleanup(); return -1; } ESP_LOGD(TAG,"d- Saving config to flash- done...."); #endif ESP_LOGD(TAG,"e- Loading config record - done...."); free(pCr2Buf); pCr2Buf = NULL; VprocTwolfHbiCleanup(); return 0; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/example_apps/tw_ldcfg.c
C
apache-2.0
5,160
/**************************************************************************** * tw_ldfw.c - To load a *.s3 firmware into the device * and optionally save the loaded image to flash * * **************************************************************************** * Copyright Microsemi Inc, 2018. All rights reserved. * Licensed under the MIT License. See LICENSE.txt in the project * root for license information. * ***************************************************************************/ #include "vproc_common.h" #include "vprocTwolf_access.h" #include "esp_log.h" /*NOTE: notice that the *.c code are included in the apps- * This is because the compiler I'm using requires that * But if your makefile is such that compiler knows where to find these files * then remove the #include *.c below */ //#undef SAVE_IMAGE_TO_FLASH /*define this macro to save the firmware from RAM to flash*/ static const char *TAG = "TW_LDFW"; /*quick test*/ /*This example host app load the *.s3 firmware to the device RAM. Optionally save it to flash * Then start the firmware from the execution address in RAM */ int main (int argc, char** argv) { VprocStatusType status = VPROC_STATUS_SUCCESS; FILE* BOOT_FD; char line[256] = ""; if (argc != 2) { ESP_LOGD(TAG,"Error: argc = %d - missing %d arg(s)... ", argc, 3 - (argc - 1)); ESP_LOGD(TAG,"command Usage:%s firmwarePath", argv[0]); exit(1); } ESP_LOGD(TAG,":%s %s %s", argv[0], argv[1], argv[2]); BOOT_FD = fopen(argv[1], "rb"); if (BOOT_FD == NULL) { ESP_LOGD(TAG,"Error: can't open file %s", argv[1]); return -1; } /*global file handle*/ status = VprocTwolfHbiInit(); if (status < 0) { perror("tw_spi_access open"); fclose(BOOT_FD); return -1; } ESP_LOGD(TAG,"1- Opening firmware file - done...."); status = VprocTwolfHbiBootPrepare(); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiBootPrepare()", status); fclose(BOOT_FD); VprocHALcleanup(); return -1; } ESP_LOGD(TAG,"-- Boot prepare - done...."); while (fgets(line, 256, BOOT_FD) != NULL) { status = VprocTwolfHbiBootMoreData(line); if (status == VPROC_STATUS_BOOT_LOADING_MORE_DATA) { continue; } else if (status == VPROC_STATUS_BOOT_LOADING_CMP) { break ; } else if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiBootMoreData()", status); fclose(BOOT_FD); VprocHALcleanup(); return -1; } } ESP_LOGD(TAG,"-- Firmware data transfer - done...."); fclose(BOOT_FD); /*clean up and verify that the boodloading completed correctly*/ status = VprocTwolfHbiBootConclude(); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfHbiBootConclude()", status); VprocHALcleanup(); return -1; } ESP_LOGD(TAG,"2- Loading firmware - done...."); #ifdef SAVE_IMAGE_TO_FLASH ESP_LOGD(TAG,"-- Saving firmware to flash...."); status = VprocTwolfSaveImgToFlash(); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfSaveImgToFlash()", status); VprocHALcleanup(); return -1; } ESP_LOGD(TAG,"-- Saving firmware to flash....done"); #endif status = VprocTwolfFirmwareStart(); if (status != VPROC_STATUS_SUCCESS) { ESP_LOGD(TAG,"Error %d:VprocTwolfFirmwareStart()", status); VprocHALcleanup(); return -1; } ESP_LOGD(TAG,"Device boot loading completed successfully..."); VprocHALcleanup(); return 0; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/example_apps/tw_ldfw.c
C
apache-2.0
3,846
/**************************************************************************** * tw_ldfwcfg.c - To load a *.s3 firmware and/or a *.cr2 into the device * and optionally save the loaded image to flash * * **************************************************************************** * Copyright Microsemi Inc, 2018. All rights reserved. * Licensed under the MIT License. See LICENSE.txt in the project * root for license information. * ***************************************************************************/ #include <stdio.h> #include <stdlib.h> /* malloc, free, rand */ #include "vproc_common.h" #include "vprocTwolf_access.h" /*NOTE: notice that the *.c code are included in the apps- * This is because the compiler I'm using requires that * But if your makefile is such that compiler knows where to find these files * then remove the #include *.c below */ #undef SAVE_IMAGE_TO_FLASH /*define this macro to save the firmware from RAM to flash*/ #undef SAVE_CFG_TO_FLASH /*define this macro to save the cfg from RAM to flash*/ /*quick test*/ uint16 numElements; dataArr* pCr2Buf; /* fseekNunlines() -- The firmware file is an ascii text file. * the information from fseek will not be useful. * this is our own fseek equivalent. */ static unsigned long fseekNunlines(FILE* BOOT_FD) { uint32 line_count = 0; int c; while ( (c = fgetc(BOOT_FD)) != EOF ) { if ( c == '\n' ) line_count++; } return line_count; } /* readCfgFile() use this function to * Read the Voice processing cr2 config file into RAM * filepath -- pointer to the location where to find the file * pCr2Buf -- the actual firmware data array will be pointed to this buffer */ static int readCfgFile(char* filepath) { unsigned int reg[2], val[2], len; uint8 done = 0; uint16 index = 0; FILE* BOOT_FD; char* s; char line[512] = ""; BOOT_FD = fopen(filepath, "rb"); if (BOOT_FD != NULL) { len = fseekNunlines(BOOT_FD); if (len <= 0) { printf("Error: file is not of the correct format...\n"); return -1; } //printf("fileLength = %u\n", len); /*start at the beginning of the file*/ //fseek(BOOT_FD, 0, SEEK_SET); /* allocate memory to contain the reg and val:*/ pCr2Buf = (dataArr*) malloc(len * sizeof(dataArr)); if (pCr2Buf == NULL) { printf ("not enough memory to allocate %u bytes.. ", len * sizeof(dataArr)); return -1; } rewind(BOOT_FD); /*read and format the data accordingly*/ numElements = 0; do { s = fgets(line, 512, BOOT_FD); if (line[0] == ';') { continue; } else if (s != NULL) { numElements++; sscanf(line, "%x %c %x", reg, s, val); pCr2Buf[index].reg = reg[0]; pCr2Buf[index].value = val[0]; // printf("pCr2Buf[%d].reg pCr2Buf[%d].value = 0x%04x\t0x%04x\n", index, index, pCr2Buf[index].reg, pCr2Buf[index].value); index++; } else { done = 1;} } while (done == 0); fclose(BOOT_FD); //printf ("size of pCr2Buf = %u bytes.. \n", len*sizeof(pCr2Buf)); } else { printf("Error: can't open file\n"); } return 0; } /*This example host app load the *.s3 firmware to the device RAM. Optionally save it to flash * Then start the firmware from the execution address in RAM * It then stops the firmware - Load the cr2 file into RAM. Optionally save it to flash * Then resstarts the firmware */ int main (int argc, char** argv) { VprocStatusType status = VPROC_STATUS_SUCCESS; FILE* BOOT_FD; char line[256] = ""; if (argc < 3) { printf("Error: argc = %d - missing %d arg(s)... \n", argc, 3 - (argc - 1)); printf("command Usage:%s firmwarePath ConfigPath\n", argv[0]); exit(1); } printf(":%s %s %s\n", argv[0], argv[1], argv[2]); BOOT_FD = fopen(argv[1], "rb"); if (BOOT_FD == NULL) { printf("Error: can't open file %s\n", argv[1]); return -1; } /*global file handle*/ status = VprocTwolfHbiInit(); //gTwolf_fd = open(file_name, O_RDWR); if (status < 0) { perror("tw_spi_access open"); fclose(BOOT_FD); return -1; } printf("1- Opening firmware file - done....\n"); status = VprocTwolfHbiBootPrepare(); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfHbiBootPrepare()\n", status); fclose(BOOT_FD); VprocTwolfHbiCleanup(); return -1; } printf("-- Boot prepare - done....\n"); while (fgets(line, 256, BOOT_FD) != NULL) { status = VprocTwolfHbiBootMoreData(line); if (status == VPROC_STATUS_BOOT_LOADING_MORE_DATA) { continue; } else if (status == VPROC_STATUS_BOOT_LOADING_CMP) { break ; } else if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfHbiBootMoreData()\n", status); fclose(BOOT_FD); VprocTwolfHbiCleanup(); return -1; } } printf("-- Firmware data transfer - done....\n"); fclose(BOOT_FD); status = VprocTwolfHbiBootConclude(); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfHbiBootConclude()\n", status); VprocTwolfHbiCleanup(); return -1; } #ifdef SAVE_IMAGE_TO_FLASH printf("-- Saving firmware to flash....\n"); status = VprocTwolfSaveImgToFlash(); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfSaveImgToFlash()\n", status); VprocTwolfHbiCleanup(); return -1; } printf("-- Saving firmware to flash....done\n"); #endif status = VprocTwolfFirmwareStart(); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfFirmwareStart()\n", status); VprocTwolfHbiCleanup(); return -1; } printf("3- Loading the config file into the device RAM\n"); if (readCfgFile(argv[2]) < 0) { printf("Error:read %s file\n", argv[2]); } printf("a- Reading config file to host RAM - done....\n"); status = VprocTwolfLoadConfig(pCr2Buf, numElements); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfLoadConfig()\n", status); VprocTwolfHbiCleanup(); return -1; } #ifdef SAVE_CFG_TO_FLASH printf("-- Saving config to flash....\n"); status = VprocTwolfSaveCfgToFlash(); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfSaveCfgToFlash()\n", status); VprocTwolfHbiCleanup(); return -1; } printf("-- Saving config to flash....done\n"); #endif printf("Device boot loading completed successfully...\n"); VprocTwolfHbiCleanup(); return 0; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/example_apps/tw_ldfwcfg.c
C
apache-2.0
7,156
/**************************************************************************** * tw_spi_access.c - Demo apps demonstrating how to access registers of the * device over spi or I2C. Loading a firmware and or config into the device * * **************************************************************************** * Copyright Microsemi Inc, 2018. All rights reserved. * Licensed under the MIT License. See LICENSE.txt in the project * root for license information. * ***************************************************************************/ #include "vproc_common.h" #include "vprocTwolf_access.h" /*NOTE: notice that the *.c code are included in the apps- * This is because the compiler I'm using requires that * But if your makefile is such that compiler knows where to find these files * then remove the #include *.c below */ #include "zl38063_config.h" #include "zl38063_firmware.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #undef SAVE_IMAGE_TO_FLASH /*define this macro to save the firmware from RAM to flash*/ #undef SAVE_CFG_TO_FLASH /*define this macro to save the cfg from RAM to flash*/ #define SAVE_IMAGE_TO_FLASH #define SAVE_CFG_TO_FLASH /*quick test*/ /*LoadFwrConfig_Alt - to load a converted *s3, *cr2 to c code into the device. * Basically instead of loading the *.s3, *cr2 directly, * use the tw_convert tool to convert the ascii hex fwr mage into code and compile * with the application * * input arg: mode: 0 - load both firmware and confing * 1 - load firmware only * 2 - load config only * -1 - Force loading */ int tw_upload_dsp_firmware(int mode) { union { short a; char b; } test_bigendian; if (mode >= 0) { uint16 vol = 0; vTaskDelay(1000 / portTICK_PERIOD_MS); int ret = VprocTwolfGetAppStatus(&vol); if (vol) { ESP_LOGW(TAG_SPI, "MCS ret:%d,Status:%d", ret, vol); return 0; } ESP_LOGI(TAG_SPI, "** Loading DSP firmware ret:%d,Status:%d **", ret, vol); } else { mode = 0; } test_bigendian.a = 1; ESP_LOGI(TAG_SPI, "b=%d", test_bigendian.b); int status = VprocTwolfHbiInit(); if (status < 0) { DEBUG_LOGE(TAG_SPI, "tw_spi_access open"); return -1; } if ((mode == 0) || (mode == 1)) { twFirmware st_Firmware; st_Firmware.st_Fwr = (twFwr *)st_twFirmware; st_Firmware.twFirmwareStreamLen = (uint16)firmwareStreamLen; st_Firmware.execAddr = (uint32)executionAddress; st_Firmware.havePrgmBase = (uint8)haveProgramBaseAddress; st_Firmware.prgmBase = (uint32)programBaseAddress; ESP_LOGI(TAG_SPI, "1- Firmware boot loading started ...."); status = VprocTwolfHbiBoot_alt(&st_Firmware); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Error %d:VprocTwolfHbiBoot()", status); // VprocTwolfHbiCleanup(); return -1; } ESP_LOGI(TAG_SPI, "2- Loading the image to RAM....done"); #ifdef SAVE_IMAGE_TO_FLASH ESP_LOGI(TAG_SPI, "-- Saving firmware to flash...."); status = VprocTwolfSaveImgToFlash(); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Error %d:VprocTwolfSaveImgToFlash()", status); // VprocTwolfHbiCleanup(); return status; } ESP_LOGI(TAG_SPI, "-- Saving firmware to flash....done"); #endif status = VprocTwolfFirmwareStart(); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Error %d:VprocTwolfFirmwareStart()", status); // VprocTwolfHbiCleanup(); return status; } } #if 1 if ((mode == 0) || (mode == 2)) { ESP_LOGI(TAG_SPI, "3- Loading the config file into the device RAM...."); status = VprocTwolfLoadConfig((dataArr *)st_twConfig, (uint16)configStreamLen); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Error %d:VprocTwolfLoadConfig()", status); // VprocTwolfHbiCleanup(); return status; } #ifdef SAVE_CFG_TO_FLASH ESP_LOGI(TAG_SPI, "-- Saving config to flash...."); status = VprocTwolfSaveCfgToFlash(); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Error %d:VprocTwolfSaveCfgToFlash()", status); // VprocTwolfHbiCleanup(); return status; } ESP_LOGI(TAG_SPI, "-- Saving config to flash....done"); #endif } /*Firmware reset - in order for the configuration to take effect*/ status = VprocTwolfReset(VPROC_RST_SOFTWARE); if (status != VPROC_STATUS_SUCCESS) { DEBUG_LOGE(TAG_SPI, "Error %d:VprocTwolfReset()", status); ESP_LOGI(TAG_SPI,"Error"); // VprocTwolfHbiCleanup(); return status; } #endif ESP_LOGI(TAG_SPI, "Device boot loading completed successfully..."); return status; } int zl38063_comm(int argc, char **argv) { VprocStatusType status = VPROC_STATUS_SUCCESS; if (argc == 1) { printf("Usage: for help type:%s -h", argv[0]); exit(1); } if (strcmp(argv[1], "-h") == 0) { printf("\nUsage:\n\t%s [-cmd mode] [options...] see supported" " command modes below\n\n", argv[0]); printf("\t-wr : to write one or more 16-bit words to the device\n" "\t-rd : to read one or more 16-bit words from the device\n" "\t-rst : to reset the device in one of these" " supported reset modes:\n" "\t\t - [0: RAM | 1: ROM | 2: SOFT | 3: AEC | 4: BOOT]\n"); printf("\t-lfcff : to load a specific firmware and related" " config from flash - arg: 1 to 14\n"); printf("\t-lfcfh-a : to load a pre-compiled firmware and related config" " from host via SPI\n"); printf("\t-lffh-a: to load a pre-compiled firmware from host via SPI\n"); printf("\t-lcfh-a: to load a pre-compiled config from host via SPI\n"); printf("\t-fclr : to erase the content of the ZL380xx slave flash\n"); printf("\t-sto : to reset the device into boot mode\n"); printf("\t-sta : to start execution of firmware found at " "exec address in RAM\n"); printf("\t-apla : to configure the ZL380xx x-point for " "audio playback mode\n"); printf("\t-arec : to configure the ZL380xx x-point for audio " "recording mode\n"); printf("Example:\n"); printf("\tEx to write 0x8004 into register 0x0300:" "\n\t%s -wr 0x0300 0x8004\n\n", argv[0]); printf("\tEx to read 12 words starting from register 0x020:" "\n\t%s -rd 0x0020 12\n\n", argv[0]); printf("\tEx to reset the device in boot mode:" "\n\t%s -rst n 'where n:[1-4]\n\n", argv[0]); printf("\tEx to load to RAM a firmware and config previously" " saved to flash at index 1:\n\t%s -lfcff 1\n\n", argv[0]); printf("\tEx to load to RAM a firmware previously" " saved to flash at index 1:\n\t%s -lfff 1\n\n", argv[0]); printf("\tEx to load to RAM the pre-compiled (in)firmware " "from teh host " "HBI (SPI):\n\t%s -lffh-a\n\n", argv[0]); printf("\tEx to load to RAM the pre-compiled (in)config " "from teh host " "HBI (SPI):\n\t%s -lcfh-a\n\n", argv[0]); printf("\tEx to load to RAM the pre-compiled (in)firmware and config " "from teh host " "HBI (SPI):\n\t%s -lfcfh-a\n\n", argv[0]); printf("\tEx to stop the firmware currently running and clear " "the RAM:\n\t%s -sto\n\n", argv[0]); printf("\tEx to start a firmware previously loaded into " "RAM:\n\t%s -sta\n\n", argv[0]); printf("\tEx to mute SOUT :\n\t%s -mute_s [1 | 0]\n\n", argv[0]); printf("\tEx to mute ROUT :\n\t%s -mute_r [1 | 0]\n\n", argv[0]); printf("\tEx to erase the slave flash device controlled by " "the ZL380xx :\n\t%s -fclr\n\n", argv[0]); printf("\tEx to configure the device for recording mode at a " "desired clock and sample rates" " with AEC off[0] or on [1]:\n\t%s -arec clkrate " "fsrate n 'where n:[0 | 1]'\n\n", argv[0]); printf("\tEx to configure the device for playback mode at a " "desired clock and sample rates" " with AEC off[0] or on [1]:\n\t%s -apla clkrate " "fsrate n 'where n:[0 | 1]'\n\n", argv[0]); return -1; } if ((argc < 3) && (strcmp(argv[1], "-wr") == 0)) { printf("Usage:%s -wr register value0 value1....value124 \n", argv[0]); return -1; } if ((argc < 3) && (strcmp(argv[1], "-rd") == 0)) { printf("Usage:%s -rd register n 'where n:[1-127]'\n", argv[0]); return -1; } if ((argc < 3) && (strcmp(argv[1], "-rst") == 0 )) { printf("Usage:%s -rst n 'where n:[0-4]'\n", argv[0]); return -1; } if ((argc < 3) && (strcmp(argv[1], "-apla") == 0)) { printf("Usage:%s -apla <clkrate in KHz> <fsrate in Hz> n" " 'where n:[0 | 1]'\n", argv[0]); return -1; } if ((argc < 3) && (strcmp(argv[1], "-arec") == 0)) { printf("Usage:%s -arec <clkrate in KHz> <fsrate in Hz> n" " 'where n:[0 | 1]'\n", argv[0]); return -1; } if ((argc < 3) && (strcmp(argv[1], "-lfcff") == 0)) { printf("Usage:%s -lfcfh 1\n", argv[0]); return -1; } /*global file handle*/ status = VprocTwolfHbiInit(); if (status < 0) { perror("tw_spi_access open"); return -1; } if ((strcmp(argv[1], "-wr") == 0) || (strcmp(argv[1], "-rd") == 0)) { int i = 0, j = 0; unsigned short val[128]; unsigned short cmdword = (unsigned short)strtoul(argv[2], NULL, 0); unsigned char numwords = 0; memset(val, 0, sizeof(val)); if (strcmp(argv[1], "-wr") == 0) { /*for WRITING 1 or more ZL380xx registers*/ unsigned short val[128]; numwords = argc - 3; /*calculate the number of words to write*/; for (i = 0; i < numwords; i++) { val[i] = (unsigned short)strtoul(argv[3 + i], NULL, 0); } status = VprocTwolfHbiWrite(cmdword, numwords, val); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfHbiWrite()\n", status); VprocTwolfHbiCleanup(); return -1; } for (i = 0; i < numwords; i++) { printf("wr: addr 0x%04x = 0x%04x\n", (cmdword + j), val[i]); j = j + 2; } } else { /*for READING 1 or more ZL380xx registers**/ numwords = (unsigned char)strtoul(argv[3], NULL, 0); if ((numwords == 0) || (numwords > 128)) { printf("number of words is out of range. Maximum is 128\n"); VprocTwolfHbiCleanup(); return -1; } status = VprocTwolfHbiRead(cmdword, numwords, val); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfHbiRead()\n", status); VprocTwolfHbiCleanup(); return -1; } for (i = 0; i < numwords; i++) { printf("RD: addr 0x%04x = 0x%04x\n", (cmdword + j), val[i]); j = j + 2; } } } else if (strcmp(argv[1], "-rst") == 0) { /*for RESETTING ZL380xx*/ unsigned char rstMode = (unsigned char)strtoul(argv[2], NULL, 0); status = VprocTwolfReset((uint16)rstMode); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfHbiRead()\n", status); VprocTwolfHbiCleanup(); return -1; } printf("Device reset completed successfully...\n"); } else if (strcmp(argv[1], "-lfcff") == 0) { /*Load ZL380x0 firmware + related config record from flash*/ unsigned short image_num = (unsigned short)strtoul(argv[2], NULL, 0); status = VprocTwolfFirmwareStop(); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfFirmwareStop()\n", status); VprocTwolfHbiCleanup(); return -1; } status = VprocTwolfLoadFwrCfgFromFlash(image_num); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfLoadFwrCfgFromFlash()\n", status); VprocTwolfHbiCleanup(); return -1; } status = VprocTwolfReset(VPROC_RST_HARDWARE_RAM); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfReset()\n", status); VprocTwolfHbiCleanup(); return -1; } printf("Device boot loading from flash completed successfully...\n"); } else if (strcmp(argv[1], "-lfff") == 0) { if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfLoadFwrFromFlash()\n", status); VprocTwolfHbiCleanup(); return -1; } printf("Device boot loading from flash completed successfully...\n"); } else if (strcmp(argv[1], "-lfcfh-a") == 0) { /*for LOADING FWR/CFG via SPI*/ if (tw_upload_dsp_firmware(0) != VPROC_STATUS_SUCCESS) printf("Device boot loading failed.....\n"); } else if (strcmp(argv[1], "-lcfh-a") == 0) { /*for LOADING CFG via SPI*/ if (tw_upload_dsp_firmware(2) != VPROC_STATUS_SUCCESS) printf("Device boot loading failed.....\n"); } else if (strcmp(argv[1], "-lffh-a") == 0) { /*for LOADING FWR via SPI*/ if (tw_upload_dsp_firmware(1) != VPROC_STATUS_SUCCESS) printf("Device boot loading failed.....\n"); } else if (strcmp(argv[1], "-sto") == 0) { /*for resetting into boot mode*/ if (VprocTwolfFirmwareStop() != 0) VprocTwolfHbiCleanup(); else printf("Firmware stopped to boot mode completed" " successfully...\n"); } else if (strcmp(argv[1], "-sta") == 0) { /*start executing FWR/CFG */ if (VprocTwolfFirmwareStart() != 0) VprocTwolfHbiCleanup(); else printf("Firmware is now running successfully...\n"); } else if (strcmp(argv[1], "-mute_r") == 0) { /*start executing FWR/CFG */ uint8 mute = (uint8)strtoul(argv[2], NULL, 0); //to do need fix //if(VprocTwolfMute(VPROC_ROUT, mute) != 0) if (1) { VprocTwolfHbiCleanup(); } else { if (mute) printf("ROUT Port muted sucessfully...\n"); else printf("ROUT Port unmuted sucessfully...\n"); } } else if (strcmp(argv[1], "-mute_s") == 0) { /*start executing FWR/CFG */ uint8 mute = (uint8)strtoul(argv[2], NULL, 0); //to do need fix //if(VprocTwolfMute(VPROC_SOUT, mute) != 0) if (1) VprocTwolfHbiCleanup(); else { if (mute) printf("SOUT Port muted sucessfully...\n"); else printf("SOUT Port unmuted sucessfully...\n"); } } else if ((strcmp(argv[1], "-arec") == 0) || (strcmp(argv[1], "-apla") == 0)) /* configure the ZL380x0 for either audio recording or playback * Over an I2S link */ { unsigned short pclkrate = (unsigned short)strtoul(argv[2], NULL, 0); unsigned short fsrate = (unsigned short)strtoul(argv[3], NULL, 0); unsigned short aecState = (unsigned char)strtoul(argv[4], NULL, 0); printf("pclkrate = %u KHz, fsrate = %u Hz, AEC state = %d\n", pclkrate, fsrate, aecState); //to do need fix #if 0 if (strcmp(argv[1], "-arec") == 0) { if (VprocTwolfUpstreamConfigure(pclkrate, fsrate, aecState) != 0) VprocTwolfHbiCleanup(); else printf("Device configured for audio recording...\n"); } else if (strcmp(argv[1], "-apla") == 0) { if (VprocTwolfDownstreamConfigure(pclkrate, fsrate, aecState) != 0) VprocTwolfHbiCleanup(); else printf("Device configured for audio playback...\n"); } #endif } else if (strcmp(argv[1], "-fclr") == 0) { /*Erase the full content of the ZL380x0 controlled slave flash*/ status = VprocTwolfEraseFlash(); if (status != VPROC_STATUS_SUCCESS) { printf("Error %d:VprocTwolfEraseFlash()\n", status); VprocTwolfHbiCleanup(); return -1; } printf("flash erasing completed successfully...\n"); } else { printf("Usage: for help type:\n%s -h\n", argv[0]); } printf("\n"); return 0; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/example_apps/tw_spi_access.c
C
apache-2.0
17,493
#ifndef TW_SPI_ACCESS_H #define TW_SPI_ACCESS_H #include <string.h> #include <stdio.h> #include <stdlib.h> int tw_upload_dsp_firmware(int mode); #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/example_apps/tw_spi_access.h
C
apache-2.0
168
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ /*Configuration file version: Microsemi_ZLS38063_1_P1_4_0_Config.cr2, modified: Tue Sep 18 20:48:31 2018*/ #ifndef _ZL38063_CONFIG_H_ #define _ZL38063_CONFIG_H_ #ifdef __cplusplus extern "C" { #endif extern const unsigned short configStreamLen; extern const dataArr st_twConfig[]; #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/firmware/zl38063_config.h
C
apache-2.0
1,595
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ /*Firmware Version : Microsemi_ZLS38063_1_P1_4_0_Firmware.s3, modified: Tue Sep 18 20:50:24 2018 */ #ifndef _ZL38063_FIRMWARE_H_ #define _ZL38063_FIRMWARE_H_ #ifdef __cplusplus extern "C" { #endif extern const twFwr st_twFirmware[]; extern const unsigned short firmwareStreamLen; extern const unsigned long programBaseAddress; extern const unsigned long executionAddress; extern const unsigned char haveProgramBaseAddress; #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/firmware/zl38063_firmware.h
C
apache-2.0
1,742
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "esp_log.h" #include "driver/i2c.h" #include "zl38063.h" #include "vprocTwolf_access.h" #include "driver/gpio.h" #include "tw_spi_access.h" #include "board.h" static const char *TAG = "zl38063"; static int8_t tw_vol[15] = { -90, -45, -30, -23, -16, -10, -4, -1, 0, 1, 2, 3, 4, 5, 6}; static int codec_init_flag = 0; audio_hal_func_t AUDIO_CODEC_ZL38063_DEFAULT_HANDLE = { .audio_codec_initialize = zl38063_codec_init, .audio_codec_deinitialize = zl38063_codec_deinit, .audio_codec_ctrl = zl38063_codec_ctrl_state, .audio_codec_config_iface = zl38063_codec_config_i2s, .audio_codec_set_mute = zl38063_codec_set_voice_mute, .audio_codec_set_volume = zl38063_codec_set_voice_volume, .audio_codec_get_volume = zl38063_codec_get_voice_volume, .audio_hal_lock = NULL, .handle = NULL, }; static bool zl38063_codec_initialized() { return codec_init_flag; } esp_err_t zl38063_codec_init(audio_hal_codec_config_t *cfg) { if (zl38063_codec_initialized()) { ESP_LOGW(TAG, "The zl38063 codec has been already initialized"); return ESP_OK; } tw_upload_dsp_firmware(0); gpio_config_t borad_conf; memset(&borad_conf, 0, sizeof(borad_conf)); borad_conf.mode = GPIO_MODE_OUTPUT; borad_conf.pin_bit_mask = 1UL << (get_reset_board_gpio()); borad_conf.pull_down_en = 0; borad_conf.pull_up_en = 0; gpio_config_t pa_conf; memset(&pa_conf, 0, sizeof(pa_conf)); pa_conf.mode = GPIO_MODE_OUTPUT; pa_conf.pin_bit_mask = 1UL << (get_pa_enable_gpio()); pa_conf.pull_down_en = 0; pa_conf.pull_up_en = 0; gpio_config(&pa_conf); gpio_config(&borad_conf); gpio_set_level(get_pa_enable_gpio(), 1); //enable PA gpio_set_level(get_reset_board_gpio(), 0); //enable DSP codec_init_flag = 1; return ESP_OK; } esp_err_t zl38063_codec_deinit(void) { gpio_set_level(get_pa_enable_gpio(), 0); gpio_set_level(get_reset_board_gpio(), 1); codec_init_flag = 0; return ESP_OK; } esp_err_t zl38063_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { return ESP_OK; } esp_err_t zl38063_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { return ESP_OK; } esp_err_t zl38063_codec_set_voice_mute(bool mute) { /* For now we do not have implementation for this */ return ESP_OK; } esp_err_t zl38063_codec_set_voice_volume(int volume) { int ret = 0; if (volume < 0 ) { volume = 0; } else if (volume >= 100) { volume = 100; } int k = volume / 7; ret = VprocTwolfSetVolume(tw_vol[k]); return ret; } esp_err_t zl38063_codec_get_voice_volume(int *volume) { int ret = 0; int8_t vol = 0; ret = VprocTwolfGetVolume(&vol); *volume = 0; for (int i = 0; i < sizeof(tw_vol); ++i) { if (vol == tw_vol[i]) { *volume = i * 7; } } return ret; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/zl38063.c
C
apache-2.0
4,201
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __ZL38063_H__ #define __ZL38063_H__ #include "audio_hal.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize ZL38063 chip * * @param cfg configuration of ZL38063 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t zl38063_codec_init(audio_hal_codec_config_t *cfg); /** * @brief Deinitialize ZL38063 chip * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t zl38063_codec_deinit(void); /** * The functions zl38063_ctrl_state and zl38063_config_i2s are not used by this driver. * They are kept here to maintain the uniformity and convenience of the interface * of the ADF project. * These settings for zl38063 are burned in firmware and configuration files. * Default i2s configuration: 48000Hz, 16bit, Left-Right channels. * Use resampling to be compatible with different file types. * * @brief Control ZL38063 chip * * @param mode codec mode * @param ctrl_state start or stop decode or encode progress * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t zl38063_codec_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); /** * @brief Configure ZL38063 codec mode and I2S interface * * @param mode codec mode * @param iface I2S config * * @return * - ESP_FAIL Parameter error * - ESP_OK Success */ esp_err_t zl38063_codec_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /** * @brief mute or unmute the codec * * @param mute: true, false * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t zl38063_codec_set_voice_mute(bool mute); /** * @brief Set voice volume * * @param volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t zl38063_codec_set_voice_volume(int volume); /** * @brief Get voice volume * * @param[out] *volume: voice volume (0~100) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t zl38063_codec_get_voice_volume(int *volume); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/driver/zl38063/zl38063.h
C
apache-2.0
3,245
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_HAL_H_ #define _AUDIO_HAL_H_ #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "audio_error.h" #ifdef __cplusplus extern "C" { #endif #define AUDIO_HAL_VOL_DEFAULT 70 typedef struct audio_hal *audio_hal_handle_t; /** * @brief Select media hal codec mode */ typedef enum { AUDIO_HAL_CODEC_MODE_ENCODE = 1, /*!< select adc */ AUDIO_HAL_CODEC_MODE_DECODE, /*!< select dac */ AUDIO_HAL_CODEC_MODE_BOTH, /*!< select both adc and dac */ AUDIO_HAL_CODEC_MODE_LINE_IN, /*!< set adc channel */ } audio_hal_codec_mode_t; /** * @brief Select adc channel for input mic signal */ typedef enum { AUDIO_HAL_ADC_INPUT_LINE1 = 0x00, /*!< mic input to adc channel 1 */ AUDIO_HAL_ADC_INPUT_LINE2, /*!< mic input to adc channel 2 */ AUDIO_HAL_ADC_INPUT_ALL, /*!< mic input to both channels of adc */ AUDIO_HAL_ADC_INPUT_DIFFERENCE, /*!< mic input to adc difference channel */ } audio_hal_adc_input_t; /** * @brief Select channel for dac output */ typedef enum { AUDIO_HAL_DAC_OUTPUT_LINE1 = 0x00, /*!< dac output signal to channel 1 */ AUDIO_HAL_DAC_OUTPUT_LINE2, /*!< dac output signal to channel 2 */ AUDIO_HAL_DAC_OUTPUT_ALL, /*!< dac output signal to both channels */ } audio_hal_dac_output_t; /** * @brief Select operating mode i.e. start or stop for audio codec chip */ typedef enum { AUDIO_HAL_CTRL_STOP = 0x00, /*!< set stop mode */ AUDIO_HAL_CTRL_START = 0x01, /*!< set start mode */ } audio_hal_ctrl_t; /** * @brief Select I2S interface operating mode i.e. master or slave for audio codec chip */ typedef enum { AUDIO_HAL_MODE_SLAVE = 0x00, /*!< set slave mode */ AUDIO_HAL_MODE_MASTER = 0x01, /*!< set master mode */ } audio_hal_iface_mode_t; /** * @brief Select I2S interface samples per second */ typedef enum { AUDIO_HAL_08K_SAMPLES, /*!< set to 8k samples per second */ AUDIO_HAL_11K_SAMPLES, /*!< set to 11.025k samples per second */ AUDIO_HAL_16K_SAMPLES, /*!< set to 16k samples in per second */ AUDIO_HAL_22K_SAMPLES, /*!< set to 22.050k samples per second */ AUDIO_HAL_24K_SAMPLES, /*!< set to 24k samples in per second */ AUDIO_HAL_32K_SAMPLES, /*!< set to 32k samples in per second */ AUDIO_HAL_44K_SAMPLES, /*!< set to 44.1k samples per second */ AUDIO_HAL_48K_SAMPLES, /*!< set to 48k samples per second */ } audio_hal_iface_samples_t; /** * @brief Select I2S interface number of bits per sample */ typedef enum { AUDIO_HAL_BIT_LENGTH_16BITS = 1, /*!< set 16 bits per sample */ AUDIO_HAL_BIT_LENGTH_24BITS, /*!< set 24 bits per sample */ AUDIO_HAL_BIT_LENGTH_32BITS, /*!< set 32 bits per sample */ } audio_hal_iface_bits_t; /** * @brief Select I2S interface format for audio codec chip */ typedef enum { AUDIO_HAL_I2S_NORMAL = 0, /*!< set normal I2S format */ AUDIO_HAL_I2S_LEFT, /*!< set all left format */ AUDIO_HAL_I2S_RIGHT, /*!< set all right format */ AUDIO_HAL_I2S_DSP, /*!< set dsp/pcm format */ } audio_hal_iface_format_t; /** * @brief I2s interface configuration for audio codec chip */ typedef struct { audio_hal_iface_mode_t mode; /*!< audio codec chip mode */ audio_hal_iface_format_t fmt; /*!< I2S interface format */ audio_hal_iface_samples_t samples; /*!< I2S interface samples per second */ audio_hal_iface_bits_t bits; /*!< i2s interface number of bits per sample */ } audio_hal_codec_i2s_iface_t; /** * @brief Configure media hal for initialization of audio codec chip */ typedef struct { audio_hal_adc_input_t adc_input; /*!< set adc channel */ audio_hal_dac_output_t dac_output; /*!< set dac channel */ audio_hal_codec_mode_t codec_mode; /*!< select codec mode: adc, dac or both */ audio_hal_codec_i2s_iface_t i2s_iface; /*!< set I2S interface configuration */ } audio_hal_codec_config_t; /** * @brief Configuration of functions and variables used to operate audio codec chip */ typedef struct audio_hal { esp_err_t (*audio_codec_initialize)(audio_hal_codec_config_t *codec_cfg); /*!< initialize codec */ esp_err_t (*audio_codec_deinitialize)(void); /*!< deinitialize codec */ esp_err_t (*audio_codec_ctrl)(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state); /*!< control codec mode and state */ esp_err_t (*audio_codec_config_iface)(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /*!< configure i2s interface */ esp_err_t (*audio_codec_set_mute) (bool mute); /*!< set codec mute */ esp_err_t (*audio_codec_set_volume)(int volume); /*!< set codec volume */ esp_err_t (*audio_codec_get_volume)(int *volume); /*!< get codec volume */ xSemaphoreHandle audio_hal_lock; /*!< semaphore of codec */ void *handle; /*!< handle of audio codec */ } audio_hal_func_t; /** * @brief Initialize media codec driver * * @note If selected codec has already been installed, it'll return the audio_hal handle. * * @param audio_hal_conf Configure structure audio_hal_config_t * @param audio_hal_func Structure containing functions used to operate audio the codec chip * * @return int, 0--success, others--fail */ audio_hal_handle_t audio_hal_init(audio_hal_codec_config_t *audio_hal_conf, audio_hal_func_t *audio_hal_func); /** * @brief Uninitialize media codec driver * * @param audio_hal reference function pointer for selected audio codec * * @return int, 0--success, others--fail */ esp_err_t audio_hal_deinit(audio_hal_handle_t audio_hal); /** * @brief Start/stop codec driver * * @param audio_hal reference function pointer for selected audio codec * @param mode select media hal codec mode either encode/decode/or both to start from audio_hal_codec_mode_t * @param audio_hal_ctrl select start stop state for specific mode * * @return int, 0--success, others--fail */ esp_err_t audio_hal_ctrl_codec(audio_hal_handle_t audio_hal, audio_hal_codec_mode_t mode, audio_hal_ctrl_t audio_hal_ctrl); /** * @brief Set codec I2S interface samples rate & bit width and format either I2S or PCM/DSP. * * @param audio_hal reference function pointer for selected audio codec * @param mode select media hal codec mode either encode/decode/or both to start from audio_hal_codec_mode_t * @param iface I2S sample rate (ex: 16000, 44100), I2S bit width (16, 24, 32),I2s format (I2S, PCM, DSP). * * @return * - 0 Success * - -1 Error */ esp_err_t audio_hal_codec_iface_config(audio_hal_handle_t audio_hal, audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface); /** * @brief Set voice mute. Enables or disables DAC mute of a codec. * @note `audio_hal_get_volume` will still give a non-zero number in mute state. It will be set to that number when speaker is unmuted. * * @param audio_hal reference function pointer for selected audio codec * @param mute true/false. If true speaker will be muted and if false speaker will be unmuted. * * @return int, 0--success, others--fail */ esp_err_t audio_hal_set_mute(audio_hal_handle_t audio_hal, bool mute); /** * @brief Set voice volume. * @note if volume is 0, mute is enabled,range is 0-100. * * @param audio_hal reference function pointer for selected audio codec * @param volume value of volume in percent(%) * * @return int, 0--success, others--fail */ esp_err_t audio_hal_set_volume(audio_hal_handle_t audio_hal, int volume); /** * @brief get voice volume. * @note if volume is 0, mute is enabled, range is 0-100. * * @param audio_hal reference function pointer for selected audio codec * @param volume value of volume in percent returned(%) * * @return int, 0--success, others--fail */ esp_err_t audio_hal_get_volume(audio_hal_handle_t audio_hal, int *volume); #ifdef __cplusplus } #endif #endif //__AUDIO_HAL_H__
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/include/audio_hal.h
C
apache-2.0
9,625
COMPONENT_ADD_LDFLAGS = -Wl,--whole-archive -l$(COMPONENT_NAME) -Wl,--no-whole-archive COMPONENT_EMBED_TXTFILES := test.pcm
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/test/component.mk
Makefile
apache-2.0
123
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "esp_log.h" #include "audio_mem.h" #include "board.h" #include "audio_hal.h" #include "driver/i2s.h" #include "driver/gpio.h" #include "unity.h" #include "es8311.h" #include "es8388.h" #include "zl38063.h" #define TEST_I2S_NUM I2S_NUM_0 static const char *TAG = "TEST_AUDIO_HAL"; extern const uint8_t test_pcm_start[] asm("_binary_test_pcm_start"); extern const uint8_t test_pcm_end[] asm("_binary_test_pcm_end"); static void i2s_init() { i2s_config_t i2s_cfg = { .mode = I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_RX, .sample_rate = 16000, .bits_per_sample = 16, .channel_format = I2S_CHANNEL_FMT_ONLY_RIGHT, .communication_format = I2S_COMM_FORMAT_I2S, .dma_buf_count = 3, .dma_buf_len = 300, .use_apll = 1, .intr_alloc_flags = ESP_INTR_FLAG_LEVEL2, }; i2s_driver_install(TEST_I2S_NUM, &i2s_cfg, 0, NULL); i2s_pin_config_t i2s_pin_cfg = {0}; get_i2s_pins(TEST_I2S_NUM, &i2s_pin_cfg); i2s_set_pin(TEST_I2S_NUM, &i2s_pin_cfg); i2s_mclk_gpio_select(TEST_I2S_NUM, GPIO_NUM_0); } static void i2s_deinit() { i2s_driver_uninstall(TEST_I2S_NUM); } TEST_CASE("Usage test", "[audio_hal]") { ESP_LOGI(TAG, "Initialize i2s"); i2s_init(); ESP_LOGI(TAG, "Start codec chip"); audio_board_handle_t board_handle = audio_board_init(); TEST_ASSERT_NOT_NULL(board_handle); TEST_ASSERT_FALSE(audio_hal_ctrl_codec(board_handle->audio_hal, AUDIO_HAL_CODEC_MODE_DECODE, AUDIO_HAL_CTRL_START)); ESP_LOGI(TAG, "Set codec volume"); TEST_ASSERT_FALSE(audio_hal_set_volume(board_handle->audio_hal, 65)); int volume = 0; TEST_ASSERT_FALSE(audio_hal_get_volume(board_handle->audio_hal, &volume)); ESP_LOGI(TAG, "Get codec volume: %d", volume); size_t bytes_written = 0; ESP_LOGI(TAG, "Start to play music"); TEST_ASSERT_FALSE(i2s_write(TEST_I2S_NUM, test_pcm_start, test_pcm_end - test_pcm_start, &bytes_written, portMAX_DELAY)); ESP_LOGW(TAG, "Reach the end of music, release all resource"); TEST_ASSERT_FALSE(audio_board_deinit(board_handle)); i2c_driver_delete(I2C_NUM_0); i2s_deinit(); } /* * To run this case, please choose Lyrat_v4.3 in menuconfig and run on lyrat_v4.3 board */ TEST_CASE("Test for es8388 driver", "[audio_hal]") { ESP_LOGI(TAG, "Initialize i2s"); i2s_init(); ESP_LOGI(TAG, "Start es8388 codec chip"); audio_hal_codec_config_t es8388_cfg = AUDIO_CODEC_DEFAULT_CONFIG(); TEST_ASSERT_FALSE(es8388_init(&es8388_cfg)); TEST_ASSERT_FALSE(es8388_config_i2s(es8388_cfg.codec_mode, &es8388_cfg.i2s_iface)); TEST_ASSERT_FALSE(es8388_ctrl_state(AUDIO_HAL_CODEC_MODE_BOTH, AUDIO_HAL_CTRL_START)); TEST_ASSERT_FALSE(es8388_set_voice_volume(50)); size_t bytes_written = 0; ESP_LOGI(TAG, "Start to play music"); TEST_ASSERT_FALSE(i2s_write(TEST_I2S_NUM, test_pcm_start, test_pcm_end - test_pcm_start, &bytes_written, portMAX_DELAY)); ESP_LOGW(TAG, "Reach the end of music, release all resource"); i2c_driver_delete(I2C_NUM_0); i2s_deinit(); } /* * To run this case, please choose Lyrat_mini in menuconfig and run on lyrat_mini board */ TEST_CASE("Test for es8311 driver", "[audio_hal]") { ESP_LOGI(TAG, "Initialize i2s"); i2s_init(); ESP_LOGI(TAG, "Start es8311 codec chip"); audio_hal_codec_config_t es8311_cfg = AUDIO_CODEC_DEFAULT_CONFIG(); TEST_ASSERT_FALSE(es8311_codec_init(&es8311_cfg)); TEST_ASSERT_FALSE(es8311_codec_config_i2s(es8311_cfg.codec_mode, &es8311_cfg.i2s_iface)); TEST_ASSERT_FALSE(es8311_codec_ctrl_state(AUDIO_HAL_CODEC_MODE_BOTH, AUDIO_HAL_CTRL_START)); TEST_ASSERT_FALSE(es8311_codec_set_voice_volume(50)); size_t bytes_written = 0; ESP_LOGI(TAG, "Start to play music"); TEST_ASSERT_FALSE(i2s_write(TEST_I2S_NUM, test_pcm_start, test_pcm_end - test_pcm_start, &bytes_written, portMAX_DELAY)); ESP_LOGW(TAG, "Reach the end of music, release all resource"); i2c_driver_delete(I2C_NUM_0); i2s_deinit(); } /* * To run this case, please choose LyratD_MSC in menuconfig and run on lyratD_MSC board */ TEST_CASE("Test for zl38063 driver", "[audio_hal]") { ESP_LOGI(TAG, "Initialize i2s"); i2s_init(); ESP_LOGI(TAG, "Start zl38063 DSP"); audio_hal_codec_config_t zl38063_cfg = AUDIO_CODEC_DEFAULT_CONFIG(); TEST_ASSERT_FALSE(zl38063_codec_init(&zl38063_cfg)); TEST_ASSERT_FALSE(zl38063_codec_config_i2s(zl38063_cfg.codec_mode, &zl38063_cfg.i2s_iface)); TEST_ASSERT_FALSE(zl38063_codec_ctrl_state(AUDIO_HAL_CODEC_MODE_BOTH, AUDIO_HAL_CTRL_START)); TEST_ASSERT_FALSE(zl38063_codec_set_voice_volume(50)); size_t bytes_written = 0; ESP_LOGI(TAG, "Start to play music"); TEST_ASSERT_FALSE(i2s_write(TEST_I2S_NUM, test_pcm_start, test_pcm_end - test_pcm_start, &bytes_written, portMAX_DELAY)); ESP_LOGW(TAG, "Reach the end of music, release all resource"); i2c_driver_delete(I2C_NUM_0); i2s_deinit(); }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_hal/test/test_audio_hal.c
C
apache-2.0
6,215
set(COMPONENT_ADD_INCLUDEDIRS "include") set(COMPONENT_SRCS "audio_element.c" "audio_event_iface.c" "audio_pipeline.c" "ringbuf.c") set(COMPONENT_REQUIRES audio_sal esp-adf-libs) register_component()
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/CMakeLists.txt
CMake
apache-2.0
264
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <stdlib.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/event_groups.h" #include "esp_log.h" #include "audio_element.h" #include "audio_mem.h" #include "audio_mutex.h" #include "audio_error.h" #include "audio_thread.h" static const char *TAG = "AUDIO_ELEMENT"; #define DEFAULT_MAX_WAIT_TIME (2000/portTICK_RATE_MS) /** * I/O Element Abstract */ typedef struct io_callback { stream_func cb; void *ctx; } io_callback_t; /** * Audio Callback Abstract */ typedef struct audio_callback { event_cb_func cb; void *ctx; } audio_callback_t; typedef struct audio_multi_rb { ringbuf_handle_t *rb; int max_rb_num; } audio_multi_rb_t; typedef enum { IO_TYPE_RB = 1, /* I/O through ringbuffer */ IO_TYPE_CB, /* I/O through callback */ } io_type_t; typedef enum { EVENTS_TYPE_Q = 1, /* Events through MessageQueue */ EVENTS_TYPE_CB, /* Events through Callback function */ } events_type_t; struct audio_element { /* Functions/RingBuffers */ el_io_func open; ctrl_func seek; process_func process; el_io_func close; el_io_func destroy; io_type_t read_type; union { ringbuf_handle_t input_rb; io_callback_t read_cb; } in; io_type_t write_type; union { ringbuf_handle_t output_rb; io_callback_t write_cb; } out; audio_multi_rb_t multi_in; audio_multi_rb_t multi_out; /* Properties */ volatile bool is_open; audio_element_state_t state; events_type_t events_type; audio_event_iface_handle_t iface_event; audio_callback_t callback_event; int buf_size; char *buf; char *tag; int task_stack; int task_prio; int task_core; xSemaphoreHandle lock; audio_element_info_t info; audio_element_info_t *report_info; bool stack_in_ext; audio_thread_t audio_thread; /* PrivateData */ void *data; EventGroupHandle_t state_event; int input_wait_time; int output_wait_time; int out_buf_size_expect; int out_rb_size; volatile bool is_running; volatile bool task_run; volatile bool stopping; }; const static int STOPPED_BIT = BIT0; const static int STARTED_BIT = BIT1; const static int BUFFER_REACH_LEVEL_BIT = BIT2; const static int TASK_CREATED_BIT = BIT3; const static int TASK_DESTROYED_BIT = BIT4; const static int PAUSED_BIT = BIT5; const static int RESUMED_BIT = BIT6; static esp_err_t audio_element_on_cmd_error(audio_element_handle_t el); static esp_err_t audio_element_on_cmd_stop(audio_element_handle_t el); static esp_err_t audio_element_force_set_state(audio_element_handle_t el, audio_element_state_t new_state) { el->state = new_state; return ESP_OK; } static esp_err_t audio_element_cmd_send(audio_element_handle_t el, audio_element_msg_cmd_t cmd) { audio_event_iface_msg_t msg = { .source = el, .source_type = AUDIO_ELEMENT_TYPE_ELEMENT, .cmd = cmd, }; ESP_LOGV(TAG, "[%s]evt internal cmd = %d", el->tag, msg.cmd); return audio_event_iface_cmd(el->iface_event, &msg); } static esp_err_t audio_element_msg_sendout(audio_element_handle_t el, audio_event_iface_msg_t *msg) { msg->source = el; msg->source_type = AUDIO_ELEMENT_TYPE_ELEMENT; if (el->events_type == EVENTS_TYPE_CB && el->callback_event.cb) { return el->callback_event.cb(el, msg, el->callback_event.ctx); } return audio_event_iface_sendout(el->iface_event, msg); } esp_err_t audio_element_process_init(audio_element_handle_t el) { if (el->open == NULL) { el->is_open = true; xEventGroupSetBits(el->state_event, STARTED_BIT); return ESP_OK; } el->is_open = true; audio_element_force_set_state(el, AEL_STATE_INITIALIZING); esp_err_t ret = el->open(el); if (ret == ESP_OK) { ESP_LOGD(TAG, "[%s] el opened", el->tag); audio_element_force_set_state(el, AEL_STATE_RUNNING); audio_element_report_status(el, AEL_STATUS_STATE_RUNNING); xEventGroupSetBits(el->state_event, STARTED_BIT); return ESP_OK; } else if (ret == AEL_IO_DONE) { ESP_LOGW(TAG, "[%s] OPEN AEL_IO_DONE", el->tag); audio_element_force_set_state(el, AEL_STATE_RUNNING); audio_element_report_status(el, AEL_STATUS_STATE_RUNNING); return ESP_OK; } else if (ret == AEL_IO_ABORT) { ESP_LOGW(TAG, "[%s] AEL_IO_ABORT, %d", el->tag, ret); audio_element_on_cmd_stop(el); } else { ESP_LOGE(TAG, "[%s] AEL_STATUS_ERROR_OPEN,%d", el->tag, ret); audio_element_force_set_state(el, AEL_STATE_ERROR); audio_element_report_status(el, AEL_STATUS_ERROR_OPEN); audio_element_on_cmd_error(el); } return ESP_FAIL; } esp_err_t audio_element_process_deinit(audio_element_handle_t el) { if (el->is_open && el->close) { ESP_LOGV(TAG, "[%s] will be closed, line %d", el->tag, __LINE__); el->close(el); } el->is_open = false; return ESP_OK; } static esp_err_t audio_element_on_cmd_error(audio_element_handle_t el) { if (el->state != AEL_STATE_STOPPED) { ESP_LOGW(TAG, "[%s] audio_element_on_cmd_error,%d", el->tag, el->state); audio_element_process_deinit(el); el->state = AEL_STATE_ERROR; audio_event_iface_set_cmd_waiting_timeout(el->iface_event, portMAX_DELAY); el->is_running = false; xEventGroupSetBits(el->state_event, STOPPED_BIT); } return ESP_OK; } static esp_err_t audio_element_on_cmd_stop(audio_element_handle_t el) { if ((el->state != AEL_STATE_FINISHED) && (el->state != AEL_STATE_STOPPED)) { audio_element_process_deinit(el); el->state = AEL_STATE_STOPPED; audio_event_iface_set_cmd_waiting_timeout(el->iface_event, portMAX_DELAY); audio_element_report_status(el, AEL_STATUS_STATE_STOPPED); el->is_running = false; el->stopping = false; ESP_LOGD(TAG, "[%s] audio_element_on_cmd_stop", el->tag); xEventGroupSetBits(el->state_event, STOPPED_BIT); } else { // Change element state to AEL_STATE_STOPPED, even if AEL_STATE_ERROR or AEL_STATE_FINISHED // Except AEL_STATE_STOPPED and is not running ESP_LOGD(TAG, "[%s] audio_element_on_cmd_stop, state:%d", el->tag, el->state); if ((el->is_running == false) && (el->state == AEL_STATE_STOPPED)) { el->stopping = false; return ESP_OK; } el->state = AEL_STATE_STOPPED; el->is_running = false; el->stopping = false; audio_element_report_status(el, AEL_STATUS_STATE_STOPPED); xEventGroupSetBits(el->state_event, STOPPED_BIT); } return ESP_OK; } static esp_err_t audio_element_on_cmd_finish(audio_element_handle_t el) { if ((el->state == AEL_STATE_ERROR) || (el->state == AEL_STATE_STOPPED)) { ESP_LOGD(TAG, "[%s] audio_element_on_cmd_finish, state:%d", el->tag, el->state); return ESP_OK; } audio_element_process_deinit(el); el->state = AEL_STATE_FINISHED; audio_event_iface_set_cmd_waiting_timeout(el->iface_event, portMAX_DELAY); audio_element_report_status(el, AEL_STATUS_STATE_FINISHED); el->is_running = false; xEventGroupSetBits(el->state_event, STOPPED_BIT); ESP_LOGD(TAG, "[%s] audio_element_on_cmd_finish", el->tag); return ESP_OK; } static esp_err_t audio_element_on_cmd_resume(audio_element_handle_t el) { if (el->state == AEL_STATE_RUNNING) { el->is_running = true; xEventGroupSetBits(el->state_event, RESUMED_BIT); return ESP_OK; } if (el->state != AEL_STATE_INIT && el->state != AEL_STATE_RUNNING && el->state != AEL_STATE_PAUSED) { audio_element_reset_output_ringbuf(el); } el->is_running = true; xEventGroupSetBits(el->state_event, RESUMED_BIT); if (audio_element_process_init(el) != ESP_OK) { audio_element_abort_output_ringbuf(el); audio_element_abort_input_ringbuf(el); el->is_running = false; return ESP_FAIL; } audio_event_iface_set_cmd_waiting_timeout(el->iface_event, 0); xEventGroupClearBits(el->state_event, STOPPED_BIT); return ESP_OK; } static esp_err_t audio_element_on_cmd(audio_event_iface_msg_t *msg, void *context) { audio_element_handle_t el = (audio_element_handle_t)context; if (msg->source_type != AUDIO_ELEMENT_TYPE_ELEMENT) { ESP_LOGE(TAG, "[%s] Invalid event type, this event should be ELEMENT type", el->tag); return ESP_FAIL; } esp_err_t ret = ESP_OK; //process an event switch (msg->cmd) { case AEL_MSG_CMD_FINISH: ESP_LOGD(TAG, "[%s] AEL_MSG_CMD_FINISH, state:%d", el->tag, el->state); ret = audio_element_on_cmd_finish(el); break; case AEL_MSG_CMD_STOP: ESP_LOGD(TAG, "[%s] AEL_MSG_CMD_STOP, state:%d", el->tag, el->state); ret = audio_element_on_cmd_stop(el); break; case AEL_MSG_CMD_PAUSE: el->state = AEL_STATE_PAUSED; audio_element_process_deinit(el); audio_event_iface_set_cmd_waiting_timeout(el->iface_event, portMAX_DELAY); audio_element_report_status(el, AEL_STATUS_STATE_PAUSED); el->is_running = false; ESP_LOGI(TAG, "[%s] AEL_MSG_CMD_PAUSE", el->tag); xEventGroupSetBits(el->state_event, PAUSED_BIT); break; case AEL_MSG_CMD_RESUME: ESP_LOGI(TAG, "[%s] AEL_MSG_CMD_RESUME,state:%d", el->tag, el->state); ret = audio_element_on_cmd_resume(el); break; case AEL_MSG_CMD_DESTROY: el->is_running = false; ESP_LOGD(TAG, "[%s] AEL_MSG_CMD_DESTROY", el->tag); ret = AEL_IO_ABORT; } return ret; } static esp_err_t audio_element_process_running(audio_element_handle_t el) { int process_len = -1; if (el->state < AEL_STATE_RUNNING || !el->is_running) { return ESP_ERR_INVALID_STATE; } process_len = el->process(el, el->buf, el->buf_size); if (process_len <= 0) { switch (process_len) { case AEL_IO_ABORT: ESP_LOGD(TAG, "[%s] ERROR_PROCESS, AEL_IO_ABORT", el->tag); audio_element_on_cmd_stop(el); break; case AEL_IO_DONE: case AEL_IO_OK: // Re-open if reset_state function called if (audio_element_get_state(el) == AEL_STATE_INIT) { return audio_element_on_cmd_resume(el); } audio_element_set_ringbuf_done(el); audio_element_on_cmd_finish(el); break; case AEL_IO_FAIL: ESP_LOGE(TAG, "[%s] ERROR_PROCESS, AEL_IO_FAIL", el->tag); audio_element_report_status(el, AEL_STATUS_ERROR_PROCESS); audio_element_on_cmd_error(el); break; case AEL_IO_TIMEOUT: ESP_LOGD(TAG, "[%s] ERROR_PROCESS, AEL_IO_TIMEOUT", el->tag); break; case AEL_PROCESS_FAIL: ESP_LOGE(TAG, "[%s] ERROR_PROCESS, AEL_PROCESS_FAIL", el->tag); audio_element_report_status(el, AEL_STATUS_ERROR_PROCESS); audio_element_on_cmd_error(el); break; default: ESP_LOGW(TAG, "[%s] Process return error,ret:%d", el->tag, process_len); break; } } return ESP_OK; } audio_element_err_t audio_element_input(audio_element_handle_t el, char *buffer, int wanted_size) { int in_len = 0; if (el->read_type == IO_TYPE_CB) { if (el->in.read_cb.cb == NULL) { ESP_LOGE(TAG, "[%s] Read IO Type callback but callback not set", el->tag); return ESP_FAIL; } in_len = el->in.read_cb.cb(el, buffer, wanted_size, el->input_wait_time, el->in.read_cb.ctx); } else if (el->read_type == IO_TYPE_RB) { if (el->in.input_rb == NULL) { ESP_LOGE(TAG, "[%s] Read IO type ringbuf but ringbuf not set", el->tag); return ESP_FAIL; } in_len = rb_read(el->in.input_rb, buffer, wanted_size, el->input_wait_time); } else { ESP_LOGE(TAG, "[%s] Invalid read IO type", el->tag); return ESP_FAIL; } if (in_len <= 0) { switch (in_len) { case AEL_IO_ABORT: ESP_LOGW(TAG, "IN-[%s] AEL_IO_ABORT", el->tag); break; case AEL_IO_DONE: case AEL_IO_OK: ESP_LOGI(TAG, "IN-[%s] AEL_IO_DONE,%d", el->tag, in_len); break; case AEL_IO_FAIL: ESP_LOGE(TAG, "IN-[%s] AEL_STATUS_ERROR_INPUT", el->tag); audio_element_report_status(el, AEL_STATUS_ERROR_INPUT); break; case AEL_IO_TIMEOUT: // ESP_LOGD(TAG, "IN-[%s] AEL_IO_TIMEOUT", el->tag); break; default: ESP_LOGE(TAG, "IN-[%s] Input return not support,ret:%d", el->tag, in_len); break; } } return in_len; } audio_element_err_t audio_element_output(audio_element_handle_t el, char *buffer, int write_size) { int output_len = 0; if (el->write_type == IO_TYPE_CB) { if (el->out.write_cb.cb && write_size) { output_len = el->out.write_cb.cb(el, buffer, write_size, el->output_wait_time, el->out.write_cb.ctx); } } else if (el->write_type == IO_TYPE_RB) { if (el->out.output_rb && write_size) { output_len = rb_write(el->out.output_rb, buffer, write_size, el->output_wait_time); if ((rb_bytes_filled(el->out.output_rb) > el->out_buf_size_expect) || (output_len < 0)) { xEventGroupSetBits(el->state_event, BUFFER_REACH_LEVEL_BIT); } } } if (output_len <= 0) { switch (output_len) { case AEL_IO_ABORT: ESP_LOGW(TAG, "OUT-[%s] AEL_IO_ABORT", el->tag); break; case AEL_IO_DONE: case AEL_IO_OK: ESP_LOGI(TAG, "OUT-[%s] AEL_IO_DONE,%d", el->tag, output_len); break; case AEL_IO_FAIL: ESP_LOGE(TAG, "OUT-[%s] AEL_STATUS_ERROR_OUTPUT", el->tag); audio_element_report_status(el, AEL_STATUS_ERROR_OUTPUT); break; case AEL_IO_TIMEOUT: ESP_LOGW(TAG, "OUT-[%s] AEL_IO_TIMEOUT", el->tag); break; default: ESP_LOGE(TAG, "OUT-[%s] Output return not support,ret:%d", el->tag, output_len); break; } } return output_len; } void audio_element_task(void *pv) { audio_element_handle_t el = (audio_element_handle_t)pv; el->task_run = true; xEventGroupSetBits(el->state_event, TASK_CREATED_BIT); audio_element_force_set_state(el, AEL_STATE_INIT); audio_event_iface_set_cmd_waiting_timeout(el->iface_event, portMAX_DELAY); if (el->buf_size > 0) { el->buf = audio_calloc(1, el->buf_size); AUDIO_MEM_CHECK(TAG, el->buf, { el->task_run = false; ESP_LOGE(TAG, "[%s] Error malloc element buffer", el->tag); }); } xEventGroupClearBits(el->state_event, STOPPED_BIT); esp_err_t ret = ESP_OK; while (el->task_run) { if ((ret = audio_event_iface_waiting_cmd_msg(el->iface_event)) != ESP_OK) { xEventGroupSetBits(el->state_event, STOPPED_BIT); /* * Do not exit task when audio_element_process_init failure to * make call audio_element_deinit safety. */ if (ret == AEL_IO_ABORT) { break; } } if (audio_element_process_running(el) != ESP_OK) { // continue; } } if (el->is_open && el->close) { ESP_LOGD(TAG, "[%s-%p] el closed", el->tag, el); el->close(el); audio_element_force_set_state(el, AEL_STATE_STOPPED); } el->is_open = false; audio_free(el->buf); el->buf = NULL; el->stopping = false; el->task_run = false; ESP_LOGD(TAG, "[%s-%p] el task deleted,%d", el->tag, el, uxTaskGetStackHighWaterMark(NULL)); xEventGroupSetBits(el->state_event, STOPPED_BIT); xEventGroupSetBits(el->state_event, RESUMED_BIT); xEventGroupSetBits(el->state_event, TASK_DESTROYED_BIT); audio_thread_delete_task(&el->audio_thread); } esp_err_t audio_element_reset_state(audio_element_handle_t el) { return audio_element_force_set_state(el, AEL_STATE_INIT); } audio_element_state_t audio_element_get_state(audio_element_handle_t el) { if (el) { return el->state; } return ESP_FAIL; } QueueHandle_t audio_element_get_event_queue(audio_element_handle_t el) { if (!el) { return NULL; } return audio_event_iface_get_queue_handle(el->iface_event); } esp_err_t audio_element_setdata(audio_element_handle_t el, void *data) { el->data = data; return ESP_OK; } void *audio_element_getdata(audio_element_handle_t el) { return el->data; } esp_err_t audio_element_set_tag(audio_element_handle_t el, const char *tag) { if (el->tag) { audio_free(el->tag); el->tag = NULL; } if (tag) { el->tag = audio_strdup(tag); AUDIO_MEM_CHECK(TAG, el->tag, { return ESP_ERR_NO_MEM; }); } return ESP_OK; } char *audio_element_get_tag(audio_element_handle_t el) { return el->tag; } esp_err_t audio_element_set_uri(audio_element_handle_t el, const char *uri) { mutex_lock(el->lock); if (el->info.uri) { audio_free(el->info.uri); el->info.uri = NULL; } if (uri) { el->info.uri = audio_strdup(uri); AUDIO_MEM_CHECK(TAG, el->info.uri, { mutex_unlock(el->lock); return ESP_ERR_NO_MEM; }); } mutex_unlock(el->lock); return ESP_OK; } char *audio_element_get_uri(audio_element_handle_t el) { mutex_lock(el->lock); char *uri = el->info.uri; mutex_unlock(el->lock); return uri; } esp_err_t audio_element_set_event_callback(audio_element_handle_t el, event_cb_func cb_func, void *ctx) { el->events_type = EVENTS_TYPE_CB; el->callback_event.cb = cb_func; el->callback_event.ctx = ctx; return ESP_OK; } esp_err_t audio_element_msg_set_listener(audio_element_handle_t el, audio_event_iface_handle_t listener) { return audio_event_iface_set_listener(el->iface_event, listener); } esp_err_t audio_element_msg_remove_listener(audio_element_handle_t el, audio_event_iface_handle_t listener) { return audio_event_iface_remove_listener(listener, el->iface_event); } esp_err_t audio_element_setinfo(audio_element_handle_t el, audio_element_info_t *info) { if (info && el) { //FIXME: We will got reset if lock mutex here mutex_lock(el->lock); memcpy(&el->info, info, sizeof(audio_element_info_t)); mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_getinfo(audio_element_handle_t el, audio_element_info_t *info) { if (info && el) { mutex_lock(el->lock); memcpy(info, &el->info, sizeof(audio_element_info_t)); mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_report_info(audio_element_handle_t el) { if (el) { audio_event_iface_msg_t msg = { 0 }; msg.cmd = AEL_MSG_CMD_REPORT_MUSIC_INFO; msg.data = NULL; ESP_LOGD(TAG, "REPORT_INFO,[%s]evt out cmd:%d,", el->tag, msg.cmd); audio_element_msg_sendout(el, &msg); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_report_codec_fmt(audio_element_handle_t el) { if (el) { audio_event_iface_msg_t msg = { 0 }; msg.cmd = AEL_MSG_CMD_REPORT_CODEC_FMT; msg.data = NULL; ESP_LOGD(TAG, "REPORT_FMT,[%s]evt out cmd:%d,", el->tag, msg.cmd); audio_element_msg_sendout(el, &msg); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_report_status(audio_element_handle_t el, audio_element_status_t status) { if (el) { audio_event_iface_msg_t msg = { 0 }; msg.cmd = AEL_MSG_CMD_REPORT_STATUS; msg.data = (void *)status; msg.data_len = sizeof(status); ESP_LOGD(TAG, "REPORT_STATUS,[%s]evt out cmd = %d,status:%d", el->tag, msg.cmd, status); return audio_element_msg_sendout(el, &msg); } return ESP_FAIL; } esp_err_t audio_element_report_pos(audio_element_handle_t el) { if (el) { audio_event_iface_msg_t msg = { 0 }; msg.cmd = AEL_MSG_CMD_REPORT_POSITION; if (el->report_info == NULL) { el->report_info = audio_calloc(1, sizeof(audio_element_info_t)); AUDIO_MEM_CHECK(TAG, el->report_info, return ESP_ERR_NO_MEM); } audio_element_getinfo(el, el->report_info); msg.data = el->report_info; msg.data_len = sizeof(audio_element_info_t); ESP_LOGD(TAG, "REPORT_POS,[%s]evt out cmd:%d,", el->tag, msg.cmd); audio_element_msg_sendout(el, &msg); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_finish_state(audio_element_handle_t el) { if (el->task_stack <= 0) { el->state = AEL_STATE_FINISHED; audio_element_report_status(el, AEL_STATUS_STATE_FINISHED); el->is_running = false; xEventGroupSetBits(el->state_event, STOPPED_BIT); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_change_cmd(audio_element_handle_t el, audio_element_msg_cmd_t cmd) { AUDIO_NULL_CHECK(TAG, el, return ESP_ERR_INVALID_ARG); return audio_element_cmd_send(el, cmd); } esp_err_t audio_element_reset_input_ringbuf(audio_element_handle_t el) { if (el->read_type != IO_TYPE_RB) { return ESP_FAIL; } int ret = ESP_OK; if (el->in.input_rb) { ret |= rb_reset(el->in.input_rb); for (int i = 0; i < el->multi_in.max_rb_num; ++i) { if (el->multi_in.rb[i]) { ret |= rb_reset(el->multi_in.rb[i]); } } } return ret; } esp_err_t audio_element_reset_output_ringbuf(audio_element_handle_t el) { if (el->write_type != IO_TYPE_RB) { return ESP_FAIL; } int ret = ESP_OK; if (el->out.output_rb) { ret |= rb_reset(el->out.output_rb); for (int i = 0; i < el->multi_out.max_rb_num; ++i) { if (el->multi_out.rb[i]) { ret |= rb_reset(el->multi_out.rb[i]); } } } return ESP_OK; } esp_err_t audio_element_abort_input_ringbuf(audio_element_handle_t el) { if (el->read_type != IO_TYPE_RB) { return ESP_FAIL; } int ret = ESP_OK; if (el->in.input_rb) { ret |= rb_abort(el->in.input_rb); for (int i = 0; i < el->multi_in.max_rb_num; ++i) { if (el->multi_in.rb[i]) { ret |= rb_abort(el->multi_in.rb[i]); } } } return ESP_OK; } esp_err_t audio_element_abort_output_ringbuf(audio_element_handle_t el) { if (el->write_type != IO_TYPE_RB) { return ESP_FAIL; } int ret = ESP_OK; if (el->out.output_rb) { ret |= rb_abort(el->out.output_rb); for (int i = 0; i < el->multi_out.max_rb_num; ++i) { if (el->multi_out.rb[i]) { ret |= rb_abort(el->multi_out.rb[i]); } } } return ESP_OK; } esp_err_t audio_element_set_ringbuf_done(audio_element_handle_t el) { int ret = ESP_OK; if (NULL == el) { return ESP_FAIL; } if (el->out.output_rb && el->write_type == IO_TYPE_RB) { ret |= rb_done_write(el->out.output_rb); for (int i = 0; i < el->multi_out.max_rb_num; ++i) { if (el->multi_out.rb[i]) { ret |= rb_done_write(el->multi_out.rb[i]); } } } return ret; } esp_err_t audio_element_set_input_ringbuf(audio_element_handle_t el, ringbuf_handle_t rb) { if (rb) { el->in.input_rb = rb; el->read_type = IO_TYPE_RB; } else if (el->read_type == IO_TYPE_RB) { el->in.input_rb = rb; } return ESP_OK; } ringbuf_handle_t audio_element_get_input_ringbuf(audio_element_handle_t el) { if (el->read_type == IO_TYPE_RB) { return el->in.input_rb; } else { return NULL; } } esp_err_t audio_element_set_output_ringbuf(audio_element_handle_t el, ringbuf_handle_t rb) { if (rb) { el->out.output_rb = rb; el->write_type = IO_TYPE_RB; } else if (el->write_type == IO_TYPE_RB) { el->out.output_rb = rb; } return ESP_OK; } ringbuf_handle_t audio_element_get_output_ringbuf(audio_element_handle_t el) { if (el->write_type == IO_TYPE_RB) { return el->out.output_rb; } else { return NULL; } } esp_err_t audio_element_set_input_timeout(audio_element_handle_t el, TickType_t timeout) { if (el) { el->input_wait_time = timeout; return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_output_timeout(audio_element_handle_t el, TickType_t timeout) { if (el) { el->output_wait_time = timeout; return ESP_OK; } return ESP_FAIL; } int audio_element_get_output_ringbuf_size(audio_element_handle_t el) { if (el) { return el->out_rb_size; } return 0; } esp_err_t audio_element_set_output_ringbuf_size(audio_element_handle_t el, int rb_size) { if (el) { el->out_rb_size = rb_size; return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_read_cb(audio_element_handle_t el, stream_func fn, void *context) { if (el) { el->in.read_cb.cb = fn; el->in.read_cb.ctx = context; el->read_type = IO_TYPE_CB; return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_write_cb(audio_element_handle_t el, stream_func fn, void *context) { if (el) { el->out.write_cb.cb = fn; el->out.write_cb.ctx = context; el->write_type = IO_TYPE_CB; return ESP_OK; } return ESP_FAIL; } stream_func audio_element_get_write_cb(audio_element_handle_t el) { if (el && el->write_type == IO_TYPE_CB) { return el->out.write_cb.cb; } ESP_LOGE(TAG, "Fail to get write callback"); return NULL; } stream_func audio_element_get_read_cb(audio_element_handle_t el) { if (el && el->read_type == IO_TYPE_CB) { return el->in.read_cb.cb; } ESP_LOGE(TAG, "Fail to get read callback"); return NULL; } esp_err_t audio_element_wait_for_stop(audio_element_handle_t el) { if (el->is_running == false) { ESP_LOGD(TAG, "[%s] Element already stopped, return without waiting", el->tag); return ESP_FAIL; } EventBits_t uxBits = xEventGroupWaitBits(el->state_event, STOPPED_BIT, false, true, DEFAULT_MAX_WAIT_TIME); esp_err_t ret = ESP_ERR_TIMEOUT; if (uxBits & STOPPED_BIT) { ret = ESP_OK; } return ret; } esp_err_t audio_element_wait_for_buffer(audio_element_handle_t el, int size_expect, TickType_t timeout) { int ret = ESP_FAIL; el->out_buf_size_expect = size_expect; if (el->out.output_rb) { xEventGroupClearBits(el->state_event, BUFFER_REACH_LEVEL_BIT); EventBits_t uxBits = xEventGroupWaitBits(el->state_event, BUFFER_REACH_LEVEL_BIT, false, true, timeout); if ((uxBits & BUFFER_REACH_LEVEL_BIT) != 0) { ret = ESP_OK; } else { ret = ESP_FAIL; } } return ret; } audio_element_handle_t audio_element_init(audio_element_cfg_t *config) { audio_element_handle_t el = audio_calloc(1, sizeof(struct audio_element)); AUDIO_MEM_CHECK(TAG, el, { return NULL; }); audio_event_iface_cfg_t evt_cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG(); evt_cfg.on_cmd = audio_element_on_cmd; evt_cfg.context = el; evt_cfg.queue_set_size = 0; // Element have no queue_set by default. evt_cfg.external_queue_size = 5; evt_cfg.internal_queue_size = 5; bool _success = ( ((config->tag ? audio_element_set_tag(el, config->tag) : audio_element_set_tag(el, "unknown")) == ESP_OK) && (el->lock = mutex_create()) && (el->iface_event = audio_event_iface_init(&evt_cfg)) && (el->state_event = xEventGroupCreate()) ); AUDIO_MEM_CHECK(TAG, _success, goto _element_init_failed); el->open = config->open; el->process = config->process; el->close = config->close; el->destroy = config->destroy; el->seek = config->seek; el->multi_in.max_rb_num = config->multi_in_rb_num; el->multi_out.max_rb_num = config->multi_out_rb_num; if (el->multi_in.max_rb_num > 0) { el->multi_in.rb = (ringbuf_handle_t *)audio_calloc(el->multi_in.max_rb_num, sizeof(ringbuf_handle_t)); AUDIO_MEM_CHECK(TAG, el->multi_in.rb, goto _element_init_failed); } if (el->multi_out.max_rb_num > 0) { el->multi_out.rb = (ringbuf_handle_t *)audio_calloc(el->multi_out.max_rb_num, sizeof(ringbuf_handle_t)); AUDIO_MEM_CHECK(TAG, el->multi_out.rb, goto _element_init_failed); } if (config->task_stack > 0) { el->task_stack = config->task_stack; el->stack_in_ext = config->stack_in_ext; } if (config->task_prio) { el->task_prio = config->task_prio; } else { el->task_prio = DEFAULT_ELEMENT_TASK_PRIO; } if (config->task_core) { el->task_core = config->task_core; } else { el->task_core = DEFAULT_ELEMENT_TASK_CORE; } if (config->out_rb_size > 0) { el->out_rb_size = config->out_rb_size; } else { el->out_rb_size = DEFAULT_ELEMENT_RINGBUF_SIZE; } el->data = config ->data; el->state = AEL_STATE_INIT; el->buf_size = config->buffer_len; audio_element_info_t info = AUDIO_ELEMENT_INFO_DEFAULT(); audio_element_setinfo(el, &info); audio_element_set_input_timeout(el, portMAX_DELAY); audio_element_set_output_timeout(el, portMAX_DELAY); if (config->read != NULL) { el->read_type = IO_TYPE_CB; el->in.read_cb.cb = config->read; } else { el->read_type = IO_TYPE_RB; } if (config->write != NULL) { el->write_type = IO_TYPE_CB; el->out.write_cb.cb = config->write; } else { el->write_type = IO_TYPE_RB; } el->events_type = EVENTS_TYPE_Q; return el; _element_init_failed: audio_element_set_uri(el, NULL); if (el->lock) { mutex_destroy(el->lock); } if (el->state_event) { vEventGroupDelete(el->state_event); } if (el->iface_event) { audio_event_iface_destroy(el->iface_event); } if (el->tag) { audio_element_set_tag(el, NULL); } if (el->multi_in.rb) { audio_free(el->multi_in.rb); el->multi_in.rb = NULL; } if (el->multi_out.rb) { audio_free(el->multi_out.rb); el->multi_out.rb = NULL; } audio_free(el); return NULL; } esp_err_t audio_element_deinit(audio_element_handle_t el) { audio_element_stop(el); audio_element_wait_for_stop(el); audio_element_terminate(el); vEventGroupDelete(el->state_event); audio_event_iface_destroy(el->iface_event); if (el->destroy) { el->destroy(el); } audio_element_set_tag(el, NULL); audio_element_set_uri(el, NULL); if (el->multi_in.rb) { audio_free(el->multi_in.rb); el->multi_in.rb = NULL; } if (el->multi_out.rb) { audio_free(el->multi_out.rb); el->multi_out.rb = NULL; } if (el->report_info) { audio_free(el->report_info); } if (el->audio_thread) { audio_thread_cleanup(&el->audio_thread); } mutex_destroy(el->lock); el->lock = NULL; audio_free(el); return ESP_OK; } esp_err_t audio_element_run(audio_element_handle_t el) { char task_name[32]; esp_err_t ret = ESP_FAIL; if (el->task_run) { ESP_LOGD(TAG, "[%s-%p] Element already created", el->tag, el); return ESP_OK; } ESP_LOGV(TAG, "[%s] Element starting...", el->tag); snprintf(task_name, 32, "el-%s", el->tag); audio_event_iface_discard(el->iface_event); xEventGroupClearBits(el->state_event, TASK_CREATED_BIT); if (el->task_stack > 0) { ret = audio_thread_create(&el->audio_thread, el->tag, audio_element_task, el, el->task_stack, el->task_prio, el->stack_in_ext, el->task_core); if (ret == ESP_FAIL) { audio_element_force_set_state(el, AEL_STATE_ERROR); audio_element_report_status(el, AEL_STATUS_ERROR_OPEN); ESP_LOGE(TAG, "[%s] audio_thread_create failed", el->tag); return ESP_FAIL; } EventBits_t uxBits = xEventGroupWaitBits(el->state_event, TASK_CREATED_BIT, false, true, DEFAULT_MAX_WAIT_TIME); if (uxBits & TASK_CREATED_BIT) { ret = ESP_OK; } } else { el->task_run = true; el->is_running = true; audio_element_force_set_state(el, AEL_STATE_RUNNING); audio_element_report_status(el, AEL_STATUS_STATE_RUNNING); ret = ESP_OK; } ESP_LOGI(TAG, "[%s-%p] Element task created", el->tag, el); return ret; } static inline esp_err_t __audio_element_term(audio_element_handle_t el, TickType_t ticks_to_wait) { xEventGroupClearBits(el->state_event, TASK_DESTROYED_BIT); if (audio_element_cmd_send(el, AEL_MSG_CMD_DESTROY) != ESP_OK) { ESP_LOGE(TAG, "[%s] Send destroy command failed", el->tag); return ESP_FAIL; } EventBits_t uxBits = xEventGroupWaitBits(el->state_event, TASK_DESTROYED_BIT, false, true, ticks_to_wait); esp_err_t ret = ESP_FAIL; if (uxBits & TASK_DESTROYED_BIT ) { ESP_LOGD(TAG, "[%s-%p] Element task destroyed", el->tag, el); ret = ESP_OK; } else { ESP_LOGW(TAG, "[%s-%p] Element task destroy timeout[%d]", el->tag, el, ticks_to_wait); } return ret; } esp_err_t audio_element_terminate(audio_element_handle_t el) { if (!el->task_run) { ESP_LOGW(TAG, "[%s] Element has not create when AUDIO_ELEMENT_TERMINATE", el->tag); return ESP_OK; } if (el->task_stack <= 0) { el->task_run = false; el->is_running = false; return ESP_OK; } return __audio_element_term(el, DEFAULT_MAX_WAIT_TIME); } esp_err_t audio_element_terminate_with_ticks(audio_element_handle_t el, TickType_t ticks_to_wait) { if (!el->task_run) { ESP_LOGW(TAG, "[%s] Element has not create when AUDIO_ELEMENT_TERMINATE, tick:%d", el->tag, ticks_to_wait); return ESP_OK; } if (el->task_stack <= 0) { el->task_run = false; el->is_running = false; return ESP_OK; } return __audio_element_term(el, ticks_to_wait); } esp_err_t audio_element_pause(audio_element_handle_t el) { if (!el->task_run) { ESP_LOGW(TAG, "[%s] Element has not create when AUDIO_ELEMENT_PAUSE", el->tag); return ESP_FAIL; } if ((el->state >= AEL_STATE_PAUSED)) { audio_element_force_set_state(el, AEL_STATE_PAUSED); ESP_LOGD(TAG, "[%s] Element already paused, state:%d", el->tag, el->state); return ESP_OK; } xEventGroupClearBits(el->state_event, PAUSED_BIT); if (el->task_stack <= 0) { el->is_running = false; audio_element_force_set_state(el, AEL_STATE_PAUSED); return ESP_OK; } if (audio_element_cmd_send(el, AEL_MSG_CMD_PAUSE) != ESP_OK) { ESP_LOGE(TAG, "[%s] Element send cmd error when AUDIO_ELEMENT_PAUSE", el->tag); return ESP_FAIL; } EventBits_t uxBits = xEventGroupWaitBits(el->state_event, PAUSED_BIT, false, true, DEFAULT_MAX_WAIT_TIME); esp_err_t ret = ESP_FAIL; if (uxBits & PAUSED_BIT) { ret = ESP_OK; } return ret; } esp_err_t audio_element_resume(audio_element_handle_t el, float wait_for_rb_threshold, TickType_t timeout) { if (!el->task_run) { ESP_LOGW(TAG, "[%s] Element has not create when AUDIO_ELEMENT_RESUME", el->tag); return ESP_FAIL; } if (el->state == AEL_STATE_RUNNING) { audio_element_report_status(el, AEL_STATUS_STATE_RUNNING); ESP_LOGD(TAG, "[%s] RESUME: Element is already running, state:%d, task_run:%d, is_running:%d", el->tag, el->state, el->task_run, el->is_running); return ESP_OK; } if (el->task_stack <= 0) { el->is_running = true; audio_element_force_set_state(el, AEL_STATE_RUNNING); audio_element_report_status(el, AEL_STATUS_STATE_RUNNING); return ESP_OK; } if (el->state == AEL_STATE_ERROR) { ESP_LOGE(TAG, "[%s] RESUME: Element error, state:%d", el->tag, el->state); return ESP_FAIL; } if (el->state == AEL_STATE_FINISHED) { ESP_LOGI(TAG, "[%s] RESUME: Element has finished, state:%d", el->tag, el->state); audio_element_report_status(el, AEL_STATUS_STATE_FINISHED); return ESP_OK; } if (wait_for_rb_threshold > 1 || wait_for_rb_threshold < 0) { return ESP_FAIL; } int ret = ESP_OK; xEventGroupClearBits(el->state_event, RESUMED_BIT); if (audio_element_cmd_send(el, AEL_MSG_CMD_RESUME) == ESP_FAIL) { ESP_LOGW(TAG, "[%s] Send resume command failed", el->tag); return ESP_FAIL; } EventBits_t uxBits = xEventGroupWaitBits(el->state_event, RESUMED_BIT, false, true, timeout); if ((uxBits & RESUMED_BIT) != RESUMED_BIT) { ESP_LOGW(TAG, "[%s-%p] RESUME timeout", el->tag, el); ret = ESP_FAIL; } else { if (wait_for_rb_threshold != 0 && el->read_type == IO_TYPE_RB) { ret = audio_element_wait_for_buffer(el, rb_get_size(el->in.input_rb) * wait_for_rb_threshold, timeout); } } return ret; } esp_err_t audio_element_stop(audio_element_handle_t el) { if (!el->task_run) { ESP_LOGD(TAG, "[%s] Element has not create when AUDIO_ELEMENT_STOP", el->tag); return ESP_FAIL; } if (el->is_running == false) { xEventGroupSetBits(el->state_event, STOPPED_BIT); audio_element_report_status(el, AEL_STATUS_STATE_STOPPED); ESP_LOGE(TAG, "[%s] Element already stopped", el->tag); return ESP_OK; } audio_element_abort_output_ringbuf(el); audio_element_abort_input_ringbuf(el); if (el->state == AEL_STATE_RUNNING) { xEventGroupClearBits(el->state_event, STOPPED_BIT); } if (el->task_stack <= 0) { el->is_running = false; audio_element_force_set_state(el, AEL_STATE_STOPPED); xEventGroupSetBits(el->state_event, STOPPED_BIT); audio_element_report_status(el, AEL_STATUS_STATE_STOPPED); return ESP_OK; } if (el->state == AEL_STATE_PAUSED) { audio_event_iface_set_cmd_waiting_timeout(el->iface_event, 0); } if (el->stopping) { ESP_LOGD(TAG, "[%s] Stop command has already sent, %d", el->tag, el->stopping); return ESP_OK; } el->stopping = true; if (audio_element_cmd_send(el, AEL_MSG_CMD_STOP) != ESP_OK) { el->stopping = false; ESP_LOGW(TAG, "[%s-%p] Send stop command failed", el->tag, el); return ESP_FAIL; } ESP_LOGD(TAG, "[%s-%p] Send stop command", el->tag, el); return ESP_OK; } esp_err_t audio_element_wait_for_stop_ms(audio_element_handle_t el, TickType_t ticks_to_wait) { if (el->is_running == false) { ESP_LOGD(TAG, "[%s] Element already stopped, return without waiting", el->tag); return ESP_FAIL; } EventBits_t uxBits = xEventGroupWaitBits(el->state_event, STOPPED_BIT, false, true, ticks_to_wait); esp_err_t ret = ESP_ERR_TIMEOUT; if (uxBits & STOPPED_BIT) { ret = ESP_OK; } return ret; } esp_err_t audio_element_multi_input(audio_element_handle_t el, char *buffer, int wanted_size, int index, TickType_t ticks_to_wait) { esp_err_t ret = ESP_OK; if (index >= el->multi_in.max_rb_num) { ESP_LOGE(TAG, "The index of ringbuffer is gather than and equal to ringbuffer maximum (%d). line %d", el->multi_in.max_rb_num, __LINE__); return ESP_FAIL; } if (el->multi_in.rb[index]) { ret = rb_read(el->multi_in.rb[index], buffer, wanted_size, ticks_to_wait); } return ret; } esp_err_t audio_element_multi_output(audio_element_handle_t el, char *buffer, int wanted_size, TickType_t ticks_to_wait) { esp_err_t ret = ESP_OK; for (int i = 0; i < el->multi_out.max_rb_num; ++i) { if (el->multi_out.rb[i]) { ret |= rb_write(el->multi_out.rb[i], buffer, wanted_size, ticks_to_wait); } } return ret; } esp_err_t audio_element_set_multi_input_ringbuf(audio_element_handle_t el, ringbuf_handle_t rb, int index) { if ((index < el->multi_in.max_rb_num) && rb) { el->multi_in.rb[index] = rb; return ESP_OK; } return ESP_ERR_INVALID_ARG; } esp_err_t audio_element_set_multi_output_ringbuf(audio_element_handle_t el, ringbuf_handle_t rb, int index) { if ((index < el->multi_out.max_rb_num) && rb) { el->multi_out.rb[index] = rb; return ESP_OK; } return ESP_ERR_INVALID_ARG; } ringbuf_handle_t audio_element_get_multi_input_ringbuf(audio_element_handle_t el, int index) { if (index < el->multi_in.max_rb_num) { return el->multi_in.rb[index]; } return NULL; } ringbuf_handle_t audio_element_get_multi_output_ringbuf(audio_element_handle_t el, int index) { if (index < el->multi_out.max_rb_num) { return el->multi_out.rb[index]; } return NULL; } esp_err_t audio_element_seek(audio_element_handle_t el, void *in_data, int in_size, void *out_data, int *out_size) { esp_err_t ret = ESP_OK; if (el && el->seek) { ret = el->seek(el, in_data, in_size, out_data, out_size); } else { ret = ESP_ERR_NOT_SUPPORTED; } return ret; } bool audio_element_is_stopping(audio_element_handle_t el) { if (el) { return el->stopping; } return false; } esp_err_t audio_element_update_byte_pos(audio_element_handle_t el, int pos) { if (el) { mutex_lock(el->lock); el->info.byte_pos += pos; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_byte_pos(audio_element_handle_t el, int pos) { if (el) { mutex_lock(el->lock); el->info.byte_pos = pos; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_update_total_bytes(audio_element_handle_t el, int total_bytes) { if (el) { mutex_lock(el->lock); el->info.total_bytes += total_bytes; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_total_bytes(audio_element_handle_t el, int total_bytes) { if (el) { mutex_lock(el->lock); el->info.total_bytes = total_bytes; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_bps(audio_element_handle_t el, int bit_rate) { if (el) { mutex_lock(el->lock); el->info.bps = bit_rate; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_codec_fmt(audio_element_handle_t el, int format) { if (el) { mutex_lock(el->lock); el->info.codec_fmt = format; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_music_info(audio_element_handle_t el, int sample_rates, int channels, int bits) { if (el) { mutex_lock(el->lock); el->info.sample_rates = sample_rates; el->info.channels = channels; el->info.bits = bits; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_duration(audio_element_handle_t el, int duration) { if (el) { mutex_lock(el->lock); el->info.duration = duration; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_reserve_user0(audio_element_handle_t el, int user_data0) { if (el) { mutex_lock(el->lock); el->info.reserve_data.user_data_0 = user_data0; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_reserve_user1(audio_element_handle_t el, int user_data1) { if (el) { mutex_lock(el->lock); el->info.reserve_data.user_data_1 = user_data1; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_reserve_user2(audio_element_handle_t el, int user_data2) { if (el) { mutex_lock(el->lock); el->info.reserve_data.user_data_2 = user_data2; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_reserve_user3(audio_element_handle_t el, int user_data3) { if (el) { mutex_lock(el->lock); el->info.reserve_data.user_data_3 = user_data3; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; } esp_err_t audio_element_set_reserve_user4(audio_element_handle_t el, int user_data4) { if (el) { mutex_lock(el->lock); el->info.reserve_data.user_data_4 = user_data4; mutex_unlock(el->lock); return ESP_OK; } return ESP_FAIL; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/audio_element.c
C
apache-2.0
47,874
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "freertos/FreeRTOSConfig.h" #include "sys/queue.h" #include "esp_log.h" #include "audio_event_iface.h" #include "audio_error.h" #include "audio_mem.h" static const char *TAG = "AUDIO_EVT"; typedef struct audio_event_iface_item { STAILQ_ENTRY(audio_event_iface_item) next; QueueHandle_t queue; int queue_size; int mark_to_remove; } audio_event_iface_item_t; typedef STAILQ_HEAD(audio_event_iface_list, audio_event_iface_item) audio_event_iface_list_t; /** * Audio event structure */ struct audio_event_iface { QueueHandle_t internal_queue; QueueHandle_t external_queue; QueueSetHandle_t queue_set; int internal_queue_size; int external_queue_size; int queue_set_size; audio_event_iface_list_t listening_queues; void *context; on_event_iface_func on_cmd; int wait_time; int type; }; audio_event_iface_handle_t audio_event_iface_init(audio_event_iface_cfg_t *config) { audio_event_iface_handle_t evt = audio_calloc(1, sizeof(struct audio_event_iface)); AUDIO_MEM_CHECK(TAG, evt, return NULL); evt->queue_set_size = config->queue_set_size; evt->internal_queue_size = config->internal_queue_size; evt->external_queue_size = config->external_queue_size; evt->context = config->context; evt->on_cmd = config->on_cmd; evt->type = config->type; if (evt->queue_set_size) { evt->queue_set = xQueueCreateSet(evt->queue_set_size); } if (evt->internal_queue_size) { evt->internal_queue = xQueueCreate(evt->internal_queue_size, sizeof(audio_event_iface_msg_t)); AUDIO_MEM_CHECK(TAG, evt->internal_queue, goto _event_iface_init_failed); } if (evt->external_queue_size) { evt->external_queue = xQueueCreate(evt->external_queue_size, sizeof(audio_event_iface_msg_t)); AUDIO_MEM_CHECK(TAG, evt->external_queue, goto _event_iface_init_failed); } else { ESP_LOGD(TAG, "This emiiter have no queue set,%p", evt); } STAILQ_INIT(&evt->listening_queues); return evt; _event_iface_init_failed: if (evt->internal_queue) { vQueueDelete(evt->internal_queue); } if (evt->external_queue) { vQueueDelete(evt->external_queue); } return NULL; } static esp_err_t audio_event_iface_cleanup_listener(audio_event_iface_handle_t listen) { audio_event_iface_item_t *item, *tmp; audio_event_iface_discard(listen); STAILQ_FOREACH_SAFE(item, &listen->listening_queues, next, tmp) { audio_event_iface_msg_t dummy; while (audio_event_iface_read(listen, &dummy, 0) == ESP_OK); while (listen->queue_set && (xQueueRemoveFromSet(item->queue, listen->queue_set) != pdPASS)) { ESP_LOGW(TAG, "Error remove listener,%p", item->queue); while (audio_event_iface_read(listen, &dummy, 0) == ESP_OK); } } if (listen->queue_set) { vQueueDelete(listen->queue_set); listen->queue_set = NULL; } return ESP_OK; } static esp_err_t audio_event_iface_update_listener(audio_event_iface_handle_t listen) { audio_event_iface_item_t *item; int queue_size = 0; STAILQ_FOREACH(item, &listen->listening_queues, next) { queue_size += item->queue_size; } if (queue_size) { listen->queue_set = xQueueCreateSet(queue_size); } STAILQ_FOREACH(item, &listen->listening_queues, next) { if (item->queue) { audio_event_iface_msg_t dummy; while (xQueueReceive(item->queue, &dummy, 0) == pdTRUE); } if (listen->queue_set && item->queue && xQueueAddToSet(item->queue, listen->queue_set) != pdPASS) { ESP_LOGE(TAG, "Error add queue items to queue set"); return ESP_FAIL; } } return ESP_OK; } esp_err_t audio_event_iface_read(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg, TickType_t wait_time) { if (evt->queue_set) { QueueSetMemberHandle_t active_queue; active_queue = xQueueSelectFromSet(evt->queue_set, wait_time); if (active_queue) { if (xQueueReceive(active_queue, msg, 0) == pdTRUE) { return ESP_OK; } } } return ESP_FAIL; } esp_err_t audio_event_iface_destroy(audio_event_iface_handle_t evt) { audio_event_iface_cleanup_listener(evt); audio_event_iface_item_t *item, *tmp; STAILQ_FOREACH_SAFE(item, &evt->listening_queues, next, tmp) { STAILQ_REMOVE(&evt->listening_queues, item, audio_event_iface_item, next); audio_free(item); } if (evt->internal_queue) { audio_event_iface_set_cmd_waiting_timeout(evt, 0); vQueueDelete(evt->internal_queue); } if (evt->external_queue) { vQueueDelete(evt->external_queue); } if (evt->queue_set) { vQueueDelete(evt->queue_set); } audio_free(evt); return ESP_OK; } esp_err_t audio_event_iface_set_listener(audio_event_iface_handle_t evt, audio_event_iface_handle_t listener) { if ((NULL == evt->external_queue) || (0 == evt->external_queue_size)) { return ESP_ERR_INVALID_ARG; } audio_event_iface_item_t *item = audio_calloc(1, sizeof(audio_event_iface_item_t)); AUDIO_MEM_CHECK(TAG, item, return ESP_ERR_NO_MEM); if (audio_event_iface_cleanup_listener(listener) != ESP_OK) { AUDIO_ERROR(TAG, "Error cleanup listener"); return ESP_FAIL; } item->queue = evt->external_queue; item->queue_size = evt->external_queue_size; STAILQ_INSERT_TAIL(&listener->listening_queues, item, next); return audio_event_iface_update_listener(listener); } esp_err_t audio_event_iface_set_msg_listener(audio_event_iface_handle_t evt, audio_event_iface_handle_t listener) { if ((NULL == evt->internal_queue) || (0 == evt->internal_queue_size)) { return ESP_ERR_INVALID_ARG; } audio_event_iface_item_t *item = audio_calloc(1, sizeof(audio_event_iface_item_t)); AUDIO_MEM_CHECK(TAG, item, return ESP_ERR_NO_MEM); if (audio_event_iface_cleanup_listener(listener) != ESP_OK) { AUDIO_ERROR(TAG, "Error cleanup listener"); return ESP_FAIL; } item->queue = evt->internal_queue; item->queue_size = evt->internal_queue_size; STAILQ_INSERT_TAIL(&listener->listening_queues, item, next); return audio_event_iface_update_listener(listener); } esp_err_t audio_event_iface_remove_listener(audio_event_iface_handle_t listen, audio_event_iface_handle_t evt) { if ((NULL == evt->external_queue) || (0 == evt->external_queue_size)) { return ESP_ERR_INVALID_ARG; } audio_event_iface_item_t *item, *tmp; if (audio_event_iface_cleanup_listener(listen) != ESP_OK) { return ESP_FAIL; } STAILQ_FOREACH_SAFE(item, &listen->listening_queues, next, tmp) { if (evt->external_queue == item->queue) { STAILQ_REMOVE(&listen->listening_queues, item, audio_event_iface_item, next); audio_free(item); } } return audio_event_iface_update_listener(listen); } esp_err_t audio_event_iface_set_cmd_waiting_timeout(audio_event_iface_handle_t evt, TickType_t wait_time) { evt->wait_time = wait_time; return ESP_OK; } esp_err_t audio_event_iface_waiting_cmd_msg(audio_event_iface_handle_t evt) { audio_event_iface_msg_t msg; if (evt->internal_queue && (xQueueReceive(evt->internal_queue, (void *)&msg, evt->wait_time) == pdTRUE)) { if (evt->on_cmd) { return evt->on_cmd((void *)&msg, evt->context); } } return ESP_OK; } esp_err_t audio_event_iface_cmd(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg) { if (evt->internal_queue && (xQueueSend(evt->internal_queue, (void *)msg, 0) != pdPASS)) { ESP_LOGW(TAG, "There are no space to dispatch queue"); return ESP_FAIL; } return ESP_OK; } esp_err_t audio_event_iface_cmd_from_isr(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg) { if (evt->internal_queue && (xQueueSendFromISR(evt->internal_queue, (void *)msg, 0) != pdPASS)) { return ESP_FAIL; } return ESP_OK; } esp_err_t audio_event_iface_sendout(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg) { if (evt->external_queue) { if (xQueueSend(evt->external_queue, (void *)msg, 0) != pdPASS) { ESP_LOGW(TAG, "There is no space in external queue"); return ESP_FAIL; } } return ESP_OK; } esp_err_t audio_event_iface_discard(audio_event_iface_handle_t evt) { audio_event_iface_msg_t msg; if (evt->external_queue && evt->external_queue_size) { while (xQueueReceive(evt->external_queue, &msg, 0) == pdTRUE); } if (evt->internal_queue && evt->internal_queue_size) { while (xQueueReceive(evt->internal_queue, &msg, 0) == pdTRUE); } if (evt->queue_set && evt->queue_set_size) { while (audio_event_iface_read(evt, &msg, 0) == ESP_OK); } return ESP_OK; } esp_err_t audio_event_iface_listen(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg, TickType_t wait_time) { if (!evt) { return ESP_FAIL; } if (audio_event_iface_read(evt, msg, wait_time) != ESP_OK) { return ESP_FAIL; } return ESP_OK; } QueueHandle_t audio_event_iface_get_queue_handle(audio_event_iface_handle_t evt) { if (!evt) { return NULL; } return evt->external_queue; } QueueHandle_t audio_event_iface_get_msg_queue_handle(audio_event_iface_handle_t evt) { if (!evt) { return NULL; } return evt->internal_queue; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/audio_event_iface.c
C
apache-2.0
11,214
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "sys/queue.h" #include "esp_log.h" #include "audio_element.h" #include "audio_pipeline.h" #include "audio_event_iface.h" #include "audio_mem.h" #include "audio_mutex.h" #include "ringbuf.h" #include "audio_error.h" static const char *TAG = "AUDIO_PIPELINE"; #define PIPELINE_DEBUG(x) debug_pipeline_lists(x, __LINE__, __func__) typedef struct ringbuf_item { STAILQ_ENTRY(ringbuf_item) next; ringbuf_handle_t rb; audio_element_handle_t host_el; bool linked; bool kept_ctx; } ringbuf_item_t; typedef STAILQ_HEAD(ringbuf_list, ringbuf_item) ringbuf_list_t; typedef struct audio_element_item { STAILQ_ENTRY(audio_element_item) next; audio_element_handle_t el; bool linked; bool kept_ctx; audio_element_status_t el_state; } audio_element_item_t; typedef STAILQ_HEAD(audio_element_list, audio_element_item) audio_element_list_t; struct audio_pipeline { audio_element_list_t el_list; ringbuf_list_t rb_list; audio_element_state_t state; xSemaphoreHandle lock; bool linked; audio_event_iface_handle_t listener; }; static audio_element_item_t *audio_pipeline_get_el_item_by_tag(audio_pipeline_handle_t pipeline, const char *tag) { audio_element_item_t *item; STAILQ_FOREACH(item, &pipeline->el_list, next) { char *el_tag = audio_element_get_tag(item->el); if (el_tag && strcasecmp(el_tag, tag) == 0) { return item; } } return NULL; } static audio_element_item_t *audio_pipeline_get_el_item_by_handle(audio_pipeline_handle_t pipeline, audio_element_handle_t el) { audio_element_item_t *item; STAILQ_FOREACH(item, &pipeline->el_list, next) { if (item->el == el) { return item; } } return NULL; } esp_err_t audio_pipeline_change_state(audio_pipeline_handle_t pipeline, audio_element_state_t new_state) { pipeline->state = new_state; return ESP_OK; } static void audio_pipeline_register_element(audio_pipeline_handle_t pipeline, audio_element_handle_t el) { if (audio_pipeline_get_el_item_by_handle(pipeline, el) != NULL) { ESP_LOGW(TAG, "%d, %s already exist in pipeline", __LINE__, audio_element_get_tag(el)); return; } audio_element_item_t *el_item = audio_calloc(1, sizeof(audio_element_item_t)); AUDIO_MEM_CHECK(TAG, el_item, return); el_item->el = el; el_item->linked = true; STAILQ_INSERT_TAIL(&pipeline->el_list, el_item, next); } static void audio_pipeline_unregister_element(audio_pipeline_handle_t pipeline, audio_element_handle_t el) { audio_element_item_t *el_item, *tmp; STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, tmp) { if (el_item->el == el) { STAILQ_REMOVE(&pipeline->el_list, el_item, audio_element_item, next); audio_free(el_item); } } } static void add_rb_to_audio_pipeline(audio_pipeline_handle_t pipeline, ringbuf_handle_t rb, audio_element_handle_t host_el) { ringbuf_item_t *rb_item = (ringbuf_item_t *)audio_calloc(1, sizeof(ringbuf_item_t)); AUDIO_MEM_CHECK(TAG, rb_item, return); rb_item->rb = rb; rb_item->linked = true; rb_item->kept_ctx = false; rb_item->host_el = host_el; STAILQ_INSERT_TAIL(&pipeline->rb_list, rb_item, next); } static void debug_pipeline_lists(audio_pipeline_handle_t pipeline, int line, const char *func) { audio_element_item_t *el_item, *el_tmp; ringbuf_item_t *rb_item, *tmp; ESP_LOGD(TAG, "FUNC:%s, LINE:%d", func, line); STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, el_tmp) { ESP_LOGD(TAG, "el-list: linked:%d, kept:%d, el:%p, %16s, in_rb:%p, out_rb:%p", el_item->linked, el_item->kept_ctx, el_item->el, audio_element_get_tag(el_item->el), audio_element_get_input_ringbuf(el_item->el), audio_element_get_output_ringbuf(el_item->el)); } STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, tmp) { ESP_LOGD(TAG, "rb-list: linked:%d, kept:%d, rb:%p, host_el:%p, %16s", rb_item->linked, rb_item->kept_ctx, rb_item->rb, rb_item->host_el, rb_item->host_el != NULL ? audio_element_get_tag(rb_item->host_el) : "NULL"); } } audio_element_handle_t audio_pipeline_get_el_by_tag(audio_pipeline_handle_t pipeline, const char *tag) { if (tag == NULL || pipeline == NULL) { ESP_LOGE(TAG, "Invalid parameters, tag:%p, p:%p", tag, pipeline); return NULL; } audio_element_item_t *item; STAILQ_FOREACH(item, &pipeline->el_list, next) { char *el_tag = audio_element_get_tag(item->el); ESP_LOGD(TAG, "Get_el_by_tag, el:%p, kept:%d, linked:%d el-tag:%16s, in_tag:%s", item->el, item->kept_ctx, item->linked, item->el != NULL ? audio_element_get_tag(item->el) : "NULL", tag); if (item->kept_ctx) { continue; } if (el_tag && strcasecmp(el_tag, tag) == 0) { return item->el; } } return NULL; } audio_element_handle_t audio_pipeline_get_el_once(audio_pipeline_handle_t pipeline, const audio_element_handle_t start_el, const char *tag) { if (tag == NULL || pipeline == NULL) { ESP_LOGE(TAG, "Invalid parameters, tag:%p, p:%p", tag, pipeline); return NULL; } audio_element_item_t *item; bool start = false; STAILQ_FOREACH(item, &pipeline->el_list, next) { if (start == false) { if (item->el == start_el) { start = true; } } else { char *el_tag = audio_element_get_tag(item->el); ESP_LOGD(TAG, "Get_el_by_el, el:%p, kept:%d, linked:%d el-tag:%16s, in_tag:%s", item->el, item->kept_ctx, item->linked, item->el != NULL ? audio_element_get_tag(item->el) : "NULL", tag); if (item->kept_ctx) { continue; } if (el_tag && strcasecmp(el_tag, tag) == 0) { return item->el; } } } return NULL; } esp_err_t audio_pipeline_set_listener(audio_pipeline_handle_t pipeline, audio_event_iface_handle_t listener) { audio_element_item_t *el_item; if (pipeline->listener) { audio_pipeline_remove_listener(pipeline); } STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked == false) { continue; } if (audio_element_msg_set_listener(el_item->el, listener) != ESP_OK) { ESP_LOGE(TAG, "Error register event with: %s", (char *)audio_element_get_tag(el_item->el)); return ESP_FAIL; } } pipeline->listener = listener; return ESP_OK; } esp_err_t audio_pipeline_remove_listener(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; if (pipeline->listener == NULL) { ESP_LOGW(TAG, "There are no listener registered"); return ESP_FAIL; } STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked == false) { continue; } if (audio_element_msg_remove_listener(el_item->el, pipeline->listener) != ESP_OK) { ESP_LOGE(TAG, "Error unregister event with: %s", audio_element_get_tag(el_item->el)); return ESP_FAIL; } } pipeline->listener = NULL; return ESP_OK; } audio_pipeline_handle_t audio_pipeline_init(audio_pipeline_cfg_t *config) { audio_pipeline_handle_t pipeline; bool _success = ( (pipeline = audio_calloc(1, sizeof(struct audio_pipeline))) && (pipeline->lock = mutex_create()) ); AUDIO_MEM_CHECK(TAG, _success, return NULL); STAILQ_INIT(&pipeline->el_list); STAILQ_INIT(&pipeline->rb_list); pipeline->state = AEL_STATE_INIT; return pipeline; } esp_err_t audio_pipeline_deinit(audio_pipeline_handle_t pipeline) { audio_pipeline_terminate(pipeline); audio_pipeline_unlink(pipeline); audio_element_item_t *el_item, *tmp; STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, tmp) { ESP_LOGD(TAG, "[%16s]-[%p]element instance has been deleted", audio_element_get_tag(el_item->el), el_item->el); audio_element_deinit(el_item->el); audio_pipeline_unregister(pipeline, el_item->el); } mutex_destroy(pipeline->lock); audio_free(pipeline); return ESP_OK; } esp_err_t audio_pipeline_register(audio_pipeline_handle_t pipeline, audio_element_handle_t el, const char *name) { audio_pipeline_unregister(pipeline, el); if (name) { audio_element_set_tag(el, name); } audio_element_item_t *el_item = audio_calloc(1, sizeof(audio_element_item_t)); AUDIO_MEM_CHECK(TAG, el_item, return ESP_ERR_NO_MEM); el_item->el = el; el_item->linked = false; STAILQ_INSERT_TAIL(&pipeline->el_list, el_item, next); return ESP_OK; } esp_err_t audio_pipeline_unregister(audio_pipeline_handle_t pipeline, audio_element_handle_t el) { audio_element_item_t *el_item, *tmp; STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, tmp) { if (el_item->el == el) { STAILQ_REMOVE(&pipeline->el_list, el_item, audio_element_item, next); audio_free(el_item); return ESP_OK; } } return ESP_FAIL; } esp_err_t audio_pipeline_resume(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; bool wait_first_el = true; esp_err_t ret = ESP_OK; STAILQ_FOREACH(el_item, &pipeline->el_list, next) { ESP_LOGD(TAG, "resume,linked:%d, state:%d,[%s-%p]", el_item->linked, audio_element_get_state(el_item->el), audio_element_get_tag(el_item->el), el_item->el); if (false == el_item->linked) { continue; } if (wait_first_el) { ret |= audio_element_resume(el_item->el, 0, 2000 / portTICK_RATE_MS); wait_first_el = false; } else { ret |= audio_element_resume(el_item->el, 0, 2000 / portTICK_RATE_MS); } } audio_pipeline_change_state(pipeline, AEL_STATE_RUNNING); return ret; } esp_err_t audio_pipeline_pause(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (false == el_item->linked) { continue; } ESP_LOGD(TAG, "pause [%s] %p", audio_element_get_tag(el_item->el), el_item->el); audio_element_pause(el_item->el); } return ESP_OK; } esp_err_t audio_pipeline_run(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; if (pipeline->state != AEL_STATE_INIT) { ESP_LOGW(TAG, "Pipeline already started, state:%d", pipeline->state); return ESP_OK; } STAILQ_FOREACH(el_item, &pipeline->el_list, next) { ESP_LOGD(TAG, "start el[%16s], linked:%d, state:%d,[%p], ", audio_element_get_tag(el_item->el), el_item->linked, audio_element_get_state(el_item->el), el_item->el); if (el_item->linked && ((AEL_STATE_INIT == audio_element_get_state(el_item->el)) || (AEL_STATE_STOPPED == audio_element_get_state(el_item->el)) || (AEL_STATE_FINISHED == audio_element_get_state(el_item->el)) || (AEL_STATE_ERROR == audio_element_get_state(el_item->el)))) { audio_element_run(el_item->el); } } AUDIO_MEM_SHOW(TAG); if (ESP_FAIL == audio_pipeline_resume(pipeline)) { ESP_LOGE(TAG, "audio_pipeline_resume failed"); audio_pipeline_change_state(pipeline, AEL_STATE_ERROR); audio_pipeline_terminate(pipeline); return ESP_FAIL; } else { audio_pipeline_change_state(pipeline, AEL_STATE_RUNNING); } ESP_LOGI(TAG, "Pipeline started"); return ESP_OK; } esp_err_t audio_pipeline_terminate(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; ESP_LOGD(TAG, "Destroy audio_pipeline elements"); STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked) { audio_element_terminate(el_item->el); } } return ESP_OK; } esp_err_t audio_pipeline_terminate_with_ticks(audio_pipeline_handle_t pipeline, TickType_t ticks_to_wait) { audio_element_item_t *el_item; esp_err_t ret = ESP_OK; ESP_LOGD(TAG, "Destroy audio_pipeline elements with ticks[%d]", ticks_to_wait); STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked) { ret |= audio_element_terminate_with_ticks(el_item->el, ticks_to_wait); } } return ret; } esp_err_t audio_pipeline_stop(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; ESP_LOGD(TAG, "audio_element_stop"); if (pipeline->state != AEL_STATE_RUNNING) { ESP_LOGW(TAG, "Without stop, st:%d", pipeline->state); return ESP_FAIL; } STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked) { audio_element_stop(el_item->el); } } return ESP_OK; } static inline esp_err_t __audio_pipeline_wait_stop(audio_pipeline_handle_t pipeline, TickType_t ticks_to_wait) { audio_element_item_t *el_item; esp_err_t ret = ESP_OK; STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked) { esp_err_t res = audio_element_wait_for_stop_ms(el_item->el, ticks_to_wait); if (res == ESP_ERR_TIMEOUT) { ESP_LOGW(TAG, "Wait stop timeout, el:%p, tag:%s", el_item->el, audio_element_get_tag(el_item->el) == NULL ? "NULL" : audio_element_get_tag(el_item->el)); } else { audio_element_reset_state(el_item->el); } ret |= res; } } audio_pipeline_change_state(pipeline, AEL_STATE_INIT); return ret; } esp_err_t audio_pipeline_wait_for_stop(audio_pipeline_handle_t pipeline) { if (pipeline->state != AEL_STATE_RUNNING) { ESP_LOGW(TAG, "Without wait stop, st:%d", pipeline->state); return ESP_FAIL; } ESP_LOGD(TAG, "%s - IN", __func__); esp_err_t ret = __audio_pipeline_wait_stop(pipeline, portMAX_DELAY); ESP_LOGD(TAG, "%s - OUT", __func__); return ret; } esp_err_t audio_pipeline_wait_for_stop_with_ticks(audio_pipeline_handle_t pipeline, TickType_t ticks_to_wait) { if (pipeline->state != AEL_STATE_RUNNING) { ESP_LOGW(TAG, "Without wait stop, st:%d", pipeline->state); return ESP_FAIL; } ESP_LOGD(TAG, "%s - IN", __func__); esp_err_t ret = __audio_pipeline_wait_stop(pipeline, ticks_to_wait); ESP_LOGD(TAG, "%s - OUT", __func__); return ret; } static esp_err_t _pipeline_rb_linked(audio_pipeline_handle_t pipeline, audio_element_handle_t el, bool first, bool last) { static ringbuf_handle_t rb; ringbuf_item_t *rb_item; if (last) { audio_element_set_input_ringbuf(el, rb); } else { if (!first) { audio_element_set_input_ringbuf(el, rb); } bool _success = ( (rb_item = audio_calloc(1, sizeof(ringbuf_item_t))) && (rb = rb_create(audio_element_get_output_ringbuf_size(el), 1)) ); AUDIO_MEM_CHECK(TAG, _success, { audio_free(rb_item); return ESP_ERR_NO_MEM; }); rb_item->rb = rb; rb_item->linked = true; rb_item->kept_ctx = false; rb_item->host_el = el; STAILQ_INSERT_TAIL(&pipeline->rb_list, rb_item, next); audio_element_set_output_ringbuf(el, rb); ESP_LOGI(TAG, "link el->rb, el:%p, tag:%s, rb:%p", el, audio_element_get_tag(el) == NULL ? "NULL" : audio_element_get_tag(el), rb); } return ESP_OK; } esp_err_t audio_pipeline_link(audio_pipeline_handle_t pipeline, const char *link_tag[], int link_num) { esp_err_t ret = ESP_OK; bool first = false, last = false; if (pipeline->linked) { audio_pipeline_unlink(pipeline); } for (int i = 0; i < link_num; i++) { audio_element_item_t *item = audio_pipeline_get_el_item_by_tag(pipeline, link_tag[i]); if (item == NULL) { ESP_LOGE(TAG, "There is 1 link_tag invalid: %s", link_tag[i]); return ESP_FAIL; } item->linked = true; item->kept_ctx = false; audio_element_handle_t el = item->el; first = (i == 0); last = (i == link_num - 1); ret = _pipeline_rb_linked(pipeline, el, first, last); if (ret != ESP_OK) { return ret; } } pipeline->linked = true; PIPELINE_DEBUG(pipeline); return ESP_OK; } esp_err_t audio_pipeline_unlink(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; ringbuf_item_t *rb_item, *tmp; if (!pipeline->linked) { return ESP_OK; } audio_pipeline_remove_listener(pipeline); STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked) { el_item->linked = false; el_item->kept_ctx = false; audio_element_set_output_ringbuf(el_item->el, NULL); audio_element_set_input_ringbuf(el_item->el, NULL); ESP_LOGD(TAG, "audio_pipeline_unlink, %p, %s", el_item->el, audio_element_get_tag(el_item->el)); } } STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, tmp) { ESP_LOGD(TAG, "audio_pipeline_unlink, RB:%p,host_el:%p", rb_item->rb, rb_item->host_el); STAILQ_REMOVE(&pipeline->rb_list, rb_item, ringbuf_item, next); if (rb_item->host_el) { audio_element_set_output_ringbuf(rb_item->host_el, NULL); audio_element_set_input_ringbuf(rb_item->host_el, NULL); } rb_destroy(rb_item->rb); rb_item->linked = false; rb_item->kept_ctx = false; rb_item->host_el = NULL; audio_free(rb_item); } ESP_LOGI(TAG, "audio_pipeline_unlinked"); STAILQ_INIT(&pipeline->rb_list); pipeline->linked = false; return ESP_OK; } esp_err_t audio_pipeline_register_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...) { va_list args; va_start(args, element_1); while (element_1) { audio_pipeline_register_element(pipeline, element_1); element_1 = va_arg(args, audio_element_handle_t); } va_end(args); return ESP_OK; } esp_err_t audio_pipeline_unregister_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...) { va_list args; va_start(args, element_1); while (element_1) { audio_pipeline_unregister_element(pipeline, element_1); element_1 = va_arg(args, audio_element_handle_t); } va_end(args); return ESP_OK; } esp_err_t audio_pipeline_link_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...) { va_list args; esp_err_t ret = ESP_OK; int idx = 0; bool first = false; bool last = false; if (pipeline->linked) { audio_pipeline_unlink(pipeline); } va_start(args, element_1); while (element_1) { audio_element_handle_t el = element_1; audio_element_item_t *item = audio_pipeline_get_el_item_by_handle(pipeline, element_1); if (item == NULL) { ESP_LOGE(TAG, "Can't found element[%p-%s] item", element_1, audio_element_get_tag(element_1)); return ESP_FAIL; } item->linked = true; item->kept_ctx = false; idx ++; first = (idx == 1); element_1 = va_arg(args, audio_element_handle_t); last = (NULL == element_1) ? true : false; ret = _pipeline_rb_linked(pipeline, el, first, last); if (ret != ESP_OK) { return ret; } } pipeline->linked = true; va_end(args); return ESP_OK; } esp_err_t audio_pipeline_link_insert(audio_pipeline_handle_t pipeline, bool first, audio_element_handle_t prev, ringbuf_handle_t conect_rb, audio_element_handle_t next) { if (first) { audio_pipeline_register_element(pipeline, prev); } ESP_LOGD(TAG, "element is prev:%p, rb:%p, next:%p", prev, conect_rb, next); audio_pipeline_register_element(pipeline, next); audio_element_set_output_ringbuf(prev, conect_rb); audio_element_set_input_ringbuf(next, conect_rb); add_rb_to_audio_pipeline(pipeline, conect_rb, prev); pipeline->linked = true; return ESP_OK; } esp_err_t audio_pipeline_listen_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...) { va_list args; va_start(args, element_1); while (element_1) { audio_element_handle_t el = element_1; element_1 = va_arg(args, audio_element_handle_t); QueueHandle_t que = audio_element_get_event_queue(el); audio_event_iface_msg_t dummy = {0}; while (1) { if (xQueueReceive(que, &dummy, 0) == pdTRUE) { ESP_LOGD(TAG, "Listen_more el:%p, que :%p, OK", el, que); } else { ESP_LOGD(TAG, "Listen_more el:%p, que :%p, FAIL", el, que); break; } } } va_end(args); PIPELINE_DEBUG(pipeline); return ESP_OK; } esp_err_t audio_pipeline_check_items_state(audio_pipeline_handle_t pipeline, audio_element_handle_t el, audio_element_status_t status) { audio_element_item_t *item; int el_cnt = 0; int el_sta_cnt = 0; audio_element_item_t *it = audio_pipeline_get_el_item_by_handle(pipeline, el); it->el_state = status; STAILQ_FOREACH(item, &pipeline->el_list, next) { if (false == item->linked) { continue; } el_cnt ++; ESP_LOGV(TAG, "pipeline state check, pl:%p, el:%p, tag:%16s, state:%d, status:%d", pipeline, item->el, audio_element_get_tag(item->el), item->el_state, status); int st = audio_element_get_state(item->el); if ((st == AEL_STATE_STOPPED) || (st == AEL_STATE_FINISHED) || (st == AEL_STATE_ERROR)) { ESP_LOGV(TAG, "Element rewrite, tag:%16s, el-state:%d, it->el_state:%d, wanted:%d", audio_element_get_tag(item->el), st, it->el_state, status); if (st == AEL_STATE_ERROR) { item->el_state = AEL_STATUS_ERROR_PROCESS; } else { item->el_state = st + AEL_STATUS_INPUT_BUFFERING; } } if (item->el_state == AEL_STATUS_NONE) { continue; } if (status == item->el_state) { el_sta_cnt++; } else if ((status == AEL_STATUS_STATE_RUNNING)) { if ((item->el_state == AEL_STATUS_STATE_FINISHED) || ((item->el_state > AEL_STATUS_NONE) && (item->el_state < AEL_STATUS_INPUT_DONE))) { el_sta_cnt++; ESP_LOGW(TAG, "Check AEL RUNNING, pl:%p, el:%p, tag:%16s, state:%d, wanted:%d", pipeline, item->el, audio_element_get_tag(item->el), item->el_state, status); } } else if (status == AEL_STATUS_STATE_PAUSED) { if ((item->el_state == AEL_STATUS_STATE_FINISHED) || ((item->el_state > AEL_STATUS_NONE) && (item->el_state < AEL_STATUS_INPUT_DONE))) { el_sta_cnt++; ESP_LOGW(TAG, "Check AEL PAUSED, pl:%p, el:%p, tag:%16s, state:%d, wanted:%d", pipeline, item->el, audio_element_get_tag(item->el), item->el_state, status); } } else if (status == AEL_STATUS_STATE_STOPPED) { if ((item->el_state == AEL_STATUS_STATE_FINISHED) || ((item->el_state > AEL_STATUS_NONE) && (item->el_state < AEL_STATUS_INPUT_DONE))) { el_sta_cnt++; ESP_LOGW(TAG, "Check AEL STOPPED, pl:%p, el:%p, tag:%16s, state:%d, wanted:%d", pipeline, item->el, audio_element_get_tag(item->el), item->el_state, status); } } else if (status == AEL_STATUS_STATE_FINISHED) { if ((item->el_state == AEL_STATUS_STATE_STOPPED) || ((item->el_state > AEL_STATUS_NONE) && (item->el_state < AEL_STATUS_INPUT_DONE))) { el_sta_cnt++; ESP_LOGW(TAG, "Check AEL FINISHED, pl:%p, el:%p, tag:%16s, state:%d, wanted:%d", pipeline, item->el, audio_element_get_tag(item->el), item->el_state, status); } } else { // TODO nothing } } if (el_cnt && (el_sta_cnt == el_cnt)) { return ESP_OK; } else { return ESP_FAIL; } } esp_err_t audio_pipeline_reset_items_state(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; ESP_LOGD(TAG, "audio_pipeline_reset_items_state"); STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked) { el_item->el_state = AEL_STATUS_NONE; } } return ESP_OK; } esp_err_t audio_pipeline_reset_ringbuffer(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked) { audio_element_reset_input_ringbuf(el_item->el); audio_element_reset_output_ringbuf(el_item->el); } } return ESP_OK; } esp_err_t audio_pipeline_reset_elements(audio_pipeline_handle_t pipeline) { audio_element_item_t *el_item; STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->linked) { audio_element_reset_state(el_item->el); } } return ESP_OK; } esp_err_t audio_pipeline_reset_kept_state(audio_pipeline_handle_t pipeline, audio_element_handle_t el) { audio_element_item_t *el_item; STAILQ_FOREACH(el_item, &pipeline->el_list, next) { if (el_item->el == el) { el_item->linked = false; el_item->kept_ctx = false; break; } } ringbuf_handle_t rb = audio_element_get_output_ringbuf(el); audio_element_set_output_ringbuf(el, NULL); ringbuf_item_t *rb_item, *tmp; STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, tmp) { if (rb_item->rb == rb) { rb_item->linked = false; rb_item->kept_ctx = false; rb_item->host_el = NULL; ESP_LOGW(TAG, "kept_reset, rb:%p", rb); break; } } pipeline->linked = false; return ESP_OK; } esp_err_t audio_pipeline_breakup_elements(audio_pipeline_handle_t pipeline, audio_element_handle_t kept_ctx_el) { if (pipeline == NULL) { ESP_LOGE(TAG, "%s have invalid args, %p", __func__, pipeline); return ESP_ERR_INVALID_ARG; } audio_pipeline_remove_listener(pipeline); audio_element_item_t *el_item, *el_tmp; ringbuf_item_t *rb_item, *tmp; bool kept = true; ESP_LOGD(TAG, "audio_pipeline_breakup_elements IN,%p,%s", kept_ctx_el, kept_ctx_el != NULL ? audio_element_get_tag(kept_ctx_el) : "NULL"); STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, el_tmp) { ESP_LOGD(TAG, "%d, el:%08x, %s, in_rb:%08x, out_rb:%08x, linked:%d, el-kept:%d", __LINE__, (int)el_item->el, audio_element_get_tag(el_item->el), (int)audio_element_get_input_ringbuf(el_item->el), (int)audio_element_get_output_ringbuf(el_item->el), el_item->linked, el_item->kept_ctx); if (!el_item->linked) { continue; } if ((!kept) && el_item->el != kept_ctx_el) { audio_element_reset_state(el_item->el); STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, tmp) { if (audio_element_get_output_ringbuf(el_item->el) == NULL) { el_item->linked = false; el_item->kept_ctx = false; audio_element_set_input_ringbuf(el_item->el, NULL); ESP_LOGD(TAG, "output ringbuf is null"); break; } else if (rb_item->rb == audio_element_get_output_ringbuf(el_item->el)) { el_item->linked = false; el_item->kept_ctx = false; rb_item->kept_ctx = false; rb_item->linked = false; rb_item->host_el = NULL; audio_element_set_output_ringbuf(el_item->el, NULL); audio_element_set_input_ringbuf(el_item->el, NULL); ESP_LOGD(TAG, "found output ringbuf, %p", el_item->el); break; } audio_element_set_output_ringbuf(el_item->el, NULL); audio_element_set_input_ringbuf(el_item->el, NULL); } } else { STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, tmp) { if (rb_item->rb == audio_element_get_output_ringbuf(el_item->el)) { el_item->linked = false; if ((audio_element_get_state(el_item->el) == AEL_STATE_RUNNING) || (audio_element_get_state(el_item->el) == AEL_STATE_PAUSED) /*|| (audio_element_get_state(el_item->el) == AEL_STATE_FINISHED)*/) { el_item->kept_ctx = true; rb_item->kept_ctx = true; ESP_LOGD(TAG, "found kept_ctx_el:%p and ringbuf:%p", el_item->el, rb_item->rb); } else { ESP_LOGW(TAG, "found kept_ctx_el and ringbuf, but not set kept, el:%p, rb:%p", el_item->el, rb_item->rb); audio_element_set_output_ringbuf(el_item->el, NULL); } kept = false; audio_element_set_input_ringbuf(el_item->el, NULL); break; } } } } // For Debug PIPELINE_DEBUG(pipeline); STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, tmp) { if (rb_item->kept_ctx == false) { rb_item->linked = false; rb_reset(rb_item->rb); } ESP_LOGD(TAG, "%d, reset rb:%p kept:%d,linked:%d", __LINE__, rb_item->rb, rb_item->kept_ctx, rb_item->linked ); } pipeline->linked = false; audio_pipeline_change_state(pipeline, AEL_STATE_INIT); return ESP_OK; } static esp_err_t audio_pipeline_el_item_link(audio_pipeline_handle_t pipeline, audio_element_item_t *src_el_item, audio_element_handle_t el, bool first, bool last) { ringbuf_item_t *cur_rb_item = NULL; ringbuf_item_t *rb_item, *rb_tmp; static ringbuf_handle_t rb; // Found the kept ringbuffer if exist if (src_el_item->kept_ctx) { STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, rb_tmp) { ESP_LOGD(TAG, "%d, rb:%p host_el:%p kept:%d,linked:%d", __LINE__, rb_item->rb, rb_item->host_el, rb_item->kept_ctx, rb_item->linked); if (rb_item->host_el == el) { cur_rb_item = rb_item; cur_rb_item->linked = true; cur_rb_item->kept_ctx = false; cur_rb_item->host_el = el; src_el_item->kept_ctx = false; ESP_LOGD(TAG, "found kept rb:%p kept:%d,linked:%d, el:%p, name:%s", rb_item->rb, rb_item->kept_ctx, rb_item->linked, src_el_item->el, audio_element_get_tag(src_el_item->el)); break; } } } else { STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, rb_tmp) { ESP_LOGD(TAG, "%d, rb:%p host_el:%p kept:%d,linked:%d", __LINE__, rb_item->rb, rb_item->host_el, rb_item->kept_ctx, rb_item->linked); if ((rb_item->linked == false) && (rb_item->kept_ctx == false)) { if (rb_item->host_el == NULL) { cur_rb_item = rb_item; cur_rb_item->linked = true; cur_rb_item->kept_ctx = false; cur_rb_item->host_el = el; rb_reset(cur_rb_item->rb); ESP_LOGD(TAG, "%d, found not used rb:%p kept:%d,linked:%d", __LINE__, rb_item->rb, rb_item->kept_ctx, rb_item->linked); break; } rb_item->host_el = NULL; } } } if ((last == false) && (cur_rb_item == NULL)) { ringbuf_handle_t tmp_rb = NULL; bool _success = ( (cur_rb_item = audio_calloc(1, sizeof(ringbuf_item_t))) && (tmp_rb = rb_create(audio_element_get_output_ringbuf_size(el), 1)) ); AUDIO_MEM_CHECK(TAG, _success, { audio_free(cur_rb_item); return ESP_ERR_NO_MEM; }); cur_rb_item->rb = tmp_rb; cur_rb_item->linked = true; cur_rb_item->kept_ctx = false; cur_rb_item->host_el = el; STAILQ_INSERT_TAIL(&pipeline->rb_list, cur_rb_item, next); ESP_LOGI(TAG, "create new rb,rb:%p", cur_rb_item->rb); } ESP_LOGD(TAG, "%d, el:%p, tag:%s, cur_rb_item:%p, rb:%p, first:%d, last:%d\r\n", __LINE__, el, audio_element_get_tag(el), cur_rb_item, cur_rb_item != NULL ? cur_rb_item->rb : NULL, first, last); if (last) { audio_element_set_input_ringbuf(el, rb); } else { if (!first) { audio_element_set_input_ringbuf(el, rb); } rb = cur_rb_item->rb; audio_element_set_output_ringbuf(el, rb); } return ESP_OK; } esp_err_t audio_pipeline_relink(audio_pipeline_handle_t pipeline, const char *link_tag[], int link_num) { if (pipeline == NULL || link_tag == NULL) { ESP_LOGE(TAG, "%s have invalid args, %p, %p", __func__, pipeline, link_tag); return ESP_ERR_INVALID_ARG; } if (pipeline->linked) { ESP_LOGE(TAG, "%s pipeline is already linked, can't relink", __func__); return ESP_FAIL; } esp_err_t ret = ESP_OK; audio_element_item_t *el_item, *el_tmp; bool first = false, last = false; for (int i = 0; i < link_num; i++) { audio_element_item_t *src_el_item = audio_pipeline_get_el_item_by_tag(pipeline, link_tag[i]); if (src_el_item == NULL) { ESP_LOGE(TAG, "There is link_tag invalid: %s", link_tag[i]); ret = ESP_FAIL; goto relink_err; } audio_element_handle_t el = NULL; STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, el_tmp) { ESP_LOGD(TAG, "%d, linked:%d, kept:%d, el:%s, el:%p, tag:%s, target-el:%p", __LINE__, el_item->linked, el_item->kept_ctx, audio_element_get_tag(el_item->el), el_item->el, link_tag[i], src_el_item->el); if (src_el_item->el == el_item->el) { el = el_item->el; break; } } if (el == NULL) { ESP_LOGE(TAG, "Can't find element, wanted_el:%s", link_tag[i]); ret = ESP_FAIL; goto relink_err; } src_el_item->linked = true; first = (i == 0); last = (i == link_num - 1); audio_pipeline_el_item_link(pipeline, src_el_item, el, first, last); } pipeline->linked = true; PIPELINE_DEBUG(pipeline); relink_err: return ret; } esp_err_t audio_pipeline_relink_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...) { AUDIO_NULL_CHECK(TAG, (pipeline || element_1), return ESP_ERR_INVALID_ARG); if (pipeline->linked) { ESP_LOGE(TAG, "%s pipeline is already linked, can't relink", __func__); return ESP_FAIL; } va_list args; audio_element_item_t *el_item, *el_tmp; va_start(args, element_1); bool first = false, last = false; uint16_t idx = 0; while (element_1) { audio_element_item_t *src_el_item = audio_pipeline_get_el_item_by_handle(pipeline, element_1); AUDIO_NULL_CHECK(TAG, src_el_item, return ESP_FAIL); audio_element_handle_t el = NULL; STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, el_tmp) { ESP_LOGD(TAG, "%d, linked:%d, kept:%d, el:%s, el:%p, tag:%s, target-el:%p", __LINE__, el_item->linked, el_item->kept_ctx, audio_element_get_tag(el_item->el), el_item->el, audio_element_get_tag(src_el_item->el), src_el_item->el); if (src_el_item->el == el_item->el) { el = el_item->el; break; } } if (el == NULL) { ESP_LOGE(TAG, "Can't find element, wanted_el:%s", audio_element_get_tag(src_el_item->el)); return ESP_FAIL; } src_el_item->linked = true; idx ++; first = (idx == 1); element_1 = va_arg(args, audio_element_handle_t); last = (NULL == element_1) ? true : false; audio_pipeline_el_item_link(pipeline, src_el_item, el, first, last); } pipeline->linked = true; PIPELINE_DEBUG(pipeline); va_end(args); return ESP_OK; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/audio_pipeline.c
C
apache-2.0
38,624
# # "main" pseudo-component makefile. # # (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/component.mk
Makefile
apache-2.0
145
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_COMMON_H_ #define _AUDIO_COMMON_H_ #ifdef __cplusplus extern "C" { #endif #include "audio_type_def.h" #define ELEMENT_SUB_TYPE_OFFSET 16 typedef enum { AUDIO_ELEMENT_TYPE_UNKNOW = 0x01<<ELEMENT_SUB_TYPE_OFFSET, AUDIO_ELEMENT_TYPE_ELEMENT= 0x01<<(ELEMENT_SUB_TYPE_OFFSET+1), AUDIO_ELEMENT_TYPE_PLAYER = 0x01<<(ELEMENT_SUB_TYPE_OFFSET+2), AUDIO_ELEMENT_TYPE_SERVICE = 0x01<<(ELEMENT_SUB_TYPE_OFFSET+3), AUDIO_ELEMENT_TYPE_PERIPH = 0x01<<(ELEMENT_SUB_TYPE_OFFSET+4), } audio_element_type_t; typedef enum { AUDIO_STREAM_NONE = 0, AUDIO_STREAM_READER, AUDIO_STREAM_WRITER } audio_stream_type_t; typedef enum { AUDIO_CODEC_TYPE_NONE = 0, AUDIO_CODEC_TYPE_DECODER, AUDIO_CODEC_TYPE_ENCODER } audio_codec_type_t; #define mem_assert(x) #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/include/audio_common.h
C
apache-2.0
2,066
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_ELEMENT_H_ #define _AUDIO_ELEMENT_H_ #include "esp_err.h" #include "audio_event_iface.h" #include "ringbuf.h" #include "audio_common.h" #ifdef __cplusplus extern "C" { #endif typedef enum { AEL_IO_OK = ESP_OK, AEL_IO_FAIL = ESP_FAIL, AEL_IO_DONE = -2, AEL_IO_ABORT = -3, AEL_IO_TIMEOUT = -4, AEL_PROCESS_FAIL = -5, } audio_element_err_t; /** * @brief Audio element state */ typedef enum { AEL_STATE_NONE = 0, AEL_STATE_INIT = 1, AEL_STATE_INITIALIZING = 2, AEL_STATE_RUNNING = 3, AEL_STATE_PAUSED = 4, AEL_STATE_STOPPED = 5, AEL_STATE_FINISHED = 6, AEL_STATE_ERROR = 7 } audio_element_state_t; /** * Audio element action command, process on dispatcher */ typedef enum { AEL_MSG_CMD_NONE = 0, // AEL_MSG_CMD_ERROR = 1, AEL_MSG_CMD_FINISH = 2, AEL_MSG_CMD_STOP = 3, AEL_MSG_CMD_PAUSE = 4, AEL_MSG_CMD_RESUME = 5, AEL_MSG_CMD_DESTROY = 6, // AEL_MSG_CMD_CHANGE_STATE = 7, AEL_MSG_CMD_REPORT_STATUS = 8, AEL_MSG_CMD_REPORT_MUSIC_INFO = 9, AEL_MSG_CMD_REPORT_CODEC_FMT = 10, AEL_MSG_CMD_REPORT_POSITION = 11, } audio_element_msg_cmd_t; /** * Audio element status report */ typedef enum { AEL_STATUS_NONE = 0, AEL_STATUS_ERROR_OPEN = 1, AEL_STATUS_ERROR_INPUT = 2, AEL_STATUS_ERROR_PROCESS = 3, AEL_STATUS_ERROR_OUTPUT = 4, AEL_STATUS_ERROR_CLOSE = 5, AEL_STATUS_ERROR_TIMEOUT = 6, AEL_STATUS_ERROR_UNKNOWN = 7, AEL_STATUS_INPUT_DONE = 8, AEL_STATUS_INPUT_BUFFERING = 9, AEL_STATUS_OUTPUT_DONE = 10, AEL_STATUS_OUTPUT_BUFFERING = 11, AEL_STATUS_STATE_RUNNING = 12, AEL_STATUS_STATE_PAUSED = 13, AEL_STATUS_STATE_STOPPED = 14, AEL_STATUS_STATE_FINISHED = 15, AEL_STATUS_MOUNTED = 16, AEL_STATUS_UNMOUNTED = 17, } audio_element_status_t; typedef struct audio_element *audio_element_handle_t; /** * @brief Audio Element user reserved data */ typedef struct { int user_data_0; /*!< user data 0 */ int user_data_1; /*!< user data 1 */ int user_data_2; /*!< user data 2 */ int user_data_3; /*!< user data 3 */ int user_data_4; /*!< user data 4 */ } audio_element_reserve_data_t; /** * @brief Audio Element informations */ typedef struct { int sample_rates; /*!< Sample rates in Hz */ int channels; /*!< Number of audio channel, mono is 1, stereo is 2 */ int bits; /*!< Bit wide (8, 16, 24, 32 bits) */ int bps; /*!< Bit per second */ int64_t byte_pos; /*!< The current position (in bytes) being processed for an element */ int64_t total_bytes; /*!< The total bytes for an element */ int duration; /*!< The duration for an element (optional) */ char *uri; /*!< URI (optional) */ esp_codec_type_t codec_fmt; /*!< Music format (optional) */ audio_element_reserve_data_t reserve_data; /*!< This value is reserved for user use (optional) */ } audio_element_info_t; #define AUDIO_ELEMENT_INFO_DEFAULT() { \ .sample_rates = 44100, \ .channels = 2, \ .bits = 16, \ .bps = 0, \ .byte_pos = 0, \ .total_bytes = 0, \ .duration = 0, \ .uri = NULL, \ .codec_fmt = ESP_CODEC_TYPE_UNKNOW \ } typedef esp_err_t (*el_io_func)(audio_element_handle_t self); typedef audio_element_err_t (*process_func)(audio_element_handle_t self, char *el_buffer, int el_buf_len); typedef audio_element_err_t (*stream_func)(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context); typedef esp_err_t (*event_cb_func)(audio_element_handle_t el, audio_event_iface_msg_t *event, void *ctx); typedef esp_err_t (*ctrl_func)(audio_element_handle_t self, void *in_data, int in_size, void *out_data, int *out_size); /** * @brief Audio Element configurations. * Each Element at startup will be a self-running task. * These tasks will execute the callback open -> [loop: read -> process -> write] -> close. * These callback functions are provided by the user corresponding to this configuration. * */ typedef struct { el_io_func open; /*!< Open callback function */ ctrl_func seek; /*!< Seek callback function */ process_func process; /*!< Process callback function */ el_io_func close; /*!< Close callback function */ el_io_func destroy; /*!< Destroy callback function */ stream_func read; /*!< Read callback function */ stream_func write; /*!< Write callback function */ int buffer_len; /*!< Buffer length use for an Element */ int task_stack; /*!< Element task stack */ int task_prio; /*!< Element task priority (based on freeRTOS priority) */ int task_core; /*!< Element task running in core (0 or 1) */ int out_rb_size; /*!< Output ringbuffer size */ void *data; /*!< User context */ const char *tag; /*!< Element tag */ bool stack_in_ext; /*!< Try to allocate stack in external memory */ int multi_in_rb_num; /*!< The number of multiple input ringbuffer */ int multi_out_rb_num; /*!< The number of multiple output ringbuffer */ } audio_element_cfg_t; #define DEFAULT_ELEMENT_RINGBUF_SIZE (8*1024) #define DEFAULT_ELEMENT_BUFFER_LENGTH (1024) #define DEFAULT_ELEMENT_STACK_SIZE (2*1024) #define DEFAULT_ELEMENT_TASK_PRIO (5) #define DEFAULT_ELEMENT_TASK_CORE (0) #define DEFAULT_AUDIO_ELEMENT_CONFIG() { \ .buffer_len = DEFAULT_ELEMENT_BUFFER_LENGTH,\ .task_stack = DEFAULT_ELEMENT_STACK_SIZE, \ .task_prio = DEFAULT_ELEMENT_TASK_PRIO, \ .task_core = DEFAULT_ELEMENT_TASK_CORE, \ .multi_in_rb_num = 0, \ .multi_out_rb_num = 0, \ } /** * @brief Initialize audio element with config. * * @param config The configuration * * @return * - audio_elemenent handle object * - NULL */ audio_element_handle_t audio_element_init(audio_element_cfg_t *config); /** * @brief Destroy audio element handle object, stop, clear, deletel all. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_deinit(audio_element_handle_t el); /** * @brief Set context data to element handle object. * It can be retrieved by calling `audio_element_getdata`. * * @param[in] el The audio element handle * @param data The data pointer * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_setdata(audio_element_handle_t el, void *data); /** * @brief Get context data from element handle object. * * @param[in] el The audio element handle * * @return data pointer */ void *audio_element_getdata(audio_element_handle_t el); /** * @brief Set elemenet tag name, or clear if tag = NULL. * * @param[in] el The audio element handle * @param[in] tag The tag name pointer * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_tag(audio_element_handle_t el, const char *tag); /** * @brief Get element tag name. * * @param[in] el The audio element handle * * @return Element tag name pointer */ char *audio_element_get_tag(audio_element_handle_t el); /** * @brief Set audio element infomation. * * @param[in] el The audio element handle * @param info The information pointer * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_setinfo(audio_element_handle_t el, audio_element_info_t *info); /** * @brief Get audio element infomation. * * @param[in] el The audio element handle * @param info The information pointer * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_getinfo(audio_element_handle_t el, audio_element_info_t *info); /** * @brief Set audio element URI. * * @param[in] el The audio element handle * @param[in] uri The uri pointer * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_uri(audio_element_handle_t el, const char *uri); /** * @brief Get audio element URI. * * @param[in] el The audio element handle * * @return URI pointer */ char *audio_element_get_uri(audio_element_handle_t el); /** * @brief Start Audio Element. * With this function, audio_element will start as freeRTOS task, * and put the task into 'PAUSED' state. * Note: Element does not actually start when this function returns * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_run(audio_element_handle_t el); /** * @brief Terminate Audio Element. * With this function, audio_element will exit the task function. * Note: this API only sends request. It does not actually terminate immediately when this function returns. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_terminate(audio_element_handle_t el); /** * @brief Terminate Audio Element with specific ticks for timeout. * With this function, audio_element will exit the task function. * Note: this API only sends request. It does not actually terminate immediately when this function returns. * * @param[in] el The audio element handle * @param[in] ticks_to_wait The maximum amount of time to blocking * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_terminate_with_ticks(audio_element_handle_t el, TickType_t ticks_to_wait); /** * @brief Request stop of the Audio Element. * After receiving the stop request, the element will ignore the actions being performed * (read/write, wait for the ringbuffer ...) and close the task, reset the state variables. * Note: this API only sends requests, Element does not actually stop when this function returns * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_stop(audio_element_handle_t el); /** * @brief After the `audio_element_stop` function is called, the Element task will perform some abort procedures. * This function will be blocked (Time is DEFAULT_MAX_WAIT_TIME) until Element Task has done and exit. * * @param[in] el The audio element handle * * @return * - ESP_OK, Success * - ESP_FAIL, The state is not AEL_STATE_RUNNING * - ESP_ERR_TIMEOUT, Timeout */ esp_err_t audio_element_wait_for_stop(audio_element_handle_t el); /** * @brief After the `audio_element_stop` function is called, the Element task will perform some abort procedures. * The maximum amount of time should block waiting for Element task has stopped. * * @param[in] el The audio element handle * @param[in] ticks_to_wait The maximum amount of time to wait for stop * * @return * - ESP_OK, Success * - ESP_FAIL, The state is not AEL_STATE_RUNNING * - ESP_ERR_TIMEOUT, Timeout */ esp_err_t audio_element_wait_for_stop_ms(audio_element_handle_t el, TickType_t ticks_to_wait); /** * @brief Request audio Element enter 'PAUSE' state. * In this state, the task will wait for any event * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_pause(audio_element_handle_t el); /** * @brief Request audio Element enter 'RUNNING' state. * In this state, the task listens to events and invokes the callback functions. * At the same time it will wait until the size/total_size of the output ringbuffer is greater than or equal to `wait_for_rb_threshold`. * If the timeout period has been exceeded and ringbuffer output has not yet reached `wait_for_rb_threshold` then the function will return. * * @param[in] el The audio element handle * @param[in] wait_for_rb_threshold The wait for rb threshold (0 .. 1) * @param[in] timeout The timeout * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_resume(audio_element_handle_t el, float wait_for_rb_threshold, TickType_t timeout); /** * @brief This function will add a `listener` to listen to all events from audio element `el`. * Any event from el->external_event will be send to the `listener`. * * @param el The audio element handle * @param listener The event will be listen to * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_msg_set_listener(audio_element_handle_t el, audio_event_iface_handle_t listener); /** * @brief This function will add a `callback` to be called from audio element `el`. * Any event to caller will cause to call callback function. * * @param el The audio element handle * @param cb_func The callback function * @param ctx Caller context * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_event_callback(audio_element_handle_t el, event_cb_func cb_func, void *ctx); /** * @brief Remove listener out of el. * No new events will be sent to the listener. * * @param[in] el The audio element handle * @param listener The listener * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_msg_remove_listener(audio_element_handle_t el, audio_event_iface_handle_t listener); /** * @brief Set Element input ringbuffer * * @param[in] el The audio element handle * @param[in] rb The ringbuffer handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_input_ringbuf(audio_element_handle_t el, ringbuf_handle_t rb); /** * @brief Get Element input ringbuffer. * * @param[in] el The audio element handle * * @return ringbuf_handle_t */ ringbuf_handle_t audio_element_get_input_ringbuf(audio_element_handle_t el); /** * @brief Set Element output ringbuffer. * * @param[in] el The audio element handle * @param[in] rb The ringbuffer handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_output_ringbuf(audio_element_handle_t el, ringbuf_handle_t rb); /** * @brief Get Element output ringbuffer. * * @param[in] el The audio element handle * * @return ringbuf_handle_t */ ringbuf_handle_t audio_element_get_output_ringbuf(audio_element_handle_t el); /** * @brief Get current Element state. * * @param[in] el The audio element handle * * @return audio_element_state_t */ audio_element_state_t audio_element_get_state(audio_element_handle_t el); /** * @brief If the element is requesting data from the input ringbuffer, this function forces it to abort. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_abort_input_ringbuf(audio_element_handle_t el); /** * @brief If the element is waiting to write data to the ringbuffer output, this function forces it to abort. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_abort_output_ringbuf(audio_element_handle_t el); /** * @brief This function will wait until the sizeof the output ringbuffer is greater than or equal to `size_expect`. * If the timeout period has been exceeded and ringbuffer output has not yet reached `size_expect` * then the function will return `ESP_FAIL` * * @param[in] el The audio element handle * @param[in] size_expect The size expect * @param[in] timeout The timeout * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_wait_for_buffer(audio_element_handle_t el, int size_expect, TickType_t timeout); /** * @brief Element will sendout event (status) to event by this function. * * @param[in] el The audio element handle * @param[in] status The status * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_report_status(audio_element_handle_t el, audio_element_status_t status); /** * @brief Element will sendout event (information) to event by this function. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_report_info(audio_element_handle_t el); /** * @brief Element will sendout event (codec format) to event by this function. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_report_codec_fmt(audio_element_handle_t el); /** * @brief Element will sendout event with a duplicate information by this function. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL * - ESP_ERR_NO_MEM */ esp_err_t audio_element_report_pos(audio_element_handle_t el); /** * @brief Set input read timeout (default is `portMAX_DELAY`). * * @param[in] el The audio element handle * @param[in] timeout The timeout * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_input_timeout(audio_element_handle_t el, TickType_t timeout); /** * @brief Set output read timeout (default is `portMAX_DELAY`). * * @param[in] el The audio element handle * @param[in] timeout The timeout * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_output_timeout(audio_element_handle_t el, TickType_t timeout); /** * @brief Reset inputbuffer. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_reset_input_ringbuf(audio_element_handle_t el); /** * @brief Set element finish state * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_finish_state(audio_element_handle_t el); /** * @brief Change element running state with specific command. * * @param[in] el The audio element handle * @param[in] cmd Specific command from audio_element_msg_cmd_t * * @return * - ESP_OK * - ESP_FAIL * - ESP_ERR_INVALID_ARG Element handle is null */ esp_err_t audio_element_change_cmd(audio_element_handle_t el, audio_element_msg_cmd_t cmd); /** * @brief Reset outputbuffer. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_reset_output_ringbuf(audio_element_handle_t el); /** * @brief Call this function to provide Element input data. * Depending on setup using ringbuffer or function callback, Element invokes read ringbuffer, or calls read callback funtion. * * @param[in] el The audio element handle * @param buffer The buffer pointer * @param[in] wanted_size The wanted size * * @return * - > 0 number of bytes produced * - <=0 audio_element_err_t */ audio_element_err_t audio_element_input(audio_element_handle_t el, char *buffer, int wanted_size); /** * @brief Call this function to sendout Element output data. * Depending on setup using ringbuffer or function callback, Element will invoke write to ringbuffer, or call write callback funtion. * * @param[in] el The audio element handle * @param buffer The buffer pointer * @param[in] write_size The write size * * @return * - > 0 number of bytes written * - <=0 audio_element_err_t */ audio_element_err_t audio_element_output(audio_element_handle_t el, char *buffer, int write_size); /** * @brief This API allows the application to set a read callback for the first audio_element in the pipeline for * allowing the pipeline to interface with other systems. The callback is invoked every time the audio * element requires data to be processed. * * @param[in] el The audio element handle * @param[in] fn Callback read function. The callback function should return number of bytes read or -1 * in case of error in reading. Note that the callback function may decide to block and * that may block the entire pipeline. * @param[in] context An optional context which will be passed to callback function on every invocation * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_read_cb(audio_element_handle_t el, stream_func fn, void *context); /** * @brief This API allows the application to set a write callback for the last audio_element in the pipeline for * allowing the pipeline to interface with other systems. * The callback is invoked every time the audio element has a processed data that needs to be passed forward. * * @param[in] el The audio element * @param[in] fn Callback write function * The callback function should return number of bytes written or -1 in case of error in writing. * Note that the callback function may decide to block and that may block the entire pipeline. * @param[in] context An optional context which will be passed to callback function on every invocation * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_write_cb(audio_element_handle_t el, stream_func fn, void *context); /** * @brief Get callback write function that register to the element * * @param[in] el The audio element * * @return * - Callback write function pointer * - NULL Failed */ stream_func audio_element_get_write_cb(audio_element_handle_t el); /** * @brief Get callback read function that register to the element * * @param[in] el The audio element * * @return * - Callback read function pointer * - NULL Failed */ stream_func audio_element_get_read_cb(audio_element_handle_t el); /** * @brief Get External queue of Emitter. * We can read any event that has been send out of Element from this `QueueHandle_t`. * * @param[in] el The audio element handle * * @return QueueHandle_t */ QueueHandle_t audio_element_get_event_queue(audio_element_handle_t el); /** * @brief Set inputbuffer and outputbuffer have finished. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_ringbuf_done(audio_element_handle_t el); /** * @brief Enforce 'AEL_STATE_INIT' state. * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_reset_state(audio_element_handle_t el); /** * @brief Get Element output ringbuffer size. * * @param[in] el The audio element handle * * @return * - =0: Parameter NULL * - >0: Size of ringbuffer */ int audio_element_get_output_ringbuf_size(audio_element_handle_t el); /** * @brief Set Element output ringbuffer size. * * @param[in] el The audio element handle * @param[in] rb_size Size of the ringbuffer * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_output_ringbuf_size(audio_element_handle_t el, int rb_size); /** * @brief Call this function to read data from multi input ringbuffer by given index. * * @param el The audio element handle * @param buffer The buffer pointer * @param wanted_size The wanted size * @param index The index of multi input ringbuffer, start from `0`, should be less than `NUMBER_OF_MULTI_RINGBUF` * @param ticks_to_wait Timeout of ringbuffer * * @return * - ESP_OK * - ESP_ERR_INVALID_ARG */ esp_err_t audio_element_multi_input(audio_element_handle_t el, char *buffer, int wanted_size, int index, TickType_t ticks_to_wait); /** * @brief Call this function write data by multi output ringbuffer. * * @param[in] el The audio element handle * @param buffer The buffer pointer * @param[in] wanted_size The wanted size * @param ticks_to_wait Timeout of ringbuffer * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_multi_output(audio_element_handle_t el, char *buffer, int wanted_size, TickType_t ticks_to_wait); /** * @brief Set multi input ringbuffer Element. * * @param[in] el The audio element handle * @param[in] rb The ringbuffer handle * @param[in] index Index of multi ringbuffer, starts from `0`, should be less than `NUMBER_OF_MULTI_RINGBUF` * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_multi_input_ringbuf(audio_element_handle_t el, ringbuf_handle_t rb, int index); /** * @brief Set multi output ringbuffer Element. * * @param[in] el The audio element handle * @param[in] rb The ringbuffer handle * @param[in] index Index of multi ringbuffer, starts from `0`, should be less than `NUMBER_OF_MULTI_RINGBUF` * * @return * - ESP_OK * - ESP_ERR_INVALID_ARG */ esp_err_t audio_element_set_multi_output_ringbuf(audio_element_handle_t el, ringbuf_handle_t rb, int index); /** * @brief Get handle of multi input ringbuffer Element by index. * * @param[in] el The audio element handle * @param[in] index Index of multi ringbuffer, starts from `0`, should be less than `NUMBER_OF_MULTI_RINGBUF` * * @return * - NULL Error * - Others ringbuf_handle_t */ ringbuf_handle_t audio_element_get_multi_input_ringbuf(audio_element_handle_t el, int index); /** * @brief Get handle of multi output ringbuffer Element by index. * * @param[in] el The audio element handle * @param[in] index Index of multi ringbuffer, starts from `0`, should be less than `NUMBER_OF_MULTI_RINGBUF` * * @return * - NULL Error * - Others ringbuf_handle_t */ ringbuf_handle_t audio_element_get_multi_output_ringbuf(audio_element_handle_t el, int index); /** * @brief Provides a way to call element's `open` * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_process_init(audio_element_handle_t el); /** * @brief Provides a way to call element's `close` * * @param[in] el The audio element handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_process_deinit(audio_element_handle_t el); /** * @brief Call element's `seek` * * @param[in] el The audio element handle * @param[in] in_data A pointer to in data * @param[in] in_size The size of the `in_data` * @param[out] out_data A pointer to the out data * @param[out] out_size The size of the `out_data` * * @return * - ESP_OK * - ESP_FAIL * - ESP_ERR_NOT_SUPPORTED */ esp_err_t audio_element_seek(audio_element_handle_t el, void *in_data, int in_size, void *out_data, int *out_size); /** * @brief Get Element stopping flag * * @param[in] el The audio element handle * * @return element's stopping flag */ bool audio_element_is_stopping(audio_element_handle_t el); /** * @brief Update the byte position of element information * * @param[in] el The audio element handle * @param[in] pos The byte_pos accumulated by this value * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_update_byte_pos(audio_element_handle_t el, int pos); /** * @brief Set the byte position of element information * * @param[in] el The audio element handle * @param[in] pos This value is assigned to byte_pos * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_byte_pos(audio_element_handle_t el, int pos); /** * @brief Update the total bytes of element information * * @param[in] el The audio element handle * @param[in] total_bytes The total_bytes accumulated by this value * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_update_total_bytes(audio_element_handle_t el, int total_bytes); /** * @brief Set the total bytes of element information * * @param[in] el The audio element handle * @param[in] total_bytes This value is assigned to total_bytes * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_total_bytes(audio_element_handle_t el, int total_bytes); /** * @brief Set the bps of element information * * @param[in] el The audio element handle * @param[in] bit_rate This value is assigned to bps * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_bps(audio_element_handle_t el, int bit_rate); /** * @brief Set the codec format of element information * * @param[in] el The audio element handle * @param[in] format This value is assigned to codec_fmt * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_codec_fmt(audio_element_handle_t el, int format); /** * @brief Set the sample_rate, channels, bits of element information * * @param[in] el The audio element handle * @param[in] sample_rates Sample_rates of music information * @param[in] channels Channels of music information * @param[in] bits Bits of music information * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_music_info(audio_element_handle_t el, int sample_rates, int channels, int bits); /** * @brief Set the duration of element information * * @param[in] el The audio element handle * @param[in] duration This value is assigned to duration * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_duration(audio_element_handle_t el, int duration); /** * @brief Set the user_data_0 of element information * * @param[in] el The audio element handle * @param[in] user_data0 This value is assigned to user_data_0 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_reserve_user0(audio_element_handle_t el, int user_data0); /** * @brief Set the user_data_1 of element information * * @param[in] el The audio element handle * @param[in] user_data1 This value is assigned to user_data_1 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_reserve_user1(audio_element_handle_t el, int user_data1); /** * @brief Set the user_data_2 of element information * * @param[in] el The audio element handle * @param[in] user_data2 This value is assigned to user_data_2 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_reserve_user2(audio_element_handle_t el, int user_data2); /** * @brief Set the user_data_3 of element information * * @param[in] el The audio element handle * @param[in] user_data3 This value is assigned to user_data_3 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_reserve_user3(audio_element_handle_t el, int user_data3); /** * @brief Set the user_data_4 of element information * * @param[in] el The audio element handle * @param[in] user_data4 This value is assigned to user_data_4 * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_element_set_reserve_user4(audio_element_handle_t el, int user_data4); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/include/audio_element.h
C
apache-2.0
34,151
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_EVENT_IFACE_H_ #define _AUDIO_EVENT_IFACE_H_ #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #ifdef __cplusplus extern "C" { #endif /** * Event message */ typedef struct { int cmd; /*!< Command id */ void *data; /*!< Data pointer */ int data_len; /*!< Data length */ void *source; /*!< Source event */ int source_type; /*!< Source type (To know where it came from) */ bool need_free_data; /*!< Need to free data pointer after the event has been processed */ } audio_event_iface_msg_t; typedef esp_err_t (*on_event_iface_func)(audio_event_iface_msg_t *, void *); typedef struct audio_event_iface *audio_event_iface_handle_t; /** * Event interface configurations */ typedef struct { int internal_queue_size; /*!< It's optional, Queue size for event `internal_queue` */ int external_queue_size; /*!< It's optional, Queue size for event `external_queue` */ int queue_set_size; /*!< It's optional, QueueSet size for event `queue_set`*/ on_event_iface_func on_cmd; /*!< Function callback for listener when any event arrived */ void *context; /*!< Context will pass to callback function */ TickType_t wait_time; /*!< Timeout to check for event queue */ int type; /*!< it will pass to audio_event_iface_msg_t source_type (To know where it came from) */ } audio_event_iface_cfg_t; #define DEFAULT_AUDIO_EVENT_IFACE_SIZE (5) #define AUDIO_EVENT_IFACE_DEFAULT_CFG() { \ .internal_queue_size = DEFAULT_AUDIO_EVENT_IFACE_SIZE, \ .external_queue_size = DEFAULT_AUDIO_EVENT_IFACE_SIZE, \ .queue_set_size = DEFAULT_AUDIO_EVENT_IFACE_SIZE, \ .on_cmd = NULL, \ .context = NULL, \ .wait_time = portMAX_DELAY, \ .type = 0, \ } /** * @brief Initialize audio event * * @param config The configurations * * @return * - ESP_OK * - ESP_FAIL */ audio_event_iface_handle_t audio_event_iface_init(audio_event_iface_cfg_t *config); /** * @brief Cleanup event, it doesn't free evt pointer * * @param evt The event * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_destroy(audio_event_iface_handle_t evt); /** * @brief Add audio event `evt` to the listener, then we can listen `evt` event from `listen` * * @param listener The event can listen another event * @param evt The event to be added to * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_set_listener(audio_event_iface_handle_t evt, audio_event_iface_handle_t listener); /** * @brief Remove audio event `evt` from the listener * * @param listener The event listener * @param evt The event to be removed from * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_remove_listener(audio_event_iface_handle_t listener, audio_event_iface_handle_t evt); /** * @brief Set current queue wait time for the event * * @param evt The event * @param[in] wait_time The wait time * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_set_cmd_waiting_timeout(audio_event_iface_handle_t evt, TickType_t wait_time); /** * @brief Waiting internal queue message * * @param evt The event * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_waiting_cmd_msg(audio_event_iface_handle_t evt); /** * @brief Trigger an event for internal queue with a message * * @param evt The event * @param msg The message * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_cmd(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg); /** * @brief It's same with `audio_event_iface_cmd`, but can send a message from ISR * * @param[in] evt The event * @param msg The message * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_cmd_from_isr(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg); /** * @brief Trigger and event out with a message * * @param evt The event * @param msg The message * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_sendout(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg); /** * @brief Discard all ongoing event message * * @param evt The event * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_discard(audio_event_iface_handle_t evt); /** * @brief Listening and invoke callback function if there are any event are comming * * @param evt The event * @param msg The message * @param wait_time The wait time * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_listen(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg, TickType_t wait_time); /** * @brief Get External queue handle of Emmitter * * @param[in] evt The external queue * * @return External QueueHandle_t */ QueueHandle_t audio_event_iface_get_queue_handle(audio_event_iface_handle_t evt); /** * @brief Read the event from all the registered event emitters in the queue set of the interface * * @param[in] evt The event interface * @param[out] msg The pointer to structure in which event is to be received * @param[in] wait_time Timeout for receiving event * * @return * - ESP_OK On successful receiving of event * - ESP_FAIL In case of a timeout or invalid parameter passed */ esp_err_t audio_event_iface_read(audio_event_iface_handle_t evt, audio_event_iface_msg_t *msg, TickType_t wait_time); /** * @brief Get Internal queue handle of Emmitter * * @param[in] evt The Internal queue * * @return Internal QueueHandle_t */ QueueHandle_t audio_event_iface_get_msg_queue_handle(audio_event_iface_handle_t evt); /** * @brief Add audio internal event `evt` to the listener, then we can listen `evt` event from `listen` * * @param listener The event can listen another event * @param evt The event to be added to * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_event_iface_set_msg_listener(audio_event_iface_handle_t evt, audio_event_iface_handle_t listener); #ifdef __cplusplus } #endif #endif //end of file _AUDIO_EVENT_IFACE_H_
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/include/audio_event_iface.h
C
apache-2.0
8,015
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_PIPELINE_H_ #define _AUDIO_PIPELINE_H_ #include "audio_element.h" #ifdef __cplusplus extern "C" { #endif typedef struct audio_pipeline *audio_pipeline_handle_t; /** * @brief Audio Pipeline configurations */ typedef struct audio_pipeline_cfg { int rb_size; /*!< Audio Pipeline ringbuffer size */ } audio_pipeline_cfg_t; #define DEFAULT_PIPELINE_RINGBUF_SIZE (8*1024) #define DEFAULT_AUDIO_PIPELINE_CONFIG() {\ .rb_size = DEFAULT_PIPELINE_RINGBUF_SIZE,\ } /** * @brief Initialize audio_pipeline_handle_t object * audio_pipeline is responsible for controlling the audio data stream and connecting the audio elements with the ringbuffer * It will connect and start the audio element in order, responsible for retrieving the data from the previous element * and passing it to the element after it. Also get events from each element, process events or pass it to a higher layer * * @param config The configuration - audio_pipeline_cfg_t * * @return * - audio_pipeline_handle_t on success * - NULL when any errors */ audio_pipeline_handle_t audio_pipeline_init(audio_pipeline_cfg_t *config); /** * @brief This function removes all of the element's links in audio_pipeline, * cancels the registration of all events, invokes the destroy functions of the registered elements, * and frees the memory allocated by the init function. * Briefly, frees all memory * * @param[in] pipeline The Audio Pipeline Handle * * @return ESP_OK */ esp_err_t audio_pipeline_deinit(audio_pipeline_handle_t pipeline); /** * @brief Registering an element for audio_pipeline, each element can be registered multiple times, * but `name` (as String) must be unique in audio_pipeline, * which is used to identify the element for link creation mentioned in the `audio_pipeline_link` * * @note Because of stop pipeline or pause pipeline depend much on register order. * Please register element strictly in the following order: input element first, process middle, output element last. * * @param[in] pipeline The Audio Pipeline Handle * @param[in] el The Audio Element Handle * @param[in] name The name identifier of the audio_element in this audio_pipeline * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_register(audio_pipeline_handle_t pipeline, audio_element_handle_t el, const char *name); /** * @brief Unregister the audio_element in audio_pipeline, remove it from the list * * @param[in] pipeline The Audio Pipeline Handle * @param[in] el The Audio Element Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_unregister(audio_pipeline_handle_t pipeline, audio_element_handle_t el); /** * @brief Start Audio Pipeline. * * With this function audio_pipeline will create tasks for all elements, * that have been linked using the linking functions. * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_run(audio_pipeline_handle_t pipeline); /** * @brief Stop Audio Pipeline. * * With this function audio_pipeline will destroy tasks of all elements, * that have been linked using the linking functions. * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_terminate(audio_pipeline_handle_t pipeline); /** * @brief Stop Audio Pipeline with specific ticks for timeout * * With this function audio_pipeline will destroy tasks of all elements, * that have been linked using the linking functions. * * @param[in] pipeline The Audio Pipeline Handle * @param[in] ticks_to_wait The maximum amount of time to block wait for element destroy * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_pipeline_terminate_with_ticks(audio_pipeline_handle_t pipeline, TickType_t ticks_to_wait); /** * @brief This function will set all the elements to the `RUNNING` state and process the audio data as an inherent feature of audio_pipeline. * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_resume(audio_pipeline_handle_t pipeline); /** * @brief This function will set all the elements to the `PAUSED` state. Everything remains the same except the data processing is stopped * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_pause(audio_pipeline_handle_t pipeline); /** * @brief Stop all of the linked elements. Used with `audio_pipeline_wait_for_stop` to keep in sync. * The link state of the elements in the pipeline is kept, events are still registered. * The stopped audio_pipeline restart by `audio_pipeline_resume`. * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_stop(audio_pipeline_handle_t pipeline); /** * @brief The `audio_pipeline_stop` function sends requests to the elements and exits. * But they need time to get rid of time-blocking tasks. * This function will wait `portMAX_DELAY` until all the Elements in the pipeline actually stop * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_wait_for_stop(audio_pipeline_handle_t pipeline); /** * @brief The `audio_pipeline_stop` function sends requests to the elements and exits. * But they need time to get rid of time-blocking tasks. * This function will wait `ticks_to_wait` until all the Elements in the pipeline actually stop * * @param[in] pipeline The Audio Pipeline Handle * @param[in] ticks_to_wait The maximum amount of time to block wait for stop * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_wait_for_stop_with_ticks(audio_pipeline_handle_t pipeline, TickType_t ticks_to_wait); /** * @brief The audio_element added to audio_pipeline will be unconnected before it is called by this function. * Based on element's `name` already registered by `audio_pipeline_register`, the path of the data will be linked in the order of the link_tag. * Element at index 0 is first, and index `link_num -1` is final. * As well as audio_pipeline will subscribe all element's events * * @param[in] pipeline The Audio Pipeline Handle * @param link_tag Array of element `name` was registered by `audio_pipeline_register` * @param[in] link_num Total number of elements of the `link_tag` array * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_link(audio_pipeline_handle_t pipeline, const char *link_tag[], int link_num); /** * @brief Removes the connection of the elements, as well as unsubscribe events * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_unlink(audio_pipeline_handle_t pipeline); /** * @brief Find un-kept element from registered pipeline by tag * * @param[in] pipeline The Audio Pipeline Handle * @param[in] tag A char pointer * * @return * - NULL when any errors * - Others on success */ audio_element_handle_t audio_pipeline_get_el_by_tag(audio_pipeline_handle_t pipeline, const char *tag); /** * @brief Based on beginning element to find un-kept element from registered pipeline by tag * * @param[in] pipeline The Audio Pipeline Handle * @param[in] start_el Specific beginning element * @param[in] tag A char pointer * * @return * - NULL when any errors * - Others on success */ audio_element_handle_t audio_pipeline_get_el_once(audio_pipeline_handle_t pipeline, const audio_element_handle_t start_el, const char *tag); /** * @brief Remove event listener from this audio_pipeline * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_remove_listener(audio_pipeline_handle_t pipeline); /** * @brief Set event listner for this audio_pipeline, any event from this pipeline can be listen to by `evt` * * @param[in] pipeline The Audio Pipeline Handle * @param[in] evt The Event Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_set_listener(audio_pipeline_handle_t pipeline, audio_event_iface_handle_t evt); /** * @brief Get the event iface using by this pipeline * * @param[in] pipeline The pipeline * * @return The Event Handle */ audio_event_iface_handle_t audio_pipeline_get_event_iface(audio_pipeline_handle_t pipeline); /** * @brief Insert the specific audio_element to audio_pipeline, previous element connect to the next element by ring buffer. * * @param[in] pipeline The audio pipeline handle * @param[in] first Previous element is first input element, need to set `true` * @param[in] prev Previous element * @param[in] conect_rb Connect ring buffer * @param[in] next Next element * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_pipeline_link_insert(audio_pipeline_handle_t pipeline, bool first, audio_element_handle_t prev, ringbuf_handle_t conect_rb, audio_element_handle_t next); /** * @brief Register a NULL-terminated list of elements to audio_pipeline. * * @param[in] pipeline The audio pipeline handle * @param[in] element_1 The element to add to the audio_pipeline. * @param[in] ... Additional elements to add to the audio_pipeline. * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_pipeline_register_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...); /** * @brief Unregister a NULL-terminated list of elements to audio_pipeline. * * @param[in] pipeline The audio pipeline handle * @param[in] element_1 The element to add to the audio_pipeline. * @param[in] ... Additional elements to add to the audio_pipeline. * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_pipeline_unregister_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...); /** * @brief Adds a NULL-terminated list of elements to audio_pipeline. * * @param[in] pipeline The audio pipeline handle * @param[in] element_1 The element to add to the audio_pipeline. * @param[in] ... Additional elements to add to the audio_pipeline. * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_pipeline_link_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...); /** * @brief Subscribe a NULL-terminated list of element's events to audio_pipeline. * * @param[in] pipeline The audio pipeline handle * @param[in] element_1 The element event to subscribe to the audio_pipeline. * @param[in] ... Additional elements event to subscribe to the audio_pipeline. * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t audio_pipeline_listen_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...); /** * @brief Update the destination element state and check the all of linked elements state are same. * * @param[in] pipeline The audio pipeline handle * @param[in] dest_el Destination element * @param[in] status The new status * * @return * - ESP_OK All linked elements state are same. * - ESP_FAIL All linked elements state are not same. */ esp_err_t audio_pipeline_check_items_state(audio_pipeline_handle_t pipeline, audio_element_handle_t dest_el, audio_element_status_t status); /** * @brief Reset pipeline element items state to `AEL_STATUS_NONE` * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_reset_items_state(audio_pipeline_handle_t pipeline); /** * @brief Reset pipeline element ringbuffer * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_reset_ringbuffer(audio_pipeline_handle_t pipeline); /** * @brief Reset Pipeline linked elements state * * @param[in] pipeline The Audio Pipeline Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_reset_elements(audio_pipeline_handle_t pipeline); /** * @brief Reset the specific element kept state * * @param[in] pipeline The Audio Pipeline Handle * @param[in] el The Audio element Handle * * @return * - ESP_OK on success * - ESP_FAIL when any errors */ esp_err_t audio_pipeline_reset_kept_state(audio_pipeline_handle_t pipeline, audio_element_handle_t el); /** * @brief Break up all the linked elements of specific `pipeline`. * The include and before `kept_ctx_el` working (AEL_STATE_RUNNING or AEL_STATE_PAUSED) elements * and connected ringbuffer will be reserved. * * @note There is no element reserved when `kept_ctx_el` is NULL. * This function will unsubscribe all element's events. * * @param[in] pipeline The audio pipeline handle * @param[in] kept_ctx_el Destination keep elements * * @return * - ESP_OK All linked elements state are same. * - ESP_ERR_INVALID_ARG Invalid parameters. */ esp_err_t audio_pipeline_breakup_elements(audio_pipeline_handle_t pipeline, audio_element_handle_t kept_ctx_el); /** * @brief Basing on element's `name` already registered by `audio_pipeline_register`, * relink the pipeline following the order of `names` in the `link_tag. * * @note If the ringbuffer is not enough to connect the new pipeline will create new ringbuffer. * * @param[in] pipeline The Audio Pipeline Handle * @param link_tag Array of elements `name` that was registered by `audio_pipeline_register` * @param[in] link_num Total number of elements of the `link_tag` array * * @return * - ESP_OK All linked elements state are same. * - ESP_FAIL Error. * - ESP_ERR_INVALID_ARG Invalid parameters. */ esp_err_t audio_pipeline_relink(audio_pipeline_handle_t pipeline, const char *link_tag[], int link_num); /** * @brief Adds a NULL-terminated list of elements to audio_pipeline. * * @note If the ringbuffer is not enough to connect the new pipeline will create new ringbuffer. * * @param[in] pipeline The Audio Pipeline Handle * @param[in] element_1 The element to add to the audio_pipeline. * @param[in] ... Additional elements to add to the audio_pipeline. * * @return * - ESP_OK All linked elements state are same. * - ESP_FAIL Error. * - ESP_ERR_INVALID_ARG Invalid parameters. */ esp_err_t audio_pipeline_relink_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...); /** * @brief Set the pipeline state. * * @param[in] pipeline The Audio Pipeline Handle * @param[in] new_state The new state will be set * * @return * - ESP_OK All linked elements state are same. * - ESP_FAIL Error. */ esp_err_t audio_pipeline_change_state(audio_pipeline_handle_t pipeline, audio_element_state_t new_state); #ifdef __cplusplus } #endif #endif /* _AUDIO_PIPELINE_H_ */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/include/audio_pipeline.h
C
apache-2.0
17,539
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _RINGBUF_H__ #define _RINGBUF_H__ #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "freertos/queue.h" #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef struct ringbuf *ringbuf_handle_t; /** * @brief Create ringbuffer with total size = block_size * n_blocks * * @param[in] block_size Size of each block * @param[in] n_blocks Number of blocks * * @return ringbuf_handle_t */ ringbuf_handle_t rb_create(int block_size, int n_blocks); /** * @brief Cleanup and free all memory created by ringbuf_handle_t * * @param[in] rb The Ringbuffer handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t rb_destroy(ringbuf_handle_t rb); /** * @brief Abort waiting until there is space for reading or writing of the ringbuffer * * @param[in] rb The Ringbuffer handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t rb_abort(ringbuf_handle_t rb); /** * @brief Reset ringbuffer, clear all values as initial state * * @param[in] rb The Ringbuffer handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t rb_reset(ringbuf_handle_t rb); /** * @brief Get total bytes available of Ringbuffer * * @param[in] rb The Ringbuffer handle * * @return total bytes available */ int rb_bytes_available(ringbuf_handle_t rb); /** * @brief Get the number of bytes that have filled the ringbuffer * * @param[in] rb The Ringbuffer handle * * @return The number of bytes that have filled the ringbuffer */ int rb_bytes_filled(ringbuf_handle_t rb); /** * @brief Get total size of Ringbuffer (in bytes) * * @param[in] rb The Ringbuffer handle * * @return total size of Ringbuffer */ int rb_get_size(ringbuf_handle_t rb); /** * @brief Read from Ringbuffer to `buf` with len and wait `tick_to_wait` ticks until enough bytes to read * if the ringbuffer bytes available is less than `len`. * If `buf` argument provided is `NULL`, then ringbuffer do pseudo reads by simply advancing pointers. * * @param[in] rb The Ringbuffer handle * @param buf The buffer pointer to read out data * @param[in] len The length request * @param[in] ticks_to_wait The ticks to wait * * @return Number of bytes read */ int rb_read(ringbuf_handle_t rb, char *buf, int len, TickType_t ticks_to_wait); /** * @brief Write to Ringbuffer from `buf` with `len` and wait `tick_to_wait` ticks until enough space to write * if the ringbuffer space available is less than `len` * * @param[in] rb The Ringbuffer handle * @param buf The buffer * @param[in] len The length * @param[in] ticks_to_wait The ticks to wait * * @return Number of bytes written */ int rb_write(ringbuf_handle_t rb, char *buf, int len, TickType_t ticks_to_wait); /** * @brief Set status of writing to ringbuffer is done * * @param[in] rb The Ringbuffer handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t rb_done_write(ringbuf_handle_t rb); /** * @brief Unblock from rb_read * * @param[in] rb The Ringbuffer handle * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t rb_unblock_reader(ringbuf_handle_t rb); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/include/ringbuf.h
C
apache-2.0
4,629
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <stdio.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "ringbuf.h" #include "esp_log.h" #include "audio_mem.h" #include "audio_error.h" #define RB_OK (ESP_OK) #define RB_FAIL (ESP_FAIL) #define RB_DONE (-2) #define RB_ABORT (-3) #define RB_TIMEOUT (-4) static const char *TAG = "RINGBUF"; struct ringbuf { char *p_o; /**< Original pointer */ char *volatile p_r; /**< Read pointer */ char *volatile p_w; /**< Write pointer */ volatile uint32_t fill_cnt; /**< Number of filled slots */ uint32_t size; /**< Buffer size */ SemaphoreHandle_t can_read; SemaphoreHandle_t can_write; SemaphoreHandle_t lock; bool abort_read; bool abort_write; bool is_done_write; /**< To signal that we are done writing */ bool unblock_reader_flag; /**< To unblock instantly from rb_read */ }; typedef struct ringbuf *ringbuf_handle_t; static esp_err_t rb_abort_read(ringbuf_handle_t rb); static esp_err_t rb_abort_write(ringbuf_handle_t rb); static void rb_release(SemaphoreHandle_t handle); ringbuf_handle_t rb_create(int block_size, int n_blocks) { if (block_size < 2) { ESP_LOGE(TAG, "Invalid size"); return NULL; } ringbuf_handle_t rb; char *buf = NULL; bool _success = ( (rb = audio_malloc(sizeof(struct ringbuf))) && (buf = audio_calloc(n_blocks, block_size)) && (rb->can_read = xSemaphoreCreateBinary()) && (rb->lock = xSemaphoreCreateMutex()) && (rb->can_write = xSemaphoreCreateBinary()) ); AUDIO_MEM_CHECK(TAG, _success, goto _rb_init_failed); rb->p_o = rb->p_r = rb->p_w = buf; rb->fill_cnt = 0; rb->size = block_size * n_blocks; rb->is_done_write = false; rb->unblock_reader_flag = false; rb->abort_read = false; rb->abort_write = false; return rb; _rb_init_failed: rb_destroy(rb); return NULL; } esp_err_t rb_destroy(ringbuf_handle_t rb) { if (rb == NULL) { return ESP_ERR_INVALID_ARG; } if (rb->p_o) { audio_free(rb->p_o); rb->p_o = NULL; } if (rb->can_read) { vSemaphoreDelete(rb->can_read); rb->can_read = NULL; } if (rb->can_write) { vSemaphoreDelete(rb->can_write); rb->can_write = NULL; } if (rb->lock) { vSemaphoreDelete(rb->lock); rb->lock = NULL; } audio_free(rb); rb = NULL; return ESP_OK; } esp_err_t rb_reset(ringbuf_handle_t rb) { if (rb == NULL) { return ESP_FAIL; } rb->p_r = rb->p_w = rb->p_o; rb->fill_cnt = 0; rb->is_done_write = false; rb->unblock_reader_flag = false; rb->abort_read = false; rb->abort_write = false; return ESP_OK; } int rb_bytes_available(ringbuf_handle_t rb) { return (rb->size - rb->fill_cnt); } int rb_bytes_filled(ringbuf_handle_t rb) { if (rb) { return rb->fill_cnt; } return ESP_FAIL; } static void rb_release(SemaphoreHandle_t handle) { xSemaphoreGive(handle); } #define rb_block(handle, time) xSemaphoreTake(handle, time) int rb_read(ringbuf_handle_t rb, char *buf, int buf_len, TickType_t ticks_to_wait) { int read_size = 0; int total_read_size = 0; int ret_val = 0; if (rb == NULL) { return RB_FAIL; } while (buf_len) { //take buffer lock if (rb_block(rb->lock, portMAX_DELAY) != pdTRUE) { ret_val = RB_TIMEOUT; goto read_err; } if (rb->fill_cnt < buf_len) { read_size = rb->fill_cnt; /** * When non-multiple of 4(word size) bytes are written to I2S, there is noise. * Below is the kind of workaround to read only in multiple of 4. Avoids noise when rb is read in small chunks. * Note that, when we have buf_len bytes available in rb, we still read those irrespective of if it's multiple of 4. */ read_size = read_size & 0xfffffffc; if ((read_size == 0) && rb->is_done_write) { read_size = rb->fill_cnt; } } else { read_size = buf_len; } if (read_size == 0) { //no data to read, release thread block to allow other threads to write data if (rb->is_done_write) { ret_val = RB_DONE; rb_release(rb->lock); goto read_err; } if (rb->abort_read) { ret_val = RB_ABORT; rb_release(rb->lock); goto read_err; } if (rb->unblock_reader_flag) { //reader_unblock is nothing but forced timeout ret_val = RB_TIMEOUT; rb_release(rb->lock); goto read_err; } rb_release(rb->lock); rb_release(rb->can_write); //wait till some data available to read if (rb_block(rb->can_read, ticks_to_wait) != pdTRUE) { ret_val = RB_TIMEOUT; goto read_err; } continue; } if ((rb->p_r + read_size) > (rb->p_o + rb->size)) { int rlen1 = rb->p_o + rb->size - rb->p_r; int rlen2 = read_size - rlen1; if (buf) { memcpy(buf, rb->p_r, rlen1); memcpy(buf + rlen1, rb->p_o, rlen2); } rb->p_r = rb->p_o + rlen2; } else { if (buf) { memcpy(buf, rb->p_r, read_size); } rb->p_r = rb->p_r + read_size; } buf_len -= read_size; rb->fill_cnt -= read_size; total_read_size += read_size; buf += read_size; rb_release(rb->lock); if (buf_len == 0) { break; } } read_err: if (total_read_size > 0) { rb_release(rb->can_write); } if ((ret_val == RB_FAIL) || (ret_val == RB_ABORT)) { total_read_size = ret_val; } rb->unblock_reader_flag = false; /* We are anyway unblocking the reader */ return total_read_size > 0 ? total_read_size : ret_val; } int rb_write(ringbuf_handle_t rb, char *buf, int buf_len, TickType_t ticks_to_wait) { int write_size; int total_write_size = 0; int ret_val = 0; if (rb == NULL || buf == NULL) { return RB_FAIL; } while (buf_len) { //take buffer lock if (rb_block(rb->lock, portMAX_DELAY) != pdTRUE) { ret_val = RB_TIMEOUT; goto write_err; } write_size = rb_bytes_available(rb); if (buf_len < write_size) { write_size = buf_len; } if (write_size == 0) { //no space to write, release thread block to allow other to read data if (rb->is_done_write) { ret_val = RB_DONE; rb_release(rb->lock); goto write_err; } if (rb->abort_write) { ret_val = RB_ABORT; rb_release(rb->lock); goto write_err; } rb_release(rb->lock); rb_release(rb->can_read); //wait till we have some empty space to write if (rb_block(rb->can_write, ticks_to_wait) != pdTRUE) { ret_val = RB_TIMEOUT; goto write_err; } continue; } if ((rb->p_w + write_size) > (rb->p_o + rb->size)) { int wlen1 = rb->p_o + rb->size - rb->p_w; int wlen2 = write_size - wlen1; memcpy(rb->p_w, buf, wlen1); memcpy(rb->p_o, buf + wlen1, wlen2); rb->p_w = rb->p_o + wlen2; } else { memcpy(rb->p_w, buf, write_size); rb->p_w = rb->p_w + write_size; } buf_len -= write_size; rb->fill_cnt += write_size; total_write_size += write_size; buf += write_size; rb_release(rb->lock); if (buf_len == 0) { break; } } write_err: if (total_write_size > 0) { rb_release(rb->can_read); } if ((ret_val == RB_FAIL) || (ret_val == RB_ABORT)) { total_write_size = ret_val; } return total_write_size > 0 ? total_write_size : ret_val; } static esp_err_t rb_abort_read(ringbuf_handle_t rb) { if (rb == NULL) { return ESP_ERR_INVALID_ARG; } rb->abort_read = true; xSemaphoreGive(rb->can_read); return ESP_OK; } static esp_err_t rb_abort_write(ringbuf_handle_t rb) { if (rb == NULL) { return ESP_ERR_INVALID_ARG; } rb->abort_write = true; xSemaphoreGive(rb->can_write); return ESP_OK; } esp_err_t rb_abort(ringbuf_handle_t rb) { if (rb == NULL) { return ESP_ERR_INVALID_ARG; } esp_err_t err = rb_abort_read(rb); err |= rb_abort_write(rb); return err; } bool rb_is_full(ringbuf_handle_t rb) { if (rb == NULL) { return false; } return (rb->size == rb->fill_cnt); } esp_err_t rb_done_write(ringbuf_handle_t rb) { if (rb == NULL) { return ESP_ERR_INVALID_ARG; } rb->is_done_write = true; rb_release(rb->can_read); return ESP_OK; } esp_err_t rb_unblock_reader(ringbuf_handle_t rb) { if (rb == NULL) { return ESP_ERR_INVALID_ARG; } rb->unblock_reader_flag = true; rb_release(rb->can_read); return ESP_OK; } bool rb_is_done_write(ringbuf_handle_t rb) { if (rb == NULL) { return false; } return (rb->is_done_write); } int rb_get_size(ringbuf_handle_t rb) { if (rb == NULL) { return ESP_ERR_INVALID_ARG; } return rb->size; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/ringbuf.c
C
apache-2.0
11,162
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <pthread.h> #include "unity.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "audio_element.h" #include "esp_log.h" #include "esp_err.h" static const char *TAG = "AUDIO_ELEMENT_TEST"; static esp_err_t _el_open(audio_element_handle_t self) { ESP_LOGI(TAG, "_el_open"); return ESP_OK; } static int _el_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait) { ESP_LOGI(TAG, "_el_read"); return len; } static int _el_process(audio_element_handle_t self, char *in_buffer, int in_len, char *out_buffer, int out_len) { ESP_LOGI(TAG, "_el_process"); vTaskDelay(100/portTICK_RATE_MS); return in_len; } static int _el_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait) { ESP_LOGI(TAG, "_el_write"); return len; } static esp_err_t _el_close(audio_element_handle_t self) { ESP_LOGI(TAG, "_el_close"); return ESP_OK; } TEST_CASE("audio_element", "esp-adf") { esp_log_level_set("*", ESP_LOG_INFO); esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_VERBOSE); ESP_LOGI(TAG, "[✓] audio_element_init element"); audio_element_handle_t el; audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG(); cfg.open = _el_open; cfg.read = _el_read; cfg.process = _el_process; cfg.write = _el_write; cfg.close = _el_close; el = audio_element_init(&cfg); TEST_ASSERT_NOT_NULL(el); TEST_ASSERT_EQUAL(ESP_OK, audio_element_run(el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_resume(el, 0, 0)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_pause(el)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_resume(el, 0, 0)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_stop(el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(el)); } TEST_CASE("audio_element_input_rb", "esp-adf") { esp_log_level_set("*", ESP_LOG_INFO); esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_VERBOSE); ESP_LOGI(TAG, "[✓] audio_element_init element"); RingbufHandle_t input_rb; audio_element_handle_t el; audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG(); cfg.open = _el_open; // cfg.read = _el_read; cfg.process = _el_process; cfg.write = _el_write; cfg.close = _el_close; el = audio_element_init(&cfg); input_rb = xRingbufferCreate(4096, RINGBUF_TYPE_NOSPLIT); audio_element_set_input_ringbuf(el, input_rb); TEST_ASSERT_NOT_NULL(el); TEST_ASSERT_EQUAL(ESP_OK, audio_element_run(el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_resume(el, 0, 0)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_pause(el)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_resume(el, 0, 0)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_stop(el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(el)); vRingbufferDelete(input_rb); } TEST_CASE("audio_element_output_rb", "esp-adf") { esp_log_level_set("*", ESP_LOG_INFO); esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_VERBOSE); ESP_LOGI(TAG, "[✓] audio_element_init element"); RingbufHandle_t output_rb; audio_element_handle_t el; audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG(); cfg.open = _el_open; cfg.read = _el_read; cfg.process = _el_process; // cfg.write = _el_write; cfg.close = _el_close; el = audio_element_init(&cfg); output_rb = xRingbufferCreate(4096, RINGBUF_TYPE_NOSPLIT); audio_element_set_output_ringbuf(el, output_rb); TEST_ASSERT_NOT_NULL(el); TEST_ASSERT_EQUAL(ESP_OK, audio_element_run(el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_resume(el, 0, 0)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_pause(el)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_resume(el, 0, 0)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_stop(el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(el)); vRingbufferDelete(output_rb); } TEST_CASE("audio_element_input_output_rb", "esp-adf") { esp_log_level_set("*", ESP_LOG_INFO); esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_VERBOSE); ESP_LOGI(TAG, "[✓] audio_element_init element"); RingbufHandle_t input_rb, output_rb; audio_element_handle_t el; audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG(); cfg.open = _el_open; // cfg.read = _el_read; cfg.process = _el_process; // cfg.write = _el_write; cfg.close = _el_close; el = audio_element_init(&cfg); output_rb = xRingbufferCreate(4096, RINGBUF_TYPE_NOSPLIT); input_rb = xRingbufferCreate(4096, RINGBUF_TYPE_NOSPLIT); audio_element_set_input_ringbuf(el, input_rb); audio_element_set_output_ringbuf(el, output_rb); TEST_ASSERT_NOT_NULL(el); TEST_ASSERT_EQUAL(ESP_OK, audio_element_run(el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_resume(el, 0, 0)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_pause(el)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_resume(el, 0, 0)); vTaskDelay(2000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_element_stop(el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(el)); vRingbufferDelete(input_rb); vRingbufferDelete(output_rb); }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/test/audio_element_test.c
C
apache-2.0
6,761
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <pthread.h> #include "unity.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "audio_event_iface.h" #include "esp_log.h" #include "esp_err.h" #include "audio_common.h" static const char *TAG = "ESP_EMITTER_TEST"; static esp_err_t event_on_cmd(audio_event_iface_msg_t *msg, void *context) { ESP_LOGI(TAG, "receive evt msg cmd = %d, source addr = %x, type = %d", msg->cmd, (int)msg->source, msg->source_type); if (msg->cmd == 9) { return ESP_FAIL; } return ESP_OK; } TEST_CASE("audio_event_iface", "esp-adf") { ESP_LOGI(TAG, "[✓] audio_event_iface_init evt1"); audio_event_iface_handle_t evt1; audio_event_iface_cfg_t cfg = AUDIO_EVENT_IFACE_DEFAULT_CFG(); cfg.on_cmd = event_on_cmd; cfg.queue_size = 10; cfg.context = &evt1; evt1 = audio_event_iface_init(&cfg); TEST_ASSERT_NOT_NULL(evt1); audio_event_iface_msg_t msg; int i; ESP_LOGI(TAG, "[✓] dispatch 10 msg to evt1"); for (i = 0; i < 10; i++) { msg.cmd = i; TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_cmd(evt1, &msg)); } msg.cmd = 10; TEST_ASSERT_EQUAL(ESP_FAIL, audio_event_iface_cmd(evt1, &msg)); ESP_LOGI(TAG, "[✓] listening 10 event have dispatched fron evt1"); while (audio_event_iface_waiting_cmd_msg(evt1) == ESP_OK); ESP_LOGI(TAG, "[✓] audio_event_iface_init evt2"); audio_event_iface_handle_t evt2; cfg.context = &evt2; cfg.type = AUDIO_ELEMENT_TYPE_PIPELINE; evt2 = audio_event_iface_init(&cfg); TEST_ASSERT_NOT_NULL(evt2); ESP_LOGI(TAG, "[✓] audio_event_iface_init evt3"); audio_event_iface_handle_t evt3; cfg.context = &evt3; cfg.type = AUDIO_ELEMENT_TYPE_PLAYER; evt3 = audio_event_iface_init(&cfg); TEST_ASSERT_NOT_NULL(evt3); ESP_LOGI(TAG, "[✓] listen evt2 from evt1"); TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(evt2, evt1)); ESP_LOGI(TAG, "[✓] listen evt3 from evt1"); TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_set_listener(evt3, evt1)); ESP_LOGI(TAG, "[✓] dispatch 2 msg to evt1"); for (i = 0; i < 2; i++) { msg.source = evt1; msg.cmd = i; TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_cmd(evt1, &msg)); } ESP_LOGI(TAG, "[✓] sendout 3 msg from evt2 to evt1"); for (i = 2; i < 5; i++) { msg.source = evt2; msg.cmd = i; TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_sendout(evt2, &msg)); } ESP_LOGI(TAG, "[✓] sendout 5 msg from evt3 to evt1"); for (i = 5; i < 10; i++) { msg.source = evt3; msg.cmd = i; TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_sendout(evt3, &msg)); } ESP_LOGI(TAG, "[✓] listening 10 event have dispatched from evt1, evt2 and evt3"); while (audio_event_iface_waiting_cmd_msg(evt1) == ESP_OK); ESP_LOGI(TAG, "[✓] remove listener from evt2"); TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(evt2, evt1)); ESP_LOGI(TAG, "[✓] remove listener from evt3"); TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_remove_listener(evt3, evt1)); ESP_LOGI(TAG, "[✓] sendout 5 msg from evt2 to evt1"); for (i = 1; i < 5; i++) { msg.source = evt2; msg.cmd = i; TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_sendout(evt2, &msg)); } ESP_LOGI(TAG, "[✓] dispatch 5 msg to evt1"); for (i = 5; i < 10; i++) { msg.source = evt1; msg.cmd = i; TEST_ASSERT_EQUAL(ESP_OK, audio_event_iface_cmd(evt1, &msg)); } ESP_LOGI(TAG, "[✓] listening 10 event have dispatched from evt1 and evt2"); while (audio_event_iface_listen(evt1) == ESP_OK); audio_event_iface_destroy(evt1); audio_event_iface_destroy(evt2); audio_event_iface_destroy(evt3); }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/test/audio_event_iface_test.c
C
apache-2.0
5,024
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <pthread.h> #include "unity.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "audio_pipeline.h" #include "esp_log.h" #include "esp_err.h" static const char *TAG = "AUDIO_ELEMENT_TEST"; static esp_err_t _el_open(audio_element_handle_t self) { ESP_LOGI(TAG, "[%s] _el_open", audio_element_get_tag(self)); return ESP_OK; } static int _el_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait) { ESP_LOGI(TAG, "[%s] _el_read", audio_element_get_tag(self)); return len; } static int _el_process(audio_element_handle_t self, char *in_buffer, int in_len, char *out_buffer, int out_len) { ESP_LOGI(TAG, "[%s] _el_process, in_len=%d, outlen=%d", audio_element_get_tag(self), in_len, out_len); vTaskDelay(100/portTICK_RATE_MS); return in_len; } static int _el_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait) { ESP_LOGI(TAG, "[%s] _el_write", audio_element_get_tag(self)); return len; } static esp_err_t _el_close(audio_element_handle_t self) { ESP_LOGI(TAG, "[%s] _el_close", audio_element_get_tag(self)); return ESP_OK; } TEST_CASE("audio_pipeline", "esp-adf") { esp_log_level_set("*", ESP_LOG_INFO); esp_log_level_set("AUDIO_PIPELINE", ESP_LOG_VERBOSE); esp_log_level_set("AUDIO_ELEMENT", ESP_LOG_VERBOSE); esp_log_level_set("AUDIO_EVENT", ESP_LOG_VERBOSE); ESP_LOGI(TAG, "[✓] init audio_pipeline and audio_element"); audio_element_handle_t first_el, mid_el, last_el; audio_element_cfg_t el_cfg = DEFAULT_AUDIO_ELEMENT_CONFIG(); el_cfg.open = _el_open; el_cfg.read = _el_read; el_cfg.process = _el_process; el_cfg.close = _el_close; first_el = audio_element_init(&el_cfg); TEST_ASSERT_NOT_NULL(first_el); el_cfg.read = NULL; el_cfg.write = NULL; mid_el = audio_element_init(&el_cfg); TEST_ASSERT_NOT_NULL(mid_el); el_cfg.write = _el_write; last_el = audio_element_init(&el_cfg); TEST_ASSERT_NOT_NULL(last_el); audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG(); audio_pipeline_handle_t pipeline = audio_pipeline_init(&pipeline_cfg); TEST_ASSERT_NOT_NULL(pipeline); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, first_el, "first")); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, mid_el, "mid")); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_register(pipeline, last_el, "last")); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_link(pipeline, (const char *[]){"first", "mid", "last"}, 3)); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline)); vTaskDelay(10000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_stop(pipeline)); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_wait_for_stop(pipeline)); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_unlink(pipeline)); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_run(pipeline)); vTaskDelay(5000/portTICK_RATE_MS); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_stop(pipeline)); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_wait_for_stop(pipeline)); TEST_ASSERT_EQUAL(ESP_OK, audio_pipeline_deinit(pipeline)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(first_el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(mid_el)); TEST_ASSERT_EQUAL(ESP_OK, audio_element_deinit(last_el)); }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/test/audio_pipeline_test.c
C
apache-2.0
4,602
# #Component Makefile # COMPONENT_ADD_LDFLAGS = -Wl,--whole-archive -l$(COMPONENT_NAME) -Wl,--no-whole-archive
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_pipeline/test/component.mk
Makefile
apache-2.0
112
set(COMPONENT_ADD_INCLUDEDIRS "include") set(COMPONENT_SRCS "audio_mem.c" "audio_sys.c" "audio_thread.c" "audio_url.c" "audio_mutex.c" "audio_queue.c" "media_os_ctype.c") register_component()
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/CMakeLists.txt
CMake
apache-2.0
315
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <stdlib.h> #include "string.h" #include "sdkconfig.h" #include "esp_system.h" #include "esp_log.h" #include "audio_mem.h" #include "esp_heap_caps.h" #include "esp_efuse.h" // #define ENABLE_AUDIO_MEM_TRACE void *audio_malloc(size_t size) { void *data = NULL; #if CONFIG_SPIRAM_BOOT_INIT data = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); #else data = malloc(size); #endif #ifdef ENABLE_AUDIO_MEM_TRACE ESP_LOGI("AUDIO_MEM", "malloc:%p, size:%d, called:0x%08x", data, size, (intptr_t)__builtin_return_address(0) - 2); #endif return data; } void audio_free(void *ptr) { free(ptr); #ifdef ENABLE_AUDIO_MEM_TRACE ESP_LOGI("AUIDO_MEM", "free:%p, called:0x%08x", ptr, (intptr_t)__builtin_return_address(0) - 2); #endif } void *audio_calloc(size_t nmemb, size_t size) { void *data = NULL; #if CONFIG_SPIRAM_BOOT_INIT data = heap_caps_malloc(nmemb * size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); if (data) { memset(data, 0, nmemb * size); } #else data = calloc(nmemb, size); #endif #ifdef ENABLE_AUDIO_MEM_TRACE ESP_LOGI("AUIDO_MEM", "calloc:%p, size:%d, called:0x%08x", data, size, (intptr_t)__builtin_return_address(0) - 2); #endif return data; } void *audio_realloc(void *ptr, size_t size) { void *p = NULL; #if CONFIG_SPIRAM_BOOT_INIT p = heap_caps_realloc(ptr, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); #else p = heap_caps_realloc(ptr, size, MALLOC_CAP_8BIT); #endif #ifdef ENABLE_AUDIO_MEM_TRACE ESP_LOGI("AUDIO_MEM", "realloc,new:%p, ptr:%p size:%d, called:0x%08x", p, ptr, size, (intptr_t)__builtin_return_address(0) - 2); #endif return p; } char *audio_strdup(const char *str) { #if CONFIG_SPIRAM_BOOT_INIT char *copy = heap_caps_malloc(strlen(str) + 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); #else char *copy = malloc(strlen(str) + 1); #endif if (copy) { strcpy(copy, str); } #ifdef ENABLE_AUDIO_MEM_TRACE ESP_LOGI("AUDIO_MEM", "strdup:%p, size:%d, called:0x%08x", copy, strlen(copy), (intptr_t)__builtin_return_address(0) - 2); #endif return copy; } void *audio_calloc_inner(size_t n, size_t size) { void *data = NULL; #if CONFIG_SPIRAM_BOOT_INIT data = heap_caps_calloc_prefer(n, size, 2, MALLOC_CAP_DEFAULT | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT, MALLOC_CAP_DEFAULT | MALLOC_CAP_SPIRAM); #else data = heap_caps_calloc(n, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); #endif #ifdef ENABLE_AUDIO_MEM_TRACE ESP_LOGI("AUIDO_MEM", "calloc_inner:%p, size:%d, called:0x%08x", data, size, (intptr_t)__builtin_return_address(0) - 2); #endif return data; } void audio_mem_print(const char *tag, int line, const char *func) { #ifdef CONFIG_SPIRAM_BOOT_INIT ESP_LOGI(tag, "Func:%s, Line:%d, MEM Total:%d Bytes, Inter:%d Bytes, Dram:%d Bytes\r\n", func, line, esp_get_free_heap_size(), heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)); #else ESP_LOGI(tag, "Func:%s, Line:%d, MEM Total:%d Bytes\r\n", func, line, esp_get_free_heap_size()); #endif } #if defined (CONFIG_SPIRAM_BOOT_INIT) bool audio_mem_spiram_is_enabled(void) { return true; } #else bool audio_mem_spiram_is_enabled(void) { return false; } #endif #if defined(CONFIG_SPIRAM_BOOT_INIT) && (CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY) bool audio_mem_spiram_stack_is_enabled(void) { bool ret = true; #if CONFIG_IDF_TARGET_ESP32 uint8_t chip_ver = esp_efuse_get_chip_ver(); if (chip_ver < 3) { ESP_LOGW("AUIDO_MEM", "Can't support stack on external memory due to ESP32 chip is %d", chip_ver); ret = false; } #endif return ret; } #else bool audio_mem_spiram_stack_is_enabled(void) { return false; } #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/audio_mem.c
C
apache-2.0
4,998
/* * ESPRESSIF MIT License * * Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "audio_mutex.h" #include "audio_idf_version.h" #include "esp_log.h" #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 3, 0)) // The xQueueSemaphoreTake is not available on FreeRTOS v8.2.0, it's compatible implementation. BaseType_t __attribute__((weak)) xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ) { xSemaphoreTake(xQueue, xTicksToWait); return pdPASS; } #endif void *mutex_create(void) { void *handle = NULL; handle = xSemaphoreCreateMutex(); return (void *) handle; } int mutex_destroy(void *mutex) { vSemaphoreDelete((QueueHandle_t)mutex); return 0; } int mutex_lock(void *mutex) { #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0)) while (xSemaphoreTake((QueueHandle_t)mutex, portMAX_DELAY) != pdPASS); #else while (xSemaphoreTake((QueueHandle_t)mutex, portMAX_DELAY) != pdPASS); #endif return 0; } int mutex_unlock(void *mutex) { int ret = 0; ret = xSemaphoreGive((QueueHandle_t)mutex); return ret; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/audio_mutex.c
C
apache-2.0
2,321
/* * ESPRESSIF MIT License * * Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "audio_queue.h" audio_queue_handle_t audio_queue_create(uint32_t queue_len, uint32_t item_size) { audio_queue_handle_t handle = NULL; handle = (QueueHandle_t)xQueueCreate(queue_len, item_size); return handle; } int audio_queue_delete(audio_queue_handle_t queue) { vQueueDelete((QueueHandle_t)queue); return 0; } int audio_queue_send(audio_queue_handle_t queue, void *item, uint32_t block_time_ms) { int ret = 0; ret = xQueueSend((QueueHandle_t)queue, item, block_time_ms / portTICK_PERIOD_MS); return ret; } int audio_queue_send_to_front(audio_queue_handle_t queue, void *item, uint32_t block_time_ms) { int ret = 0; ret = xQueueSendToFront((QueueHandle_t)queue, item, block_time_ms / portTICK_PERIOD_MS); return ret; } int audio_queue_recv(audio_queue_handle_t queue, void *item, uint32_t block_time_ms) { int ret = 0; ret = xQueueReceive((QueueHandle_t)queue, item, block_time_ms / portTICK_PERIOD_MS); return ret; } int audio_queue_message_available(const audio_queue_handle_t queue) { int ret = 0; ret = uxQueueMessagesWaiting((QueueHandle_t)queue); return ret; } int audio_queue_spaces_available(const audio_queue_handle_t queue) { int ret = 0; ret = uxQueueSpacesAvailable((QueueHandle_t)queue); return ret; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/audio_queue.c
C
apache-2.0
2,636
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <sys/time.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_log.h" #include "audio_mem.h" #include "audio_error.h" #include "audio_sys.h" #include "soc/soc_memory_layout.h" static const char *TAG = "AUDIO_SYS"; #define ARRAY_SIZE_OFFSET 8 // Increase this if audio_sys_get_real_time_stats returns ESP_ERR_INVALID_SIZE #define AUDIO_SYS_TASKS_ELAPSED_TIME_MS 1000 // Period of stats measurement const char *task_state[] = { "Running", "Ready", "Blocked", "Suspended", "Deleted" }; /** @brief * "Extr": Allocated task stack from psram, "Intr": Allocated task stack from internel */ const char *task_stack[] = {"Extr", "Intr"}; int audio_sys_get_tick_by_time_ms(int ms) { return (ms / portTICK_PERIOD_MS); } int64_t audio_sys_get_time_ms(void) { struct timeval te; gettimeofday(&te, NULL); int64_t milliseconds = te.tv_sec * 1000LL + te.tv_usec / 1000; return milliseconds; } esp_err_t audio_sys_get_real_time_stats(void) { #if (CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID && CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS) TaskStatus_t *start_array = NULL, *end_array = NULL; UBaseType_t start_array_size, end_array_size; uint32_t start_run_time, end_run_time; uint32_t task_elapsed_time, percentage_time; esp_err_t ret; // Allocate array to store current task states start_array_size = uxTaskGetNumberOfTasks() + ARRAY_SIZE_OFFSET; start_array = audio_malloc(sizeof(TaskStatus_t) * start_array_size); AUDIO_MEM_CHECK(TAG, start_array, { ret = ESP_FAIL; goto exit; }); // Get current task states start_array_size = uxTaskGetSystemState(start_array, start_array_size, &start_run_time); if (start_array_size == 0) { ESP_LOGE(TAG, "Insufficient array size for uxTaskGetSystemState. Trying increasing ARRAY_SIZE_OFFSET"); ret = ESP_FAIL; goto exit; } vTaskDelay(pdMS_TO_TICKS(AUDIO_SYS_TASKS_ELAPSED_TIME_MS)); // Allocate array to store tasks states post delay end_array_size = uxTaskGetNumberOfTasks() + ARRAY_SIZE_OFFSET; end_array = audio_malloc(sizeof(TaskStatus_t) * end_array_size); AUDIO_MEM_CHECK(TAG, start_array, { ret = ESP_FAIL; goto exit; }); // Get post delay task states end_array_size = uxTaskGetSystemState(end_array, end_array_size, &end_run_time); if (end_array_size == 0) { ESP_LOGE(TAG, "Insufficient array size for uxTaskGetSystemState. Trying increasing ARRAY_SIZE_OFFSET"); ret = ESP_FAIL; goto exit; } // Calculate total_elapsed_time in units of run time stats clock period. uint32_t total_elapsed_time = (end_run_time - start_run_time); if (total_elapsed_time == 0) { ESP_LOGE(TAG, "Delay duration too short. Trying increasing AUDIO_SYS_TASKS_ELAPSED_TIME_MS"); ret = ESP_FAIL; goto exit; } ESP_LOGI(TAG, "| Task | Run Time | Per | Prio | HWM | State | CoreId | Stack "); // Match each task in start_array to those in the end_array for (int i = 0; i < start_array_size; i++) { for (int j = 0; j < end_array_size; j++) { if (start_array[i].xHandle == end_array[j].xHandle) { task_elapsed_time = end_array[j].ulRunTimeCounter - start_array[i].ulRunTimeCounter; percentage_time = (task_elapsed_time * 100UL) / (total_elapsed_time * portNUM_PROCESSORS); ESP_LOGI(TAG, "| %-17s | %-11d |%2d%% | %-4u | %-9u | %-7s | %-8x | %s", start_array[i].pcTaskName, task_elapsed_time, percentage_time, start_array[i].uxCurrentPriority, start_array[i].usStackHighWaterMark, task_state[(start_array[i].eCurrentState)], start_array[i].xCoreID, task_stack[esp_ptr_internal(pxTaskGetStackStart(start_array[i].xHandle))]); // Mark that task have been matched by overwriting their handles start_array[i].xHandle = NULL; end_array[j].xHandle = NULL; break; } } } // Print unmatched tasks for (int i = 0; i < start_array_size; i++) { if (start_array[i].xHandle != NULL) { ESP_LOGI(TAG, "| %s | Deleted", start_array[i].pcTaskName); } } for (int i = 0; i < end_array_size; i++) { if (end_array[i].xHandle != NULL) { ESP_LOGI(TAG, "| %s | Created", end_array[i].pcTaskName); } } printf("\n"); ret = ESP_OK; exit: // Common return path if (start_array) { audio_free(start_array); start_array = NULL; } if (end_array) { audio_free(end_array); end_array = NULL; } return ret; #else ESP_LOGW(TAG, "Please enbale `CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID` and `CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS` in menuconfig"); return ESP_FAIL; #endif }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/audio_sys.c
C
apache-2.0
6,230
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "esp_log.h" #include "audio_mem.h" #include "audio_error.h" #include "audio_thread.h" static const char *TAG = "AUDIO_THREAD"; BaseType_t __attribute__((weak)) xTaskCreateRestrictedPinnedToCore(const TaskParameters_t *const pxTaskDefinition, TaskHandle_t *pxCreatedTask, const BaseType_t xCoreID) { ESP_LOGE(TAG, "Not found right %s.\r\nPlease enter IDF-PATH with \"cd $IDF_PATH\" and apply the IDF patch with \"git apply $ADF_PATH/idf_patches/idf_v3.3_freertos.patch\" first\r\n", __func__); return pdFALSE; } esp_err_t audio_thread_create(audio_thread_t *p_handle, const char *name, void(*main_func)(void *arg), void *arg, uint32_t stack, int prio, bool stack_in_ext, int core_id) { StackType_t *task_stack = NULL; if (stack_in_ext && audio_mem_spiram_stack_is_enabled()) { /* * Note: 1. ESP32-ECO3 chip support stack on external memory only. * 2. Make sure selected the `CONFIG_SPIRAM_BOOT_INIT` and `CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY` by `make menuconfig` * 3. Please apply the $ADF_PATH/idf_patches/idf_v3.3_freertos.patch * */ ESP_LOGI(TAG, "The %s task allocate stack on external memory", name); /* task_stack freed by freertos*/ task_stack = (StackType_t *) audio_calloc(1, stack); AUDIO_MEM_CHECK(TAG, task_stack, goto audio_thread_create_error ); TaskParameters_t xRegParameters = { .pvTaskCode = main_func, .pcName = name, .usStackDepth = stack, .pvParameters = arg, .uxPriority = prio | portPRIVILEGE_BIT, .puxStackBuffer = task_stack, .xRegions = {{ .pvBaseAddress = 0x00, .ulLengthInBytes = 0x00, .ulParameters = 0x00, } } }; if (xTaskCreateRestrictedPinnedToCore(&xRegParameters, (xTaskHandle)p_handle, core_id) != pdPASS) { ESP_LOGE(TAG, "Error creating RestrictedPinnedToCore %s", name); goto audio_thread_create_error; } } else { if (xTaskCreatePinnedToCore(main_func, name, stack, arg, prio, (xTaskHandle)p_handle, core_id) != pdPASS) { ESP_LOGE(TAG, "Error creating task %s", name); goto audio_thread_create_error; } } return ESP_OK; audio_thread_create_error: if (task_stack) { audio_free(task_stack); } return ESP_FAIL; } esp_err_t audio_thread_cleanup(audio_thread_t *p_handle) { // TODO nothing return ESP_OK; } esp_err_t audio_thread_delete_task(audio_thread_t *p_handle) { vTaskDelete(NULL); return ESP_OK; /* Control never reach here if this is self delete */ }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/audio_thread.c
C
apache-2.0
4,095
#include <string.h> #include <ctype.h> #include "audio_error.h" #include "esp_log.h" #include "audio_mem.h" static char *TAG = "AUDIO_URL"; static unsigned char char_to_hex(unsigned char x) { return x > 9 ? x + 0x37 : x + 0x30; } char *audio_url_encode(const char *str) { int out_len = (strlen(str) + 1) * 3; char *final = audio_malloc(out_len); AUDIO_MEM_CHECK(TAG, final, return NULL); char *tmp = final; for (size_t i = 0; i < strlen(str); i++) { if (isalnum((unsigned char)str[i]) || (str[i] == '-') || (str[i] == '_') || (str[i] == '.') || (str[i] == '!') || (str[i] == '@') || (str[i] == '#') || (str[i] == '$') || (str[i] == '&') || (str[i] == '*') || (str[i] == '(') || (str[i] == ')') || (str[i] == '=') || (str[i] == ':') || (str[i] == '/') || (str[i] == ',') || (str[i] == ';') || (str[i] == '?') || (str[i] == '+') || (str[i] == '\'') || (str[i] == '~')) { *final++ = str[i]; } else { *final++ = '%'; *final++ = char_to_hex((unsigned char)str[i] >> 4); *final++ = char_to_hex((unsigned char)str[i] % 16); } } *final = 0; return tmp; } char *audio_url_decode(const char *str) { char *final = audio_malloc(strlen(str) + 1); AUDIO_MEM_CHECK(TAG, final, return NULL); char *tmp = final; while (*str) { if (*str == '%') { char buffer[3] = { str[1], str[2], 0 }; *final++ = strtol(buffer, NULL, 16); str += 3; } else { *final++ = *str++; } } *final = 0; return tmp; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/audio_url.c
C
apache-2.0
1,707
# # Component Makefile COMPONENT_ADD_INCLUDEDIRS := . ./include COMPONENT_SRCDIRS := .
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/component.mk
Makefile
apache-2.0
90
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_ERROR_H_ #define _AUDIO_ERROR_H_ #include "esp_err.h" #ifdef __cplusplus extern "C" { #endif #ifndef __FILENAME__ #define __FILENAME__ __FILE__ #endif #define ESP_ERR_ADF_BASE 0x80000 /*!< Starting number of ESP-ADF error codes */ /* * ESP-ADF error code field start from 0x80000, end of the -1. * The whole area is divided into series independent modules. * The range of each module is 0x1000. * ////////////////////////////////////////////////////////// * ESP-Audio module starting on 0x81000; * */ #define ESP_ERR_ADF_NO_ERROR ESP_OK #define ESP_ERR_ADF_NO_FAIL ESP_FAIL #define ESP_ERR_ADF_UNKNOWN ESP_ERR_ADF_BASE + 0 #define ESP_ERR_ADF_ALREADY_EXISTS ESP_ERR_ADF_BASE + 1 #define ESP_ERR_ADF_MEMORY_LACK ESP_ERR_ADF_BASE + 2 #define ESP_ERR_ADF_INVALID_URI ESP_ERR_ADF_BASE + 3 #define ESP_ERR_ADF_INVALID_PATH ESP_ERR_ADF_BASE + 4 #define ESP_ERR_ADF_INVALID_PARAMETER ESP_ERR_ADF_BASE + 5 #define ESP_ERR_ADF_NOT_READY ESP_ERR_ADF_BASE + 6 #define ESP_ERR_ADF_NOT_SUPPORT ESP_ERR_ADF_BASE + 7 #define ESP_ERR_ADF_NOT_FOUND ESP_ERR_ADF_BASE + 8 #define ESP_ERR_ADF_TIMEOUT ESP_ERR_ADF_BASE + 9 #define ESP_ERR_ADF_INITIALIZED ESP_ERR_ADF_BASE + 10 #define ESP_ERR_ADF_UNINITIALIZED ESP_ERR_ADF_BASE + 11 #define AUDIO_CHECK(TAG, a, action, msg) if (!(a)) { \ ESP_LOGE(TAG,"%s:%d (%s): %s", __FILENAME__, __LINE__, __FUNCTION__, msg); \ action; \ } #define AUDIO_MEM_CHECK(TAG, a, action) AUDIO_CHECK(TAG, a, action, "Memory exhausted") #define AUDIO_NULL_CHECK(TAG, a, action) AUDIO_CHECK(TAG, a, action, "Got NULL Pointer") #define AUDIO_ERROR(TAG, str) ESP_LOGE(TAG, "%s:%d (%s): %s", __FILENAME__, __LINE__, __FUNCTION__, str) #define ESP_EXISTS (ESP_OK + 1) #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/include/audio_error.h
C
apache-2.0
3,374
/* * ESPRESSIF MIT License * * Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __AUDIO_IDF_VERSION_H__ #define __AUDIO_IDF_VERSION_H__ #ifdef __cplusplus extern "C" { #endif #if __has_include("esp_idf_version.h") #include "esp_idf_version.h" #else #define ESP_IDF_VERSION_VAL(major, minor, patch) 1 #endif #ifdef __cplusplus } #endif #endif /* #ifndef __AUDIO_IDF_VERSION_H__ */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/include/audio_idf_version.h
C
apache-2.0
1,549
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_MEM_H_ #define _AUDIO_MEM_H_ #include <esp_types.h> #ifdef __cplusplus extern "C" { #endif /** * @brief Malloc memory in ADF * * @param[in] size memory size * * @return * - valid pointer on success * - NULL when any errors */ void *audio_malloc(size_t size); /** * @brief Free memory in ADF * * @param[in] ptr memory pointer * * @return * - void */ void audio_free(void *ptr); /** * @brief Malloc memory in ADF, if spi ram is enabled, it will malloc memory in the spi ram * * @param[in] nmemb number of block * @param[in] size block memory size * * @return * - valid pointer on success * - NULL when any errors */ void *audio_calloc(size_t nmemb, size_t size); /** * @brief Malloc memory in ADF, it will malloc to internal memory * * @param[in] nmemb number of block * @param[in] size block memory size * * @return * - valid pointer on success * - NULL when any errors */ void *audio_calloc_inner(size_t nmemb, size_t size); /** * @brief Print heap memory status * * @param[in] tag tag of log * @param[in] line line of log * @param[in] func function name of log * * @return * - void */ void audio_mem_print(const char *tag, int line, const char *func); /** * @brief Reallocate memory in ADF, if spi ram is enabled, it will allocate memory in the spi ram * * @param[in] ptr memory pointer * @param[in] size block memory size * * @return * - valid pointer on success * - NULL when any errors */ void *audio_realloc(void *ptr, size_t size); /** * @brief Duplicate given string. * * Allocate new memory, copy contents of given string into it and return the pointer * * @param[in] str String to be duplicated * * @return * - Pointer to new malloc'ed string * - NULL otherwise */ char *audio_strdup(const char *str); /** * @brief SPI ram is enabled or not * * @return * - true, spi ram is enabled * - false, spi ram is not enabled */ bool audio_mem_spiram_is_enabled(void); /** * @brief Stack on external SPI ram is enabled or not * * @return * - true, stack on spi ram is enabled * - false, stack on spi ram is not enabled */ bool audio_mem_spiram_stack_is_enabled(void); #define AUDIO_MEM_SHOW(x) audio_mem_print(x, __LINE__, __func__) #ifdef __cplusplus } #endif #endif /*_AUDIO_MEM_H_*/
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/include/audio_mem.h
C
apache-2.0
3,647
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __AUDIO_MUTEX_H__ #define __AUDIO_MUTEX_H__ #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Create a mutex instance * * @return - Others: A mutex handle is returned * - NULL: Failed to create mutex */ void *mutex_create(void); /** * @brief Delete the mutex instance * * @param mutex The pointer to mutex handle * * @return - 0: Success to delete mutex */ int mutex_destroy(void *mutex); /** * @brief Take the mutex * * @param mutex The pointer to mutex handle * * @return - 0: The lock was obtained */ int mutex_lock(void *mutex); /** * @brief Release the mutex * * @param mutex The pointer to mutex handle * * @return - 0: The lock was released */ int mutex_unlock(void *mutex); #ifdef __cplusplus } #endif #endif /* #ifndef __AUDIO_MUTEX_H__ */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/include/audio_mutex.h
C
apache-2.0
2,243
/* * ESPRESSIF MIT License * * Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __AUDIO_QUEUE_H__ #define __AUDIO_QUEUE_H__ #ifdef __cplusplus extern "C" { #endif typedef void* audio_queue_handle_t; /** * @brief Allocate queue instance with given item size and length * * @param queue_len The maximum number of items that the queue can contain * @param item_size The number of bytes each item in the queue will require * * @return - Others: Queue handle is returned * - NULL: Failed to create queue handle */ audio_queue_handle_t audio_queue_create(uint32_t queue_len, uint32_t item_size); /** * @brief Delete the queue * * @param queue A pointer to queue handle * * @return - 0: The queue deleted successfully */ int audio_queue_delete(audio_queue_handle_t queue); /** * @brief Post an item on given queue * * @param queue A pointer to queue handle * @param item A pointer to the item that is to be placed on the queue * @param block_time_ms The maximum amount of millisecond the task should block waiting for space * to become available on the queue, should it already be full * * @return - 0: The item was successfully posted * - Otherwise: Queue full error */ int audio_queue_send(audio_queue_handle_t queue, void *item, uint32_t block_time_ms); /** * @brief Post an item to the front of a queue * * @param queue A pointer to queue handle * @param item A pointer to the item that is to be placed on the queue * @param block_time_ms The maximum amount of millisecond the task should block waiting for space * to become available on the queue, should it already be full * * @return - 0: The item was successfully posted * - Otherwise: Queue full error */ int audio_queue_send_to_front(audio_queue_handle_t queue, void *item, uint32_t block_time_ms); /** * @brief Receive an item from a queue. * * @param queue A pointer to queue handle * @param item A pointer to the item that is to be placed on the queue * @param block_time_ms The maximum amount of millisecond the task should block waiting for space * to become available on the queue, should it already be full * * @return - 0: An item was successfully received from the queue * - Otherwise: Failed to received queue */ int audio_queue_recv(audio_queue_handle_t queue, void *item, uint32_t block_time_ms); /** * @brief Return the number of messages stored in a queue. * * @param queue A pointer to queue handle * * @return The number of messages available in the queue. */ int audio_queue_message_available(const audio_queue_handle_t queue); /** * @brief Return the number of free spaces available in a queue. * * @param queue A pointer to queue handle * * @return The number of spaces available in the queue. */ int audio_queue_spaces_available(const audio_queue_handle_t queue); #ifdef __cplusplus } #endif #endif /* #ifndef __AUDIO_QUEUE_H__ */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/include/audio_queue.h
C
apache-2.0
4,527
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_SYS_H_ #define _AUDIO_SYS_H_ #include "esp_err.h" #ifdef __cplusplus extern "C" { #endif #define ___STR___(x) #x #define STR_AUDIO(x) ___STR___(x) #if defined(__GNUC__) && (__GNUC__ >= 7) #define FALL_THROUGH __attribute__ ((fallthrough)) #else #define FALL_THROUGH ((void)0) #endif /* __GNUC__ >= 7 */ /** * @brief Get system ticks by given millisecond * * @param[in] ms millisecond * * @return * - tick */ int audio_sys_get_tick_by_time_ms(int ms); /** * @brief Get system time with millisecond * * @return * - time with millisecond */ int64_t audio_sys_get_time_ms(void); /** * @brief Function to print the CPU usage of tasks over a given AUDIO_SYS_TASKS_ELAPSED_TIME_MS. * * This function will measure and print the CPU usage of tasks over a specified * number of ticks (i.e. real time stats). This is implemented by simply calling * uxTaskGetSystemState() twice separated by a delay, then calculating the * differences of task run times before and after the delay. * * @note If any tasks are added or removed during the delay, the stats of * those tasks will not be printed. * @note This function should be called from a high priority task to minimize * inaccuracies with delays. * @note When running in dual core mode, each core will correspond to 50% of * the run time. * * @return * - ESP_OK * - ESP_FIAL */ esp_err_t audio_sys_get_real_time_stats(void); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/include/audio_sys.h
C
apache-2.0
2,747
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _AUDIO_THREAD_H_ #define _AUDIO_THREAD_H_ #include "esp_err.h" #include "stdbool.h" #ifdef __cplusplus extern "C" { #endif #define audio_thread_t xTaskHandle /** * @brief Allocate handle if not allocated and create a thread * * @param p_handle pointer to audio_thread_t handle * @param name Task name * @param main_func The function which task will execute * @param stack Task stack * @param prio Task priority * @param stack_in_ext If task should reside in external memory * @param core_id Core to which task will be pinned * * @return - ESP_OK : Task creation successful * - ESP_FAIL: Failed to create task * * @note - Please apply the $ADF_PATH/idf_patches/idf_v3.3/4.x_freertos.patch first. * - Please enable support for external RAM and `Allow external memory as an argument to xTaskCreateStatic` * to be able to use external memory for task stack, namely `CONFIG_SPIRAM_BOOT_INIT=y` and `CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y`. * */ esp_err_t audio_thread_create(audio_thread_t *p_handle, const char* name, void(*main_func)(void* arg), void *arg, uint32_t stack, int prio, bool stack_in_ext, int core_id); /** * @brief Cleanup all the task memory * * @param p_handle The pointer to audio_thread_t handle * * @return - ESP_OK : Task cleanup successful * - ESP_FAIL: Task is already cleaned up * * @note must be called from different task after this task is deleted. */ esp_err_t audio_thread_cleanup(audio_thread_t *p_handle); /** * @brief Delete the task * * @param p_handle The pointer to audio_thread_t handle * * @return - ESP_OK : Task deleted successfully * - ESP_FAIL: Task is not running or cleaned up * * @note This only deletes the task and all the memory cleanup should be done with `audio_thread_cleanup` */ esp_err_t audio_thread_delete_task(audio_thread_t *p_handle); #ifdef __cplusplus } #endif #endif /* #ifndef _AUDIO_THREAD_H_ */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/include/audio_thread.h
C
apache-2.0
3,444
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __AUDIO_URL_H__ #define __AUDIO_URL_H__ #ifdef __cplusplus extern "C" { #endif /** * @brief Allocate new memory, encoding given string to percent-encoding and return the pointer * * @note Returned pointer should be freed by user. * ALPHA(0x41-0x5A and 0x61-0x7A), DIGIT (0x30-0x39) and "~!@#$&*()=:/,;?+'-_." are reserved. * * @param str String to be encode * * @return * - valid pointer on success * - NULL when any errors */ char *audio_url_encode(const char *str); /** * @brief Allocate new memory, decoding given percent-encoding string and return the pointer * * @note Returned pointer should be freed by user * * @param str String to be decode * * @return * - valid pointer on success * - NULL when any errors */ char *audio_url_decode(const char *str); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/include/audio_url.h
C
apache-2.0
2,091
/* * ESPRESSIF MIT License * * Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef __MEDIA_OS_CTYPE_H__ #define __MEDIA_OS_CTYPE_H__ #ifdef __cplusplus extern "C" { #endif /** * @brief Checks whether c is either a decimal digit or an uppercase or lowercase letter. * The result is true if either isalpha or isdigit would also return true. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is either a digit or a letter. * Zero (i.e., false) otherwise. * */ int media_os_isalnum(int c); /** * @brief Checks whether c is an alphabetic letter. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is an alphabetic letter. * Zero (i.e., false) otherwise. * */ int media_os_isalpha(int c); /** * @brief Checks whether c is a blank character. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is a blank character. * Zero (i.e., false) otherwise. * */ int media_os_isblank(int c); /** * @brief Checks whether c is a control character. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is a control character. * Zero (i.e., false) otherwise. * */ int media_os_iscntrl(int c); /** * @brief Checks whether c is a decimal digit character. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is a decimal digit. * Zero (i.e., false) otherwise. * */ int media_os_isdigit(int c); /** * @brief Checks whether c is a character with graphical representation. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c has a graphical representation as character. * Zero (i.e., false) otherwise. */ int media_os_isgraph(int c); /** * @brief Checks whether c is a lowercase letter. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is a lowercase alphabetic letter. * Zero (i.e., false) otherwise. * */ int media_os_islower(int c); /** * @brief Checks whether c is a printable character. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is a printable character. * Zero (i.e., false) otherwise. * */ int media_os_isprint(int c); /** * @brief Checks whether c is a punctuation character. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is a punctuation character. * Zero (i.e., false) otherwise. * */ int media_os_ispunct(int c); /** * @brief Checks whether c is a white-space character. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is a white-space character. * Zero (i.e., false) otherwise. * */ int media_os_isspace(int c); /** * @brief Checks if parameter c is an uppercase alphabetic letter. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is an uppercase alphabetic letter. * Zero (i.e., false) otherwise. * */ int media_os_isupper(int c); /** * @brief Checks whether c is a hexdecimal digit character. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return A value different from zero (i.e., true) if indeed c is a hexadecimal digit. * Zero (i.e., false) otherwise. * */ int media_os_isxdigit(int c); /** * @brief Converts c to its lowercase equivalent if c is an uppercase letter and * has a lowercase equivalent. If no such conversion is possible, the value returned is c unchanged. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return The lowercase equivalent to c, if such value exists, or c (unchanged) otherwise. * The value is returned as an int value that can be implicitly casted to char. * */ int media_os_tolower(int c); /** * @brief Converts c to its uppercase equivalent if c is a lowercase letter and * has an uppercase equivalent. If no such conversion is possible, the value returned is c unchanged. * * @param[in] Character to be checked, casted as an int, or EOF. * * @return The uppercase equivalent to c, if such value exists, or c (unchanged) otherwise. * The value is returned as an int value that can be implicitly casted to char. * */ int media_os_toupper(int c); #ifdef __cplusplus } #endif #endif /* #ifndef __MEDIA_OS_CTYPE_H__ */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/include/media_os_ctype.h
C
apache-2.0
6,376
/* * ESPRESSIF MIT License * * Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "ctype.h" int media_os_isalnum(int c) { return isalnum(c); } int media_os_isalpha(int c) { return isalpha(c); } int media_os_isblank(int c) { return isblank(c); } int media_os_iscntrl(int c) { return iscntrl(c); } int media_os_isdigit(int c) { return isdigit(c); } int media_os_isgraph(int c) { return isgraph(c); } int media_os_islower(int c) { return islower(c); } int media_os_isprint(int c) { return isprint(c); } int media_os_ispunct(int c) { return ispunct(c); } int media_os_isspace(int c) { return isspace(c); } int media_os_isupper(int c) { return isupper(c); } int media_os_isxdigit(int c) { return isxdigit(c); } int media_os_tolower(int c) { return tolower(c); } int media_os_toupper(int c) { return toupper(c); }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/media_os_ctype.c
C
apache-2.0
2,041
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <pthread.h> #include "unity.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "audio_mem.h" #include "esp_log.h" #include "esp_err.h" static const char* TAG = "AUDIO_MEM_TEST"; TEST_CASE("audio_mem", "esp-adf") { esp_log_level_set("AUDIO_MEM", ESP_LOG_VERBOSE); ESP_LOGI(TAG, "[✓] audio_malloc,audio_callo,audio_calloc_inner, audio_inaudio memory print"); AUDIO_MEM_SHOW(TAG); uint8_t* pdata = audio_malloc(1024); TEST_ASSERT_NOT_NULL(pdata); AUDIO_MEM_SHOW(TAG); audio_free(pdata); AUDIO_MEM_SHOW(TAG); pdata = audio_calloc(1, 2 * 1024 * 1024); TEST_ASSERT_NOT_NULL(pdata); AUDIO_MEM_SHOW(TAG); audio_free(pdata); AUDIO_MEM_SHOW(TAG); pdata = audio_calloc_inner(1, 1024); TEST_ASSERT_NOT_NULL(pdata); AUDIO_MEM_SHOW(TAG); audio_free(pdata); AUDIO_MEM_SHOW(TAG); } TEST_CASE("audio_strdup", "esp-adf") { esp_log_level_set("AUDIO_STRDUP", ESP_LOG_VERBOSE); ESP_LOGI(TAG, "[✓] audio_strdup"); AUDIO_MEM_SHOW(TAG); char * strings = "audio string dump"; char* pdata = audio_strdup(strings); TEST_ASSERT_NOT_NULL(pdata); AUDIO_MEM_SHOW(TAG); audio_free(pdata); AUDIO_MEM_SHOW(TAG); } TEST_CASE("audio_realloc", "esp-adf") { esp_log_level_set("AUDIO_REALLOC", ESP_LOG_VERBOSE); ESP_LOGI(TAG, "[✓] audio_realloc"); AUDIO_MEM_SHOW(TAG); uint8_t* pdata = audio_malloc(1024); TEST_ASSERT_NOT_NULL(pdata); AUDIO_MEM_SHOW(TAG); pdata = audio_realloc(pdata, 2 * 1024); TEST_ASSERT_NOT_NULL(pdata); AUDIO_MEM_SHOW(TAG); audio_free(pdata); AUDIO_MEM_SHOW(TAG); }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/test/audio_mem_test.c
C
apache-2.0
2,880
# #Component Makefile # COMPONENT_ADD_LDFLAGS = -Wl,--whole-archive -l$(COMPONENT_NAME) -Wl,--no-whole-archive
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_sal/test/component.mk
Makefile
apache-2.0
112
set(COMPONENT_SRCS "fatfs_stream.c" "i2s_stream.c" "http_stream.c" "hls_playlist.c" "raw_stream.c" "spiffs_stream.c" "tone_stream.c" "algorithm_stream.c" "tcp_client_stream.c" "pwm_stream.c" "tts_stream.c") set(COMPONENT_ADD_INCLUDEDIRS "include") set(COMPONENT_REQUIRES audio_pipeline audio_sal esp_http_client tcp_transport spiffs esp-adf-libs audio_board esp-sr bootloader_support esp_dispatcher esp_actions tone_partition) register_component()
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/CMakeLists.txt
CMake
apache-2.0
651
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <string.h> #include "esp_log.h" #include "audio_pipeline.h" #include "audio_element.h" #include "audio_mem.h" #include "audio_error.h" #include "esp_aec.h" #include "esp_agc.h" #include "esp_ns.h" #include "esp_resample.h" #include "algorithm_stream.h" #define NS_FRAME_BYTES 320 // 10ms data frame (10 * 16 * 2) #define AGC_FRAME_BYTES 320 // 10ms data frame (10 * 16 * 2) #define AEC_FRAME_BYTES 512 // 16ms data frame (16 * 16 * 2) #define ALGORITHM_STREAM_DEFAULT_AEC_MODE 3 #define ALGORITHM_STREAM_DEFAULT_AGC_MODE 3 #define ALGORITHM_STREAM_DEFAULT_AGC_FRAME_LENGTH 10 //ms #define ALGORITHM_STREAM_RESAMPE_DEFAULT_COMPLEXITY 0 #define ALGORITHM_STREAM_RESAMPE_DEFAULT_MAX_INPUT_SIZE (AEC_FRAME_BYTES * 8) #define ALGORITHM_STREAM_FULL_FUCTION_MASK (ALGORITHM_STREAM_USE_AEC | ALGORITHM_STREAM_USE_AGC | ALGORITHM_STREAM_USE_NS) static const char *TAG = "ALGORITHM_STREAM"; typedef struct { void *rsp_handle; unsigned char *rsp_in; unsigned char *rsp_out; int in_offset; int ap_factor; int16_t *aec_buff; resample_info_t rsp_info; ringbuf_handle_t input_rb; bool data_need_be_resampled; bool data_need_be_divided_after_rsp; //The encode mode of resample function doesn't support change channels bool is_after_reset_res_info; } algorithm_data_info_t; typedef struct { void *ns_handle; void *aec_handle; void *agc_handle; char *scale_buff; int16_t *aec_buff; int16_t *ns_buff; int16_t *agc_buff; int8_t algo_mask; algorithm_data_info_t record; algorithm_data_info_t reference; algorithm_stream_input_type_t input_type; } algo_stream_t; static esp_err_t create_record_rsp_handle(algo_stream_t *algo); static esp_err_t create_reference_rsp_handle(algo_stream_t *algo); static esp_err_t destroy_record_rsp_handle(algo_stream_t *algo); static esp_err_t destroy_reference_rsp_handle(algo_stream_t *algo); static esp_err_t is_valid_algorithm_rsp_samplerate(int samplerate) { if (samplerate < 8000 || samplerate > 96000) { ESP_LOGE(TAG, "The sample rate should be within range [8000,96000], here is %d Hz", samplerate); return ESP_FAIL; } return ESP_OK; } static esp_err_t is_valid_algorithm_rsp_channel(int channel) { if (channel != 1 && channel != 2) { ESP_LOGE(TAG, "The number of channels should be either 1 or 2, here is %d", channel); return ESP_FAIL; } return ESP_OK; } static esp_err_t algorithm_data_info_destroy(algorithm_data_info_t *data_info) { static void *rsp_handle; if (rsp_handle == data_info->rsp_handle) { // Avoid the rsp handle be destroyed twice. return ESP_OK; } if (data_info->rsp_handle) { rsp_handle = data_info->rsp_handle; esp_resample_destroy(data_info->rsp_handle); data_info->rsp_handle = NULL; } if (data_info->aec_buff) { audio_free(data_info->aec_buff); data_info->aec_buff = NULL; } return ESP_OK; } static esp_err_t _algo_close(audio_element_handle_t self) { algo_stream_t *algo = (algo_stream_t *)audio_element_getdata(self); algorithm_data_info_t *record = &algo->record; algorithm_data_info_t *reference = &algo->reference; if (algo->ns_handle) { ns_destroy(algo->ns_handle); algo->ns_handle = NULL; } if (algo->aec_handle) { aec_destroy(algo->aec_handle); algo->aec_handle = NULL; } if (algo->agc_handle) { esp_agc_clse(algo->agc_handle); algo->agc_handle = NULL; } if (algo->ns_buff) { audio_free(algo->ns_buff); algo->ns_buff = NULL; } if (algo->aec_buff) { audio_free(algo->aec_buff); algo->aec_buff = NULL; } if (algo->agc_buff) { audio_free(algo->agc_buff); algo->agc_buff = NULL; } if (algo->scale_buff) { audio_free(algo->scale_buff); algo->scale_buff = NULL; } algorithm_data_info_destroy(record); algorithm_data_info_destroy(reference); return ESP_OK; } static esp_err_t _algo_open(audio_element_handle_t self) { algo_stream_t *algo = (algo_stream_t *)audio_element_getdata(self); bool _success = true; if (algo->algo_mask & ALGORITHM_STREAM_USE_AEC) { _success &= ((algo->aec_handle = aec_pro_create(AEC_FRAME_LENGTH_MS, ALGORITHM_STREAM_DEFAULT_CHANNEL, ALGORITHM_STREAM_DEFAULT_AEC_MODE)) != NULL); } if (algo->algo_mask & ALGORITHM_STREAM_USE_AGC) { _success &= ((algo->agc_handle = esp_agc_open(ALGORITHM_STREAM_DEFAULT_AGC_MODE, ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ)) != NULL); } if (algo->algo_mask & ALGORITHM_STREAM_USE_NS) { _success &= ((algo->ns_handle = ns_create(ALGORITHM_STREAM_DEFAULT_AGC_FRAME_LENGTH)) != NULL); } AUDIO_NULL_CHECK(TAG, _success, { _algo_close(self); return ESP_FAIL; }); return ESP_OK; } static int algorithm_process(audio_element_handle_t self) { algo_stream_t *algo = (algo_stream_t *)audio_element_getdata(self); static int copy_cnt, cur_pos; algorithm_data_info_t *record = &algo->record; algorithm_data_info_t *reference = &algo->reference; if (algo->algo_mask & ALGORITHM_STREAM_USE_AEC) { aec_process(algo->aec_handle, record->aec_buff, reference->aec_buff, algo->aec_buff); memcpy(algo->scale_buff + cur_pos, algo->aec_buff, AEC_FRAME_BYTES); cur_pos += AEC_FRAME_BYTES; copy_cnt = cur_pos / AGC_FRAME_BYTES; for (int i = 0; i < copy_cnt; i++) { if ((algo->algo_mask & ALGORITHM_STREAM_USE_NS) && (algo->algo_mask & ALGORITHM_STREAM_USE_AGC)) { ns_process(algo->ns_handle, (int16_t *)algo->scale_buff + i * (NS_FRAME_BYTES >> 1), algo->ns_buff); esp_agc_process(algo->agc_handle, algo->ns_buff, algo->agc_buff, (AGC_FRAME_BYTES >> 1), ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ); audio_element_output(self, (char *)algo->agc_buff, AGC_FRAME_BYTES); } else if (algo->algo_mask & ALGORITHM_STREAM_USE_NS) { ns_process(algo->ns_handle, (int16_t *)algo->scale_buff + i * (NS_FRAME_BYTES >> 1), algo->ns_buff); audio_element_output(self, (char *)algo->ns_buff, NS_FRAME_BYTES); } else if (algo->algo_mask & ALGORITHM_STREAM_USE_AGC) { esp_agc_process(algo->agc_handle, (int16_t *)algo->scale_buff + i * (AGC_FRAME_BYTES >> 1), algo->agc_buff, (AGC_FRAME_BYTES >> 1), ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ); audio_element_output(self, (char *)algo->ns_buff, AGC_FRAME_BYTES); } else { audio_element_output(self, (char *)algo->aec_buff, AEC_FRAME_BYTES); cur_pos -= AEC_FRAME_BYTES; return AEC_FRAME_BYTES; } } memcpy(algo->scale_buff, algo->scale_buff + AGC_FRAME_BYTES * copy_cnt, cur_pos - AGC_FRAME_BYTES * copy_cnt); cur_pos -= AGC_FRAME_BYTES * copy_cnt; return AGC_FRAME_BYTES * copy_cnt; } else { if((algo->algo_mask & ALGORITHM_STREAM_USE_AGC) && (algo->algo_mask & ALGORITHM_STREAM_USE_NS)) { ns_process(algo->ns_handle, (int16_t *)algo->scale_buff, algo->ns_buff); esp_agc_process(algo->agc_handle, algo->ns_buff, algo->agc_buff, (AGC_FRAME_BYTES >> 1), ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ); audio_element_output(self, (char *)algo->agc_buff, AGC_FRAME_BYTES); return AGC_FRAME_BYTES; } else if (algo->algo_mask & ALGORITHM_STREAM_USE_NS) { ns_process(algo->ns_handle, (int16_t *)algo->scale_buff, algo->ns_buff); audio_element_output(self, (char *)algo->ns_buff, NS_FRAME_BYTES); return NS_FRAME_BYTES; } else if (algo->algo_mask & ALGORITHM_STREAM_USE_AGC) { esp_agc_process(algo->agc_handle, (int16_t *)algo->scale_buff, algo->agc_buff, (AGC_FRAME_BYTES >> 1), ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ); audio_element_output(self, (char *)algo->agc_buff, AGC_FRAME_BYTES); return AGC_FRAME_BYTES; } else { return AEL_IO_FAIL; } } } static esp_err_t algorithm_data_divided(int16_t *raw_buff, int len, int16_t *left_channel, int linear_lfac, int16_t *right_channel, int linear_rfac) { // To improve efficiency, data splitting and linear amplification are integrated into one function for (int i = 0; i < len / 4; i++) { if (left_channel) { left_channel[i] = raw_buff[i << 1] * linear_lfac; } if (right_channel) { right_channel[i] = raw_buff[(i << 1) + 1] * linear_rfac; } } return ESP_OK; } static esp_err_t algorithm_data_linear_amplication(int16_t *raw_buff, int len, int linear_factor) { for (int i = 0; i < len / 2; i++) { raw_buff[i] *= linear_factor; } return ESP_OK; } static int algorithm_data_process_for_type1(audio_element_handle_t self) { algo_stream_t *algo = (algo_stream_t *)audio_element_getdata(self); algorithm_data_info_t *record = &algo->record; algorithm_data_info_t *reference = &algo->reference; int in_ret = 0, bytes_consume = 0, out_len_bytes = record->rsp_info.out_len_bytes; char tmp_buffer[2 * AEC_FRAME_BYTES] = {0}; if (record->data_need_be_resampled) { // When use input type1, use record or reference handle is the same. if (record->in_offset > 0) { memmove(record->rsp_in, &record->rsp_in[ALGORITHM_STREAM_RESAMPE_DEFAULT_MAX_INPUT_SIZE - record->in_offset], record->in_offset); } in_ret = audio_element_input(self, (char *)&record->rsp_in[record->in_offset], ALGORITHM_STREAM_RESAMPE_DEFAULT_MAX_INPUT_SIZE - record->in_offset); if (in_ret <= 0) { return in_ret; } else { record->in_offset += in_ret; bytes_consume = esp_resample_run(record->rsp_handle, (void *)&record->rsp_info, record->rsp_in, record->rsp_out, record->in_offset, &out_len_bytes); ESP_LOGD(TAG, "in_ret = %d, out_len_bytes = %d, bytes_consume = %d", in_ret, out_len_bytes, bytes_consume); if ((bytes_consume > 0) && (out_len_bytes == record->rsp_info.out_len_bytes)) { record->in_offset -= bytes_consume; algorithm_data_divided((int16_t *)record->rsp_out, out_len_bytes, reference->aec_buff, reference->ap_factor, record->aec_buff, record->ap_factor); return algorithm_process(self); } else { ESP_LOGE(TAG, "Fail to resample"); return AEL_IO_FAIL; } } } else { in_ret = audio_element_input(self, tmp_buffer, AEC_FRAME_BYTES * 2); if (in_ret <= 0) { return in_ret; } else { algorithm_data_divided((int16_t *)tmp_buffer, AEC_FRAME_BYTES * 2, reference->aec_buff, reference->ap_factor, record->aec_buff, record->ap_factor); return algorithm_process(self); } } } static int algorithm_data_pre_process_for_type2(audio_element_handle_t self, algorithm_data_info_t *data_info, int input_buffer_index) { algo_stream_t *algo = (algo_stream_t *)audio_element_getdata(self); int in_ret = 0, bytes_consume = 0, out_len_bytes = data_info->rsp_info.out_len_bytes, basic_frame_size; char tmp_buffer[2 * AEC_FRAME_BYTES] = {0}; int16_t *input_buffer; if (algo->algo_mask & ALGORITHM_STREAM_USE_AEC) { input_buffer = data_info->aec_buff; basic_frame_size = AEC_FRAME_BYTES; } else { basic_frame_size = AGC_FRAME_BYTES; input_buffer = (int16_t *)algo->scale_buff; } if (data_info->data_need_be_resampled) { if (data_info->in_offset > 0) { memmove(data_info->rsp_in, &data_info->rsp_in[ALGORITHM_STREAM_RESAMPE_DEFAULT_MAX_INPUT_SIZE - data_info->in_offset], data_info->in_offset); } if (input_buffer_index < 0) { in_ret = audio_element_input(self, (char *)&data_info->rsp_in[data_info->in_offset], ALGORITHM_STREAM_RESAMPE_DEFAULT_MAX_INPUT_SIZE - data_info->in_offset); } else { in_ret = audio_element_multi_input(self, (char *)&data_info->rsp_in[data_info->in_offset], ALGORITHM_STREAM_RESAMPE_DEFAULT_MAX_INPUT_SIZE - data_info->in_offset, input_buffer_index, portMAX_DELAY); } if (in_ret <= 0) { return in_ret; } else { data_info->in_offset += in_ret; bytes_consume = esp_resample_run(data_info->rsp_handle, (void *)&data_info->rsp_info, data_info->rsp_in, data_info->rsp_out, data_info->in_offset, &out_len_bytes); ESP_LOGD(TAG, "in_ret = %d, out_len_bytes = %d, bytes_consume = %d", in_ret, out_len_bytes, bytes_consume); if ((bytes_consume > 0) && (out_len_bytes == data_info->rsp_info.out_len_bytes)) { data_info->in_offset -= bytes_consume; if (data_info->data_need_be_divided_after_rsp) { algorithm_data_divided((int16_t *)data_info->rsp_out, out_len_bytes, input_buffer, data_info->ap_factor, NULL, 0); } else { memcpy(input_buffer, data_info->rsp_out, out_len_bytes); algorithm_data_linear_amplication(input_buffer, out_len_bytes, data_info->ap_factor); } } else { ESP_LOGE(TAG, "Fail to resample"); return AEL_IO_FAIL; } } } else { if (data_info->data_need_be_divided_after_rsp) { if (input_buffer_index < 0) { in_ret = audio_element_input(self, tmp_buffer, basic_frame_size * 2); } else { in_ret = audio_element_multi_input(self, tmp_buffer, basic_frame_size * 2, input_buffer_index, portMAX_DELAY); } if (in_ret <= 0) { return in_ret; } else { algorithm_data_divided((int16_t *)tmp_buffer, basic_frame_size * 2, input_buffer, data_info->ap_factor, NULL, 0); } } else { if (input_buffer_index < 0) { in_ret = audio_element_input(self, (char *)input_buffer, basic_frame_size); } else { in_ret = audio_element_multi_input(self, (char *)input_buffer, basic_frame_size, input_buffer_index, portMAX_DELAY); } if (in_ret <= 0) { return in_ret; } else { algorithm_data_linear_amplication(input_buffer, basic_frame_size, data_info->ap_factor); } } } return basic_frame_size; } static int algorithm_data_process_for_type2(audio_element_handle_t self) { int ret = 0; algo_stream_t *algo = (algo_stream_t *)audio_element_getdata(self); algorithm_data_info_t *record = &algo->record; algorithm_data_info_t *reference = &algo->reference; if (algo->algo_mask & ALGORITHM_STREAM_USE_AEC) { ret |= algorithm_data_pre_process_for_type2(self, reference, 0); } ret |= algorithm_data_pre_process_for_type2(self, record, -1); if (ret <= 0) { return ret; } return algorithm_process(self); } static audio_element_err_t _algo_process(audio_element_handle_t self, char *in_buffer, int in_len) { int ret = ESP_OK; algo_stream_t *algo = (algo_stream_t *)audio_element_getdata(self); if (algo->record.is_after_reset_res_info) { ret = destroy_record_rsp_handle(algo); if (ret != ESP_OK) { return AEL_PROCESS_FAIL; } ret = create_record_rsp_handle(algo); if (ret != ESP_OK) { return AEL_PROCESS_FAIL; } } if (algo->reference.is_after_reset_res_info) { ret = destroy_reference_rsp_handle(algo); if (ret != ESP_OK) { return AEL_PROCESS_FAIL; } ret = create_reference_rsp_handle(algo); if (ret != ESP_OK) { return AEL_PROCESS_FAIL; } } if (algo->input_type == ALGORITHM_STREAM_INPUT_TYPE1) { ret = algorithm_data_process_for_type1(self); } else if (algo->input_type == ALGORITHM_STREAM_INPUT_TYPE2) { ret = algorithm_data_process_for_type2(self); } else { ESP_LOGE(TAG, "Type %d is not supported", algo->input_type); return AEL_IO_FAIL; } return ret; } static esp_err_t algorithm_resample_config(resample_info_t *rsp_cfg, algorithm_data_info_t *data_info, algorithm_stream_input_type_t type) { AUDIO_NULL_CHECK(TAG, rsp_cfg, return ESP_FAIL); AUDIO_NULL_CHECK(TAG, data_info, return ESP_FAIL); rsp_cfg->dest_rate = ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ; rsp_cfg->dest_ch = ALGORITHM_STREAM_DEFAULT_CHANNEL; // The encode resample cannot process diffrent channel rsp_cfg->mode = RESAMPLE_ENCODE_MODE; rsp_cfg->sample_bits = ALGORITHM_STREAM_DEFAULT_SAMPLE_BIT; rsp_cfg->max_indata_bytes = ALGORITHM_STREAM_RESAMPE_DEFAULT_MAX_INPUT_SIZE; // The max input data maybe 48K 2ch --> 16k 1ch; so max_data = AEC_FRAME_BYTES * 6 rsp_cfg->complexity = ALGORITHM_STREAM_RESAMPE_DEFAULT_COMPLEXITY; rsp_cfg->type = ESP_RESAMPLE_TYPE_AUTO; if (type == ALGORITHM_STREAM_INPUT_TYPE1) { data_info->data_need_be_divided_after_rsp = false; if (data_info->rsp_info.src_rate != ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ) { data_info->data_need_be_resampled = true; } else { data_info->data_need_be_resampled = false; } return ESP_OK; } if ((data_info->rsp_info.src_rate == ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ) && (data_info->rsp_info.src_ch == ALGORITHM_STREAM_DEFAULT_CHANNEL)) { data_info->data_need_be_resampled = false; data_info->data_need_be_divided_after_rsp = false; } else if (data_info->rsp_info.src_rate == ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ) { data_info->data_need_be_resampled = false; data_info->data_need_be_divided_after_rsp = true; } else { data_info->data_need_be_resampled = true; if (data_info->rsp_info.src_ch == 2) { data_info->data_need_be_divided_after_rsp = true; } else if (data_info->rsp_info.src_ch == 1) { data_info->data_need_be_divided_after_rsp = false; } else { ESP_LOGE(TAG, "The channel number should be 0 or 1"); return ESP_FAIL; } } return ESP_OK; } static esp_err_t _esp_algorithm_resample_create(algorithm_data_info_t *info, resample_info_t *rsp_cfg, int src_rate, int src_ch, bool is_divided_after_rsp, int8_t mask) { AUDIO_NULL_CHECK(TAG, info, return ESP_FAIL); AUDIO_NULL_CHECK(TAG, rsp_cfg, return ESP_FAIL); rsp_cfg->src_rate = src_rate; rsp_cfg->dest_ch = src_ch; rsp_cfg->src_ch = src_ch; if (is_divided_after_rsp) { if (mask & ALGORITHM_STREAM_USE_AEC) { rsp_cfg->out_len_bytes = AEC_FRAME_BYTES * 2; } else { rsp_cfg->out_len_bytes = AGC_FRAME_BYTES * 2; } } else { if (mask & ALGORITHM_STREAM_USE_AEC) { rsp_cfg->out_len_bytes = AEC_FRAME_BYTES; } else { rsp_cfg->out_len_bytes = AGC_FRAME_BYTES; } } memcpy(&info->rsp_info, rsp_cfg, sizeof(resample_info_t)); info->rsp_handle = esp_resample_create(rsp_cfg, &info->rsp_in, &info->rsp_out); AUDIO_NULL_CHECK(TAG, info->rsp_handle, { ESP_LOGE(TAG, "Fail to create recorder resample handle"); return ESP_FAIL; }); return ESP_OK; } static esp_err_t create_record_rsp_handle(algo_stream_t *algo) { AUDIO_NULL_CHECK(TAG, algo, return ESP_FAIL); algorithm_data_info_t *record = &algo->record; resample_info_t rsp_cfg; algorithm_resample_config(&rsp_cfg, record, algo->input_type); algo->record.is_after_reset_res_info = false; if (algo->input_type == ALGORITHM_STREAM_INPUT_TYPE1) { if (record->data_need_be_resampled) { return _esp_algorithm_resample_create(record, &rsp_cfg, record->rsp_info.src_rate, 2, 1, ALGORITHM_STREAM_USE_AEC); } else { return ESP_OK; } } if (record->data_need_be_resampled) { return _esp_algorithm_resample_create(record, &rsp_cfg, record->rsp_info.src_rate, record->rsp_info.src_ch, record->data_need_be_divided_after_rsp, algo->algo_mask); } return ESP_OK; } static esp_err_t create_reference_rsp_handle(algo_stream_t *algo) { AUDIO_NULL_CHECK(TAG, algo, return ESP_FAIL); algorithm_data_info_t *reference = &algo->reference; resample_info_t rsp_cfg; algorithm_resample_config(&rsp_cfg, reference, algo->input_type); algo->reference.is_after_reset_res_info = false; if (reference->data_need_be_resampled) { return _esp_algorithm_resample_create(reference, &rsp_cfg, reference->rsp_info.src_rate, reference->rsp_info.src_ch, reference->data_need_be_divided_after_rsp, algo->algo_mask); } return ESP_OK; } static esp_err_t destroy_record_rsp_handle(algo_stream_t *algo) { AUDIO_NULL_CHECK(TAG, algo, return ESP_FAIL); algorithm_data_info_t *record = &algo->record; AUDIO_NULL_CHECK(TAG, record, return ESP_FAIL); if (record->rsp_handle != NULL) { esp_resample_destroy(record->rsp_handle); record->rsp_handle = NULL; } return ESP_OK; } static esp_err_t destroy_reference_rsp_handle(algo_stream_t *algo) { AUDIO_NULL_CHECK(TAG, algo, return ESP_FAIL); algorithm_data_info_t *reference = &algo->reference; AUDIO_NULL_CHECK(TAG, reference, return ESP_FAIL); if (reference->rsp_handle != NULL) { esp_resample_destroy(reference->rsp_handle); reference->rsp_handle = NULL; } return ESP_OK; } ringbuf_handle_t algo_stream_get_multi_input_rb(audio_element_handle_t algo_handle) { AUDIO_NULL_CHECK(TAG, algo_handle, return NULL); return audio_element_get_multi_input_ringbuf(algo_handle, 0); } audio_element_handle_t algo_stream_init(algorithm_stream_cfg_t *config) { AUDIO_NULL_CHECK(TAG, config, return NULL); if ((config->rec_linear_factor <= 0) || (config->ref_linear_factor <= 0)) { ESP_LOGE(TAG, "The linear amplication factor should be greater than 0"); return NULL; } if ((config->algo_mask < 0) || (config->algo_mask > ALGORITHM_STREAM_FULL_FUCTION_MASK)) { // ESP_LOGE(TAG, "Please choose a reasonable mask value"); return NULL; } algo_stream_t *algo = (algo_stream_t *)audio_calloc(1, sizeof(algo_stream_t)); AUDIO_NULL_CHECK(TAG, algo, return NULL); algorithm_data_info_t *record = &algo->record; algorithm_data_info_t *reference = &algo->reference; record->ap_factor = config->rec_linear_factor; reference->ap_factor = config->ref_linear_factor; audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG(); cfg.open = _algo_open; cfg.close = _algo_close; cfg.process = _algo_process; cfg.task_stack = config->task_stack; cfg.task_prio = config->task_prio; cfg.task_core = config->task_core; cfg.multi_in_rb_num = config->input_type; cfg.tag = "algorithm"; if (config->input_type == ALGORITHM_STREAM_INPUT_TYPE1) { if ((config->ref_sample_rate != config->rec_sample_rate) || (config->ref_ch != config->rec_ch)) { ESP_LOGE(TAG, "The frequence and channel number should be the same, please check about that!"); audio_free(algo); return NULL; } if (config->algo_mask != (ALGORITHM_STREAM_USE_AEC | ALGORITHM_STREAM_USE_AGC | ALGORITHM_STREAM_USE_NS)) { ESP_LOGE(TAG, "When type1 is choosen, both these algorithms should be used"); audio_free(algo); return NULL; } } cfg.buffer_len = AEC_FRAME_BYTES; algo->input_type = config->input_type; algo->algo_mask = config->algo_mask; algo->record.rsp_info.src_ch = config->rec_ch; algo->record.rsp_info.src_rate = config->rec_sample_rate; algo->reference.rsp_info.src_ch = config->ref_ch; algo->reference.rsp_info.src_rate = config->ref_sample_rate; audio_element_handle_t el = audio_element_init(&cfg); AUDIO_NULL_CHECK(TAG, el, { audio_free(algo); return NULL; }); bool _success = true; _success &= (create_record_rsp_handle(algo) == ESP_OK); _success &= (create_reference_rsp_handle(algo) == ESP_OK); _success &= ((algo->scale_buff = audio_calloc(1, AEC_FRAME_BYTES + AGC_FRAME_BYTES)) != NULL); if (algo->algo_mask & ALGORITHM_STREAM_USE_AEC) { _success &= ( (algo->aec_buff = audio_calloc(1, AEC_FRAME_BYTES)) && (record->aec_buff = audio_calloc(1, AEC_FRAME_BYTES)) && (reference->aec_buff = audio_calloc(1, AEC_FRAME_BYTES)) ); } if (algo->algo_mask & ALGORITHM_STREAM_USE_AGC) { _success &= ((algo->agc_buff = audio_calloc(1, AGC_FRAME_BYTES)) != NULL); } if (algo->algo_mask & ALGORITHM_STREAM_USE_NS) { _success &= ((algo->ns_buff = audio_calloc(1, NS_FRAME_BYTES)) != NULL); } AUDIO_NULL_CHECK(TAG, _success, { ESP_LOGE(TAG, "Error occured"); _algo_close(el); audio_free(algo); return NULL; }); audio_element_setdata(el, algo); return el; } esp_err_t algo_stream_set_record_rate(audio_element_handle_t algo_handle, int rec_ch, int rec_sample_rate) { AUDIO_NULL_CHECK(TAG, algo_handle, return ESP_FAIL); algo_stream_t *algo = (algo_stream_t *)audio_element_getdata(algo_handle); if (algo->record.rsp_info.src_ch == rec_ch && algo->record.rsp_info.src_rate == rec_sample_rate) { return ESP_OK; } if (is_valid_algorithm_rsp_channel(rec_ch) != ESP_OK || is_valid_algorithm_rsp_samplerate(rec_sample_rate) != ESP_OK ) { return ESP_ERR_INVALID_ARG; } else { if (algo->input_type == ALGORITHM_STREAM_INPUT_TYPE1) { algo->reference.is_after_reset_res_info = true; algo->reference.rsp_info.src_ch = rec_ch; algo->reference.rsp_info.src_rate = rec_sample_rate; } algo->record.is_after_reset_res_info = true; algo->record.rsp_info.src_ch = rec_ch; algo->record.rsp_info.src_rate = rec_sample_rate; ESP_LOGI(TAG, "reset channel number of record signal : %d, sample rate of record signal: %d", rec_ch, rec_sample_rate); } return ESP_OK; } esp_err_t algo_stream_set_reference_rate(audio_element_handle_t algo_handle, int ref_ch, int ref_sample_rate) { AUDIO_NULL_CHECK(TAG, algo_handle, return ESP_FAIL); algo_stream_t *algo = (algo_stream_t *)audio_element_getdata(algo_handle); if (algo->reference.rsp_info.src_ch == ref_ch && algo->reference.rsp_info.src_rate == ref_sample_rate) { return ESP_OK; } if (is_valid_algorithm_rsp_channel(ref_ch) != ESP_OK || is_valid_algorithm_rsp_samplerate(ref_sample_rate) != ESP_OK ) { return ESP_ERR_INVALID_ARG; } else { if (algo->input_type == ALGORITHM_STREAM_INPUT_TYPE1) { algo->record.is_after_reset_res_info = true; algo->record.rsp_info.src_ch = ref_ch; algo->record.rsp_info.src_rate = ref_sample_rate; } algo->reference.is_after_reset_res_info = true; algo->reference.rsp_info.src_ch = ref_ch; algo->reference.rsp_info.src_rate = ref_sample_rate; ESP_LOGI(TAG, "reset channel number of reference signal: %d, sample rate of reference signal %d", ref_ch, ref_sample_rate); } return ESP_OK; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/algorithm_stream.c
C
apache-2.0
29,242
# # "main" pseudo-component makefile. # # (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/component.mk
Makefile
apache-2.0
147
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <sys/unistd.h> #include <sys/stat.h> #include <stdio.h> #include <string.h> #include "errno.h" #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "fatfs_stream.h" #include "audio_common.h" #include "audio_mem.h" #include "audio_element.h" #include "wav_head.h" #include "esp_log.h" #include "unistd.h" #include "fcntl.h" #define FILE_WAV_SUFFIX_TYPE "wav" #define FILE_OPUS_SUFFIX_TYPE "opus" #define FILE_AMR_SUFFIX_TYPE "amr" #define FILE_AMRWB_SUFFIX_TYPE "Wamr" static const char *TAG = "FATFS_STREAM"; typedef enum { STREAM_TYPE_UNKNOW, STREAM_TYPE_WAV, STREAM_TYPE_OPUS, STREAM_TYPE_AMR, STREAM_TYPE_AMRWB, } wr_stream_type_t; typedef struct fatfs_stream { audio_stream_type_t type; int block_size; bool is_open; int file; wr_stream_type_t w_type; bool write_header; } fatfs_stream_t; static wr_stream_type_t get_type(const char *str) { char *relt = strrchr(str, '.'); if (relt != NULL) { relt ++; ESP_LOGD(TAG, "result = %s", relt); if (strncasecmp(relt, FILE_WAV_SUFFIX_TYPE, 3) == 0) { return STREAM_TYPE_WAV; } else if (strncasecmp(relt, FILE_OPUS_SUFFIX_TYPE, 4) == 0) { return STREAM_TYPE_OPUS; } else if (strncasecmp(relt, FILE_AMR_SUFFIX_TYPE, 3) == 0) { return STREAM_TYPE_AMR; } else if (strncasecmp(relt, FILE_AMRWB_SUFFIX_TYPE, 4) == 0) { return STREAM_TYPE_AMRWB; } else { return STREAM_TYPE_UNKNOW; } } else { return STREAM_TYPE_UNKNOW; } } static esp_err_t _fatfs_open(audio_element_handle_t self) { fatfs_stream_t *fatfs = (fatfs_stream_t *)audio_element_getdata(self); audio_element_info_t info; char *uri = audio_element_get_uri(self); if (uri == NULL) { ESP_LOGE(TAG, "Error, uri is not set"); return ESP_FAIL; } ESP_LOGD(TAG, "_fatfs_open, uri:%s", uri); char *path = strstr(uri, "/sdcard"); audio_element_getinfo(self, &info); if (path == NULL) { ESP_LOGE(TAG, "Error, need file path to open"); return ESP_FAIL; } if (fatfs->is_open) { ESP_LOGE(TAG, "already opened"); return ESP_FAIL; } if (fatfs->type == AUDIO_STREAM_READER) { fatfs->file = open(path, O_RDONLY); if (fatfs->file == -1) { ESP_LOGE(TAG, "Failed to open. File name: %s, error message: %s, line: %d", path, strerror(errno), __LINE__); return ESP_FAIL; } struct stat siz = { 0 }; stat(path, &siz); info.total_bytes = siz.st_size; ESP_LOGI(TAG, "File size: %d byte, file position: %d", (int)siz.st_size, (int)info.byte_pos); if (info.byte_pos > 0) { if (lseek(fatfs->file, info.byte_pos, SEEK_SET) < 0) { ESP_LOGE(TAG, "Error seek file. Error message: %s, line: %d", strerror(errno), __LINE__); return ESP_FAIL; } } } else if (fatfs->type == AUDIO_STREAM_WRITER) { fatfs->file = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU); if (fatfs->file == -1) { ESP_LOGE(TAG, "Failed to open. File name: %s, error message: %s, line: %d", path, strerror(errno), __LINE__); return ESP_FAIL; } fatfs->w_type = get_type(path); if ((STREAM_TYPE_WAV == fatfs->w_type) && (fatfs->write_header == true)) { wav_header_t info = {0}; write(fatfs->file, &info, sizeof(wav_header_t)); fsync(fatfs->file); } else if ((STREAM_TYPE_AMR == fatfs->w_type) && (fatfs->write_header == true)) { write(fatfs->file, "#!AMR\n", 6); fsync(fatfs->file); } else if ((STREAM_TYPE_AMRWB == fatfs->w_type) && (fatfs->write_header == true)) { write(fatfs->file, "#!AMR-WB\n", 9); fsync(fatfs->file); } } else { ESP_LOGE(TAG, "FATFS must be Reader or Writer"); return ESP_FAIL; } fatfs->is_open = true; int ret = audio_element_set_total_bytes(self, info.total_bytes); return ret; } static int _fatfs_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context) { fatfs_stream_t *fatfs = (fatfs_stream_t *)audio_element_getdata(self); audio_element_info_t info; audio_element_getinfo(self, &info); ESP_LOGD(TAG, "read len=%d, pos=%d/%d", len, (int)info.byte_pos, (int)info.total_bytes); /* use file descriptors to access files */ int rlen = read(fatfs->file, buffer, len); if (rlen == 0) { ESP_LOGW(TAG, "No more data, ret:%d", rlen); } else if (rlen == -1) { ESP_LOGE(TAG, "The error is happened in reading data. Error message: %s", strerror(errno)); } else { audio_element_update_byte_pos(self, rlen); } return rlen; } static int _fatfs_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context) { fatfs_stream_t *fatfs = (fatfs_stream_t *)audio_element_getdata(self); audio_element_info_t info; audio_element_getinfo(self, &info); int wlen = write(fatfs->file, buffer, len); fsync(fatfs->file); if (wlen > 0) { audio_element_update_byte_pos(self, wlen); } if (wlen == -1) { ESP_LOGE(TAG, "The error is happened in writing data. Error message: %s", strerror(errno)); } return wlen; } static int _fatfs_process(audio_element_handle_t self, char *in_buffer, int in_len) { int r_size = audio_element_input(self, in_buffer, in_len); int w_size = 0; if (r_size > 0) { w_size = audio_element_output(self, in_buffer, r_size); } else { w_size = r_size; } return w_size; } static esp_err_t _fatfs_close(audio_element_handle_t self) { fatfs_stream_t *fatfs = (fatfs_stream_t *)audio_element_getdata(self); if (AUDIO_STREAM_WRITER == fatfs->type && (-1 != fatfs->file) && (true == fatfs->write_header) && STREAM_TYPE_WAV == fatfs->w_type) { wav_header_t *wav_info = (wav_header_t *) audio_malloc(sizeof(wav_header_t)); AUDIO_MEM_CHECK(TAG, wav_info, return ESP_ERR_NO_MEM); if (lseek(fatfs->file, 0, SEEK_SET) < 0) { ESP_LOGE(TAG, "Error seek file. Error message: %s, line: %d", strerror(errno), __LINE__); } audio_element_info_t info; audio_element_getinfo(self, &info); wav_head_init(wav_info, info.sample_rates, info.bits, info.channels); wav_head_size(wav_info, (uint32_t)info.byte_pos); write(fatfs->file, wav_info, sizeof(wav_header_t)); fsync(fatfs->file); audio_free(wav_info); } if (fatfs->is_open) { close(fatfs->file); fatfs->is_open = false; } if (AEL_STATE_PAUSED != audio_element_get_state(self)) { audio_element_report_info(self); audio_element_set_byte_pos(self, 0); } return ESP_OK; } static esp_err_t _fatfs_destroy(audio_element_handle_t self) { fatfs_stream_t *fatfs = (fatfs_stream_t *)audio_element_getdata(self); audio_free(fatfs); return ESP_OK; } audio_element_handle_t fatfs_stream_init(fatfs_stream_cfg_t *config) { audio_element_handle_t el; fatfs_stream_t *fatfs = audio_calloc(1, sizeof(fatfs_stream_t)); AUDIO_MEM_CHECK(TAG, fatfs, return NULL); audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG(); cfg.open = _fatfs_open; cfg.close = _fatfs_close; cfg.process = _fatfs_process; cfg.destroy = _fatfs_destroy; cfg.task_stack = config->task_stack; cfg.task_prio = config->task_prio; cfg.task_core = config->task_core; cfg.out_rb_size = config->out_rb_size; cfg.buffer_len = config->buf_sz; cfg.stack_in_ext = config->ext_stack; if (cfg.buffer_len == 0) { cfg.buffer_len = FATFS_STREAM_BUF_SIZE; } cfg.tag = "file"; fatfs->type = config->type; fatfs->write_header = config->write_header; if (config->type == AUDIO_STREAM_WRITER) { cfg.write = _fatfs_write; } else { cfg.read = _fatfs_read; } el = audio_element_init(&cfg); AUDIO_MEM_CHECK(TAG, el, goto _fatfs_init_exit); audio_element_setdata(el, fatfs); return el; _fatfs_init_exit: audio_free(fatfs); return NULL; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/fatfs_stream.c
C
apache-2.0
9,594
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <sys/unistd.h> #include <sys/stat.h> #include <string.h> #include "audio_mem.h" #include "hls_playlist.h" #include "esp_log.h" #include "errno.h" static const char *TAG = "HLS_PLAYLIST"; #define MAX_PLAYLIST_TRACKS (128) #define MAX_PLAYLIST_KEEP_TRACKS (18) typedef struct track_ { char *uri; bool is_played; STAILQ_ENTRY(track_) next; } track_t; static void hls_remove_played_entry(playlist_t *playlist) { track_t *track; /* Remove head entry if total_entries are > MAX_PLAYLIST_KEEP_TRACKS */ if (playlist->total_tracks > MAX_PLAYLIST_KEEP_TRACKS) { track = STAILQ_FIRST(&playlist->tracks); if (track->is_played) { STAILQ_REMOVE_HEAD(&playlist->tracks, next); audio_free(track->uri); audio_free(track); playlist->total_tracks--; } } } void hls_playlist_insert(playlist_t *playlist, char *track_uri) { track_t *track; const char *host_uri = (const char *) playlist->host_uri; while (playlist->total_tracks > MAX_PLAYLIST_TRACKS) { track = STAILQ_FIRST(&playlist->tracks); if (track == NULL) { break; } STAILQ_REMOVE(&playlist->tracks, track, track_, next); ESP_LOGD(TAG, "Remove %s", track->uri); audio_free(track->uri); audio_free(track); playlist->total_tracks --; } track = audio_calloc(1, sizeof(track_t)); if (track == NULL) { return; } if (strstr(track_uri, "http") == track_uri) { // Full URI track->uri = audio_strdup(track_uri); } else if (strstr(track_uri, "//") == track_uri) { // schemeless URI if (strstr(host_uri, "https") == host_uri) { asprintf(&track->uri, "https:%s", track_uri); } else { asprintf(&track->uri, "http:%s", track_uri); } } else if (strstr(track_uri, "/") == track_uri) { // Root uri char *url = audio_strdup(host_uri); if (url == NULL) { return; } char *host = strstr(url, "//"); if (host == NULL) { audio_free(url); return; } host += 2; char *path = strstr(host, "/"); if (path == NULL) { audio_free(url); return; } path[0] = 0; asprintf(&track->uri, "%s%s", url, track_uri); audio_free(url); } else { // Relative URI char *url = audio_strdup(host_uri); if (url == NULL) { return; } char *pos = strrchr(url, '/'); // Search for last "/" if (pos == NULL) { audio_free(url); return; } pos[1] = '\0'; asprintf(&track->uri, "%s%s", url, track_uri); audio_free(url); } if (track->uri == NULL) { ESP_LOGE(TAG, "Error insert URI to playlist"); audio_free(track); return; } track_t *find = NULL; STAILQ_FOREACH(find, &playlist->tracks, next) { if (strcmp(find->uri, track->uri) == 0) { ESP_LOGW(TAG, "URI exist"); audio_free(track->uri); audio_free(track); return; } } ESP_LOGD(TAG, "INSERT %s", track->uri); STAILQ_INSERT_TAIL(&playlist->tracks, track, next); playlist->total_tracks++; hls_remove_played_entry(playlist); } char *hls_playlist_get_next_track(playlist_t *playlist) { track_t *track; hls_remove_played_entry(playlist); /* Find not played entry. */ STAILQ_FOREACH(track, &playlist->tracks, next) { if (!track->is_played) { track->is_played = true; return track->uri; } } return NULL; } void hls_playlist_clear(playlist_t *playlist) { track_t *track, *tmp; STAILQ_FOREACH_SAFE(track, &playlist->tracks, next, tmp) { STAILQ_REMOVE(&playlist->tracks, track, track_, next); audio_free(track->uri); audio_free(track); } if (playlist->host_uri) { audio_free(playlist->host_uri); playlist->host_uri = NULL; } playlist->is_incomplete = false; playlist->total_tracks = 0; playlist->total_read = 0; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/hls_playlist.c
C
apache-2.0
5,409
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _HLS_PLAYLIST_H_ #define _HLS_PLAYLIST_H_ #ifdef __cplusplus extern "C" { #endif #include "esp_err.h" #include "stdbool.h" #include "sys/queue.h" struct track_; // Forward declaration typedef STAILQ_HEAD(track_list, track_) track_list_t; typedef struct { char *host_uri; char *data; int index; int remain; int total_read; track_list_t tracks; int total_tracks; int content_length; bool is_incomplete; /* Indicates if playlist is live stream and must be fetched again */ } playlist_t; /** * @brief Insert a track into hls_playlist * * @param playlist playlist handle * @param track_uri Track URI to be inserted in playlist * */ void hls_playlist_insert(playlist_t *playlist, char *track_uri); /** * @brief Get next not-played track from playlist * * @param playlist playlist handle * * @return * - NULL if no playable track * - Playable track * * @note returned track must `not` be freed by application */ char *hls_playlist_get_next_track(playlist_t *playlist); /** * @brief Clear all the tracks from playlist * * @param playlist playlist handle * */ void hls_playlist_clear(playlist_t *playlist); #ifdef __cplusplus } #endif #endif /* #ifndef _HLS_PLAYLIST_H_ */
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/hls_playlist.h
C
apache-2.0
2,633
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include "http_stream.h" #include <string.h> #include <strings.h> #include <sys/stat.h> #include <sys/unistd.h> #include "audio_element.h" #include "audio_mem.h" #include "esp_http_client.h" #include "esp_log.h" #include "esp_system.h" #include "freertos/FreeRTOS.h" #include "freertos/ringbuf.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "hls_playlist.h" static const char *TAG = "HTTP_STREAM"; #define MAX_PLAYLIST_LINE_SIZE (512) #define HTTP_STREAM_BUFFER_SIZE (2048) #define HTTP_MAX_CONNECT_TIMES (5) typedef struct http_stream { audio_stream_type_t type; bool is_open; esp_http_client_handle_t client; http_stream_event_handle_t hook; audio_stream_type_t stream_type; void *user_data; bool enable_playlist_parser; bool auto_connect_next_track; /* connect next track without open/close */ bool is_variant_playlist; bool is_playlist_resolved; playlist_t *variant_playlist; /* contains more playlists */ playlist_t *playlist; /* media playlist */ int _errno; int connect_times; } http_stream_t; static esp_err_t http_stream_auto_connect_next_track(audio_element_handle_t el); static esp_codec_type_t get_audio_type(const char *content_type) { if (strcasecmp(content_type, "mp3") == 0 || strcasecmp(content_type, "audio/mp3") == 0 || strcasecmp(content_type, "audio/mpeg") == 0 || strcasecmp(content_type, "binary/octet-stream") == 0 || strcasecmp(content_type, "application/octet-stream") == 0) { return ESP_CODEC_TYPE_MP3; } if (strcasecmp(content_type, "audio/aac") == 0 || strcasecmp(content_type, "audio/x-aac") == 0 || strcasecmp(content_type, "audio/mp4") == 0 || strcasecmp(content_type, "audio/aacp") == 0 || strcasecmp(content_type, "video/MP2T") == 0) { return ESP_CODEC_TYPE_AAC; } if (strcasecmp(content_type, "audio/wav") == 0) { return ESP_CODEC_TYPE_WAV; } if (strcasecmp(content_type, "audio/opus") == 0) { return ESP_CODEC_TYPE_OPUS; } if (strcasecmp(content_type, "application/vnd.apple.mpegurl") == 0 || strcasecmp(content_type, "vnd.apple.mpegURL") == 0) { return ESP_AUDIO_TYPE_M3U8; } if (strncasecmp(content_type, "audio/x-scpls", strlen("audio/x-scpls")) == 0) { return ESP_AUDIO_TYPE_PLS; } return ESP_CODEC_TYPE_UNKNOW; } static esp_err_t _http_event_handle(esp_http_client_event_t *evt) { audio_element_handle_t el = (audio_element_handle_t)evt->user_data; if (evt->event_id != HTTP_EVENT_ON_HEADER) { return ESP_OK; } if (strcasecmp(evt->header_key, "Content-Type") == 0) { ESP_LOGD(TAG, "%s = %s", evt->header_key, evt->header_value); audio_element_set_codec_fmt(el, get_audio_type(evt->header_value)); } return ESP_OK; } static int dispatch_hook(audio_element_handle_t self, http_stream_event_id_t type, void *buffer, int buffer_len) { http_stream_t *http_stream = (http_stream_t *)audio_element_getdata(self); http_stream_event_msg_t msg; msg.event_id = type; msg.http_client = http_stream->client; msg.user_data = http_stream->user_data; msg.buffer = buffer; msg.buffer_len = buffer_len; msg.el = self; if (http_stream->hook) { return http_stream->hook(&msg); } return ESP_OK; } static bool _is_playlist(audio_element_info_t *info, const char *uri) { if (info->codec_fmt == ESP_AUDIO_TYPE_M3U8 || info->codec_fmt == ESP_AUDIO_TYPE_PLS) { return true; } char *dot = strrchr(uri, '.'); if (dot && (strcasecmp(dot, ".m3u") == 0 || strcasecmp(dot, ".m3u8") == 0)) { return true; } return false; } static bool _get_line_in_buffer(http_stream_t *http, char **out) { *out = NULL; char c; if (http->playlist->remain > 0) { bool is_end_of_line = false; *out = http->playlist->data + http->playlist->index; int idx = http->playlist->index; while ((c = http->playlist->data[idx])) { if (c == '\r' || c == '\n') { http->playlist->data[idx] = 0; is_end_of_line = true; } else if (is_end_of_line) { http->playlist->remain -= idx - http->playlist->index; http->playlist->index = idx; return true; } idx++; } if (http->playlist->total_read >= http->playlist->content_length) { http->playlist->remain = 0; return true; // This is the last remaining line } } return false; } static char *_client_read_line(http_stream_t *http) { int need_read = MAX_PLAYLIST_LINE_SIZE; int rlen; char *line; if (_get_line_in_buffer(http, &line)) { return line; } if (http->playlist->total_read >= http->playlist->content_length) { return NULL; } need_read -= http->playlist->remain; if (need_read > 0) { if (http->playlist->remain > 0) { memmove(http->playlist->data, http->playlist->data + http->playlist->index, http->playlist->remain); http->playlist->index = 0; } rlen = esp_http_client_read(http->client, http->playlist->data + http->playlist->remain, need_read); if (rlen > 0) { http->playlist->remain += rlen; http->playlist->total_read += rlen; http->playlist->data[http->playlist->remain] = '\0'; if (_get_line_in_buffer(http, &line)) { return line; } } else { ESP_LOGD(TAG, "Finish reading data, rlen:%d", rlen); line = NULL; } } return line; } static esp_err_t _resolve_playlist(audio_element_handle_t self, const char *uri) { audio_element_info_t info; http_stream_t *http = (http_stream_t *)audio_element_getdata(self); audio_element_getinfo(self, &info); if (http->is_playlist_resolved && http->is_variant_playlist) { // We do not support more than 2 levels of redirection in m3u. return ESP_ERR_INVALID_STATE; } if (http->is_playlist_resolved) { /** * The one we resolved is variant playlist * We need to move this playlist to variant_playlist and parse this one. */ /* If there already is a variant data, free it */ hls_playlist_clear(http->variant_playlist); http->is_variant_playlist = true; http->is_playlist_resolved = false; playlist_t *tmp = http->variant_playlist; http->variant_playlist = http->playlist; http->playlist = tmp; } http->playlist->content_length = info.total_bytes; http->playlist->remain = 0; http->playlist->index = 0; http->playlist->total_read = 0; if (http->playlist->host_uri) { audio_free(http->playlist->host_uri); } http->playlist->host_uri = audio_strdup(uri); char *line = NULL; bool valid_playlist = false; bool is_playlist_uri = false; if (info.codec_fmt == ESP_AUDIO_TYPE_PLS) { /* pls playlist */ while ((line = _client_read_line(http))) { ESP_LOGD(TAG, "Playlist line = %s", line); if (!strncmp(line, "File", sizeof("File") - 1)) { // this line contains url int i = 4; while (line[i++] != '=') ; // Skip till '=' hls_playlist_insert(http->playlist, line + i); } else { /* Ignore all other lines */ } } return ESP_OK; } /* M3U8 playlist */ http->playlist->is_incomplete = true; #define ENDLIST_TAG "#EXT-X-ENDLIST" #define VARIANT_TAG "#EXT-X-STREAM-INF" while ((line = _client_read_line(http))) { ESP_LOGD(TAG, "Playlist line = %s", line); if (!valid_playlist && strcmp(line, "#EXTM3U") == 0) { valid_playlist = true; continue; } if (strstr(line, "http") == (void *)line) { hls_playlist_insert(http->playlist, line); valid_playlist = true; continue; } if (!valid_playlist) { break; } if (!is_playlist_uri && strstr(line, "#EXTINF") == (void *)line) { is_playlist_uri = true; continue; } else if (!is_playlist_uri && strstr(line, VARIANT_TAG) == (void *)line) { /** * Non-standard attribute. * There are multiple variants of audios. We do not support this for now. */ is_playlist_uri = true; continue; } else if (strstr(line, ENDLIST_TAG) == (void *)line) { /* Got the ENDLIST_TAG, mark our playlist as complete and break! */ http->playlist->is_incomplete = false; break; } else if (strncmp(line, "#", 1) == 0) { /** * Some other playlist field we don't support. * Simply treat this as a comment and continue to find next line. */ continue; } if (!is_playlist_uri) { continue; } is_playlist_uri = false; hls_playlist_insert(http->playlist, line); } if (http->playlist->is_incomplete) { ESP_LOGI(TAG, "Live stream URI. Need to be fetched again!"); } return valid_playlist ? ESP_OK : ESP_FAIL; } static char *_playlist_get_next_track(audio_element_handle_t self) { http_stream_t *http = (http_stream_t *)audio_element_getdata(self); if (http->enable_playlist_parser && http->is_playlist_resolved) { return hls_playlist_get_next_track(http->playlist); } return NULL; } static esp_err_t _http_open(audio_element_handle_t self) { http_stream_t *http = (http_stream_t *)audio_element_getdata(self); esp_err_t err; char *uri = NULL; audio_element_info_t info; ESP_LOGD(TAG, "_http_open"); if (http->is_open) { ESP_LOGE(TAG, "already opened"); return ESP_FAIL; } http->_errno = 0; _stream_open_begin: uri = _playlist_get_next_track(self); if (uri == NULL) { if (http->is_playlist_resolved && http->enable_playlist_parser) { if (dispatch_hook(self, HTTP_STREAM_FINISH_PLAYLIST, NULL, 0) != ESP_OK) { ESP_LOGE(TAG, "Failed to process user callback"); return ESP_FAIL; } goto _stream_open_begin; } uri = audio_element_get_uri(self); } if (uri == NULL) { ESP_LOGE(TAG, "Error open connection, uri = NULL"); return ESP_FAIL; } audio_element_getinfo(self, &info); ESP_LOGD(TAG, "URI=%s", uri); // if not initialize http client, initial it if (http->client == NULL) { esp_http_client_config_t http_cfg = { .url = uri, .event_handler = _http_event_handle, .user_data = self, .timeout_ms = 30 * 1000, .buffer_size = HTTP_STREAM_BUFFER_SIZE, }; http->client = esp_http_client_init(&http_cfg); AUDIO_MEM_CHECK(TAG, http->client, return ESP_ERR_NO_MEM); } else { esp_http_client_set_url(http->client, uri); } if (info.byte_pos) { char rang_header[32]; snprintf(rang_header, 32, "bytes=%d-", (int)info.byte_pos); esp_http_client_set_header(http->client, "Range", rang_header); } if (dispatch_hook(self, HTTP_STREAM_PRE_REQUEST, NULL, 0) != ESP_OK) { ESP_LOGE(TAG, "Failed to process user callback"); return ESP_FAIL; } if (http->stream_type == AUDIO_STREAM_WRITER) { err = esp_http_client_open(http->client, -1); if (err == ESP_OK) { http->is_open = true; } return err; } char *buffer = NULL; int post_len = esp_http_client_get_post_field(http->client, &buffer); _stream_redirect: if ((err = esp_http_client_open(http->client, post_len)) != ESP_OK) { ESP_LOGE(TAG, "Failed to open http stream"); return err; } int wrlen = dispatch_hook(self, HTTP_STREAM_ON_REQUEST, buffer, post_len); if (wrlen < 0) { ESP_LOGE(TAG, "Failed to process user callback"); return ESP_FAIL; } if (post_len && buffer && wrlen == 0) { if (esp_http_client_write(http->client, buffer, post_len) <= 0) { ESP_LOGE(TAG, "Failed to write data to http stream"); return ESP_FAIL; } ESP_LOGD(TAG, "len=%d, data=%s", post_len, buffer); } if (dispatch_hook(self, HTTP_STREAM_POST_REQUEST, NULL, 0) < 0) { esp_http_client_close(http->client); return ESP_FAIL; } /* * Due to the total byte of content has been changed after seek, set info.total_bytes at beginning only. */ int64_t cur_pos = esp_http_client_fetch_headers(http->client); audio_element_getinfo(self, &info); if (info.byte_pos <= 0) { info.total_bytes = cur_pos; } ESP_LOGI(TAG, "total_bytes=%d", (int)info.total_bytes); int status_code = esp_http_client_get_status_code(http->client); if (status_code == 301 || status_code == 302) { esp_http_client_set_redirection(http->client); goto _stream_redirect; } if (status_code != 200 && (esp_http_client_get_status_code(http->client) != 206)) { ESP_LOGE(TAG, "Invalid HTTP stream, status code = %d", status_code); if (http->enable_playlist_parser) { hls_playlist_clear(http->playlist); http->is_playlist_resolved = false; hls_playlist_clear(http->variant_playlist); http->is_variant_playlist = false; } return ESP_FAIL; } /** * `audio_element_setinfo` is risky affair. * It overwrites URI pointer as well. Pay attention to that! */ audio_element_set_total_bytes(self, info.total_bytes); if (_is_playlist(&info, uri) == true) { /** * `goto _stream_open_begin` blocks on http_open until it gets valid URL. * Ensure that the stop command is processed */ if (audio_element_is_stopping(self) == true) { ESP_LOGW(TAG, "Http_open got stop cmd at opening"); return ESP_OK; } if (_resolve_playlist(self, uri) == ESP_OK) { http->is_playlist_resolved = true; goto _stream_open_begin; } } http->is_open = true; audio_element_report_codec_fmt(self); return ESP_OK; } static esp_err_t _http_close(audio_element_handle_t self) { http_stream_t *http = (http_stream_t *)audio_element_getdata(self); ESP_LOGD(TAG, "_http_close"); while (http->is_open) { http->is_open = false; if (http->stream_type != AUDIO_STREAM_WRITER) { break; } if (dispatch_hook(self, HTTP_STREAM_POST_REQUEST, NULL, 0) < 0) { break; } esp_http_client_fetch_headers(http->client); if (dispatch_hook(self, HTTP_STREAM_FINISH_REQUEST, NULL, 0) < 0) { break; } } if (http->enable_playlist_parser) { hls_playlist_clear(http->playlist); hls_playlist_clear(http->variant_playlist); http->is_variant_playlist = false; http->is_playlist_resolved = false; } if (AEL_STATE_PAUSED != audio_element_get_state(self)) { audio_element_report_pos(self); audio_element_set_byte_pos(self, 0); } if (http->client) { esp_http_client_close(http->client); esp_http_client_cleanup(http->client); http->client = NULL; } return ESP_OK; } static esp_err_t _http_reconnect(audio_element_handle_t self) { esp_err_t err = ESP_OK; audio_element_info_t info = { 0 }; AUDIO_NULL_CHECK(TAG, self, return ESP_FAIL); err |= audio_element_getinfo(self, &info); err |= _http_close(self); err |= audio_element_set_byte_pos(self, info.byte_pos); err |= _http_open(self); return err; } static int _http_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context) { http_stream_t *http = (http_stream_t *)audio_element_getdata(self); audio_element_info_t info; audio_element_getinfo(self, &info); int wrlen = dispatch_hook(self, HTTP_STREAM_ON_RESPONSE, buffer, len); int rlen = wrlen; if (rlen == 0) { rlen = esp_http_client_read(http->client, buffer, len); } if (rlen <= 0 && http->auto_connect_next_track) { if (http_stream_auto_connect_next_track(self) == ESP_OK) { rlen = esp_http_client_read(http->client, buffer, len); } } if (rlen <= 0) { http->_errno = esp_http_client_get_errno(http->client); ESP_LOGW(TAG, "No more data,errno:%d, total_bytes:%llu, rlen = %d", http->_errno, info.byte_pos, rlen); if (http->_errno != 0) { // Error occuered, reset connection ESP_LOGW(TAG, "Got %d errno(%s)", http->_errno, strerror(http->_errno)); return http->_errno; } if (http->auto_connect_next_track) { if (dispatch_hook(self, HTTP_STREAM_FINISH_PLAYLIST, NULL, 0) != ESP_OK) { ESP_LOGE(TAG, "Failed to process user callback"); return ESP_FAIL; } } else { if (dispatch_hook(self, HTTP_STREAM_FINISH_TRACK, NULL, 0) != ESP_OK) { ESP_LOGE(TAG, "Failed to process user callback"); return ESP_FAIL; } } return ESP_OK; } else { audio_element_update_byte_pos(self, rlen); } ESP_LOGD(TAG, "req lengh=%d, read=%d, pos=%d/%d", len, rlen, (int)info.byte_pos, (int)info.total_bytes); return rlen; } static int _http_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context) { http_stream_t *http = (http_stream_t *)audio_element_getdata(self); int wrlen = dispatch_hook(self, HTTP_STREAM_ON_REQUEST, buffer, len); if (wrlen < 0) { ESP_LOGE(TAG, "Failed to process user callback"); return ESP_FAIL; } if (wrlen > 0) { return wrlen; } if ((wrlen = esp_http_client_write(http->client, buffer, len)) <= 0) { http->_errno = esp_http_client_get_errno(http->client); ESP_LOGE(TAG, "Failed to write data to http stream, wrlen=%d, errno=%d(%s)", wrlen, http->_errno, strerror(http->_errno)); } return wrlen; } static int _http_process(audio_element_handle_t self, char *in_buffer, int in_len) { int r_size = audio_element_input(self, in_buffer, in_len); if (audio_element_is_stopping(self) == true) { ESP_LOGW(TAG, "No output due to stopping"); return AEL_IO_ABORT; } int w_size = 0; if (r_size > 0) { http_stream_t *http = (http_stream_t *)audio_element_getdata(self); if (http->_errno != 0) { esp_err_t ret = ESP_OK; if (http->connect_times > HTTP_MAX_CONNECT_TIMES) { ESP_LOGE(TAG, "reconnect times more than %d, disconnect http stream", HTTP_MAX_CONNECT_TIMES); return ESP_FAIL; }; http->connect_times++; ret = _http_reconnect(self); if (ret != ESP_OK) { ESP_LOGE(TAG, "Failed to reset connection"); return ret; } ESP_LOGW(TAG, "reconnect to peer successful"); return ESP_ERR_INVALID_STATE; } else { http->connect_times = 0; w_size = audio_element_output(self, in_buffer, r_size); audio_element_multi_output(self, in_buffer, r_size, 0); } } else { w_size = r_size; } return w_size; } static esp_err_t _http_destroy(audio_element_handle_t self) { http_stream_t *http = (http_stream_t *)audio_element_getdata(self); if (http->playlist) { audio_free(http->playlist->data); audio_free(http->playlist); } if (http->variant_playlist) { audio_free(http->variant_playlist->data); audio_free(http->variant_playlist); } audio_free(http); return ESP_OK; } audio_element_handle_t http_stream_init(http_stream_cfg_t *config) { audio_element_handle_t el; http_stream_t *http = audio_calloc(1, sizeof(http_stream_t)); AUDIO_MEM_CHECK(TAG, http, return NULL); audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG(); cfg.open = _http_open; cfg.close = _http_close; cfg.process = _http_process; cfg.destroy = _http_destroy; cfg.task_stack = config->task_stack; cfg.task_prio = config->task_prio; cfg.task_core = config->task_core; cfg.stack_in_ext = config->stack_in_ext; cfg.out_rb_size = config->out_rb_size; cfg.multi_out_rb_num = config->multi_out_num; cfg.tag = "http"; http->type = config->type; http->enable_playlist_parser = config->enable_playlist_parser; http->auto_connect_next_track = config->auto_connect_next_track; http->hook = config->event_handle; http->stream_type = config->type; http->user_data = config->user_data; if (http->enable_playlist_parser) { http->playlist = audio_calloc(1, sizeof(playlist_t)); AUDIO_MEM_CHECK(TAG, http->playlist, { audio_free(http); return NULL; }); http->playlist->data = audio_calloc(1, MAX_PLAYLIST_LINE_SIZE + 1); AUDIO_MEM_CHECK(TAG, http->playlist->data, { audio_free(http->playlist); audio_free(http); return NULL; }); STAILQ_INIT(&http->playlist->tracks); http->variant_playlist = audio_calloc(1, sizeof(playlist_t)); AUDIO_MEM_CHECK(TAG, http->variant_playlist, { audio_free(http->playlist); audio_free(http); return NULL; }); http->variant_playlist->data = audio_calloc(1, MAX_PLAYLIST_LINE_SIZE + 1); AUDIO_MEM_CHECK(TAG, http->variant_playlist->data, { audio_free(http->playlist); audio_free(http->variant_playlist); audio_free(http); return NULL; }); STAILQ_INIT(&http->variant_playlist->tracks); } if (config->type == AUDIO_STREAM_READER) { cfg.read = _http_read; } else if (config->type == AUDIO_STREAM_WRITER) { cfg.write = _http_write; } el = audio_element_init(&cfg); AUDIO_MEM_CHECK(TAG, el, { audio_free(http->playlist); audio_free(http->variant_playlist); audio_free(http); return NULL; }); audio_element_setdata(el, http); return el; } esp_err_t http_stream_next_track(audio_element_handle_t el) { http_stream_t *http = (http_stream_t *)audio_element_getdata(el); if (!(http->enable_playlist_parser && http->is_playlist_resolved)) { /** * This is not a playlist! * Do not reset states for restart element. * Just return. */ ESP_LOGD(TAG, "Direct URI. Stream will be stopped"); return ESP_OK; } audio_element_reset_state(el); audio_element_set_byte_pos(el, 0); audio_element_set_total_bytes(el, 0); http->is_open = false; return ESP_OK; } esp_err_t http_stream_auto_connect_next_track(audio_element_handle_t el) { audio_element_info_t info; audio_element_getinfo(el, &info); http_stream_t *http = (http_stream_t *)audio_element_getdata(el); char *track = _playlist_get_next_track(el); if (track) { esp_http_client_set_url(http->client, track); char *buffer = NULL; int post_len = esp_http_client_get_post_field(http->client, &buffer); redirection: if ((esp_http_client_open(http->client, post_len)) != ESP_OK) { ESP_LOGE(TAG, "Failed to open http stream"); return ESP_FAIL; } if (dispatch_hook(el, HTTP_STREAM_POST_REQUEST, NULL, 0) < 0) { esp_http_client_close(http->client); return ESP_FAIL; } info.total_bytes = esp_http_client_fetch_headers(http->client); ESP_LOGD(TAG, "total_bytes=%d", (int)info.total_bytes); int status_code = esp_http_client_get_status_code(http->client); if (status_code == 301 || status_code == 302) { esp_http_client_set_redirection(http->client); goto redirection; } return ESP_OK; } return ESP_FAIL; } esp_err_t http_stream_fetch_again(audio_element_handle_t el) { http_stream_t *http = (http_stream_t *)audio_element_getdata(el); if (!http->playlist->is_incomplete) { ESP_LOGI(TAG, "Finished playing."); return ESP_ERR_NOT_SUPPORTED; } else { ESP_LOGI(TAG, "Fetching again..."); audio_element_set_uri(el, http->playlist->host_uri); http->is_playlist_resolved = false; } return ESP_OK; } esp_err_t http_stream_restart(audio_element_handle_t el) { http_stream_t *http = (http_stream_t *)audio_element_getdata(el); http->is_playlist_resolved = false; return ESP_OK; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/http_stream.c
C
apache-2.0
26,359
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #include <stdlib.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/ringbuf.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "driver/i2s.h" #include "esp_log.h" #include "esp_err.h" #include "audio_common.h" #include "audio_mem.h" #include "audio_element.h" #include "i2s_stream.h" #include "esp_alc.h" #include "board_pins_config.h" static const char *TAG = "I2S_STREAM"; #if defined(ESP_IDF_VERSION) #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 2, 0)) #define SOC_I2S_SUPPORTS_ADC_DAC 1 #include "driver/dac.h" #endif #else #define SOC_I2S_SUPPORTS_ADC_DAC 1 #endif // defined(ESP_IDF_VERSION) typedef struct i2s_stream { audio_stream_type_t type; i2s_stream_cfg_t config; bool is_open; bool use_alc; void *volume_handle; int volume; bool uninstall_drv; } i2s_stream_t; #ifdef CONFIG_IDF_TARGET_ESP32 static esp_err_t i2s_mono_fix(int bits, uint8_t *sbuff, uint32_t len) { if (bits == 16) { int16_t *temp_buf = (int16_t *)sbuff; int16_t temp_box; int k = len >> 1; for (int i = 0; i < k; i += 2) { temp_box = temp_buf[i]; temp_buf[i] = temp_buf[i + 1]; temp_buf[i + 1] = temp_box; } } else if (bits == 32) { int32_t *temp_buf = (int32_t *)sbuff; int32_t temp_box; int k = len >> 2; for (int i = 0; i < k; i += 4) { temp_box = temp_buf[i]; temp_buf[i] = temp_buf[i + 1]; temp_buf[i + 1] = temp_box; } } else { ESP_LOGE(TAG, "%s %dbits is not supported", __func__, bits); return ESP_FAIL; } return ESP_OK; } #endif #if SOC_I2S_SUPPORTS_ADC_DAC /** * @brief Scale data to 16bit/32bit for I2S DMA output. * DAC can only output 8bit data value. * I2S DMA will still send 16bit or 32bit data, the highest 8bit contains DAC data. */ static int i2s_dac_data_scale(int bits, uint8_t *sBuff, uint32_t len) { if (bits == 16) { short *buf16 = (short *)sBuff; int k = len >> 1; for (int i = 0; i < k; i++) { buf16[i] &= 0xff00; buf16[i] += 0x8000;//turn signed value into unsigned, expand negative value into positive range } } else if (bits == 32) { int *buf32 = (int *)sBuff; int k = len >> 2; for (int i = 0; i < k; i++) { buf32[i] &= 0xff000000; buf32[i] += 0x80000000;//turn signed value into unsigned } } else { ESP_LOGE(TAG, "in %s %dbits is not supported", __func__, bits); return -1; } return 0; } #endif static int i2s_stream_clear_dma_buffer(audio_element_handle_t self) { i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(self); int index = i2s->config.i2s_config.dma_buf_count; uint8_t *buf = audio_calloc(1, i2s->config.i2s_config.dma_buf_len * 4); AUDIO_MEM_CHECK(TAG, buf, return ESP_ERR_NO_MEM); #if SOC_I2S_SUPPORTS_ADC_DAC if ((i2s->config.i2s_config.mode & I2S_MODE_DAC_BUILT_IN) != 0) { memset(buf, 0x80, i2s->config.i2s_config.dma_buf_len * 4); } #endif while (index--) { audio_element_output(self, (char *)buf, i2s->config.i2s_config.dma_buf_len * 4); } if (buf) { audio_free(buf); } return ESP_OK; } static esp_err_t _i2s_open(audio_element_handle_t self) { i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(self); ESP_LOGD(TAG, "_i2s_open %d", (int)i2s->config.i2s_port); if (i2s->is_open) { return ESP_OK; } if (i2s->type == AUDIO_STREAM_READER) { audio_element_info_t i2s_info = {0}; i2s_info.bits = 16; i2s_info.channels = 1; i2s_info.sample_rates = 16000; audio_element_getinfo(self, &i2s_info); ESP_LOGI(TAG, "AUDIO_STREAM_READER,Rate:%d,ch:%d", i2s_info.sample_rates, i2s_info.channels); if (i2s_set_clk(i2s->config.i2s_port, i2s_info.sample_rates, i2s_info.bits, i2s_info.channels) == ESP_FAIL) { ESP_LOGE(TAG, "i2s_set_clk failed, type = %d", i2s->config.type); return ESP_FAIL; } } else if (i2s->type == AUDIO_STREAM_WRITER) { audio_element_set_input_timeout(self, 10 / portTICK_RATE_MS); ESP_LOGI(TAG, "AUDIO_STREAM_WRITER"); } i2s->is_open = true; if (i2s->use_alc) { i2s->volume_handle = alc_volume_setup_open(); if (i2s->volume_handle == NULL) { ESP_LOGE(TAG, "i2s create the handle for setting volume failed, in line(%d)", __LINE__); return ESP_FAIL; } } return ESP_OK; } static esp_err_t _i2s_destroy(audio_element_handle_t self) { i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(self); if (i2s->uninstall_drv) { i2s_driver_uninstall(i2s->config.i2s_port); } audio_free(i2s); return ESP_OK; } static esp_err_t _i2s_close(audio_element_handle_t self) { i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(self); esp_err_t ret = i2s_stream_clear_dma_buffer(self); if (ret != ESP_OK) { return ret; } i2s->is_open = false; if (AEL_STATE_PAUSED != audio_element_get_state(self)) { audio_element_report_pos(self); audio_element_set_byte_pos(self, 0); } if (i2s->use_alc) { if (i2s->volume_handle != NULL) { alc_volume_setup_close(i2s->volume_handle); } } return ESP_OK; } static int _i2s_read(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context) { i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(self); size_t bytes_read = 0; i2s_read(i2s->config.i2s_port, buffer, len, &bytes_read, ticks_to_wait); audio_element_info_t info; audio_element_getinfo(self, &info); if (bytes_read > 0) { #ifdef CONFIG_IDF_TARGET_ESP32 if (info.channels == 1) { i2s_mono_fix(info.bits, (uint8_t *)buffer, bytes_read); } #endif } return bytes_read; } static int _i2s_write(audio_element_handle_t self, char *buffer, int len, TickType_t ticks_to_wait, void *context) { i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(self); len = len >> 2 << 2; size_t bytes_written = 0; audio_element_info_t info; audio_element_getinfo(self, &info); if (len > 0) { #ifdef CONFIG_IDF_TARGET_ESP32 if (info.channels == 1) { i2s_mono_fix(info.bits, (uint8_t *)buffer, len); } #endif #if SOC_I2S_SUPPORTS_ADC_DAC if ((i2s->config.i2s_config.mode & I2S_MODE_DAC_BUILT_IN) != 0) { i2s_dac_data_scale(info.bits, (uint8_t *)buffer, len); } #endif } i2s_write(i2s->config.i2s_port, buffer, len, &bytes_written, ticks_to_wait); return bytes_written; } static int _i2s_process(audio_element_handle_t self, char *in_buffer, int in_len) { int r_size = audio_element_input(self, in_buffer, in_len); int w_size = 0; i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(self); audio_element_info_t i2s_info = {0}; if (r_size == AEL_IO_TIMEOUT) { #if SOC_I2S_SUPPORTS_ADC_DAC if ((i2s->config.i2s_config.mode & I2S_MODE_DAC_BUILT_IN) != 0) { memset(in_buffer, 0x80, in_len); } else #endif { memset(in_buffer, 0x00, in_len); } r_size = in_len; } if ((r_size > 0)) { if (i2s->use_alc) { audio_element_getinfo(self, &i2s_info); alc_volume_setup_process(in_buffer, r_size, i2s_info.channels, i2s->volume_handle, i2s->volume); } audio_element_multi_output(self, in_buffer, r_size, 0); w_size = audio_element_output(self, in_buffer, r_size); audio_element_update_byte_pos(self, w_size); } else { esp_err_t ret = i2s_stream_clear_dma_buffer(self); if (ret != ESP_OK) { return ret; } w_size = r_size; } return w_size; } esp_err_t i2s_stream_set_clk(audio_element_handle_t i2s_stream, int rate, int bits, int ch) { esp_err_t err = ESP_OK; i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(i2s_stream); audio_element_state_t state = audio_element_get_state(i2s_stream); if (state == AEL_STATE_RUNNING) { audio_element_pause(i2s_stream); } audio_element_set_music_info(i2s_stream, rate, ch, bits); if (i2s_set_clk(i2s->config.i2s_port, rate, bits, ch) == ESP_FAIL) { ESP_LOGE(TAG, "i2s_set_clk failed, type = %d,port:%d", i2s->config.type, i2s->config.i2s_port); err = ESP_FAIL; } if (state == AEL_STATE_RUNNING) { audio_element_resume(i2s_stream, 0, 0); } return err; } int i2s_alc_volume_set(audio_element_handle_t i2s_stream, int volume) { i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(i2s_stream); if (i2s->use_alc) { i2s->volume = volume; return ESP_OK; } else { ESP_LOGW(TAG, "The ALC don't be used. It can not be set."); return ESP_FAIL; } } int i2s_alc_volume_get(audio_element_handle_t i2s_stream, int *volume) { i2s_stream_t *i2s = (i2s_stream_t *)audio_element_getdata(i2s_stream); if (i2s->use_alc) { *volume = i2s->volume; return ESP_OK; } else { ESP_LOGW(TAG, "The ALC don't be used"); return ESP_FAIL; } } audio_element_handle_t i2s_stream_init(i2s_stream_cfg_t *config) { audio_element_cfg_t cfg = DEFAULT_AUDIO_ELEMENT_CONFIG(); audio_element_handle_t el; cfg.open = _i2s_open; cfg.close = _i2s_close; cfg.process = _i2s_process; cfg.destroy = _i2s_destroy; cfg.task_stack = config->task_stack; cfg.task_prio = config->task_prio; cfg.task_core = config->task_core; cfg.stack_in_ext = config->stack_in_ext; cfg.out_rb_size = config->out_rb_size; cfg.multi_out_rb_num = config->multi_out_num; cfg.tag = "iis"; cfg.buffer_len = I2S_STREAM_BUF_SIZE; i2s_stream_t *i2s = audio_calloc(1, sizeof(i2s_stream_t)); AUDIO_MEM_CHECK(TAG, i2s, return NULL); memcpy(&i2s->config, config, sizeof(i2s_stream_cfg_t)); i2s->type = config->type; i2s->use_alc = config->use_alc; i2s->volume = config->volume; i2s->uninstall_drv = config->uninstall_drv; if (config->type == AUDIO_STREAM_READER) { cfg.read = _i2s_read; } else if (config->type == AUDIO_STREAM_WRITER) { cfg.write = _i2s_write; } esp_err_t ret = i2s_driver_install(i2s->config.i2s_port, &i2s->config.i2s_config, 0, NULL); if (ret != ESP_OK && ret != ESP_ERR_INVALID_STATE) { audio_free(i2s); return NULL; } el = audio_element_init(&cfg); AUDIO_MEM_CHECK(TAG, el, { audio_free(i2s); return NULL; }); audio_element_setdata(el, i2s); audio_element_set_music_info(el, config->i2s_config.sample_rate, config->i2s_config.channel_format < I2S_CHANNEL_FMT_ONLY_RIGHT ? 2 : 1, config->i2s_config.bits_per_sample); #if SOC_I2S_SUPPORTS_ADC_DAC if ((config->i2s_config.mode & I2S_MODE_DAC_BUILT_IN) != 0) { i2s_set_dac_mode(I2S_DAC_CHANNEL_BOTH_EN); } else #endif { i2s_pin_config_t i2s_pin_cfg = {0}; get_i2s_pins(i2s->config.i2s_port, &i2s_pin_cfg); i2s_set_pin(i2s->config.i2s_port, &i2s_pin_cfg); } i2s_mclk_gpio_select(i2s->config.i2s_port, i2s->config.i2s_port); return el; }
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/i2s_stream.c
C
apache-2.0
12,797
/* * ESPRESSIF MIT License * * Copyright (c) 2019 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _ALGORITHM_STREAM_H_ #define _ALGORITHM_STREAM_H_ #include "audio_element.h" #ifdef __cplusplus extern "C" { #endif #define ALGORITHM_STREAM_PINNED_TO_CORE 0 #define ALGORITHM_STREAM_TASK_PERIOD 5 #define ALGORITHM_STREAM_TASK_STACK_SIZE (5 * 1024) #define ALGORITHM_STREAM_DEFAULT_SAMPLE_RATE_HZ 16000 //Hz #define ALGORITHM_STREAM_DEFAULT_SAMPLE_BIT 16 #define ALGORITHM_STREAM_DEFAULT_CHANNEL 1 /* // AEC: Acoustic Echo Cancellation // AGC: Automatic Gain Control // WWE: Wake Word Engine // NS: Noise Suppression +-----------+ | | | TYPE 1 | | | +--------------------------------------+-----------+----------------------------------------+ | | | reference signal | +-----------+ | +-----------+ +-----------\ +-----------+ +-----------+ +-----------+ | | | | | | | \ | | | | | | | | I2S read |-------|->| Resample |--->| Data split |--->| AEC |--->| NS |--->| AGC | | | | | | | | / | | | | | | | +-----------+ | +-----------+ +-----------/ +------------ +-----------+ +-----------+ | | record signal | | | +-------------------------------------------------------------------------------------------+ +-----------+ | | | TYPE 2 | | | +--------------------------------------+-----------+----------------------------------------+ | | | | +-----------+ | +-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | | | | | | | | | | | | | | | | I2S read |-------|->| Resample |--->| rec signal|--->| AEC |--->| NS |--->| AGC | | | | | | | | | | | | | | | | +-----------+ | +-----------+ +-----------+ +-----^-----+ +-----------+ +-----------+ | | | | +-----------+ | +-----------+ +-----------+ | | | | | | | | | | | | input_rb |-------|->| Resample |--->| ref signal|----------+ | | | | | | | | | +-----------+ | +-----------+ +-----------+ | | | +-------------------------------------------------------------------------------------------+ */ /** * @brief Two types of algorithm stream input method */ typedef enum { ALGORITHM_STREAM_INPUT_TYPE1 = 0, /*!< Type 1 is default used by mini-board, the reference signal and the recording signal are respectively read in from the left channel and the right channel of the same I2S */ ALGORITHM_STREAM_INPUT_TYPE2 = 1, /*!< As the simple diagram above shows, when type2 is choosen, the recording signal and reference signal should be input by users. */ } algorithm_stream_input_type_t; /*!< The recording signal is inputted by I2S element by default, and the reference signal should be inputted to the algorithm element by using multiple input buffer. */ /*!< When use type2, you can combine arbitrarily the algorithm modules you want to use, use algo_mask parameters below to configure that. */ /** * @brief Choose the algorithm to be used */ typedef enum { ALGORITHM_STREAM_USE_AEC = (0x1 << 0), /*!< Use AEC */ ALGORITHM_STREAM_USE_AGC = (0x1 << 1), /*!< Use AGC */ ALGORITHM_STREAM_USE_NS = (0x1 << 2) /*!< Use NS */ } algorithm_stream_mask_t; /** * @brief Algorithm stream configurations */ typedef struct { algorithm_stream_input_type_t input_type; /*!< Input type of stream */ int task_stack; /*!< Task stack size */ int task_prio; /*!< Task peroid */ int task_core; /*!< The core that task to be created */ int rec_ch; /*!< Channel number of record signal */ int ref_ch; /*!< Channel number of reference signal */ int ref_sample_rate; /*!< Sample rate of reference signal */ int rec_sample_rate; /*!< Sample rate of record signal */ int rec_linear_factor; /*!< The linear amplication factor of record signal*/ int ref_linear_factor; /*!< The linear amplication factor of reference signal */ int8_t algo_mask; /*!< Choose algorithm to use */ } algorithm_stream_cfg_t; #define ALGORITHM_STREAM_CFG_DEFAULT() { \ .input_type = ALGORITHM_STREAM_INPUT_TYPE1, \ .task_stack = ALGORITHM_STREAM_TASK_STACK_SIZE, \ .task_prio = ALGORITHM_STREAM_TASK_PERIOD, \ .task_core = ALGORITHM_STREAM_PINNED_TO_CORE, \ .rec_ch = 1, \ .ref_ch = 1, \ .ref_sample_rate = 16000, \ .rec_sample_rate = 16000, \ .rec_linear_factor = 1, \ .ref_linear_factor = 3, \ .algo_mask = (ALGORITHM_STREAM_USE_AEC | ALGORITHM_STREAM_USE_AGC | ALGORITHM_STREAM_USE_NS), \ } /** * @brief Initialize algorithm stream * * @param config The algorithm Stream configuration * * @return The audio element handle */ audio_element_handle_t algo_stream_init(algorithm_stream_cfg_t *config); /** * @brief Get reference signal input ringbuff * * @note If input type2 is choosen, call this function to get ringbuffer to input reference data. * * @param algo_handle Handle of algorithm stream * * @return Ringbuffer handle to get * */ ringbuf_handle_t algo_stream_get_multi_input_rb(audio_element_handle_t algo_handle); /** * @brief Setup record signal clock for algorithm stream, this function is only used with handle created by `algo_stream_init` * * @param[in] algo_handle The algorithm stream element handle * @param[in] rec_ch Channel number of record signal * @param[in] rec_sample_rate Sample rate of record signal * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t algo_stream_set_record_rate(audio_element_handle_t algo_handle, int rec_ch, int rec_sample_rate); /** * @brief Setup reference signal clock for algorithm stream, this function is only used with handle created by `algo_stream_init` * * @param[in] algo_handle The algorithm stream element handle * @param[in] ref_ch Channel number of reference signal * @param[in] ref_sample_rate Sample rate of reference signal * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t algo_stream_set_reference_rate(audio_element_handle_t algo_handle, int ref_ch, int ref_sample_rate); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/algorithm_stream.h
C
apache-2.0
10,486
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _FATFS_STREAM_H_ #define _FATFS_STREAM_H_ #include "audio_error.h" #include "audio_element.h" #include "audio_common.h" #ifdef __cplusplus extern "C" { #endif /** * @brief FATFS Stream configurations, if any entry is zero then the configuration will be set to default values */ typedef struct { audio_stream_type_t type; /*!< Stream type */ int buf_sz; /*!< Audio Element Buffer size */ int out_rb_size; /*!< Size of output ringbuffer */ int task_stack; /*!< Task stack size */ int task_core; /*!< Task running in core (0 or 1) */ int task_prio; /*!< Task priority (based on freeRTOS priority) */ bool ext_stack; /*!< Allocate stack on extern ram */ bool write_header; /*!< Choose to write amrnb/amrwb header in fatfs whether or not (true or false, true means choose to write amrnb header) */ } fatfs_stream_cfg_t; #define FATFS_STREAM_BUF_SIZE (2048) #define FATFS_STREAM_TASK_STACK (3072) #define FATFS_STREAM_TASK_CORE (0) #define FATFS_STREAM_TASK_PRIO (4) #define FATFS_STREAM_RINGBUFFER_SIZE (8 * 1024) #define FATFS_STREAM_CFG_DEFAULT() { \ .type = AUDIO_STREAM_NONE, \ .buf_sz = FATFS_STREAM_BUF_SIZE, \ .out_rb_size = FATFS_STREAM_RINGBUFFER_SIZE, \ .task_stack = FATFS_STREAM_TASK_STACK, \ .task_core = FATFS_STREAM_TASK_CORE, \ .task_prio = FATFS_STREAM_TASK_PRIO, \ .ext_stack = false, \ .write_header = true, \ } /** * @brief Create a handle to an Audio Element to stream data from FatFs to another Element * or get data from other elements written to FatFs, depending on the configuration * the stream type, either AUDIO_STREAM_READER or AUDIO_STREAM_WRITER. * * @param config The configuration * * @return The Audio Element handle */ audio_element_handle_t fatfs_stream_init(fatfs_stream_cfg_t *config); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/fatfs_stream.h
C
apache-2.0
3,461
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _HTTP_STREAM_H_ #define _HTTP_STREAM_H_ #include "audio_error.h" #include "audio_element.h" #include "audio_common.h" #ifdef __cplusplus extern "C" { #endif /** * @brief HTTP Stream hook type */ typedef enum { HTTP_STREAM_PRE_REQUEST = 0x01, /*!< The event handler will be called before HTTP Client making the connection to the server */ HTTP_STREAM_ON_REQUEST, /*!< The event handler will be called when HTTP Client is requesting data, * If the fucntion return the value (-1: ESP_FAIL), HTTP Client will be stopped * If the fucntion return the value > 0, HTTP Stream will ignore the post_field * If the fucntion return the value = 0, HTTP Stream continue send data from post_field (if any) */ HTTP_STREAM_ON_RESPONSE, /*!< The event handler will be called when HTTP Client is receiving data * If the fucntion return the value (-1: ESP_FAIL), HTTP Client will be stopped * If the fucntion return the value > 0, HTTP Stream will ignore the read function * If the fucntion return the value = 0, HTTP Stream continue read data from HTTP Server */ HTTP_STREAM_POST_REQUEST, /*!< The event handler will be called after HTTP Client send header and body to the server, before fetching the headers */ HTTP_STREAM_FINISH_REQUEST, /*!< The event handler will be called after HTTP Client fetch the header and ready to read HTTP body */ HTTP_STREAM_RESOLVE_ALL_TRACKS, HTTP_STREAM_FINISH_TRACK, HTTP_STREAM_FINISH_PLAYLIST, } http_stream_event_id_t; /** * @brief Stream event message */ typedef struct { http_stream_event_id_t event_id; /*!< Event ID */ void *http_client; /*!< Reference to HTTP Client using by this HTTP Stream */ void *buffer; /*!< Reference to Buffer using by the Audio Element */ int buffer_len; /*!< Length of buffer */ void *user_data; /*!< User data context, from `http_stream_cfg_t` */ audio_element_handle_t el; /*!< Audio element context */ } http_stream_event_msg_t; typedef int (*http_stream_event_handle_t)(http_stream_event_msg_t *msg); /** * @brief HTTP Stream configurations * Default value will be used if any entry is zero */ typedef struct { audio_stream_type_t type; /*!< Type of stream */ int out_rb_size; /*!< Size of output ringbuffer */ int task_stack; /*!< Task stack size */ int task_core; /*!< Task running in core (0 or 1) */ int task_prio; /*!< Task priority (based on freeRTOS priority) */ bool stack_in_ext; /*!< Try to allocate stack in external memory */ http_stream_event_handle_t event_handle; /*!< The hook function for HTTP Stream */ void *user_data; /*!< User data context */ bool auto_connect_next_track;/*!< connect next track without open/close */ bool enable_playlist_parser; /*!< Enable playlist parser*/ int multi_out_num; /*!< The number of multiple output */ } http_stream_cfg_t; #define HTTP_STREAM_TASK_STACK (6 * 1024) #define HTTP_STREAM_TASK_CORE (0) #define HTTP_STREAM_TASK_PRIO (4) #define HTTP_STREAM_RINGBUFFER_SIZE (20 * 1024) #define HTTP_STREAM_CFG_DEFAULT() { \ .type = AUDIO_STREAM_READER, \ .out_rb_size = HTTP_STREAM_RINGBUFFER_SIZE, \ .task_stack = HTTP_STREAM_TASK_STACK, \ .task_core = HTTP_STREAM_TASK_CORE, \ .task_prio = HTTP_STREAM_TASK_PRIO, \ .stack_in_ext = true, \ .event_handle = NULL, \ .user_data = NULL, \ .auto_connect_next_track = false, \ .enable_playlist_parser = false, \ .multi_out_num = 0, \ } /** * @brief Create a handle to an Audio Element to stream data from HTTP to another Element * or get data from other elements sent to HTTP, depending on the configuration * the stream type, either AUDIO_STREAM_READER or AUDIO_STREAM_WRITER. * * @param config The configuration * * @return The Audio Element handle */ audio_element_handle_t http_stream_init(http_stream_cfg_t *config); /** * @brief Connect to next track in the playlist. * * This function can be used in event_handler of http_stream. * User can call this function to connect to next track in playlist when he/she gets `HTTP_STREAM_FINISH_TRACK` event * * @param el The http_stream element handle * * @return * - ESP_OK on success * - ESP_FAIL on errors */ esp_err_t http_stream_next_track(audio_element_handle_t el); esp_err_t http_stream_restart(audio_element_handle_t el); /** * @brief Try to fetch the tracks again. * * If this is live stream we will need to keep fetching URIs. * * @param el The http_stream element handle * * @return * - ESP_OK on success * - ESP_ERR_NOT_SUPPORTED if playlist is finished */ esp_err_t http_stream_fetch_again(audio_element_handle_t el); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/http_stream.h
C
apache-2.0
7,014
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _I2S_STREAM_WRITER_H_ #define _I2S_STREAM_WRITER_H_ #include "driver/i2s.h" #include "audio_common.h" #include "audio_error.h" #include "audio_idf_version.h" #ifdef __cplusplus extern "C" { #endif /** * @brief I2S Stream configurations * Default value will be used if any entry is zero */ typedef struct { audio_stream_type_t type; /*!< Type of stream */ i2s_config_t i2s_config; /*!< I2S driver configurations */ i2s_port_t i2s_port; /*!< I2S driver hardware port */ bool use_alc; /*!< It is a flag for ALC. If use ALC, the value is true. Or the value is false */ int volume; /*!< The volume of audio input data will be set. */ int out_rb_size; /*!< Size of output ringbuffer */ int task_stack; /*!< Task stack size */ int task_core; /*!< Task running in core (0 or 1) */ int task_prio; /*!< Task priority (based on freeRTOS priority) */ bool stack_in_ext; /*!< Try to allocate stack in external memory */ int multi_out_num; /*!< The number of multiple output */ bool uninstall_drv; /*!< whether uninstall the i2s driver when stream destroyed*/ } i2s_stream_cfg_t; #define I2S_STREAM_TASK_STACK (3072+512) #define I2S_STREAM_BUF_SIZE (2048) #define I2S_STREAM_TASK_PRIO (23) #define I2S_STREAM_TASK_CORE (0) #define I2S_STREAM_RINGBUFFER_SIZE (8 * 1024) #if (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 3, 0)) #define I2S_STREAM_CFG_DEFAULT() { \ .type = AUDIO_STREAM_WRITER, \ .i2s_config = { \ .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_RX), \ .sample_rate = 44100, \ .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, \ .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, \ .communication_format = I2S_COMM_FORMAT_I2S, \ .intr_alloc_flags = ESP_INTR_FLAG_LEVEL2 | ESP_INTR_FLAG_IRAM, \ .dma_buf_count = 3, \ .dma_buf_len = 300, \ .use_apll = true, \ .tx_desc_auto_clear = true, \ .fixed_mclk = 0 \ }, \ .i2s_port = I2S_NUM_0, \ .use_alc = false, \ .volume = 0, \ .out_rb_size = I2S_STREAM_RINGBUFFER_SIZE, \ .task_stack = I2S_STREAM_TASK_STACK, \ .task_core = I2S_STREAM_TASK_CORE, \ .task_prio = I2S_STREAM_TASK_PRIO, \ .stack_in_ext = false, \ .multi_out_num = 0, \ .uninstall_drv = true, \ } #define I2S_STREAM_INTERNAL_DAC_CFG_DEFAULT() { \ .type = AUDIO_STREAM_WRITER, \ .i2s_config = { \ .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_DAC_BUILT_IN | I2S_MODE_TX),\ .sample_rate = 44100, \ .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, \ .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, \ .communication_format = I2S_COMM_FORMAT_I2S_MSB, \ .intr_alloc_flags = ESP_INTR_FLAG_LEVEL2, \ .dma_buf_count = 3, \ .dma_buf_len = 300, \ .use_apll = false, \ .tx_desc_auto_clear = true, \ .fixed_mclk = 0 \ }, \ .i2s_port = I2S_NUM_0, \ .use_alc = false, \ .volume = 0, \ .out_rb_size = I2S_STREAM_RINGBUFFER_SIZE, \ .task_stack = I2S_STREAM_TASK_STACK, \ .task_core = I2S_STREAM_TASK_CORE, \ .task_prio = I2S_STREAM_TASK_PRIO, \ .stack_in_ext = false, \ .multi_out_num = 0, \ .uninstall_drv = false, \ } #define I2S_STREAM_TX_PDM_CFG_DEFAULT() { \ .type = AUDIO_STREAM_WRITER, \ .i2s_config = { \ .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_PDM | I2S_MODE_TX), \ .sample_rate = 44100, \ .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, \ .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, \ .communication_format = I2S_COMM_FORMAT_I2S_MSB, \ .dma_buf_count = 3, \ .dma_buf_len = 300, \ .use_apll = true, \ .tx_desc_auto_clear = true, \ .fixed_mclk = 0 \ }, \ .i2s_port = I2S_NUM_0, \ .use_alc = false, \ .volume = 0, \ .out_rb_size = I2S_STREAM_RINGBUFFER_SIZE, \ .task_stack = I2S_STREAM_TASK_STACK, \ .task_core = I2S_STREAM_TASK_CORE, \ .task_prio = I2S_STREAM_TASK_PRIO, \ .stack_in_ext = false, \ .multi_out_num = 0, \ .uninstall_drv = false, \ } #else #define I2S_STREAM_CFG_DEFAULT() { \ .type = AUDIO_STREAM_WRITER, \ .i2s_config = { \ .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_RX), \ .sample_rate = 44100, \ .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, \ .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, \ .communication_format = I2S_COMM_FORMAT_STAND_I2S, \ .intr_alloc_flags = ESP_INTR_FLAG_LEVEL2 | ESP_INTR_FLAG_IRAM, \ .dma_buf_count = 3, \ .dma_buf_len = 300, \ .use_apll = true, \ .tx_desc_auto_clear = true, \ .fixed_mclk = 0 \ }, \ .i2s_port = I2S_NUM_0, \ .use_alc = false, \ .volume = 0, \ .out_rb_size = I2S_STREAM_RINGBUFFER_SIZE, \ .task_stack = I2S_STREAM_TASK_STACK, \ .task_core = I2S_STREAM_TASK_CORE, \ .task_prio = I2S_STREAM_TASK_PRIO, \ .stack_in_ext = false, \ .multi_out_num = 0, \ .uninstall_drv = true, \ } #define I2S_STREAM_INTERNAL_DAC_CFG_DEFAULT() { \ .type = AUDIO_STREAM_WRITER, \ .i2s_config = { \ .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_DAC_BUILT_IN | I2S_MODE_TX),\ .sample_rate = 44100, \ .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, \ .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, \ .communication_format = I2S_COMM_FORMAT_STAND_MSB, \ .intr_alloc_flags = ESP_INTR_FLAG_LEVEL2, \ .dma_buf_count = 3, \ .dma_buf_len = 300, \ .use_apll = false, \ .tx_desc_auto_clear = true, \ .fixed_mclk = 0 \ }, \ .i2s_port = I2S_NUM_0, \ .use_alc = false, \ .volume = 0, \ .out_rb_size = I2S_STREAM_RINGBUFFER_SIZE, \ .task_stack = I2S_STREAM_TASK_STACK, \ .task_core = I2S_STREAM_TASK_CORE, \ .task_prio = I2S_STREAM_TASK_PRIO, \ .stack_in_ext = false, \ .multi_out_num = 0, \ .uninstall_drv = false, \ } #define I2S_STREAM_TX_PDM_CFG_DEFAULT() { \ .type = AUDIO_STREAM_WRITER, \ .i2s_config = { \ .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_PDM | I2S_MODE_TX), \ .sample_rate = 44100, \ .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, \ .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, \ .communication_format = I2S_COMM_FORMAT_STAND_MSB, \ .dma_buf_count = 3, \ .dma_buf_len = 300, \ .use_apll = true, \ .tx_desc_auto_clear = true, \ .fixed_mclk = 0 \ }, \ .i2s_port = I2S_NUM_0, \ .use_alc = false, \ .volume = 0, \ .out_rb_size = I2S_STREAM_RINGBUFFER_SIZE, \ .task_stack = I2S_STREAM_TASK_STACK, \ .task_core = I2S_STREAM_TASK_CORE, \ .task_prio = I2S_STREAM_TASK_PRIO, \ .stack_in_ext = false, \ .multi_out_num = 0, \ .uninstall_drv = false, \ } #endif /** * @brief Create a handle to an Audio Element to stream data from I2S to another Element * or get data from other elements sent to I2S, depending on the configuration of stream type * is AUDIO_STREAM_READER or AUDIO_STREAM_WRITER. * @note If I2S stream is enabled with built-in DAC mode, please don't use I2S_NUM_1. The built-in * DAC functions are only supported on I2S0 for the current ESP32 chip. * @param config The configuration * * @return The Audio Element handle */ audio_element_handle_t i2s_stream_init(i2s_stream_cfg_t *config); /** * @brief Setup clock for I2S Stream, this function is only used with handle created by `i2s_stream_init` * * @param[in] i2s_stream The i2s element handle * @param[in] rate Clock rate (in Hz) * @param[in] bits Audio bit width (8, 16, 24, 32) * @param[in] ch Number of Audio channels (1: Mono, 2: Stereo) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t i2s_stream_set_clk(audio_element_handle_t i2s_stream, int rate, int bits, int ch); /** * @brief Setup volume of stream by using ALC * * @param[in] i2s_stream The i2s element handle * @param[in] volume The volume of stream will be set. * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t i2s_alc_volume_set(audio_element_handle_t i2s_stream, int volume); /** * @brief Get volume of stream * * @param[in] i2s_stream The i2s element handle * @param[in] volume The volume of stream * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t i2s_alc_volume_get(audio_element_handle_t i2s_stream, int *volume); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/i2s_stream.h
C
apache-2.0
16,854
/* * * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _PWM_STREAM_H_ #define _PWM_STREAM_H_ #include "driver/ledc.h" #include "driver/timer.h" #ifdef __cplusplus extern "C" { #endif /** * @brief PWM audio configurations * */ typedef struct { timer_group_t tg_num; /*!< timer group number (0 - 1) */ timer_idx_t timer_num; /*!< timer number (0 - 1) */ int gpio_num_left; /*!< the LEDC output gpio_num, Left channel */ int gpio_num_right; /*!< the LEDC output gpio_num, Right channel */ ledc_channel_t ledc_channel_left; /*!< LEDC channel (0 - 7), Corresponding to left channel*/ ledc_channel_t ledc_channel_right; /*!< LEDC channel (0 - 7), Corresponding to right channel*/ ledc_timer_t ledc_timer_sel; /*!< Select the timer source of channel (0 - 3) */ ledc_timer_bit_t duty_resolution; /*!< ledc pwm bits */ uint32_t data_len; /*!< ringbuffer size */ } audio_pwm_config_t; /** * @brief PWM Stream configurations * Default value will be used if any entry is zero */ typedef struct { audio_stream_type_t type; /*!< Type of stream */ audio_pwm_config_t pwm_config; /*!< driver configurations */ int out_rb_size; /*!< Size of output ringbuffer */ int task_stack; /*!< Task stack size */ int task_core; /*!< Task running in core (0 or 1) */ int task_prio; /*!< Task priority (based on freeRTOS priority) */ int buffer_len; /*!< pwm_stream buffer length */ bool ext_stack; /*!< Allocate stack on extern ram */ } pwm_stream_cfg_t; #define PWM_STREAM_GPIO_NUM_LEFT GPIO_NUM_18 #define PWM_STREAM_GPIO_NUM_RIGHT GPIO_NUM_17 #define PWM_STREAM_TASK_STACK (3072+512) #define PWM_STREAM_BUF_SIZE (2048) #define PWM_STREAM_TASK_PRIO (23) #define PWM_STREAM_TASK_CORE (0) #define PWM_STREAM_RINGBUFFER_SIZE (0) #define PWM_CONFIG_RINGBUFFER_SIZE (1024*8) #define PWM_STREAM_CFG_DEFAULT() { \ .type = AUDIO_STREAM_WRITER, \ .pwm_config = { \ .tg_num = TIMER_GROUP_0, \ .timer_num = TIMER_0, \ .gpio_num_left = PWM_STREAM_GPIO_NUM_LEFT, \ .gpio_num_right = PWM_STREAM_GPIO_NUM_RIGHT, \ .ledc_channel_left = LEDC_CHANNEL_0, \ .ledc_channel_right = LEDC_CHANNEL_1, \ .ledc_timer_sel = LEDC_TIMER_0, \ .duty_resolution = LEDC_TIMER_8_BIT, \ .data_len = PWM_CONFIG_RINGBUFFER_SIZE, \ }, \ .out_rb_size = PWM_STREAM_RINGBUFFER_SIZE, \ .task_stack = PWM_STREAM_TASK_STACK, \ .task_core = PWM_STREAM_TASK_CORE, \ .task_prio = PWM_STREAM_TASK_PRIO, \ .buffer_len = PWM_STREAM_BUF_SIZE, \ .ext_stack = false, \ } /** * @brief Initialize PWM stream * * @param config The PWM Stream configuration * * @return The audio element handle */ audio_element_handle_t pwm_stream_init(pwm_stream_cfg_t *config); /** * @brief Setup clock for PWM Stream, this function is only used with handle created by `pwm_stream_init` * * @param[in] pwm_stream The pwm element handle * @param[in] rate Clock rate (in Hz) * @param[in] bits Audio bit width (16, 32) * @param[in] ch Number of Audio channels (1: Mono, 2: Stereo) * * @return * - ESP_OK * - ESP_FAIL */ esp_err_t pwm_stream_set_clk(audio_element_handle_t pwm_stream, int rate, int bits, int ch); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/pwm_stream.h
C
apache-2.0
5,232
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _RAW_STREAM_H_ #define _RAW_STREAM_H_ #include "audio_error.h" #include "audio_element.h" #include "audio_common.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Raw stream provides APIs to obtain the pipeline data without output stream or * fill the pipeline data without input stream. * The stream has two types / modes, reader and writer: * * - AUDIO_STREAM_READER, e.g. [i2s]->[filter]->[raw],[i2s]->[codec-amr]->[raw] * - AUDIO_STREAM_WRITER, e.g. [raw]->[codec-mp3]->[i2s] */ /** * Raw Stream configurations */ typedef struct { audio_stream_type_t type; /*!< Type of stream */ int out_rb_size; /*!< Size of output ringbuffer */ } raw_stream_cfg_t; #define RAW_STREAM_RINGBUFFER_SIZE (8 * 1024) #define RAW_STREAM_CFG_DEFAULT() {\ .type = AUDIO_STREAM_NONE, \ .out_rb_size = RAW_STREAM_RINGBUFFER_SIZE, \ } /** * @brief Initialize RAW stream * * @param cfg The RAW Stream configuration * * @return The audio element handle */ audio_element_handle_t raw_stream_init(raw_stream_cfg_t *cfg); /** * @brief Read data from Stream * * @param pipeline The audio pipeline handle * @param buffer The buffer * @param buf_size Maximum number of bytes to be read. * * @return Number of bytes actually read. */ int raw_stream_read(audio_element_handle_t pipeline, char *buffer, int buf_size); /** * @brief Write data to Stream * * @param pipeline The audio pipeline handle * @param buffer The buffer * @param buf_size Number of bytes to write * * @return Number of bytes written */ int raw_stream_write(audio_element_handle_t pipeline, char *buffer, int buf_size); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/raw_stream.h
C
apache-2.0
3,068
/* * ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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 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. * */ #ifndef _SPIFFS_STREAM_H_ #define _SPIFFS_STREAM_H_ #include "audio_error.h" #include "audio_element.h" #include "audio_common.h" #ifdef __cplusplus extern "C" { #endif /** * @brief SPIFFS Stream configuration, if any entry is zero then the configuration will be set to default values */ typedef struct { audio_stream_type_t type; /*!< Stream type */ int buf_sz; /*!< Audio Element Buffer size */ int out_rb_size; /*!< Size of output ringbuffer */ int task_stack; /*!< Task stack size */ int task_core; /*!< Task running in core (0 or 1) */ int task_prio; /*!< Task priority (based on freeRTOS priority) */ bool write_header; /*!< Choose to write amrnb/armwb header in spiffs whether or not (true or false, true means choose to write amrnb header) */ } spiffs_stream_cfg_t; #define SPIFFS_STREAM_BUF_SIZE (2048) #define SPIFFS_STREAM_TASK_STACK (3072) #define SPIFFS_STREAM_TASK_CORE (0) #define SPIFFS_STREAM_TASK_PRIO (4) #define SPIFFS_STREAM_RINGBUFFER_SIZE (8 * 1024) #define SPIFFS_STREAM_CFG_DEFAULT() { \ .type = AUDIO_STREAM_NONE, \ .buf_sz = SPIFFS_STREAM_BUF_SIZE, \ .out_rb_size = SPIFFS_STREAM_RINGBUFFER_SIZE, \ .task_stack = SPIFFS_STREAM_TASK_STACK, \ .task_core = SPIFFS_STREAM_TASK_CORE, \ .task_prio = SPIFFS_STREAM_TASK_PRIO, \ .write_header = true, \ } /** * @brief Create a handle to an Audio Element to stream data from SPIFFS to another Element * or get data from other elements written to SPIFFS, depending on the configuration * the stream type, either AUDIO_STREAM_READER or AUDIO_STREAM_WRITER. * * @param config The configuration * * @return The Audio Element handle */ audio_element_handle_t spiffs_stream_init(spiffs_stream_cfg_t *config); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/espressif_adf/esp-adf/components/audio_stream/include/spiffs_stream.h
C
apache-2.0
3,348