mirror of
https://github.com/sle118/squeezelite-esp32.git
synced 2025-12-16 00:17:03 +03:00
Compare commits
28 Commits
I2S-4MFlas
...
SqueezeAmp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c143ea56ff | ||
|
|
3fc7e68163 | ||
|
|
2dea2ca08c | ||
|
|
2584026e5c | ||
|
|
f2b0c40848 | ||
|
|
1876b26100 | ||
|
|
f84e856e68 | ||
|
|
34fa7203be | ||
|
|
751d683b3e | ||
|
|
b000bbd383 | ||
|
|
6f504839bb | ||
|
|
b48e9fe1fa | ||
|
|
eb6b99d461 | ||
|
|
405c7742ef | ||
|
|
eab321d233 | ||
|
|
50475e9305 | ||
|
|
a1e15abba7 | ||
|
|
7e733f4fa9 | ||
|
|
3e35937272 | ||
|
|
2d9dd14e06 | ||
|
|
698cc70aa3 | ||
|
|
6e67606a07 | ||
|
|
f6f2f612a1 | ||
|
|
60bf802f3f | ||
|
|
f7c9f08071 | ||
|
|
9be4593d81 | ||
|
|
922889fee2 | ||
|
|
a8e28f9ff0 |
7
.github/workflows/esp-idf-v4.3-build.yml
vendored
7
.github/workflows/esp-idf-v4.3-build.yml
vendored
@@ -27,11 +27,14 @@ jobs:
|
||||
matrix:
|
||||
node: [I2S-4MFlash, SqueezeAmp, Muse]
|
||||
depth: [16, 32]
|
||||
exclude:
|
||||
- node: Muse
|
||||
depth: 32
|
||||
steps:
|
||||
- name: Set target name
|
||||
run: |
|
||||
echo "TARGET_BUILD_NAME=${{ matrix.node }}" >> $GITHUB_ENV
|
||||
echo "build_version_prefix=1." >> $GITHUB_ENV
|
||||
echo "build_version_prefix=2." >> $GITHUB_ENV
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 15
|
||||
@@ -66,7 +69,7 @@ jobs:
|
||||
echo "tag=${tag}" >> $GITHUB_ENV
|
||||
last_commit="$(git log --pretty=format:'%s' --max-count=1)"
|
||||
if [[ "$last_commit" =~ .*"Release".* ]]; then echo "release_flag=1" >> $GITHUB_ENV; else echo "release_flag=0" >> $GITHUB_ENV; fi
|
||||
name="1.${BUILD_NUMBER}-${{matrix.depth}}#v4.0#${TARGET_BUILD_NAME}#${branch_name}"
|
||||
name="${build_version_prefix}${BUILD_NUMBER}-${{matrix.depth}}#v4.0#${TARGET_BUILD_NAME}#${branch_name}"
|
||||
artifact_prefix="squeezelite-esp32-${branch_name}-${TARGET_BUILD_NAME}-${{matrix.depth}}-${build_version_prefix}${BUILD_NUMBER}"
|
||||
artifact_file_name="${artifact_prefix}.zip"
|
||||
artifact_bin_file_name="${artifact_prefix}.bin"
|
||||
|
||||
16
.gitignore
vendored
16
.gitignore
vendored
@@ -1,30 +1,16 @@
|
||||
|
||||
build/
|
||||
|
||||
.vscode/c_cpp_properties.json
|
||||
|
||||
.vscode/launch.json
|
||||
|
||||
.vscode/settings.json
|
||||
|
||||
.vscode/tasks.json
|
||||
|
||||
alltags.txt
|
||||
|
||||
components/wifi-manager/network_manager_handlers.multi
|
||||
|
||||
esp32.code-workspace
|
||||
|
||||
sdkconfig.old
|
||||
|
||||
test/.vscode/c_cpp_properties.json
|
||||
|
||||
test/.vscode/launch.json
|
||||
|
||||
test/.vscode/settings.json
|
||||
|
||||
test/.vscode/tasks.json
|
||||
|
||||
test/sdkconfig
|
||||
|
||||
components/wifi-manager/UML-State-Machine-in-C
|
||||
*.bak
|
||||
|
||||
@@ -1,7 +1,21 @@
|
||||
set(srcs i2s.c i2s_hal.c spi_master.c)
|
||||
idf_component_register( SRCS ${srcs}
|
||||
INCLUDE_DIRS ${IDF_PATH}/components/driver
|
||||
)
|
||||
set(lib_dir ${build_dir}/esp-idf)
|
||||
|
||||
set(driver i2s.c i2s_hal.c spi_bus_lock.c)
|
||||
string(REPLACE ".c" ".c.obj" driver_obj "${driver}")
|
||||
|
||||
idf_component_register( SRCS ${driver}
|
||||
REQUIRES driver
|
||||
INCLUDE_DIRS ${IDF_PATH}/components/driver
|
||||
PRIV_INCLUDE_DIRS ${IDF_PATH}/components/driver/include/driver
|
||||
)
|
||||
|
||||
# CMake is just a pile of crap
|
||||
message("overriding ${srcs} !! THIS MUST BE REQUIRED BY ONE COMPONENT BUT NOT MAIN !!")
|
||||
message("!! overriding ${driver} !!")
|
||||
message("CAREFUL, LIBRARIES STRIPPING FROM DUPLICATED COMPONENTS DEPENDS ON THIS BEING REBUILD")
|
||||
|
||||
add_custom_command(
|
||||
TARGET ${COMPONENT_LIB}
|
||||
PRE_LINK
|
||||
COMMAND xtensa-esp32-elf-ar -d ${lib_dir}/driver/libdriver.a ${driver_obj}
|
||||
VERBATIM
|
||||
)
|
||||
@@ -166,7 +166,7 @@ void i2s_hal_format_config(i2s_hal_context_t *hal, const i2s_config_t *i2s_confi
|
||||
break;
|
||||
}
|
||||
}
|
||||
#include "stdio.h"
|
||||
|
||||
void i2s_hal_config_param(i2s_hal_context_t *hal, const i2s_config_t *i2s_config)
|
||||
{
|
||||
//reset i2s
|
||||
|
||||
849
components/_override/spi_bus_lock.c
Normal file
849
components/_override/spi_bus_lock.c
Normal file
@@ -0,0 +1,849 @@
|
||||
// Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include <stdatomic.h>
|
||||
#include "sdkconfig.h"
|
||||
#include "spi_common_internal.h"
|
||||
#include "esp_intr_alloc.h"
|
||||
#include "soc/soc_caps.h"
|
||||
#include "stdatomic.h"
|
||||
#include "esp_log.h"
|
||||
#include <strings.h>
|
||||
#include "esp_heap_caps.h"
|
||||
|
||||
/*
|
||||
* This lock is designed to solve the conflicts between SPI devices (used in tasks) and
|
||||
* the background operations (ISR or cache access).
|
||||
*
|
||||
* There are N (device/task) + 1 (BG) acquiring processer candidates that may touch the bus.
|
||||
*
|
||||
* The core of the lock is a `status` atomic variable, which is always available. No intermediate
|
||||
* status is allowed. The atomic operations (mainly `atomic_fetch_and`, `atomic_fetch_or`)
|
||||
* atomically read the status, and bitwisely write status value ORed / ANDed with given masks.
|
||||
*
|
||||
* Definitions of the status:
|
||||
* - [30] WEAK_BG_FLAG, active when the BG is the cache
|
||||
* - [29:20] LOCK bits, active when corresponding device is asking for acquiring
|
||||
* - [19:10] PENDING bits, active when the BG acknowledges the REQ bits, but hasn't fully handled them.
|
||||
* - [ 9: 0] REQ bits, active when corresponding device is requesting for BG operations.
|
||||
*
|
||||
* The REQ bits together PENDING bits are called BG bits, which represent the actual BG request
|
||||
* state of devices. Either one of REQ or PENDING being active indicates the device has pending BG
|
||||
* requests. Reason of having two bits instead of one is in the appendix below.
|
||||
*
|
||||
* Acquiring processer means the current processor (task or ISR) allowed to touch the critical
|
||||
* resources, or the SPI bus.
|
||||
*
|
||||
* States of the lock:
|
||||
* - STATE_IDLE: There's no acquiring processor. No device is acquiring the bus, and no BG
|
||||
* operation is in progress.
|
||||
*
|
||||
* - STATE_ACQ: The acquiring processor is a device task. This means one of the devices is
|
||||
* acquiring the bus.
|
||||
*
|
||||
* - STATE_BG: The acquiring processor is the ISR, and there is no acquiring device.
|
||||
*
|
||||
* - STATE_BG_ACQ: The acquiring processor is the ISR, and there is an acquiring device.
|
||||
*
|
||||
*
|
||||
* Whenever a bit is written to the status, it means the a device on a task is trying to acquire
|
||||
* the lock (either for the task, or the ISR). When there is no LOCK bits or BG bits active, the
|
||||
* caller immediately become the acquiring processor. Otherwise, the task has to block, and the ISR
|
||||
* will not be invoked until scheduled by the current acquiring processor.
|
||||
*
|
||||
* The acquiring processor is responsible to assign the next acquiring processor by calling the
|
||||
* scheduler, usually after it finishes some requests, and cleared the corresponding status bit.
|
||||
* But there is one exception, when the last bit is cleared from the status, after which there is
|
||||
* no other LOCK bits or BG bits active, the acquiring processor lost its role immediately, and
|
||||
* don't need to call the scheduler to assign the next acquiring processor.
|
||||
*
|
||||
* The acquiring processor may also choose to assign a new acquiring device when there is no, by
|
||||
* calling `spi_bus_lock_bg_rotate_acq_dev` in the ISR. But the acquiring processor, in this case,
|
||||
* is still the ISR, until it calls the scheduler.
|
||||
*
|
||||
*
|
||||
* Transition of the FSM:
|
||||
*
|
||||
* - STATE_IDLE: no acquiring device, nor acquiring processor, no LOCK or BG bits active
|
||||
* -> STATE_BG: by `req_core`
|
||||
* -> STATE_ACQ: by `acquire_core`
|
||||
*
|
||||
* - STATE_BG:
|
||||
* * No acquiring device, the ISR is the acquiring processor, there is BG bits active, but no LOCK
|
||||
* bits
|
||||
* * The BG operation should be enabled while turning into this state.
|
||||
*
|
||||
* -> STATE_IDLE: by `bg_exit_core` after `clear_pend_core` for all BG bits
|
||||
* -> STATE_BG_ACQ: by `schedule_core`, when there is new LOCK bit set (by `acquire_core`)
|
||||
*
|
||||
* - STATE_BG_ACQ:
|
||||
* * There is acquiring device, the ISR is the acquiring processor, there may be BG bits active for
|
||||
* the acquiring device.
|
||||
* * The BG operation should be enabled while turning into this state.
|
||||
*
|
||||
* -> STATE_ACQ: by `bg_exit_core` after `clear_pend_core` for all BG bits for the acquiring
|
||||
* device.
|
||||
*
|
||||
* Should not go to the STATE_ACQ (unblock the acquiring task) until all requests of the
|
||||
* acquiring device are finished. This is to preserve the sequence of foreground (polling) and
|
||||
* background operations of the device. The background operations queued before the acquiring
|
||||
* should be completed first.
|
||||
*
|
||||
* - STATE_ACQ:
|
||||
* * There is acquiring device, the task is the acquiring processor, there is no BG bits active for
|
||||
* the acquiring device.
|
||||
* * The acquiring task (if blocked at `spi_bus_lock_acquire_start` or `spi_bus_lock_wait_bg_done`)
|
||||
* should be resumed while turning into this state.
|
||||
*
|
||||
* -> STATE_BG_ACQ: by `req_core`
|
||||
* -> STATE_BG_ACQ (other device): by `acquire_end_core`, when there is LOCK bit for another
|
||||
* device, and the new acquiring device has active BG bits.
|
||||
* -> STATE_ACQ (other device): by `acquire_end_core`, when there is LOCK bit for another devices,
|
||||
* but the new acquiring device has no active BG bits.
|
||||
* -> STATE_BG: by `acquire_end_core` when there is no LOCK bit active, but there are active BG
|
||||
* bits.
|
||||
* -> STATE_IDLE: by `acquire_end_core` when there is no LOCK bit, nor BG bit active.
|
||||
*
|
||||
* The `req_core` used in the task is a little special. It asks for acquiring processor for the
|
||||
* ISR. When it succeed for the first time, it will invoke the ISR (hence passing the acquiring
|
||||
* role to the BG). Otherwise it will not block, the ISR will be automatically be invoked by other
|
||||
* acquiring processor. The caller of `req_core` will never become acquiring processor by this
|
||||
* function.
|
||||
*
|
||||
*
|
||||
* Appendix: The design, that having both request bit and pending bit, is to solve the
|
||||
* concurrency issue between tasks and the bg, when the task can queue several requests,
|
||||
* however the request bit cannot represent the number of requests queued.
|
||||
*
|
||||
* Here's the workflow of task and ISR work concurrently:
|
||||
* - Task: (a) Write to Queue -> (b) Write request bit
|
||||
* The Task have to write request bit (b) after the data is prepared in the queue (a),
|
||||
* otherwise the BG may fail to read from the queue when it sees the request bit set.
|
||||
*
|
||||
* - BG: (c) Read queue -> (d) Clear request bit
|
||||
* Since the BG cannot know the number of requests queued, it have to repeatedly check the
|
||||
* queue (c), until it find the data is empty, and then clear the request bit (d).
|
||||
*
|
||||
* The events are possible to happen in the order: (c) -> (a) -> (b) -> (d). This may cause a false
|
||||
* clear of the request bit. And there will be data prepared in the queue, but the request bit is
|
||||
* inactive.
|
||||
*
|
||||
* (e) move REQ bits to PEND bits, happen before (c) is introduced to solve this problem. In this
|
||||
* case (d) is changed to clear the PEND bit. Even if (e) -> (c) -> (a) -> (b) -> (d), only PEND
|
||||
* bit is cleared, while the REQ bit is still active.
|
||||
*/
|
||||
|
||||
struct spi_bus_lock_dev_t;
|
||||
typedef struct spi_bus_lock_dev_t spi_bus_lock_dev_t;
|
||||
|
||||
typedef struct spi_bus_lock_t spi_bus_lock_t;
|
||||
|
||||
|
||||
#define MAX_DEV_NUM 10
|
||||
|
||||
// Bit 29-20: lock bits, Bit 19-10: pending bits
|
||||
// Bit 9-0: request bits, Bit 30:
|
||||
#define LOCK_SHIFT 20
|
||||
#define PENDING_SHIFT 10
|
||||
#define REQ_SHIFT 0
|
||||
|
||||
#define WEAK_BG_FLAG BIT(30) /**< The bus is permanently requested by background operations.
|
||||
* This flag is weak, will not prevent acquiring of devices. But will help the BG to be re-enabled again after the bus is release.
|
||||
*/
|
||||
|
||||
// get the bit mask wher bit [high-1, low] are all 1'b1 s.
|
||||
#define BIT1_MASK(high, low) ((UINT32_MAX << (high)) ^ (UINT32_MAX << (low)))
|
||||
|
||||
#define LOCK_BIT(mask) ((mask) << LOCK_SHIFT)
|
||||
#define REQUEST_BIT(mask) ((mask) << REQ_SHIFT)
|
||||
#define PENDING_BIT(mask) ((mask) << PENDING_SHIFT)
|
||||
#define DEV_MASK(id) (LOCK_BIT(1<<id) | PENDING_BIT(1<<id) | REQUEST_BIT(1<<id))
|
||||
#define ID_DEV_MASK(mask) (ffs(mask) - 1)
|
||||
|
||||
#define REQ_MASK BIT1_MASK(REQ_SHIFT+MAX_DEV_NUM, REQ_SHIFT)
|
||||
#define PEND_MASK BIT1_MASK(PENDING_SHIFT+MAX_DEV_NUM, PENDING_SHIFT)
|
||||
#define BG_MASK BIT1_MASK(REQ_SHIFT+MAX_DEV_NUM*2, REQ_SHIFT)
|
||||
#define LOCK_MASK BIT1_MASK(LOCK_SHIFT+MAX_DEV_NUM, LOCK_SHIFT)
|
||||
|
||||
#define DEV_REQ_MASK(dev) ((dev)->mask & REQ_MASK)
|
||||
#define DEV_PEND_MASK(dev) ((dev)->mask & PEND_MASK)
|
||||
#define DEV_BG_MASK(dev) ((dev)->mask & BG_MASK)
|
||||
|
||||
struct spi_bus_lock_t {
|
||||
/**
|
||||
* The core of the lock. These bits are status of the lock, which should be always available.
|
||||
* No intermediate status is allowed. This is realized by atomic operations, mainly
|
||||
* `atomic_fetch_and`, `atomic_fetch_or`, which atomically read the status, and bitwise write
|
||||
* status value ORed / ANDed with given masks.
|
||||
*
|
||||
* The request bits together pending bits represent the actual bg request state of one device.
|
||||
* Either one of them being active indicates the device has pending bg requests.
|
||||
*
|
||||
* Whenever a bit is written to the status, it means the a device on a task is trying to
|
||||
* acquire the lock. But this will succeed only when no LOCK or BG bits active.
|
||||
*
|
||||
* The acquiring processor is responsible to call the scheduler to pass its role to other tasks
|
||||
* or the BG, unless it clear the last bit in the status register.
|
||||
*/
|
||||
//// Critical resources, they are only writable by acquiring processor, and stable only when read by the acquiring processor.
|
||||
atomic_uint_fast32_t status;
|
||||
spi_bus_lock_dev_t* volatile acquiring_dev; ///< The acquiring device
|
||||
bool volatile acq_dev_bg_active; ///< BG is the acquiring processor serving the acquiring device, used for the wait_bg to skip waiting quickly.
|
||||
bool volatile in_isr; ///< ISR is touching HW
|
||||
//// End of critical resources
|
||||
|
||||
atomic_intptr_t dev[DEV_NUM_MAX]; ///< Child locks.
|
||||
bg_ctrl_func_t bg_enable; ///< Function to enable background operations.
|
||||
bg_ctrl_func_t bg_disable; ///< Function to disable background operations
|
||||
void* bg_arg; ///< Argument for `bg_enable` and `bg_disable` functions.
|
||||
|
||||
spi_bus_lock_dev_t* last_dev; ///< Last used device, to decide whether to refresh all registers.
|
||||
int periph_cs_num; ///< Number of the CS pins the HW has.
|
||||
|
||||
//debug information
|
||||
int host_id; ///< Host ID, for debug information printing
|
||||
uint32_t new_req; ///< Last int_req when `spi_bus_lock_bg_start` is called. Debug use.
|
||||
};
|
||||
|
||||
struct spi_bus_lock_dev_t {
|
||||
SemaphoreHandle_t semphr; ///< Binray semaphore to notify the device it claimed the bus
|
||||
spi_bus_lock_t* parent; ///< Pointer to parent spi_bus_lock_t
|
||||
uint32_t mask; ///< Bitwise OR-ed mask of the REQ, PEND, LOCK bits of this device
|
||||
};
|
||||
|
||||
portMUX_TYPE s_spinlock = portMUX_INITIALIZER_UNLOCKED;
|
||||
|
||||
DRAM_ATTR static const char TAG[] = "bus_lock";
|
||||
|
||||
#define LOCK_CHECK(a, str, ret_val, ...) \
|
||||
if (!(a)) { \
|
||||
ESP_LOGE(TAG,"%s(%d): "str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \
|
||||
return (ret_val); \
|
||||
}
|
||||
|
||||
static inline int mask_get_id(uint32_t mask);
|
||||
static inline int dev_lock_get_id(spi_bus_lock_dev_t *dev_lock);
|
||||
|
||||
/*******************************************************************************
|
||||
* atomic operations to the status
|
||||
******************************************************************************/
|
||||
SPI_MASTER_ISR_ATTR static inline uint32_t lock_status_fetch_set(spi_bus_lock_t *lock, uint32_t set)
|
||||
{
|
||||
return atomic_fetch_or(&lock->status, set);
|
||||
}
|
||||
|
||||
IRAM_ATTR static inline uint32_t lock_status_fetch_clear(spi_bus_lock_t *lock, uint32_t clear)
|
||||
{
|
||||
return atomic_fetch_and(&lock->status, ~clear);
|
||||
}
|
||||
|
||||
IRAM_ATTR static inline uint32_t lock_status_fetch(spi_bus_lock_t *lock)
|
||||
{
|
||||
return atomic_load(&lock->status);
|
||||
}
|
||||
|
||||
SPI_MASTER_ISR_ATTR static inline void lock_status_init(spi_bus_lock_t *lock)
|
||||
{
|
||||
atomic_store(&lock->status, 0);
|
||||
}
|
||||
|
||||
// return the remaining status bits
|
||||
IRAM_ATTR static inline uint32_t lock_status_clear(spi_bus_lock_t* lock, uint32_t clear)
|
||||
{
|
||||
//the fetch and clear should be atomic, avoid missing the all '0' status when all bits are clear.
|
||||
uint32_t state = lock_status_fetch_clear(lock, clear);
|
||||
return state & (~clear);
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
* Schedule service
|
||||
*
|
||||
* The modification to the status bits may cause rotating of the acquiring processor. It also have
|
||||
* effects to `acquired_dev` (the acquiring device), `in_isr` (HW used in BG), and
|
||||
* `acq_dev_bg_active` (wait_bg_end can be skipped) members of the lock structure.
|
||||
*
|
||||
* Most of them should be atomic, and special attention should be paid to the operation
|
||||
* sequence.
|
||||
******************************************************************************/
|
||||
SPI_MASTER_ISR_ATTR static inline void resume_dev_in_isr(spi_bus_lock_dev_t *dev_lock, BaseType_t *do_yield)
|
||||
{
|
||||
xSemaphoreGiveFromISR(dev_lock->semphr, do_yield);
|
||||
}
|
||||
|
||||
IRAM_ATTR static inline void resume_dev(const spi_bus_lock_dev_t *dev_lock)
|
||||
{
|
||||
xSemaphoreGive(dev_lock->semphr);
|
||||
}
|
||||
|
||||
SPI_MASTER_ISR_ATTR static inline void bg_disable(spi_bus_lock_t *lock)
|
||||
{
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->bg_disable);
|
||||
lock->bg_disable(lock->bg_arg);
|
||||
}
|
||||
|
||||
IRAM_ATTR static inline void bg_enable(spi_bus_lock_t* lock)
|
||||
{
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->bg_enable);
|
||||
lock->bg_enable(lock->bg_arg);
|
||||
}
|
||||
|
||||
// Set the REQ bit. If we become the acquiring processor, invoke the ISR and pass that to it.
|
||||
// The caller will never become the acquiring processor after this function returns.
|
||||
SPI_MASTER_ATTR static inline void req_core(spi_bus_lock_dev_t *dev_handle)
|
||||
{
|
||||
spi_bus_lock_t *lock = dev_handle->parent;
|
||||
|
||||
// Though `acquired_dev` is critical resource, `dev_handle == lock->acquired_dev`
|
||||
// is a stable statement unless `acquire_start` or `acquire_end` is called by current
|
||||
// device.
|
||||
if (dev_handle == lock->acquiring_dev){
|
||||
// Set the REQ bit and check BG bits if we are the acquiring processor.
|
||||
// If the BG bits were not active before, invoke the BG again.
|
||||
|
||||
// Avoid competitive risk against the `clear_pend_core`, `acq_dev_bg_active` should be set before
|
||||
// setting REQ bit.
|
||||
lock->acq_dev_bg_active = true;
|
||||
uint32_t status = lock_status_fetch_set(lock, DEV_REQ_MASK(dev_handle));
|
||||
if ((status & DEV_BG_MASK(dev_handle)) == 0) {
|
||||
bg_enable(lock); //acquiring processor passed to BG
|
||||
}
|
||||
} else {
|
||||
uint32_t status = lock_status_fetch_set(lock, DEV_REQ_MASK(dev_handle));
|
||||
if (status == 0) {
|
||||
bg_enable(lock); //acquiring processor passed to BG
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Set the LOCK bit. Handle related stuff and return true if we become the acquiring processor.
|
||||
SPI_MASTER_ISR_ATTR static inline bool acquire_core(spi_bus_lock_dev_t *dev_handle)
|
||||
{
|
||||
spi_bus_lock_t* lock = dev_handle->parent;
|
||||
portENTER_CRITICAL_SAFE(&s_spinlock);
|
||||
uint32_t status = lock_status_fetch_set(lock, dev_handle->mask & LOCK_MASK);
|
||||
portEXIT_CRITICAL_SAFE(&s_spinlock);
|
||||
|
||||
// Check all bits except WEAK_BG
|
||||
if ((status & (BG_MASK | LOCK_MASK)) == 0) {
|
||||
//succeed at once
|
||||
lock->acquiring_dev = dev_handle;
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acq_dev_bg_active);
|
||||
if (status & WEAK_BG_FLAG) {
|
||||
//Mainly to disable the cache (Weak_BG), that is not able to disable itself
|
||||
bg_disable(lock);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the next acquiring processor according to the status. Will directly change
|
||||
* the acquiring device if new one found.
|
||||
*
|
||||
* Cases:
|
||||
* - BG should still be the acquiring processor (Return false):
|
||||
* 1. Acquiring device has active BG bits: out_desired_dev = new acquiring device
|
||||
* 2. No acquiring device, but BG active: out_desired_dev = randomly pick one device with active BG bits
|
||||
* - BG should yield to the task (Return true):
|
||||
* 3. Acquiring device has no active BG bits: out_desired_dev = new acquiring device
|
||||
* 4. No acquiring device while no active BG bits: out_desired_dev=NULL
|
||||
*
|
||||
* Acquiring device task need to be resumed only when case 3.
|
||||
*
|
||||
* This scheduling can happen in either task or ISR, so `in_isr` or `bg_active` not touched.
|
||||
*
|
||||
* @param lock
|
||||
* @param status Current status
|
||||
* @param out_desired_dev Desired device to work next, see above.
|
||||
*
|
||||
* @return False if BG should still be the acquiring processor, otherwise True (yield to task).
|
||||
*/
|
||||
IRAM_ATTR static inline bool
|
||||
schedule_core(spi_bus_lock_t *lock, uint32_t status, spi_bus_lock_dev_t **out_desired_dev)
|
||||
{
|
||||
spi_bus_lock_dev_t* desired_dev = NULL;
|
||||
uint32_t lock_bits = (status & LOCK_MASK) >> LOCK_SHIFT;
|
||||
uint32_t bg_bits = status & BG_MASK;
|
||||
bg_bits = ((bg_bits >> REQ_SHIFT) | (bg_bits >> PENDING_SHIFT)) & REQ_MASK;
|
||||
|
||||
bool bg_yield;
|
||||
if (lock_bits) {
|
||||
int dev_id = mask_get_id(lock_bits);
|
||||
desired_dev = (spi_bus_lock_dev_t *)atomic_load(&lock->dev[dev_id]);
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(desired_dev);
|
||||
|
||||
lock->acquiring_dev = desired_dev;
|
||||
bg_yield = ((bg_bits & desired_dev->mask) == 0);
|
||||
lock->acq_dev_bg_active = !bg_yield;
|
||||
} else {
|
||||
lock->acq_dev_bg_active = false;
|
||||
if (bg_bits) {
|
||||
int dev_id = mask_get_id(bg_bits);
|
||||
desired_dev = (spi_bus_lock_dev_t *)atomic_load(&lock->dev[dev_id]);
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(desired_dev);
|
||||
|
||||
lock->acquiring_dev = NULL;
|
||||
bg_yield = false;
|
||||
} else {
|
||||
desired_dev = NULL;
|
||||
lock->acquiring_dev = NULL;
|
||||
bg_yield = true;
|
||||
}
|
||||
}
|
||||
*out_desired_dev = desired_dev;
|
||||
return bg_yield;
|
||||
}
|
||||
|
||||
//Clear the LOCK bit and trigger a rescheduling.
|
||||
IRAM_ATTR static inline void acquire_end_core(spi_bus_lock_dev_t *dev_handle)
|
||||
{
|
||||
spi_bus_lock_t* lock = dev_handle->parent;
|
||||
//uint32_t status = lock_status_clear(lock, dev_handle->mask & LOCK_MASK);
|
||||
spi_bus_lock_dev_t* desired_dev = NULL;
|
||||
|
||||
portENTER_CRITICAL_SAFE(&s_spinlock);
|
||||
uint32_t status = lock_status_clear(lock, dev_handle->mask & LOCK_MASK);
|
||||
bool invoke_bg = !schedule_core(lock, status, &desired_dev);
|
||||
portEXIT_CRITICAL_SAFE(&s_spinlock);
|
||||
|
||||
if (invoke_bg) {
|
||||
bg_enable(lock);
|
||||
} else if (desired_dev) {
|
||||
resume_dev(desired_dev);
|
||||
} else if (status & WEAK_BG_FLAG) {
|
||||
bg_enable(lock);
|
||||
}
|
||||
}
|
||||
|
||||
// Move the REQ bits to corresponding PEND bits. Must be called by acquiring processor.
|
||||
// Have no side effects on the acquiring device/processor.
|
||||
SPI_MASTER_ISR_ATTR static inline void update_pend_core(spi_bus_lock_t *lock, uint32_t status)
|
||||
{
|
||||
uint32_t active_req_bits = status & REQ_MASK;
|
||||
#if PENDING_SHIFT > REQ_SHIFT
|
||||
uint32_t pending_mask = active_req_bits << (PENDING_SHIFT - REQ_SHIFT);
|
||||
#else
|
||||
uint32_t pending_mask = active_req_bits >> (REQ_SHIFT - PENDING_SHIFT);
|
||||
#endif
|
||||
// We have to set the PEND bits and then clear the REQ bits, since BG bits are using bitwise OR logic,
|
||||
// this will not influence the effectiveness of the BG bits of every device.
|
||||
lock_status_fetch_set(lock, pending_mask);
|
||||
lock_status_fetch_clear(lock, active_req_bits);
|
||||
}
|
||||
|
||||
// Clear the PEND bit (not REQ bit!) of a device, return the suggestion whether we can try to quit the ISR.
|
||||
// Lost the acquiring processor immediately when the BG bits for active device are inactive, indiciating by the return value.
|
||||
// Can be called only when ISR is acting as the acquiring processor.
|
||||
SPI_MASTER_ISR_ATTR static inline bool clear_pend_core(spi_bus_lock_dev_t *dev_handle)
|
||||
{
|
||||
bool finished;
|
||||
spi_bus_lock_t *lock = dev_handle->parent;
|
||||
uint32_t pend_mask = DEV_PEND_MASK(dev_handle);
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(lock_status_fetch(lock) & pend_mask);
|
||||
|
||||
uint32_t status = lock_status_clear(lock, pend_mask);
|
||||
|
||||
if (lock->acquiring_dev == dev_handle) {
|
||||
finished = ((status & DEV_REQ_MASK(dev_handle)) == 0);
|
||||
if (finished) {
|
||||
lock->acq_dev_bg_active = false;
|
||||
}
|
||||
} else {
|
||||
finished = (status == 0);
|
||||
}
|
||||
return finished;
|
||||
}
|
||||
|
||||
// Return true if the ISR has already touched the HW, which means previous operations should
|
||||
// be terminated first, before we use the HW again. Otherwise return false.
|
||||
// In either case `in_isr` will be marked as true, until call to `bg_exit_core` with `wip=false` successfully.
|
||||
SPI_MASTER_ISR_ATTR static inline bool bg_entry_core(spi_bus_lock_t *lock)
|
||||
{
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acquiring_dev || lock->acq_dev_bg_active);
|
||||
/*
|
||||
* The interrupt is disabled at the entry of ISR to avoid competitive risk as below:
|
||||
*
|
||||
* The `esp_intr_enable` will be called (b) after new BG request is queued (a) in the task;
|
||||
* while `esp_intr_disable` should be called (c) if we check and found the sending queue is empty (d).
|
||||
* If (c) happens after (d), if things happens in this sequence:
|
||||
* (d) -> (a) -> (b) -> (c), the interrupt will be disabled while there's pending BG request in the queue.
|
||||
*
|
||||
* To avoid this, interrupt is disabled here, and re-enabled later if required. (c) -> (d) -> (a) -> (b) -> revert (c) if !d
|
||||
*/
|
||||
bg_disable(lock);
|
||||
if (lock->in_isr) {
|
||||
return false;
|
||||
} else {
|
||||
lock->in_isr = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle the conditions of status and interrupt, avoiding the ISR being disabled when there is any new coming BG requests.
|
||||
// When called with `wip=true`, means the ISR is performing some operations. Will enable the interrupt again and exit unconditionally.
|
||||
// When called with `wip=false`, will only return `true` when there is no coming BG request. If return value is `false`, the ISR should try again.
|
||||
// Will not change acquiring device.
|
||||
SPI_MASTER_ISR_ATTR static inline bool bg_exit_core(spi_bus_lock_t *lock, bool wip, BaseType_t *do_yield)
|
||||
{
|
||||
//See comments in `bg_entry_core`, re-enable interrupt disabled in entry if we do need the interrupt
|
||||
if (wip) {
|
||||
bg_enable(lock);
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acquiring_dev || lock->acq_dev_bg_active);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ret;
|
||||
uint32_t status = lock_status_fetch(lock);
|
||||
if (lock->acquiring_dev) {
|
||||
if (status & DEV_BG_MASK(lock->acquiring_dev)) {
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->acq_dev_bg_active);
|
||||
ret = false;
|
||||
} else {
|
||||
// The request may happen any time, even after we fetched the status.
|
||||
// The value of `acq_dev_bg_active` is random.
|
||||
resume_dev_in_isr(lock->acquiring_dev, do_yield);
|
||||
ret = true;
|
||||
}
|
||||
} else {
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acq_dev_bg_active);
|
||||
ret = !(status & BG_MASK);
|
||||
}
|
||||
if (ret) {
|
||||
//when successfully exit, but no transaction done, mark BG as inactive
|
||||
lock->in_isr = false;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
IRAM_ATTR static inline void dev_wait_prepare(spi_bus_lock_dev_t *dev_handle)
|
||||
{
|
||||
xSemaphoreTake(dev_handle->semphr, 0);
|
||||
}
|
||||
|
||||
SPI_MASTER_ISR_ATTR static inline esp_err_t dev_wait(spi_bus_lock_dev_t *dev_handle, TickType_t wait)
|
||||
{
|
||||
BaseType_t ret = xSemaphoreTake(dev_handle->semphr, wait);
|
||||
|
||||
if (ret == pdFALSE) return ESP_ERR_TIMEOUT;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
* Initialization & Deinitialization
|
||||
******************************************************************************/
|
||||
esp_err_t spi_bus_init_lock(spi_bus_lock_handle_t *out_lock, const spi_bus_lock_config_t *config)
|
||||
{
|
||||
spi_bus_lock_t* lock = (spi_bus_lock_t*)calloc(sizeof(spi_bus_lock_t), 1);
|
||||
if (lock == NULL) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
lock_status_init(lock);
|
||||
lock->acquiring_dev = NULL;
|
||||
lock->last_dev = NULL;
|
||||
lock->periph_cs_num = config->cs_num;
|
||||
lock->host_id = config->host_id;
|
||||
|
||||
*out_lock = lock;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void spi_bus_deinit_lock(spi_bus_lock_handle_t lock)
|
||||
{
|
||||
for (int i = 0; i < DEV_NUM_MAX; i++) {
|
||||
assert(atomic_load(&lock->dev[i]) == (intptr_t)NULL);
|
||||
}
|
||||
free(lock);
|
||||
}
|
||||
|
||||
static int try_acquire_free_dev(spi_bus_lock_t *lock, bool cs_required)
|
||||
{
|
||||
if (cs_required) {
|
||||
int i;
|
||||
for (i = 0; i < lock->periph_cs_num; i++) {
|
||||
intptr_t null = (intptr_t) NULL;
|
||||
//use 1 to occupy the slot, actual setup comes later
|
||||
if (atomic_compare_exchange_strong(&lock->dev[i], &null, (intptr_t) 1)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return ((i == lock->periph_cs_num)? -1: i);
|
||||
} else {
|
||||
int i;
|
||||
for (i = DEV_NUM_MAX - 1; i >= 0; i--) {
|
||||
intptr_t null = (intptr_t) NULL;
|
||||
//use 1 to occupy the slot, actual setup comes later
|
||||
if (atomic_compare_exchange_strong(&lock->dev[i], &null, (intptr_t) 1)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t spi_bus_lock_register_dev(spi_bus_lock_handle_t lock, spi_bus_lock_dev_config_t *config,
|
||||
spi_bus_lock_dev_handle_t *out_dev_handle)
|
||||
{
|
||||
if (lock == NULL) return ESP_ERR_INVALID_ARG;
|
||||
int id = try_acquire_free_dev(lock, config->flags & SPI_BUS_LOCK_DEV_FLAG_CS_REQUIRED);
|
||||
if (id == -1) return ESP_ERR_NOT_SUPPORTED;
|
||||
|
||||
spi_bus_lock_dev_t* dev_lock = (spi_bus_lock_dev_t*)heap_caps_calloc(sizeof(spi_bus_lock_dev_t), 1, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
|
||||
if (dev_lock == NULL) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
dev_lock->semphr = xSemaphoreCreateBinary();
|
||||
if (dev_lock->semphr == NULL) {
|
||||
free(dev_lock);
|
||||
atomic_store(&lock->dev[id], (intptr_t)NULL);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
dev_lock->parent = lock;
|
||||
dev_lock->mask = DEV_MASK(id);
|
||||
|
||||
ESP_LOGV(TAG, "device registered on bus %d slot %d.", lock->host_id, id);
|
||||
atomic_store(&lock->dev[id], (intptr_t)dev_lock);
|
||||
*out_dev_handle = dev_lock;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void spi_bus_lock_unregister_dev(spi_bus_lock_dev_handle_t dev_handle)
|
||||
{
|
||||
int id = dev_lock_get_id(dev_handle);
|
||||
|
||||
spi_bus_lock_t* lock = dev_handle->parent;
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(atomic_load(&lock->dev[id]) == (intptr_t)dev_handle);
|
||||
|
||||
if (lock->last_dev == dev_handle) lock->last_dev = NULL;
|
||||
|
||||
atomic_store(&lock->dev[id], (intptr_t)NULL);
|
||||
if (dev_handle->semphr) {
|
||||
vSemaphoreDelete(dev_handle->semphr);
|
||||
}
|
||||
|
||||
free(dev_handle);
|
||||
}
|
||||
|
||||
IRAM_ATTR static inline int mask_get_id(uint32_t mask)
|
||||
{
|
||||
return ID_DEV_MASK(mask);
|
||||
}
|
||||
|
||||
IRAM_ATTR static inline int dev_lock_get_id(spi_bus_lock_dev_t *dev_lock)
|
||||
{
|
||||
return mask_get_id(dev_lock->mask);
|
||||
}
|
||||
|
||||
void spi_bus_lock_set_bg_control(spi_bus_lock_handle_t lock, bg_ctrl_func_t bg_enable, bg_ctrl_func_t bg_disable, void *arg)
|
||||
{
|
||||
lock->bg_enable = bg_enable;
|
||||
lock->bg_disable = bg_disable;
|
||||
lock->bg_arg = arg;
|
||||
}
|
||||
|
||||
IRAM_ATTR int spi_bus_lock_get_dev_id(spi_bus_lock_dev_handle_t dev_handle)
|
||||
{
|
||||
return (dev_handle? dev_lock_get_id(dev_handle): -1);
|
||||
}
|
||||
|
||||
//will be called when cache disabled
|
||||
IRAM_ATTR bool spi_bus_lock_touch(spi_bus_lock_dev_handle_t dev_handle)
|
||||
{
|
||||
spi_bus_lock_dev_t* last_dev = dev_handle->parent->last_dev;
|
||||
dev_handle->parent->last_dev = dev_handle;
|
||||
if (last_dev != dev_handle) {
|
||||
int last_dev_id = (last_dev? dev_lock_get_id(last_dev): -1);
|
||||
ESP_DRAM_LOGV(TAG, "SPI dev changed from %d to %d",
|
||||
last_dev_id, dev_lock_get_id(dev_handle));
|
||||
}
|
||||
return (dev_handle != last_dev);
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
* Acquiring service
|
||||
******************************************************************************/
|
||||
IRAM_ATTR esp_err_t spi_bus_lock_acquire_start(spi_bus_lock_dev_t *dev_handle, TickType_t wait)
|
||||
{
|
||||
LOCK_CHECK(wait == portMAX_DELAY, "timeout other than portMAX_DELAY not supported", ESP_ERR_INVALID_ARG);
|
||||
|
||||
spi_bus_lock_t* lock = dev_handle->parent;
|
||||
|
||||
// Clear the semaphore before checking
|
||||
dev_wait_prepare(dev_handle);
|
||||
if (!acquire_core(dev_handle)) {
|
||||
//block until becoming the acquiring processor (help by previous acquiring processor)
|
||||
esp_err_t err = dev_wait(dev_handle, wait);
|
||||
//TODO: add timeout handling here.
|
||||
if (err != ESP_OK) return err;
|
||||
}
|
||||
|
||||
ESP_DRAM_LOGV(TAG, "dev %d acquired.", dev_lock_get_id(dev_handle));
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->acquiring_dev == dev_handle);
|
||||
|
||||
//When arrives at here, requests of this device should already be handled
|
||||
uint32_t status = lock_status_fetch(lock);
|
||||
(void) status;
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK((status & DEV_BG_MASK(dev_handle)) == 0);
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
IRAM_ATTR esp_err_t spi_bus_lock_acquire_end(spi_bus_lock_dev_t *dev_handle)
|
||||
{
|
||||
//release the bus
|
||||
spi_bus_lock_t* lock = dev_handle->parent;
|
||||
LOCK_CHECK(lock->acquiring_dev == dev_handle, "Cannot release a lock that hasn't been acquired.", ESP_ERR_INVALID_STATE);
|
||||
|
||||
acquire_end_core(dev_handle);
|
||||
|
||||
ESP_LOGV(TAG, "dev %d released.", dev_lock_get_id(dev_handle));
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
SPI_MASTER_ISR_ATTR spi_bus_lock_dev_handle_t spi_bus_lock_get_acquiring_dev(spi_bus_lock_t *lock)
|
||||
{
|
||||
return lock->acquiring_dev;
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
* BG (background operation) service
|
||||
******************************************************************************/
|
||||
SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_entry(spi_bus_lock_t* lock)
|
||||
{
|
||||
return bg_entry_core(lock);
|
||||
}
|
||||
|
||||
SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_exit(spi_bus_lock_t* lock, bool wip, BaseType_t* do_yield)
|
||||
{
|
||||
return bg_exit_core(lock, wip, do_yield);
|
||||
}
|
||||
|
||||
SPI_MASTER_ATTR esp_err_t spi_bus_lock_bg_request(spi_bus_lock_dev_t *dev_handle)
|
||||
{
|
||||
req_core(dev_handle);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
IRAM_ATTR esp_err_t spi_bus_lock_wait_bg_done(spi_bus_lock_dev_handle_t dev_handle, TickType_t wait)
|
||||
{
|
||||
spi_bus_lock_t *lock = dev_handle->parent;
|
||||
LOCK_CHECK(lock->acquiring_dev == dev_handle, "Cannot wait for a device that is not acquired", ESP_ERR_INVALID_STATE);
|
||||
LOCK_CHECK(wait == portMAX_DELAY, "timeout other than portMAX_DELAY not supported", ESP_ERR_INVALID_ARG);
|
||||
|
||||
// If no BG bits active, skip quickly. This is ensured by `spi_bus_lock_wait_bg_done`
|
||||
// cannot be executed with `bg_request` on the same device concurrently.
|
||||
if (lock_status_fetch(lock) & DEV_BG_MASK(dev_handle)) {
|
||||
// Clear the semaphore before checking
|
||||
dev_wait_prepare(dev_handle);
|
||||
if (lock_status_fetch(lock) & DEV_BG_MASK(dev_handle)) {
|
||||
//block until becoming the acquiring processor (help by previous acquiring processor)
|
||||
esp_err_t err = dev_wait(dev_handle, wait);
|
||||
//TODO: add timeout handling here.
|
||||
if (err != ESP_OK) return err;
|
||||
}
|
||||
}
|
||||
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acq_dev_bg_active);
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK((lock_status_fetch(lock) & DEV_BG_MASK(dev_handle)) == 0);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_clear_req(spi_bus_lock_dev_t *dev_handle)
|
||||
{
|
||||
bool finished = clear_pend_core(dev_handle);
|
||||
ESP_EARLY_LOGV(TAG, "dev %d served from bg.", dev_lock_get_id(dev_handle));
|
||||
return finished;
|
||||
}
|
||||
|
||||
SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_check_dev_acq(spi_bus_lock_t *lock,
|
||||
spi_bus_lock_dev_handle_t *out_dev_lock)
|
||||
{
|
||||
BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acquiring_dev);
|
||||
uint32_t status = lock_status_fetch(lock);
|
||||
return schedule_core(lock, status, out_dev_lock);
|
||||
}
|
||||
|
||||
SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_check_dev_req(spi_bus_lock_dev_t *dev_lock)
|
||||
{
|
||||
spi_bus_lock_t* lock = dev_lock->parent;
|
||||
uint32_t status = lock_status_fetch(lock);
|
||||
uint32_t dev_status = status & dev_lock->mask;
|
||||
|
||||
// move REQ bits of all device to corresponding PEND bits.
|
||||
// To reduce executing time, only done when the REQ bit of the calling device is set.
|
||||
if (dev_status & REQ_MASK) {
|
||||
update_pend_core(lock, status);
|
||||
return true;
|
||||
} else {
|
||||
return dev_status & PEND_MASK;
|
||||
}
|
||||
}
|
||||
|
||||
SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_req_exist(spi_bus_lock_t *lock)
|
||||
{
|
||||
uint32_t status = lock_status_fetch(lock);
|
||||
return status & BG_MASK;
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
* Static variables of the locks of the main flash
|
||||
******************************************************************************/
|
||||
#if CONFIG_SPI_FLASH_SHARE_SPI1_BUS
|
||||
static spi_bus_lock_dev_t lock_main_flash_dev;
|
||||
|
||||
static spi_bus_lock_t main_spi_bus_lock = {
|
||||
/*
|
||||
* the main bus cache is permanently required, this flag is set here and never clear so that the
|
||||
* cache will always be enabled if acquiring devices yield.
|
||||
*/
|
||||
.status = ATOMIC_VAR_INIT(WEAK_BG_FLAG),
|
||||
.acquiring_dev = NULL,
|
||||
.dev = {ATOMIC_VAR_INIT((intptr_t)&lock_main_flash_dev)},
|
||||
.new_req = 0,
|
||||
.periph_cs_num = SOC_SPI_PERIPH_CS_NUM(0),
|
||||
};
|
||||
const spi_bus_lock_handle_t g_main_spi_bus_lock = &main_spi_bus_lock;
|
||||
|
||||
esp_err_t spi_bus_lock_init_main_bus(void)
|
||||
{
|
||||
spi_bus_main_set_lock(g_main_spi_bus_lock);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static StaticSemaphore_t main_flash_semphr;
|
||||
|
||||
static spi_bus_lock_dev_t lock_main_flash_dev = {
|
||||
.semphr = NULL,
|
||||
.parent = &main_spi_bus_lock,
|
||||
.mask = DEV_MASK(0),
|
||||
};
|
||||
const spi_bus_lock_dev_handle_t g_spi_lock_main_flash_dev = &lock_main_flash_dev;
|
||||
|
||||
esp_err_t spi_bus_lock_init_main_dev(void)
|
||||
{
|
||||
g_spi_lock_main_flash_dev->semphr = xSemaphoreCreateBinaryStatic(&main_flash_semphr);
|
||||
if (g_spi_lock_main_flash_dev->semphr == NULL) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
#else //CONFIG_SPI_FLASH_SHARE_SPI1_BUS
|
||||
|
||||
//when the dev lock is not initialized, point to NULL
|
||||
const spi_bus_lock_dev_handle_t g_spi_lock_main_flash_dev = NULL;
|
||||
|
||||
#endif
|
||||
@@ -1,11 +1,16 @@
|
||||
# the JPEG library is in ROM but seems to fail randomly (PSRAM issue?)
|
||||
set(TJPGD tjpgd)
|
||||
|
||||
idf_component_register(SRC_DIRS . core core/ifaces fonts
|
||||
INCLUDE_DIRS . fonts core
|
||||
REQUIRES platform_config tools esp_common
|
||||
PRIV_REQUIRES services freertos driver
|
||||
EMBED_FILES note.jpg
|
||||
)
|
||||
PRIV_REQUIRES services freertos driver ${TJPGD}
|
||||
EMBED_FILES note.jpg )
|
||||
|
||||
if (NOT TJPGD)
|
||||
add_compile_definitions(TJPGD_ROM)
|
||||
endif()
|
||||
|
||||
set_source_files_properties(display.c
|
||||
PROPERTIES COMPILE_FLAGS
|
||||
-Wno-format-overflow
|
||||
)
|
||||
-Wno-format-overflow )
|
||||
|
||||
@@ -8,7 +8,11 @@
|
||||
|
||||
#include <string.h>
|
||||
#include "math.h"
|
||||
#ifdef TJPGD_ROM
|
||||
#include "esp32/rom/tjpgd.h"
|
||||
#else
|
||||
#include "tjpgd.h"
|
||||
#endif
|
||||
#include "esp_log.h"
|
||||
|
||||
#include "gds.h"
|
||||
@@ -142,7 +146,7 @@ static unsigned OutHandlerDirect(JDEC *Decoder, void *Bitmap, JRECT *Frame) {
|
||||
JpegCtx *Context = (JpegCtx*) Decoder->device;
|
||||
uint8_t *Pixels = (uint8_t*) Bitmap;
|
||||
int Shift = 8 - Context->Depth;
|
||||
|
||||
|
||||
// decoded image is RGB888, shift only make sense for grayscale
|
||||
if (Context->Mode == GDS_RGB888) {
|
||||
OUTHANDLERDIRECT(Scaler888, 0);
|
||||
|
||||
@@ -12,8 +12,11 @@ add_definitions(-DBELL_USE_MBEDTLS)
|
||||
add_definitions(-Wno-unused-variable -Wno-unused-const-variable -Wchar-subscripts -Wunused-label -Wmaybe-uninitialized -Wmisleading-indentation)
|
||||
|
||||
set(BELL_DISABLE_CODECS ON)
|
||||
set(BELL_EXTERNAL_TREMOR "idf::codecs")
|
||||
set(BELL_EXTERNAL_CJSON "idf::json")
|
||||
set(BELL_DISABLE_SINKS ON)
|
||||
set(CSPOT_TARGET_ESP32 ON)
|
||||
# becase CMake is so broken, the cache set below overrides a normal "set" for the first build
|
||||
set(BELL_EXTERNAL_TREMOR "idf::codecs" CACHE STRING "provide own codecs")
|
||||
set(BELL_EXTERNAL_CJSON "idf::json" CACHE STRING "provide own CJSON")
|
||||
|
||||
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/cspot ${CMAKE_CURRENT_BINARY_DIR}/cspot)
|
||||
target_link_libraries(${COMPONENT_LIB} PRIVATE cspot ${EXTRA_REQ_LIBS})
|
||||
|
||||
@@ -126,9 +126,12 @@ static void cspotTask(void *pvParameters) {
|
||||
case CSpotEventType::PLAY_PAUSE: {
|
||||
bool isPaused = std::get<bool>(event.data);
|
||||
if (isPaused) cspot.cHandler(CSPOT_PAUSE);
|
||||
else cspot.cHandler(CSPOT_PLAY);
|
||||
else cspot.cHandler(CSPOT_PLAY, false);
|
||||
break;
|
||||
}
|
||||
case CSpotEventType::PLAYBACK_START:
|
||||
cspot.cHandler(CSPOT_PLAY, (int) std::get<bool>(event.data));
|
||||
break;
|
||||
case CSpotEventType::LOAD:
|
||||
cspot.cHandler(CSPOT_LOAD, std::get<int>(event.data), -1);
|
||||
break;
|
||||
@@ -253,7 +256,7 @@ void ShimAudioSink::feedPCMFrames(const uint8_t *data, size_t bytes) {
|
||||
/****************************************************************************************
|
||||
* NVSFile class to store config
|
||||
*/
|
||||
bool NVSFile::readFile(std::string filename, std::string &fileContent) {
|
||||
bool NVSFile::readFile(std::string filename, std::string &fileContent) {
|
||||
auto search = files.find(filename);
|
||||
|
||||
// cache
|
||||
@@ -347,7 +350,7 @@ void ShimHTTPServer::registerHandler(bell::RequestType requestType, const std::s
|
||||
.user_ctx = NULL,
|
||||
};
|
||||
|
||||
// find athe first free spot and register handler
|
||||
// find the first free spot and register handler
|
||||
for (int i = 0; i < sizeof(uriHandlers)/sizeof(bell::httpHandler); i++) {
|
||||
if (!uriHandlers[i]) {
|
||||
uriHandlers[i] = handler;
|
||||
|
||||
@@ -25,26 +25,22 @@ if(UNIX AND NOT APPLE)
|
||||
# TODO: migrate from this to native linux mDNS
|
||||
endif()
|
||||
|
||||
if (GENERATE_PROTOS)
|
||||
file(GLOB SOURCES "src/*.cpp" "src/*.c")
|
||||
set(NANOPB_OPTIONS "-I${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
set(PROTOS protobuf/authentication.proto protobuf/mercury.proto protobuf/keyexchange.proto protobuf/spirc.proto protobuf/metadata.proto)
|
||||
message(${PROTOS})
|
||||
message("building protobuf")
|
||||
message(${CMAKE_CURRENT_SOURCE_DIR})
|
||||
nanopb_generate_cpp(PROTO_SRCS PROTO_HDRS RELPATH ${CMAKE_CURRENT_SOURCE_DIR} ${PROTOS})
|
||||
add_custom_target(generate_proto_sources DEPENDS ${PROTO_SRCS} ${PROTO_HDRS})
|
||||
set_source_files_properties(${PROTO_SRCS} ${PROTO_HDRS} PROPERTIES GENERATED TRUE)
|
||||
set(GENERATED_INCLUDES ${CMAKE_CURRENT_BINARY_DIR})
|
||||
else()
|
||||
file(GLOB SOURCES "src/*.cpp" "src/*.c" "protobuf/*.c")
|
||||
message("BEWARE => NOT GENERATING PROTOBUF")
|
||||
set(GENERATED_INCLUDES ".")
|
||||
endif()
|
||||
# Build protobuf code
|
||||
#set(NANOPB_OPTIONS "-I${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
#file(GLOB PROTOS protobuf/*.proto)
|
||||
#nanopb_generate_cpp(PROTO_SRCS PROTO_HDRS RELPATH ${CMAKE_CURRENT_SOURCE_DIR} ${PROTOS})
|
||||
#add_custom_target(generate_proto_sources DEPENDS ${PROTO_SRCS} ${PROTO_HDRS})
|
||||
#set_source_files_properties(${PROTO_SRCS} ${PROTO_HDRS}
|
||||
# PROPERTIES GENERATED TRUE)
|
||||
|
||||
file(GLOB SOURCES "src/*.cpp" "src/*.c" "protobuf/*.c")
|
||||
message("BEWARE => NOT GENERATING PROTOBUF")
|
||||
set(GENERATED_INCLUDES ".")
|
||||
|
||||
add_library(cspot STATIC ${SOURCES} ${PROTO_SRCS})
|
||||
# PUBLIC to propagate includes from bell to cspot dependents
|
||||
target_compile_definitions(bell PUBLIC PB_ENABLE_MALLOC)
|
||||
target_compile_definitions(bell PUBLIC PB_FIELD_32BIT)
|
||||
target_link_libraries(cspot PUBLIC ${EXTRA_LIBS})
|
||||
#target_include_directories(cspot PUBLIC "include" ${CMAKE_CURRENT_BINARY_DIR} ${NANOPB_INCLUDE_DIRS})
|
||||
target_include_directories(cspot PUBLIC "include" ${GENERATED_INCLUDES} ${NANOPB_INCLUDE_DIRS})
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
cmake_minimum_required(VERSION 2.8.12)
|
||||
cmake_policy(SET CMP0077 NEW)
|
||||
|
||||
project(bell)
|
||||
|
||||
# Configurable options
|
||||
option(BELL_DISABLE_CODECS "Disable libhelix AAC and MP3 codecs" OFF)
|
||||
#set(BELL_EXTERNAL_CJSON "" CACHE STRING "External cJSON library target name, optional")
|
||||
#set(BELL_EXTERNAL_TREMOR "" CACHE STRING "External tremor library target name, optional")
|
||||
option(BELL_DISABLE_SINKS "Disable built-in audio sink implementations" OFF)
|
||||
option(BELL_USE_ALSA "Enable ALSA sink" OFF)
|
||||
option(BELL_USE_PORTAUDIO "Enable PortAudio sink" OFF)
|
||||
set(BELL_EXTERNAL_CJSON "" CACHE STRING "External cJSON library target name, optional")
|
||||
set(BELL_EXTERNAL_TREMOR "" CACHE STRING "External tremor library target name, optional")
|
||||
|
||||
# Include nanoPB library
|
||||
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/nanopb/extra)
|
||||
find_package(Nanopb REQUIRED)
|
||||
include_directories(${NANOPB_INCLUDE_DIRS})
|
||||
list(APPEND EXTRA_INCLUDES ${NANOPB_INCLUDE_DIRS})
|
||||
|
||||
# CMake options
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
|
||||
add_definitions(-DUSE_DEFAULT_STDLIB=1)
|
||||
|
||||
# Main library sources
|
||||
@@ -74,6 +79,33 @@ else()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(NOT BELL_DISABLE_SINKS)
|
||||
set(PLATFORM "unix")
|
||||
if(ESP_PLATFORM)
|
||||
set(PLATFORM "esp")
|
||||
endif()
|
||||
# Add all built-in audio sinks
|
||||
file(GLOB SINK_SOURCES "src/sinks/${PLATFORM}/*.cpp" "src/sinks/${PLATFORM}/*.c")
|
||||
# Find ALSA if required, else remove the sink
|
||||
if(BELL_USE_ALSA)
|
||||
find_package(ALSA REQUIRED)
|
||||
list(APPEND EXTRA_INCLUDES ${ALSA_INCLUDE_DIRS})
|
||||
list(APPEND EXTRA_LIBS ${ALSA_LIBRARIES})
|
||||
else()
|
||||
list(REMOVE_ITEM SINK_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/sinks/unix/ALSAAudioSink.cpp)
|
||||
endif()
|
||||
# Find PortAudio if required, else remove the sink
|
||||
if(BELL_USE_PORTAUDIO)
|
||||
find_package(portaudio REQUIRED)
|
||||
list(APPEND EXTRA_INCLUDES ${PORTAUDIO_INCLUDE_DIRS})
|
||||
list(APPEND EXTRA_LIBS ${PORTAUDIO_LIBRARIES})
|
||||
else()
|
||||
list(REMOVE_ITEM SINK_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/sinks/unix/PortAudioSink.cpp)
|
||||
endif()
|
||||
list(APPEND SOURCES ${SINK_SOURCES})
|
||||
list(APPEND EXTRA_INCLUDES "include/sinks/${PLATFORM}")
|
||||
endif()
|
||||
|
||||
if(BELL_EXTERNAL_CJSON)
|
||||
list(APPEND EXTRA_LIBS ${BELL_EXTERNAL_CJSON})
|
||||
else()
|
||||
@@ -91,9 +123,7 @@ else()
|
||||
endif()
|
||||
|
||||
add_library(bell STATIC ${SOURCES})
|
||||
|
||||
message(${NANOPB_INCLUDE_DIRS})
|
||||
# PUBLIC to propagate esp-idf includes to bell dependents
|
||||
target_link_libraries(bell PUBLIC ${EXTRA_LIBS})
|
||||
target_include_directories(bell PUBLIC "include" ${EXTRA_INCLUDES} ${CMAKE_CURRENT_BINARY_DIR})
|
||||
target_include_directories(bell PUBLIC "include" "include/platform" ${EXTRA_INCLUDES} ${CMAKE_CURRENT_BINARY_DIR})
|
||||
target_compile_definitions(bell PUBLIC PB_ENABLE_MALLOC)
|
||||
|
||||
@@ -80,9 +80,8 @@ void bell::HTTPServer::listen() {
|
||||
socket(server->ai_family, server->ai_socktype, server->ai_protocol);
|
||||
struct sockaddr_in clientname;
|
||||
socklen_t incomingSockSize;
|
||||
int i;
|
||||
int yes = true;
|
||||
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) {
|
||||
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*) &yes, sizeof(int)) < 0) {
|
||||
throw std::runtime_error("setsockopt failed: " +
|
||||
std::string(strerror(errno)));
|
||||
}
|
||||
@@ -100,62 +99,65 @@ void bell::HTTPServer::listen() {
|
||||
FD_ZERO(&activeFdSet);
|
||||
FD_SET(sockfd, &activeFdSet);
|
||||
|
||||
for (;;) {
|
||||
for (int maxfd = sockfd;;) {
|
||||
/* Block until input arrives on one or more active sockets. */
|
||||
readFdSet = activeFdSet;
|
||||
struct timeval tv = {0, 100000};
|
||||
|
||||
if (select(FD_SETSIZE, &readFdSet, NULL, NULL, &tv) < 0) {
|
||||
|
||||
if (select(maxfd + 1, &readFdSet, NULL, NULL, &tv) < 0) {
|
||||
BELL_LOG(error, "http", "Error in select");
|
||||
perror("select");
|
||||
// exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* Service all the sockets with input pending. */
|
||||
for (i = 0; i < FD_SETSIZE; ++i)
|
||||
if (FD_ISSET(i, &readFdSet)) {
|
||||
if (i == sockfd) {
|
||||
/* Connection request on original socket. */
|
||||
int newFd;
|
||||
incomingSockSize = sizeof(clientname);
|
||||
newFd = accept(sockfd, (struct sockaddr *)&clientname,
|
||||
&incomingSockSize);
|
||||
if (newFd < 0) {
|
||||
perror("accept");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
/* Service listening socket. */
|
||||
if (FD_ISSET(sockfd, &readFdSet)) {
|
||||
int newFd;
|
||||
incomingSockSize = sizeof(clientname);
|
||||
newFd = accept(sockfd, (struct sockaddr*)&clientname,
|
||||
&incomingSockSize);
|
||||
if (newFd < 0) {
|
||||
perror("accept");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
FD_SET(newFd, &activeFdSet);
|
||||
FD_SET(newFd, &activeFdSet);
|
||||
|
||||
HTTPConnection conn = {.buffer = std::vector<uint8_t>(128),
|
||||
.httpMethod = ""};
|
||||
HTTPConnection conn = { .buffer = std::vector<uint8_t>(128),
|
||||
.httpMethod = "" };
|
||||
|
||||
this->connections.insert({newFd, conn});
|
||||
} else {
|
||||
/* Data arriving on an already-connected socket. */
|
||||
readFromClient(i);
|
||||
}
|
||||
}
|
||||
this->connections.insert({ newFd, conn });
|
||||
}
|
||||
|
||||
/* Service other sockets and update set & max */
|
||||
maxfd = sockfd;
|
||||
for (auto it = this->connections.cbegin();
|
||||
it != this->connections.cend() /* not hoisted */;
|
||||
/* no increment */) {
|
||||
it != this->connections.cend() /* not hoisted */;
|
||||
/* no increment */) {
|
||||
int fd = (*it).first;
|
||||
if ((*it).second.toBeClosed) {
|
||||
close((*it).first);
|
||||
FD_CLR((*it).first, &activeFdSet);
|
||||
close(fd);
|
||||
FD_CLR(fd, &activeFdSet);
|
||||
this->connections.erase(
|
||||
it++); // or "it = m.erase(it)" since C++11
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
if (fd != sockfd && FD_ISSET(fd, &readFdSet)) {
|
||||
/* Data arriving on an already-connected socket. */
|
||||
readFromClient(fd);
|
||||
}
|
||||
if (fd > maxfd) maxfd = fd;
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
void bell::HTTPServer::readFromClient(int clientFd) {
|
||||
HTTPConnection &conn = this->connections[clientFd];
|
||||
|
||||
int nbytes = recv(clientFd, &conn.buffer[0], conn.buffer.size(), 0);
|
||||
int nbytes = recv(clientFd, (char*) &conn.buffer[0], conn.buffer.size(), 0);
|
||||
if (nbytes < 0) {
|
||||
BELL_LOG(error, "http", "Error reading from client");
|
||||
perror("recv");
|
||||
|
||||
@@ -32,19 +32,19 @@ public:
|
||||
std::function<void()> endOfFileCallback;
|
||||
int volume = 255;
|
||||
uint32_t logVolume;
|
||||
bool needFlush = false;
|
||||
std::atomic<bool> isRunning = false;
|
||||
trackChangedCallback trackChanged;
|
||||
std::mutex runningMutex;
|
||||
|
||||
void setVolume(uint32_t volume);
|
||||
void handleLoad(std::shared_ptr<TrackReference> track, std::function<void()> &trackLoadedCallback, uint32_t position_ms, bool isPaused);
|
||||
void handleLoad(std::shared_ptr<TrackReference> track, std::function<void(bool)> &trackLoadedCallback, uint32_t position_ms, bool isPaused);
|
||||
void pause();
|
||||
void cancelCurrentTrack();
|
||||
void seekMs(size_t positionMs);
|
||||
void feedPCM(uint8_t *data, size_t len);
|
||||
void play();
|
||||
void stop();
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#error Regenerate this file with the current version of nanopb generator.
|
||||
#endif
|
||||
|
||||
PB_BIND(Header, Header, AUTO)
|
||||
PB_BIND(Header, Header, 2)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -12,9 +12,9 @@
|
||||
/* Struct definitions */
|
||||
typedef struct _Header {
|
||||
bool has_uri;
|
||||
char uri[64];
|
||||
char uri[256];
|
||||
bool has_method;
|
||||
char method[32];
|
||||
char method[64];
|
||||
} Header;
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ extern const pb_msgdesc_t Header_msg;
|
||||
#define Header_fields &Header_msg
|
||||
|
||||
/* Maximum encoded size of messages (where known) */
|
||||
#define Header_size 98
|
||||
#define Header_size 323
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#include "Logger.h"
|
||||
|
||||
AudioChunkManager::AudioChunkManager()
|
||||
: bell::Task("AudioChunkManager", 4 * 1024, -1, 0) {
|
||||
: bell::Task("AudioChunkManager", 4 * 1024, -1, 1) {
|
||||
this->chunks = std::vector<std::shared_ptr<AudioChunk>>();
|
||||
startTask();
|
||||
}
|
||||
|
||||
@@ -5,8 +5,13 @@
|
||||
static size_t vorbisReadCb(void *ptr, size_t size, size_t nmemb, ChunkedAudioStream *self)
|
||||
{
|
||||
size_t readSize = 0;
|
||||
while (readSize < nmemb * size && self->byteStream->position() < self->byteStream->size()) {
|
||||
readSize += self->byteStream->read((uint8_t *) ptr + readSize, (size * nmemb) - readSize);
|
||||
while (readSize < nmemb * size && self->byteStream->position() < self->byteStream->size() && self->isRunning) {
|
||||
size_t bytes = self->byteStream->read((uint8_t *) ptr + readSize, (size * nmemb) - readSize);
|
||||
if (bytes <= 0) {
|
||||
CSPOT_LOG(info, "unexpected end/error of stream");
|
||||
return readSize;
|
||||
}
|
||||
readSize += bytes;
|
||||
}
|
||||
return readSize;
|
||||
}
|
||||
|
||||
@@ -115,7 +115,6 @@ std::shared_ptr<AudioChunk> MercuryManager::fetchAudioChunk(std::vector<uint8_t>
|
||||
this->session->shanConn->sendPacket(static_cast<uint8_t>(MercuryType::AUDIO_CHUNK_REQUEST_COMMAND), buffer);
|
||||
|
||||
// Used for broken connection detection
|
||||
CSPOT_LOG(info, "requesting Chunk %hu", this->audioChunkSequence - 1);
|
||||
this->lastRequestTimestamp = this->timeProvider->getSyncedTimestamp();
|
||||
return this->audioChunkManager->registerNewChunk(this->audioChunkSequence - 1, audioKey, startPos, endPos);
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ std::vector<uint8_t> PlainConnection::readBlock(size_t size)
|
||||
break;
|
||||
default:
|
||||
if (retries++ > 4) throw std::runtime_error("Error in read");
|
||||
|
||||
goto READ;
|
||||
}
|
||||
}
|
||||
idx += n;
|
||||
|
||||
@@ -114,7 +114,7 @@ void Player::runTask()
|
||||
}
|
||||
else
|
||||
{
|
||||
usleep(10000);
|
||||
usleep(20000);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -147,7 +147,7 @@ void Player::cancelCurrentTrack()
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleLoad(std::shared_ptr<TrackReference> trackReference, std::function<void()>& trackLoadedCallback, uint32_t position_ms, bool isPaused)
|
||||
void Player::handleLoad(std::shared_ptr<TrackReference> trackReference, std::function<void(bool)>& trackLoadedCallback, uint32_t position_ms, bool isPaused)
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(loadTrackMutex);
|
||||
|
||||
@@ -166,7 +166,9 @@ void Player::handleLoad(std::shared_ptr<TrackReference> trackReference, std::fun
|
||||
|
||||
this->nextTrack->trackInfoReceived = this->trackChanged;
|
||||
this->nextTrack->loadedTrackCallback = [this, framesCallback, trackLoadedCallback]() {
|
||||
trackLoadedCallback();
|
||||
bool needFlush = currentTrack != nullptr && currentTrack->audioStream != nullptr && currentTrack->audioStream->isRunning;
|
||||
cancelCurrentTrack();
|
||||
trackLoadedCallback(needFlush);
|
||||
|
||||
this->nextTrackMutex.lock();
|
||||
this->nextTrack->audioStream->streamFinishedCallback = this->endOfFileCallback;
|
||||
@@ -175,7 +177,6 @@ void Player::handleLoad(std::shared_ptr<TrackReference> trackReference, std::fun
|
||||
this->nextTrack->loaded = true;
|
||||
this->nextTrackMutex.unlock();
|
||||
|
||||
cancelCurrentTrack();
|
||||
};
|
||||
this->nextTrackMutex.unlock();
|
||||
}
|
||||
|
||||
@@ -190,10 +190,10 @@ void SpircController::handleFrame(std::vector<uint8_t> &data) {
|
||||
void SpircController::loadTrack(uint32_t position_ms, bool isPaused) {
|
||||
sendEvent(CSpotEventType::LOAD, (int) position_ms);
|
||||
state->setPlaybackState(PlaybackState::Loading);
|
||||
std::function<void()> loadedLambda = [=]() {
|
||||
std::function<void(bool)> loadedLambda = [=](bool needFlush) {
|
||||
// Loading finished, notify that playback started
|
||||
setPause(isPaused, false);
|
||||
sendEvent(CSpotEventType::PLAYBACK_START);
|
||||
sendEvent(CSpotEventType::PLAYBACK_START, needFlush);
|
||||
};
|
||||
|
||||
player->handleLoad(state->getCurrentTrack(), loadedLambda, position_ms,
|
||||
|
||||
@@ -106,7 +106,7 @@ void SpotifyTrack::trackInformationCallback(std::unique_ptr<MercuryResponse> res
|
||||
altIndex++;
|
||||
CSPOT_LOG(info, "Trying alternative %d", altIndex);
|
||||
|
||||
if(altIndex > trackInfo.alternative_count) {
|
||||
if(altIndex >= trackInfo.alternative_count) {
|
||||
// no alternatives for song
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,10 @@ static bool enable_bt_sink;
|
||||
|
||||
#if CONFIG_CSPOT_SINK
|
||||
#include "cspot_sink.h"
|
||||
|
||||
static bool enable_cspot;
|
||||
#define CSPOT_OUTPUT_SIZE ((48000 * BYTES_PER_FRAME * 2) & ~BYTES_PER_FRAME)
|
||||
|
||||
#endif
|
||||
|
||||
#if CONFIG_AIRPLAY_SINK
|
||||
@@ -47,7 +50,7 @@ static EXT_RAM_ATTR struct {
|
||||
} raop_sync;
|
||||
#endif
|
||||
|
||||
static bool abort_sink ;
|
||||
static enum { SINK_RUNNING, SINK_ABORT, SINK_DISCARD } sink_state;
|
||||
|
||||
#define LOCK_O mutex_lock(outputbuf->mutex)
|
||||
#define UNLOCK_O mutex_unlock(outputbuf->mutex)
|
||||
@@ -77,10 +80,10 @@ static void sink_data_handler(const uint8_t *data, uint32_t len)
|
||||
}
|
||||
|
||||
LOCK_O;
|
||||
abort_sink = false;
|
||||
if (sink_state == SINK_ABORT) sink_state = SINK_RUNNING;
|
||||
|
||||
// there will always be room at some point
|
||||
while (len && wait && !abort_sink) {
|
||||
while (len && wait && sink_state == SINK_RUNNING) {
|
||||
bytes = min(_buf_space(outputbuf), _buf_cont_write(outputbuf)) / (BYTES_PER_FRAME / 4);
|
||||
bytes = min(len, bytes);
|
||||
#if BYTES_PER_FRAME == 4
|
||||
@@ -95,7 +98,7 @@ static void sink_data_handler(const uint8_t *data, uint32_t len)
|
||||
#endif
|
||||
_buf_inc_writep(outputbuf, bytes * BYTES_PER_FRAME / 4);
|
||||
space = _buf_space(outputbuf);
|
||||
|
||||
|
||||
len -= bytes;
|
||||
data += bytes;
|
||||
|
||||
@@ -156,7 +159,7 @@ static bool bt_sink_cmd_handler(bt_sink_cmd_t cmd, va_list args)
|
||||
_buf_flush(outputbuf);
|
||||
output.state = OUTPUT_STOPPED;
|
||||
output.stop_time = gettime_ms();
|
||||
abort_sink = true;
|
||||
sink_state = SINK_ABORT;
|
||||
LOG_INFO("BT stop");
|
||||
break;
|
||||
case BT_SINK_PAUSE:
|
||||
@@ -295,7 +298,7 @@ static bool raop_sink_cmd_handler(raop_event_t event, va_list args)
|
||||
_buf_flush(outputbuf);
|
||||
raop_state = event;
|
||||
if (output.state > OUTPUT_STOPPED) output.state = OUTPUT_STOPPED;
|
||||
abort_sink = true;
|
||||
sink_state = SINK_ABORT;
|
||||
output.frames_played = 0;
|
||||
output.stop_time = gettime_ms();
|
||||
break;
|
||||
@@ -351,41 +354,48 @@ static bool cspot_cmd_handler(cspot_event_t cmd, va_list args)
|
||||
output.frames_played = 0;
|
||||
output.state = OUTPUT_STOPPED;
|
||||
_buf_flush(outputbuf);
|
||||
_buf_limit(outputbuf, 0);
|
||||
_buf_limit(outputbuf, CSPOT_OUTPUT_SIZE);
|
||||
if (decode.state != DECODE_STOPPED) decode.state = DECODE_ERROR;
|
||||
LOG_INFO("CSpot connected");
|
||||
break;
|
||||
case CSPOT_DISC:
|
||||
_buf_flush(outputbuf);
|
||||
abort_sink = true;
|
||||
sink_state = SINK_ABORT;
|
||||
output.external = 0;
|
||||
output.state = OUTPUT_STOPPED;
|
||||
output.stop_time = gettime_ms();
|
||||
LOG_INFO("CSpot disconnected");
|
||||
break;
|
||||
case CSPOT_TRACK:
|
||||
_buf_flush(outputbuf);
|
||||
abort_sink = true;
|
||||
LOG_INFO("CSpot sink new track rate %d", output.next_sample_rate);
|
||||
break;
|
||||
case CSPOT_PLAY:
|
||||
case CSPOT_PLAY: {
|
||||
int flush = va_arg(args, int);
|
||||
if (flush) {
|
||||
_buf_flush(outputbuf);
|
||||
sink_state = SINK_ABORT;
|
||||
} else {
|
||||
sink_state = SINK_RUNNING;
|
||||
}
|
||||
output.state = OUTPUT_RUNNING;
|
||||
LOG_INFO("CSpot play");
|
||||
break;
|
||||
}
|
||||
case CSPOT_SEEK:
|
||||
//TODO: can it be merged with flush (shall we stop)
|
||||
_buf_flush(outputbuf);
|
||||
abort_sink = true;
|
||||
sink_state = SINK_ABORT;
|
||||
LOG_INFO("CSpot seek by %d", va_arg(args, int));
|
||||
break;
|
||||
case CSPOT_FLUSH:
|
||||
_buf_flush(outputbuf);
|
||||
abort_sink = true;
|
||||
__attribute__ ((fallthrough));
|
||||
sink_state = SINK_DISCARD;
|
||||
output.state = OUTPUT_STOPPED;
|
||||
LOG_INFO("CSpot flush");
|
||||
break;
|
||||
case CSPOT_PAUSE:
|
||||
output.state = OUTPUT_STOPPED;
|
||||
output.stop_time = gettime_ms();
|
||||
LOG_INFO("CSpot pause/flush");
|
||||
LOG_INFO("CSpot pause");
|
||||
break;
|
||||
case CSPOT_VOLUME: {
|
||||
u32_t volume = va_arg(args, u32_t);
|
||||
|
||||
@@ -864,7 +864,7 @@ static void grfa_handler(u8_t *data, int len) {
|
||||
} else if (artwork.size) GDS_ClearWindow(display, artwork.x, artwork.y, -1, -1, GDS_COLOR_BLACK);
|
||||
|
||||
artwork.full = artwork.enable && artwork.x == 0 && artwork.y == 0;
|
||||
LOG_INFO("gfra en:%u x:%hu, y:%hu", artwork.enable, artwork.x, artwork.y);
|
||||
LOG_DEBUG("gfra en:%u x:%hu, y:%hu", artwork.enable, artwork.x, artwork.y);
|
||||
|
||||
// done in any case
|
||||
return;
|
||||
@@ -883,7 +883,7 @@ static void grfa_handler(u8_t *data, int len) {
|
||||
artwork.y = htons(pkt->y);
|
||||
artwork.full = artwork.enable && artwork.x == 0 && artwork.y == 0;
|
||||
if (artwork.data) free(artwork.data);
|
||||
artwork.data = malloc(length);
|
||||
artwork.data = malloc(length);
|
||||
}
|
||||
|
||||
// copy artwork data
|
||||
@@ -891,12 +891,14 @@ static void grfa_handler(u8_t *data, int len) {
|
||||
artwork.size += size;
|
||||
if (artwork.size == length) {
|
||||
GDS_ClearWindow(display, artwork.x, artwork.y, -1, -1, GDS_COLOR_BLACK);
|
||||
xSemaphoreTake(displayer.mutex, portMAX_DELAY);
|
||||
GDS_DrawJPEG(display, artwork.data, artwork.x, artwork.y, artwork.y < displayer.height ? (GDS_IMAGE_RIGHT | GDS_IMAGE_TOP) : GDS_IMAGE_CENTER);
|
||||
xSemaphoreGive(displayer.mutex);
|
||||
free(artwork.data);
|
||||
artwork.data = NULL;
|
||||
}
|
||||
|
||||
LOG_INFO("gfra l:%u x:%hu, y:%hu, o:%u s:%u", length, artwork.x, artwork.y, offset, size);
|
||||
|
||||
LOG_DEBUG("gfra l:%u x:%hu, y:%hu, o:%u s:%u", length, artwork.x, artwork.y, offset, size);
|
||||
}
|
||||
|
||||
/****************************************************************************************
|
||||
@@ -1316,7 +1318,7 @@ static void displayer_task(void *args) {
|
||||
// need to make sure we own display
|
||||
if (display && displayer.owned) GDS_Update(display);
|
||||
else if (!led_display) displayer.wake = LONG_WAKE;
|
||||
|
||||
|
||||
// release semaphore and sleep what's needed
|
||||
xSemaphoreGive(displayer.mutex);
|
||||
|
||||
|
||||
@@ -110,8 +110,7 @@ void ws2812_control_init(void)
|
||||
|
||||
void ws2812_write_leds(struct led_state new_state) {
|
||||
setup_rmt_data_buffer(new_state);
|
||||
ESP_ERROR_CHECK(rmt_write_items(LED_RMT_TX_CHANNEL, led_data_buffer, LED_BUFFER_ITEMS, false));
|
||||
ESP_ERROR_CHECK(rmt_wait_tx_done(LED_RMT_TX_CHANNEL, portMAX_DELAY));
|
||||
rmt_write_items(LED_RMT_TX_CHANNEL, led_data_buffer, LED_BUFFER_ITEMS, false);
|
||||
}
|
||||
|
||||
void setup_rmt_data_buffer(struct led_state new_state)
|
||||
|
||||
3
components/tjpgd/CMakeLists.txt
Normal file
3
components/tjpgd/CMakeLists.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
idf_component_register( SRC_DIRS .
|
||||
INCLUDE_DIRS .
|
||||
)
|
||||
968
components/tjpgd/tjpgd.c
Normal file
968
components/tjpgd/tjpgd.c
Normal file
@@ -0,0 +1,968 @@
|
||||
/*----------------------------------------------------------------------------/
|
||||
/ TJpgDec - Tiny JPEG Decompressor R0.01b (C)ChaN, 2012
|
||||
/-----------------------------------------------------------------------------/
|
||||
/ The TJpgDec is a generic JPEG decompressor module for tiny embedded systems.
|
||||
/ This is a free software that opened for education, research and commercial
|
||||
/ developments under license policy of following terms.
|
||||
/
|
||||
/ Copyright (C) 2012, ChaN, all right reserved.
|
||||
/
|
||||
/ * The TJpgDec module is a free software and there is NO WARRANTY.
|
||||
/ * No restriction on use. You can use, modify and redistribute it for
|
||||
/ personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
|
||||
/ * Redistributions of source code must retain the above copyright notice.
|
||||
/
|
||||
/-----------------------------------------------------------------------------/
|
||||
/ Oct 04,'11 R0.01 First release.
|
||||
/ Feb 19,'12 R0.01a Fixed decompression fails when scan starts with an escape seq.
|
||||
/ Sep 03,'12 R0.01b Added JD_TBLCLIP option.
|
||||
/----------------------------------------------------------------------------*/
|
||||
|
||||
#include "tjpgd.h"
|
||||
|
||||
#define SUPPORT_JPEG 1
|
||||
|
||||
#ifdef SUPPORT_JPEG
|
||||
/*-----------------------------------------------*/
|
||||
/* Zigzag-order to raster-order conversion table */
|
||||
/*-----------------------------------------------*/
|
||||
|
||||
#define ZIG(n) Zig[n]
|
||||
|
||||
static
|
||||
const BYTE Zig[64] = { /* Zigzag-order to raster-order conversion table */
|
||||
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
|
||||
12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
|
||||
35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
|
||||
58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*-------------------------------------------------*/
|
||||
/* Input scale factor of Arai algorithm */
|
||||
/* (scaled up 16 bits for fixed point operations) */
|
||||
/*-------------------------------------------------*/
|
||||
|
||||
#define IPSF(n) Ipsf[n]
|
||||
|
||||
static
|
||||
const WORD Ipsf[64] = { /* See also aa_idct.png */
|
||||
(WORD)(1.00000*8192), (WORD)(1.38704*8192), (WORD)(1.30656*8192), (WORD)(1.17588*8192), (WORD)(1.00000*8192), (WORD)(0.78570*8192), (WORD)(0.54120*8192), (WORD)(0.27590*8192),
|
||||
(WORD)(1.38704*8192), (WORD)(1.92388*8192), (WORD)(1.81226*8192), (WORD)(1.63099*8192), (WORD)(1.38704*8192), (WORD)(1.08979*8192), (WORD)(0.75066*8192), (WORD)(0.38268*8192),
|
||||
(WORD)(1.30656*8192), (WORD)(1.81226*8192), (WORD)(1.70711*8192), (WORD)(1.53636*8192), (WORD)(1.30656*8192), (WORD)(1.02656*8192), (WORD)(0.70711*8192), (WORD)(0.36048*8192),
|
||||
(WORD)(1.17588*8192), (WORD)(1.63099*8192), (WORD)(1.53636*8192), (WORD)(1.38268*8192), (WORD)(1.17588*8192), (WORD)(0.92388*8192), (WORD)(0.63638*8192), (WORD)(0.32442*8192),
|
||||
(WORD)(1.00000*8192), (WORD)(1.38704*8192), (WORD)(1.30656*8192), (WORD)(1.17588*8192), (WORD)(1.00000*8192), (WORD)(0.78570*8192), (WORD)(0.54120*8192), (WORD)(0.27590*8192),
|
||||
(WORD)(0.78570*8192), (WORD)(1.08979*8192), (WORD)(1.02656*8192), (WORD)(0.92388*8192), (WORD)(0.78570*8192), (WORD)(0.61732*8192), (WORD)(0.42522*8192), (WORD)(0.21677*8192),
|
||||
(WORD)(0.54120*8192), (WORD)(0.75066*8192), (WORD)(0.70711*8192), (WORD)(0.63638*8192), (WORD)(0.54120*8192), (WORD)(0.42522*8192), (WORD)(0.29290*8192), (WORD)(0.14932*8192),
|
||||
(WORD)(0.27590*8192), (WORD)(0.38268*8192), (WORD)(0.36048*8192), (WORD)(0.32442*8192), (WORD)(0.27590*8192), (WORD)(0.21678*8192), (WORD)(0.14932*8192), (WORD)(0.07612*8192)
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*---------------------------------------------*/
|
||||
/* Conversion table for fast clipping process */
|
||||
/*---------------------------------------------*/
|
||||
|
||||
#if JD_TBLCLIP
|
||||
|
||||
#define BYTECLIP(v) Clip8[(UINT)(v) & 0x3FF]
|
||||
|
||||
static
|
||||
const BYTE Clip8[1024] = {
|
||||
/* 0..255 */
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
|
||||
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
|
||||
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
|
||||
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
|
||||
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
|
||||
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
|
||||
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
|
||||
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
|
||||
/* 256..511 */
|
||||
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||
/* -512..-257 */
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
/* -256..-1 */
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
};
|
||||
|
||||
#else /* JD_TBLCLIP */
|
||||
|
||||
inline
|
||||
BYTE BYTECLIP (
|
||||
INT val
|
||||
)
|
||||
{
|
||||
if (val < 0) val = 0;
|
||||
if (val > 255) val = 255;
|
||||
|
||||
return (BYTE)val;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Allocate a memory block from memory pool */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
static
|
||||
void* alloc_pool ( /* Pointer to allocated memory block (NULL:no memory available) */
|
||||
JDEC* jd, /* Pointer to the decompressor object */
|
||||
UINT nd /* Number of bytes to allocate */
|
||||
)
|
||||
{
|
||||
char *rp = 0;
|
||||
|
||||
|
||||
nd = (nd + 3) & ~3; /* Align block size to the word boundary */
|
||||
|
||||
if (jd->sz_pool >= nd) {
|
||||
jd->sz_pool -= nd;
|
||||
rp = (char*)jd->pool; /* Get start of available memory pool */
|
||||
jd->pool = (void*)(rp + nd); /* Allocate requierd bytes */
|
||||
}
|
||||
|
||||
return (void*)rp; /* Return allocated memory block (NULL:no memory to allocate) */
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Create de-quantization and prescaling tables with a DQT segment */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
static
|
||||
UINT create_qt_tbl ( /* 0:OK, !0:Failed */
|
||||
JDEC* jd, /* Pointer to the decompressor object */
|
||||
const BYTE* data, /* Pointer to the quantizer tables */
|
||||
UINT ndata /* Size of input data */
|
||||
)
|
||||
{
|
||||
UINT i;
|
||||
BYTE d, z;
|
||||
LONG *pb;
|
||||
|
||||
|
||||
while (ndata) { /* Process all tables in the segment */
|
||||
if (ndata < 65) return JDR_FMT1; /* Err: table size is unaligned */
|
||||
ndata -= 65;
|
||||
d = *data++; /* Get table property */
|
||||
if (d & 0xF0) return JDR_FMT1; /* Err: not 8-bit resolution */
|
||||
i = d & 3; /* Get table ID */
|
||||
pb = alloc_pool(jd, 64 * sizeof (LONG));/* Allocate a memory block for the table */
|
||||
if (!pb) return JDR_MEM1; /* Err: not enough memory */
|
||||
jd->qttbl[i] = pb; /* Register the table */
|
||||
for (i = 0; i < 64; i++) { /* Load the table */
|
||||
z = ZIG(i); /* Zigzag-order to raster-order conversion */
|
||||
pb[z] = (LONG)((DWORD)*data++ * IPSF(z)); /* Apply scale factor of Arai algorithm to the de-quantizers */
|
||||
}
|
||||
}
|
||||
|
||||
return JDR_OK;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Create huffman code tables with a DHT segment */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
static
|
||||
UINT create_huffman_tbl ( /* 0:OK, !0:Failed */
|
||||
JDEC* jd, /* Pointer to the decompressor object */
|
||||
const BYTE* data, /* Pointer to the packed huffman tables */
|
||||
UINT ndata /* Size of input data */
|
||||
)
|
||||
{
|
||||
UINT i, j, b, np, cls, num;
|
||||
BYTE d, *pb, *pd;
|
||||
WORD hc, *ph;
|
||||
|
||||
|
||||
while (ndata) { /* Process all tables in the segment */
|
||||
if (ndata < 17) return JDR_FMT1; /* Err: wrong data size */
|
||||
ndata -= 17;
|
||||
d = *data++; /* Get table number and class */
|
||||
cls = (d >> 4); num = d & 0x0F; /* class = dc(0)/ac(1), table number = 0/1 */
|
||||
if (d & 0xEE) return JDR_FMT1; /* Err: invalid class/number */
|
||||
pb = alloc_pool(jd, 16); /* Allocate a memory block for the bit distribution table */
|
||||
if (!pb) return JDR_MEM1; /* Err: not enough memory */
|
||||
jd->huffbits[num][cls] = pb;
|
||||
for (np = i = 0; i < 16; i++) { /* Load number of patterns for 1 to 16-bit code */
|
||||
pb[i] = b = *data++;
|
||||
np += b; /* Get sum of code words for each code */
|
||||
}
|
||||
|
||||
ph = alloc_pool(jd, np * sizeof (WORD));/* Allocate a memory block for the code word table */
|
||||
if (!ph) return JDR_MEM1; /* Err: not enough memory */
|
||||
jd->huffcode[num][cls] = ph;
|
||||
hc = 0;
|
||||
for (j = i = 0; i < 16; i++) { /* Re-build huffman code word table */
|
||||
b = pb[i];
|
||||
while (b--) ph[j++] = hc++;
|
||||
hc <<= 1;
|
||||
}
|
||||
|
||||
if (ndata < np) return JDR_FMT1; /* Err: wrong data size */
|
||||
ndata -= np;
|
||||
pd = alloc_pool(jd, np); /* Allocate a memory block for the decoded data */
|
||||
if (!pd) return JDR_MEM1; /* Err: not enough memory */
|
||||
jd->huffdata[num][cls] = pd;
|
||||
for (i = 0; i < np; i++) { /* Load decoded data corresponds to each code ward */
|
||||
d = *data++;
|
||||
if (!cls && d > 11) return JDR_FMT1;
|
||||
*pd++ = d;
|
||||
}
|
||||
}
|
||||
|
||||
return JDR_OK;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Extract N bits from input stream */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
static
|
||||
INT bitext ( /* >=0: extracted data, <0: error code */
|
||||
JDEC* jd, /* Pointer to the decompressor object */
|
||||
UINT nbit /* Number of bits to extract (1 to 11) */
|
||||
)
|
||||
{
|
||||
BYTE msk, s, *dp;
|
||||
UINT dc, v, f;
|
||||
|
||||
|
||||
msk = jd->dmsk; dc = jd->dctr; dp = jd->dptr; /* Bit mask, number of data available, read ptr */
|
||||
s = *dp; v = f = 0;
|
||||
do {
|
||||
if (!msk) { /* Next byte? */
|
||||
if (!dc) { /* No input data is available, re-fill input buffer */
|
||||
dp = jd->inbuf; /* Top of input buffer */
|
||||
dc = jd->infunc(jd, dp, JD_SZBUF);
|
||||
if (!dc) return 0 - (INT)JDR_INP; /* Err: read error or wrong stream termination */
|
||||
} else {
|
||||
dp++; /* Next data ptr */
|
||||
}
|
||||
dc--; /* Decrement number of available bytes */
|
||||
if (f) { /* In flag sequence? */
|
||||
f = 0; /* Exit flag sequence */
|
||||
if (*dp != 0) return 0 - (INT)JDR_FMT1; /* Err: unexpected flag is detected (may be collapted data) */
|
||||
*dp = s = 0xFF; /* The flag is a data 0xFF */
|
||||
} else {
|
||||
s = *dp; /* Get next data byte */
|
||||
if (s == 0xFF) { /* Is start of flag sequence? */
|
||||
f = 1; continue; /* Enter flag sequence */
|
||||
}
|
||||
}
|
||||
msk = 0x80; /* Read from MSB */
|
||||
}
|
||||
v <<= 1; /* Get a bit */
|
||||
if (s & msk) v++;
|
||||
msk >>= 1;
|
||||
nbit--;
|
||||
} while (nbit);
|
||||
jd->dmsk = msk; jd->dctr = dc; jd->dptr = dp;
|
||||
|
||||
return (INT)v;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Extract a huffman decoded data from input stream */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
static
|
||||
INT huffext ( /* >=0: decoded data, <0: error code */
|
||||
JDEC* jd, /* Pointer to the decompressor object */
|
||||
const BYTE* hbits, /* Pointer to the bit distribution table */
|
||||
const WORD* hcode, /* Pointer to the code word table */
|
||||
const BYTE* hdata /* Pointer to the data table */
|
||||
)
|
||||
{
|
||||
BYTE msk, s, *dp;
|
||||
UINT dc, v, f, bl, nd;
|
||||
|
||||
|
||||
msk = jd->dmsk; dc = jd->dctr; dp = jd->dptr; /* Bit mask, number of data available, read ptr */
|
||||
s = *dp; v = f = 0;
|
||||
bl = 16; /* Max code length */
|
||||
do {
|
||||
if (!msk) { /* Next byte? */
|
||||
if (!dc) { /* No input data is available, re-fill input buffer */
|
||||
dp = jd->inbuf; /* Top of input buffer */
|
||||
dc = jd->infunc(jd, dp, JD_SZBUF);
|
||||
if (!dc) return 0 - (INT)JDR_INP; /* Err: read error or wrong stream termination */
|
||||
} else {
|
||||
dp++; /* Next data ptr */
|
||||
}
|
||||
dc--; /* Decrement number of available bytes */
|
||||
if (f) { /* In flag sequence? */
|
||||
f = 0; /* Exit flag sequence */
|
||||
if (*dp != 0)
|
||||
return 0 - (INT)JDR_FMT1; /* Err: unexpected flag is detected (may be collapted data) */
|
||||
*dp = s = 0xFF; /* The flag is a data 0xFF */
|
||||
} else {
|
||||
s = *dp; /* Get next data byte */
|
||||
if (s == 0xFF) { /* Is start of flag sequence? */
|
||||
f = 1; continue; /* Enter flag sequence, get trailing byte */
|
||||
}
|
||||
}
|
||||
msk = 0x80; /* Read from MSB */
|
||||
}
|
||||
v <<= 1; /* Get a bit */
|
||||
if (s & msk) v++;
|
||||
msk >>= 1;
|
||||
|
||||
for (nd = *hbits++; nd; nd--) { /* Search the code word in this bit length */
|
||||
if (v == *hcode++) { /* Matched? */
|
||||
jd->dmsk = msk; jd->dctr = dc; jd->dptr = dp;
|
||||
return *hdata; /* Return the decoded data */
|
||||
}
|
||||
hdata++;
|
||||
}
|
||||
bl--;
|
||||
} while (bl);
|
||||
|
||||
return 0 - (INT)JDR_FMT1; /* Err: code not found (may be collapted data) */
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Apply Inverse-DCT in Arai Algorithm (see also aa_idct.png) */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
static
|
||||
void block_idct (
|
||||
LONG* src, /* Input block data (de-quantized and pre-scaled for Arai Algorithm) */
|
||||
BYTE* dst /* Pointer to the destination to store the block as byte array */
|
||||
)
|
||||
{
|
||||
const LONG M13 = (LONG)(1.41421*4096), M2 = (LONG)(1.08239*4096), M4 = (LONG)(2.61313*4096), M5 = (LONG)(1.84776*4096);
|
||||
LONG v0, v1, v2, v3, v4, v5, v6, v7;
|
||||
LONG t10, t11, t12, t13;
|
||||
UINT i;
|
||||
|
||||
/* Process columns */
|
||||
for (i = 0; i < 8; i++) {
|
||||
v0 = src[8 * 0]; /* Get even elements */
|
||||
v1 = src[8 * 2];
|
||||
v2 = src[8 * 4];
|
||||
v3 = src[8 * 6];
|
||||
|
||||
t10 = v0 + v2; /* Process the even elements */
|
||||
t12 = v0 - v2;
|
||||
t11 = (v1 - v3) * M13 >> 12;
|
||||
v3 += v1;
|
||||
t11 -= v3;
|
||||
v0 = t10 + v3;
|
||||
v3 = t10 - v3;
|
||||
v1 = t11 + t12;
|
||||
v2 = t12 - t11;
|
||||
|
||||
v4 = src[8 * 7]; /* Get odd elements */
|
||||
v5 = src[8 * 1];
|
||||
v6 = src[8 * 5];
|
||||
v7 = src[8 * 3];
|
||||
|
||||
t10 = v5 - v4; /* Process the odd elements */
|
||||
t11 = v5 + v4;
|
||||
t12 = v6 - v7;
|
||||
v7 += v6;
|
||||
v5 = (t11 - v7) * M13 >> 12;
|
||||
v7 += t11;
|
||||
t13 = (t10 + t12) * M5 >> 12;
|
||||
v4 = t13 - (t10 * M2 >> 12);
|
||||
v6 = t13 - (t12 * M4 >> 12) - v7;
|
||||
v5 -= v6;
|
||||
v4 -= v5;
|
||||
|
||||
src[8 * 0] = v0 + v7; /* Write-back transformed values */
|
||||
src[8 * 7] = v0 - v7;
|
||||
src[8 * 1] = v1 + v6;
|
||||
src[8 * 6] = v1 - v6;
|
||||
src[8 * 2] = v2 + v5;
|
||||
src[8 * 5] = v2 - v5;
|
||||
src[8 * 3] = v3 + v4;
|
||||
src[8 * 4] = v3 - v4;
|
||||
|
||||
src++; /* Next column */
|
||||
}
|
||||
|
||||
/* Process rows */
|
||||
src -= 8;
|
||||
for (i = 0; i < 8; i++) {
|
||||
v0 = src[0] + (128L << 8); /* Get even elements (remove DC offset (-128) here) */
|
||||
v1 = src[2];
|
||||
v2 = src[4];
|
||||
v3 = src[6];
|
||||
|
||||
t10 = v0 + v2; /* Process the even elements */
|
||||
t12 = v0 - v2;
|
||||
t11 = (v1 - v3) * M13 >> 12;
|
||||
v3 += v1;
|
||||
t11 -= v3;
|
||||
v0 = t10 + v3;
|
||||
v3 = t10 - v3;
|
||||
v1 = t11 + t12;
|
||||
v2 = t12 - t11;
|
||||
|
||||
v4 = src[7]; /* Get odd elements */
|
||||
v5 = src[1];
|
||||
v6 = src[5];
|
||||
v7 = src[3];
|
||||
|
||||
t10 = v5 - v4; /* Process the odd elements */
|
||||
t11 = v5 + v4;
|
||||
t12 = v6 - v7;
|
||||
v7 += v6;
|
||||
v5 = (t11 - v7) * M13 >> 12;
|
||||
v7 += t11;
|
||||
t13 = (t10 + t12) * M5 >> 12;
|
||||
v4 = t13 - (t10 * M2 >> 12);
|
||||
v6 = t13 - (t12 * M4 >> 12) - v7;
|
||||
v5 -= v6;
|
||||
v4 -= v5;
|
||||
|
||||
dst[0] = BYTECLIP((v0 + v7) >> 8); /* Descale the transformed values 8 bits and output */
|
||||
dst[7] = BYTECLIP((v0 - v7) >> 8);
|
||||
dst[1] = BYTECLIP((v1 + v6) >> 8);
|
||||
dst[6] = BYTECLIP((v1 - v6) >> 8);
|
||||
dst[2] = BYTECLIP((v2 + v5) >> 8);
|
||||
dst[5] = BYTECLIP((v2 - v5) >> 8);
|
||||
dst[3] = BYTECLIP((v3 + v4) >> 8);
|
||||
dst[4] = BYTECLIP((v3 - v4) >> 8);
|
||||
dst += 8;
|
||||
|
||||
src += 8; /* Next row */
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Load all blocks in the MCU into working buffer */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
static
|
||||
JRESULT mcu_load (
|
||||
JDEC* jd /* Pointer to the decompressor object */
|
||||
)
|
||||
{
|
||||
LONG *tmp = (LONG*)jd->workbuf; /* Block working buffer for de-quantize and IDCT */
|
||||
UINT blk, nby, nbc, i, z, id, cmp;
|
||||
INT b, d, e;
|
||||
BYTE *bp;
|
||||
const BYTE *hb, *hd;
|
||||
const WORD *hc;
|
||||
const LONG *dqf;
|
||||
|
||||
|
||||
nby = jd->msx * jd->msy; /* Number of Y blocks (1, 2 or 4) */
|
||||
nbc = 2; /* Number of C blocks (2) */
|
||||
bp = jd->mcubuf; /* Pointer to the first block */
|
||||
|
||||
for (blk = 0; blk < nby + nbc; blk++) {
|
||||
cmp = (blk < nby) ? 0 : blk - nby + 1; /* Component number 0:Y, 1:Cb, 2:Cr */
|
||||
id = cmp ? 1 : 0; /* Huffman table ID of the component */
|
||||
|
||||
/* Extract a DC element from input stream */
|
||||
hb = jd->huffbits[id][0]; /* Huffman table for the DC element */
|
||||
hc = jd->huffcode[id][0];
|
||||
hd = jd->huffdata[id][0];
|
||||
b = huffext(jd, hb, hc, hd); /* Extract a huffman coded data (bit length) */
|
||||
if (b < 0) return 0 - b; /* Err: invalid code or input */
|
||||
d = jd->dcv[cmp]; /* DC value of previous block */
|
||||
if (b) { /* If there is any difference from previous block */
|
||||
e = bitext(jd, b); /* Extract data bits */
|
||||
if (e < 0) return 0 - e; /* Err: input */
|
||||
b = 1 << (b - 1); /* MSB position */
|
||||
if (!(e & b)) e -= (b << 1) - 1; /* Restore sign if needed */
|
||||
d += e; /* Get current value */
|
||||
jd->dcv[cmp] = (SHORT)d; /* Save current DC value for next block */
|
||||
}
|
||||
dqf = jd->qttbl[jd->qtid[cmp]]; /* De-quantizer table ID for this component */
|
||||
tmp[0] = d * dqf[0] >> 8; /* De-quantize, apply scale factor of Arai algorithm and descale 8 bits */
|
||||
|
||||
/* Extract following 63 AC elements from input stream */
|
||||
for (i = 1; i < 64; i++) tmp[i] = 0; /* Clear rest of elements */
|
||||
hb = jd->huffbits[id][1]; /* Huffman table for the AC elements */
|
||||
hc = jd->huffcode[id][1];
|
||||
hd = jd->huffdata[id][1];
|
||||
i = 1; /* Top of the AC elements */
|
||||
do {
|
||||
b = huffext(jd, hb, hc, hd); /* Extract a huffman coded value (zero runs and bit length) */
|
||||
if (b == 0) break; /* EOB? */
|
||||
if (b < 0) return 0 - b; /* Err: invalid code or input error */
|
||||
z = (UINT)b >> 4; /* Number of leading zero elements */
|
||||
if (z) {
|
||||
i += z; /* Skip zero elements */
|
||||
if (i >= 64) return JDR_FMT1; /* Too long zero run */
|
||||
}
|
||||
if (b &= 0x0F) { /* Bit length */
|
||||
d = bitext(jd, b); /* Extract data bits */
|
||||
if (d < 0) return 0 - d; /* Err: input device */
|
||||
b = 1 << (b - 1); /* MSB position */
|
||||
if (!(d & b)) d -= (b << 1) - 1;/* Restore negative value if needed */
|
||||
z = ZIG(i); /* Zigzag-order to raster-order converted index */
|
||||
tmp[z] = d * dqf[z] >> 8; /* De-quantize, apply scale factor of Arai algorithm and descale 8 bits */
|
||||
}
|
||||
} while (++i < 64); /* Next AC element */
|
||||
|
||||
if (JD_USE_SCALE && jd->scale == 3)
|
||||
*bp = (*tmp / 256) + 128; /* If scale ratio is 1/8, IDCT can be ommited and only DC element is used */
|
||||
else
|
||||
block_idct(tmp, bp); /* Apply IDCT and store the block to the MCU buffer */
|
||||
|
||||
bp += 64; /* Next block */
|
||||
}
|
||||
|
||||
return JDR_OK; /* All blocks have been loaded successfully */
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Output an MCU: Convert YCrCb to RGB and output it in RGB form */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
static
|
||||
JRESULT mcu_output (
|
||||
JDEC* jd, /* Pointer to the decompressor object */
|
||||
UINT (*outfunc)(JDEC*, void*, JRECT*), /* RGB output function */
|
||||
UINT x, /* MCU position in the image (left of the MCU) */
|
||||
UINT y /* MCU position in the image (top of the MCU) */
|
||||
)
|
||||
{
|
||||
const INT CVACC = (sizeof (INT) > 2) ? 1024 : 128;
|
||||
UINT ix, iy, mx, my, rx, ry;
|
||||
INT yy, cb, cr;
|
||||
BYTE *py, *pc, *rgb24;
|
||||
JRECT rect;
|
||||
|
||||
|
||||
mx = jd->msx * 8; my = jd->msy * 8; /* MCU size (pixel) */
|
||||
rx = (x + mx <= jd->width) ? mx : jd->width - x; /* Output rectangular size (it may be clipped at right/bottom end) */
|
||||
ry = (y + my <= jd->height) ? my : jd->height - y;
|
||||
if (JD_USE_SCALE) {
|
||||
rx >>= jd->scale; ry >>= jd->scale;
|
||||
if (!rx || !ry) return JDR_OK; /* Skip this MCU if all pixel is to be rounded off */
|
||||
x >>= jd->scale; y >>= jd->scale;
|
||||
}
|
||||
rect.left = x; rect.right = x + rx - 1; /* Rectangular area in the frame buffer */
|
||||
rect.top = y; rect.bottom = y + ry - 1;
|
||||
|
||||
|
||||
if (!JD_USE_SCALE || jd->scale != 3) { /* Not for 1/8 scaling */
|
||||
|
||||
/* Build an RGB MCU from discrete comopnents */
|
||||
rgb24 = (BYTE*)jd->workbuf;
|
||||
for (iy = 0; iy < my; iy++) {
|
||||
pc = jd->mcubuf;
|
||||
py = pc + iy * 8;
|
||||
if (my == 16) { /* Double block height? */
|
||||
pc += 64 * 4 + (iy >> 1) * 8;
|
||||
if (iy >= 8) py += 64;
|
||||
} else { /* Single block height */
|
||||
pc += mx * 8 + iy * 8;
|
||||
}
|
||||
for (ix = 0; ix < mx; ix++) {
|
||||
cb = pc[0] - 128; /* Get Cb/Cr component and restore right level */
|
||||
cr = pc[64] - 128;
|
||||
if (mx == 16) { /* Double block width? */
|
||||
if (ix == 8) py += 64 - 8; /* Jump to next block if double block heigt */
|
||||
pc += ix & 1; /* Increase chroma pointer every two pixels */
|
||||
} else { /* Single block width */
|
||||
pc++; /* Increase chroma pointer every pixel */
|
||||
}
|
||||
yy = *py++; /* Get Y component */
|
||||
|
||||
/* Convert YCbCr to RGB */
|
||||
*rgb24++ = /* R */ BYTECLIP(yy + ((INT)(1.402 * CVACC) * cr) / CVACC);
|
||||
*rgb24++ = /* G */ BYTECLIP(yy - ((INT)(0.344 * CVACC) * cb + (INT)(0.714 * CVACC) * cr) / CVACC);
|
||||
*rgb24++ = /* B */ BYTECLIP(yy + ((INT)(1.772 * CVACC) * cb) / CVACC);
|
||||
}
|
||||
}
|
||||
|
||||
/* Descale the MCU rectangular if needed */
|
||||
if (JD_USE_SCALE && jd->scale) {
|
||||
UINT x, y, r, g, b, s, w, a;
|
||||
BYTE *op;
|
||||
|
||||
/* Get averaged RGB value of each square correcponds to a pixel */
|
||||
s = jd->scale * 2; /* Bumber of shifts for averaging */
|
||||
w = 1 << jd->scale; /* Width of square */
|
||||
a = (mx - w) * 3; /* Bytes to skip for next line in the square */
|
||||
op = (BYTE*)jd->workbuf;
|
||||
for (iy = 0; iy < my; iy += w) {
|
||||
for (ix = 0; ix < mx; ix += w) {
|
||||
rgb24 = (BYTE*)jd->workbuf + (iy * mx + ix) * 3;
|
||||
r = g = b = 0;
|
||||
for (y = 0; y < w; y++) { /* Accumulate RGB value in the square */
|
||||
for (x = 0; x < w; x++) {
|
||||
r += *rgb24++;
|
||||
g += *rgb24++;
|
||||
b += *rgb24++;
|
||||
}
|
||||
rgb24 += a;
|
||||
} /* Put the averaged RGB value as a pixel */
|
||||
*op++ = (BYTE)(r >> s);
|
||||
*op++ = (BYTE)(g >> s);
|
||||
*op++ = (BYTE)(b >> s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else { /* For only 1/8 scaling (left-top pixel in each block are the DC value of the block) */
|
||||
|
||||
/* Build a 1/8 descaled RGB MCU from discrete comopnents */
|
||||
rgb24 = (BYTE*)jd->workbuf;
|
||||
pc = jd->mcubuf + mx * my;
|
||||
cb = pc[0] - 128; /* Get Cb/Cr component and restore right level */
|
||||
cr = pc[64] - 128;
|
||||
for (iy = 0; iy < my; iy += 8) {
|
||||
py = jd->mcubuf;
|
||||
if (iy == 8) py += 64 * 2;
|
||||
for (ix = 0; ix < mx; ix += 8) {
|
||||
yy = *py; /* Get Y component */
|
||||
py += 64;
|
||||
|
||||
/* Convert YCbCr to RGB */
|
||||
*rgb24++ = /* R */ BYTECLIP(yy + ((INT)(1.402 * CVACC) * cr / CVACC));
|
||||
*rgb24++ = /* G */ BYTECLIP(yy - ((INT)(0.344 * CVACC) * cb + (INT)(0.714 * CVACC) * cr) / CVACC);
|
||||
*rgb24++ = /* B */ BYTECLIP(yy + ((INT)(1.772 * CVACC) * cb / CVACC));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Squeeze up pixel table if a part of MCU is to be truncated */
|
||||
mx >>= jd->scale;
|
||||
if (rx < mx) {
|
||||
BYTE *s, *d;
|
||||
UINT x, y;
|
||||
|
||||
s = d = (BYTE*)jd->workbuf;
|
||||
for (y = 0; y < ry; y++) {
|
||||
for (x = 0; x < rx; x++) { /* Copy effective pixels */
|
||||
*d++ = *s++;
|
||||
*d++ = *s++;
|
||||
*d++ = *s++;
|
||||
}
|
||||
s += (mx - rx) * 3; /* Skip truncated pixels */
|
||||
}
|
||||
}
|
||||
|
||||
/* Convert RGB888 to RGB565 if needed */
|
||||
if (JD_FORMAT == 1) {
|
||||
BYTE *s = (BYTE*)jd->workbuf;
|
||||
WORD w, *d = (WORD*)s;
|
||||
UINT n = rx * ry;
|
||||
|
||||
do {
|
||||
w = (*s++ & 0xF8) << 8; /* RRRRR----------- */
|
||||
w |= (*s++ & 0xFC) << 3; /* -----GGGGGG----- */
|
||||
w |= *s++ >> 3; /* -----------BBBBB */
|
||||
*d++ = w;
|
||||
} while (--n);
|
||||
}
|
||||
|
||||
/* Output the RGB rectangular */
|
||||
return outfunc(jd, jd->workbuf, &rect) ? JDR_OK : JDR_INTR;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Process restart interval */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
static
|
||||
JRESULT restart (
|
||||
JDEC* jd, /* Pointer to the decompressor object */
|
||||
WORD rstn /* Expected restert sequense number */
|
||||
)
|
||||
{
|
||||
UINT i, dc;
|
||||
WORD d;
|
||||
BYTE *dp;
|
||||
|
||||
|
||||
/* Discard padding bits and get two bytes from the input stream */
|
||||
dp = jd->dptr; dc = jd->dctr;
|
||||
d = 0;
|
||||
for (i = 0; i < 2; i++) {
|
||||
if (!dc) { /* No input data is available, re-fill input buffer */
|
||||
dp = jd->inbuf;
|
||||
dc = jd->infunc(jd, dp, JD_SZBUF);
|
||||
if (!dc) return JDR_INP;
|
||||
} else {
|
||||
dp++;
|
||||
}
|
||||
dc--;
|
||||
d = (d << 8) | *dp; /* Get a byte */
|
||||
}
|
||||
jd->dptr = dp; jd->dctr = dc; jd->dmsk = 0;
|
||||
|
||||
/* Check the marker */
|
||||
if ((d & 0xFFD8) != 0xFFD0 || (d & 7) != (rstn & 7))
|
||||
return JDR_FMT1; /* Err: expected RSTn marker is not detected (may be collapted data) */
|
||||
|
||||
/* Reset DC offset */
|
||||
jd->dcv[2] = jd->dcv[1] = jd->dcv[0] = 0;
|
||||
|
||||
return JDR_OK;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Analyze the JPEG image and Initialize decompressor object */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
#define LDB_WORD(ptr) (WORD)(((WORD)*((BYTE*)(ptr))<<8)|(WORD)*(BYTE*)((ptr)+1))
|
||||
|
||||
|
||||
JRESULT jd_prepare (
|
||||
JDEC* jd, /* Blank decompressor object */
|
||||
UINT (*infunc)(JDEC*, BYTE*, UINT), /* JPEG strem input function */
|
||||
void* pool, /* Working buffer for the decompression session */
|
||||
UINT sz_pool, /* Size of working buffer */
|
||||
void* dev /* I/O device identifier for the session */
|
||||
)
|
||||
{
|
||||
BYTE *seg, b;
|
||||
WORD marker;
|
||||
DWORD ofs;
|
||||
UINT n, i, j, len;
|
||||
JRESULT rc;
|
||||
|
||||
|
||||
if (!pool) return JDR_PAR;
|
||||
|
||||
jd->pool = pool; /* Work memroy */
|
||||
jd->sz_pool = sz_pool; /* Size of given work memory */
|
||||
jd->infunc = infunc; /* Stream input function */
|
||||
jd->device = dev; /* I/O device identifier */
|
||||
jd->nrst = 0; /* No restart interval (default) */
|
||||
|
||||
for (i = 0; i < 2; i++) { /* Nulls pointers */
|
||||
for (j = 0; j < 2; j++) {
|
||||
jd->huffbits[i][j] = 0;
|
||||
jd->huffcode[i][j] = 0;
|
||||
jd->huffdata[i][j] = 0;
|
||||
}
|
||||
}
|
||||
for (i = 0; i < 4; i++) jd->qttbl[i] = 0;
|
||||
|
||||
jd->inbuf = seg = alloc_pool(jd, JD_SZBUF); /* Allocate stream input buffer */
|
||||
if (!seg) return JDR_MEM1;
|
||||
|
||||
if (jd->infunc(jd, seg, 2) != 2) return JDR_INP;/* Check SOI marker */
|
||||
if (LDB_WORD(seg) != 0xFFD8) return JDR_FMT1; /* Err: SOI is not detected */
|
||||
ofs = 2;
|
||||
|
||||
for (;;) {
|
||||
/* Get a JPEG marker */
|
||||
if (jd->infunc(jd, seg, 4) != 4) return JDR_INP;
|
||||
marker = LDB_WORD(seg); /* Marker */
|
||||
len = LDB_WORD(seg + 2); /* Length field */
|
||||
if (len <= 2 || (marker >> 8) != 0xFF) return JDR_FMT1;
|
||||
len -= 2; /* Content size excluding length field */
|
||||
ofs += 4 + len; /* Number of bytes loaded */
|
||||
|
||||
switch (marker & 0xFF) {
|
||||
case 0xC0: /* SOF0 (baseline JPEG) */
|
||||
/* Load segment data */
|
||||
if (len > JD_SZBUF) return JDR_MEM2;
|
||||
if (jd->infunc(jd, seg, len) != len) return JDR_INP;
|
||||
|
||||
jd->width = LDB_WORD(seg+3); /* Image width in unit of pixel */
|
||||
jd->height = LDB_WORD(seg+1); /* Image height in unit of pixel */
|
||||
if (seg[5] != 3) return JDR_FMT3; /* Err: Supports only Y/Cb/Cr format */
|
||||
|
||||
/* Check three image components */
|
||||
for (i = 0; i < 3; i++) {
|
||||
b = seg[7 + 3 * i]; /* Get sampling factor */
|
||||
if (!i) { /* Y component */
|
||||
if (b != 0x11 && b != 0x22 && b != 0x21)/* Check sampling factor */
|
||||
return JDR_FMT3; /* Err: Supports only 4:4:4, 4:2:0 or 4:2:2 */
|
||||
jd->msx = b >> 4; jd->msy = b & 15; /* Size of MCU [blocks] */
|
||||
} else { /* Cb/Cr component */
|
||||
if (b != 0x11) return JDR_FMT3; /* Err: Sampling factor of Cr/Cb must be 1 */
|
||||
}
|
||||
b = seg[8 + 3 * i]; /* Get dequantizer table ID for this component */
|
||||
if (b > 3) return JDR_FMT3; /* Err: Invalid ID */
|
||||
jd->qtid[i] = b;
|
||||
}
|
||||
break;
|
||||
|
||||
case 0xDD: /* DRI */
|
||||
/* Load segment data */
|
||||
if (len > JD_SZBUF) return JDR_MEM2;
|
||||
if (jd->infunc(jd, seg, len) != len) return JDR_INP;
|
||||
|
||||
/* Get restart interval (MCUs) */
|
||||
jd->nrst = LDB_WORD(seg);
|
||||
break;
|
||||
|
||||
case 0xC4: /* DHT */
|
||||
/* Load segment data */
|
||||
if (len > JD_SZBUF) return JDR_MEM2;
|
||||
if (jd->infunc(jd, seg, len) != len) return JDR_INP;
|
||||
|
||||
/* Create huffman tables */
|
||||
rc = create_huffman_tbl(jd, seg, len);
|
||||
if (rc) return rc;
|
||||
break;
|
||||
|
||||
case 0xDB: /* DQT */
|
||||
/* Load segment data */
|
||||
if (len > JD_SZBUF) return JDR_MEM2;
|
||||
if (jd->infunc(jd, seg, len) != len) return JDR_INP;
|
||||
|
||||
/* Create de-quantizer tables */
|
||||
rc = create_qt_tbl(jd, seg, len);
|
||||
if (rc) return rc;
|
||||
break;
|
||||
|
||||
case 0xDA: /* SOS */
|
||||
/* Load segment data */
|
||||
if (len > JD_SZBUF) return JDR_MEM2;
|
||||
if (jd->infunc(jd, seg, len) != len) return JDR_INP;
|
||||
|
||||
if (!jd->width || !jd->height) return JDR_FMT1; /* Err: Invalid image size */
|
||||
|
||||
if (seg[0] != 3) return JDR_FMT3; /* Err: Supports only three color components format */
|
||||
|
||||
/* Check if all tables corresponding to each components have been loaded */
|
||||
for (i = 0; i < 3; i++) {
|
||||
b = seg[2 + 2 * i]; /* Get huffman table ID */
|
||||
if (b != 0x00 && b != 0x11) return JDR_FMT3; /* Err: Different table number for DC/AC element */
|
||||
b = i ? 1 : 0;
|
||||
if (!jd->huffbits[b][0] || !jd->huffbits[b][1]) /* Check huffman table for this component */
|
||||
return JDR_FMT1; /* Err: Huffman table not loaded */
|
||||
if (!jd->qttbl[jd->qtid[i]]) return JDR_FMT1; /* Err: Dequantizer table not loaded */
|
||||
}
|
||||
|
||||
/* Allocate working buffer for MCU and RGB */
|
||||
n = jd->msy * jd->msx; /* Number of Y blocks in the MCU */
|
||||
if (!n) return JDR_FMT1; /* Err: SOF0 has not been loaded */
|
||||
len = n * 64 * 2 + 64; /* Allocate buffer for IDCT and RGB output */
|
||||
if (len < 256) len = 256; /* but at least 256 byte is required for IDCT */
|
||||
jd->workbuf = alloc_pool(jd, len); /* and it may occupy a part of following MCU working buffer for RGB output */
|
||||
if (!jd->workbuf) return JDR_MEM1; /* Err: not enough memory */
|
||||
jd->mcubuf = alloc_pool(jd, (n + 2) * 64); /* Allocate MCU working buffer */
|
||||
if (!jd->mcubuf) return JDR_MEM1; /* Err: not enough memory */
|
||||
|
||||
/* Pre-load the JPEG data to extract it from the bit stream */
|
||||
jd->dptr = seg; jd->dctr = 0; jd->dmsk = 0; /* Prepare to read bit stream */
|
||||
if (ofs %= JD_SZBUF) { /* Align read offset to JD_SZBUF */
|
||||
jd->dctr = jd->infunc(jd, seg + ofs, JD_SZBUF - (UINT)ofs);
|
||||
jd->dptr = seg + ofs - 1;
|
||||
}
|
||||
|
||||
return JDR_OK; /* Initialization succeeded. Ready to decompress the JPEG image. */
|
||||
|
||||
case 0xC1: /* SOF1 */
|
||||
case 0xC2: /* SOF2 */
|
||||
case 0xC3: /* SOF3 */
|
||||
case 0xC5: /* SOF5 */
|
||||
case 0xC6: /* SOF6 */
|
||||
case 0xC7: /* SOF7 */
|
||||
case 0xC9: /* SOF9 */
|
||||
case 0xCA: /* SOF10 */
|
||||
case 0xCB: /* SOF11 */
|
||||
case 0xCD: /* SOF13 */
|
||||
case 0xCE: /* SOF14 */
|
||||
case 0xCF: /* SOF15 */
|
||||
case 0xD9: /* EOI */
|
||||
return JDR_FMT3; /* Unsuppoted JPEG standard (may be progressive JPEG) */
|
||||
|
||||
default: /* Unknown segment (comment, exif or etc..) */
|
||||
/* Skip segment data */
|
||||
if (jd->infunc(jd, 0, len) != len) /* Null pointer specifies to skip bytes of stream */
|
||||
return JDR_INP;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*-----------------------------------------------------------------------*/
|
||||
/* Start to decompress the JPEG picture */
|
||||
/*-----------------------------------------------------------------------*/
|
||||
|
||||
JRESULT jd_decomp (
|
||||
JDEC* jd, /* Initialized decompression object */
|
||||
UINT (*outfunc)(JDEC*, void*, JRECT*), /* RGB output function */
|
||||
BYTE scale /* Output de-scaling factor (0 to 3) */
|
||||
)
|
||||
{
|
||||
UINT x, y, mx, my;
|
||||
WORD rst, rsc;
|
||||
JRESULT rc;
|
||||
|
||||
if (scale > (JD_USE_SCALE ? 3 : 0)) return JDR_PAR;
|
||||
jd->scale = scale;
|
||||
|
||||
mx = jd->msx * 8; my = jd->msy * 8; /* Size of the MCU (pixel) */
|
||||
|
||||
jd->dcv[2] = jd->dcv[1] = jd->dcv[0] = 0; /* Initialize DC values */
|
||||
rst = rsc = 0;
|
||||
|
||||
rc = JDR_OK;
|
||||
for (y = 0; y < jd->height; y += my) { /* Vertical loop of MCUs */
|
||||
for (x = 0; x < jd->width; x += mx) { /* Horizontal loop of MCUs */
|
||||
if (jd->nrst && rst++ == jd->nrst) { /* Process restart interval if enabled */
|
||||
rc = restart(jd, rsc++);
|
||||
if (rc != JDR_OK) return rc;
|
||||
rst = 1;
|
||||
}
|
||||
rc = mcu_load(jd); /* Load an MCU (decompress huffman coded stream and apply IDCT) */
|
||||
if (rc != JDR_OK) return rc;
|
||||
rc = mcu_output(jd, outfunc, x, y); /* Output the MCU (color space conversion, scaling and output) */
|
||||
if (rc != JDR_OK) return rc;
|
||||
}
|
||||
}
|
||||
|
||||
return rc;
|
||||
}
|
||||
#endif//SUPPORT_JPEG
|
||||
|
||||
99
components/tjpgd/tjpgd.h
Normal file
99
components/tjpgd/tjpgd.h
Normal file
@@ -0,0 +1,99 @@
|
||||
/*----------------------------------------------------------------------------/
|
||||
/ TJpgDec - Tiny JPEG Decompressor include file (C)ChaN, 2012
|
||||
/----------------------------------------------------------------------------*/
|
||||
#ifndef _TJPGDEC
|
||||
#define _TJPGDEC
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* System Configurations */
|
||||
|
||||
#define JD_SZBUF 512 /* Size of stream input buffer */
|
||||
#define JD_FORMAT 0 /* Output pixel format 0:RGB888 (3 BYTE/pix), 1:RGB565 (1 WORD/pix) */
|
||||
#define JD_USE_SCALE 1 /* Use descaling feature for output */
|
||||
#define JD_TBLCLIP 1 /* Use table for saturation (might be a bit faster but increases 1K bytes of code size) */
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* These types must be 16-bit, 32-bit or larger integer */
|
||||
typedef int INT;
|
||||
typedef unsigned int UINT;
|
||||
|
||||
/* These types must be 8-bit integer */
|
||||
typedef char CHAR;
|
||||
typedef unsigned char UCHAR;
|
||||
typedef unsigned char BYTE;
|
||||
|
||||
/* These types must be 16-bit integer */
|
||||
typedef short SHORT;
|
||||
typedef unsigned short USHORT;
|
||||
typedef unsigned short WORD;
|
||||
typedef unsigned short WCHAR;
|
||||
|
||||
/* These types must be 32-bit integer */
|
||||
typedef long LONG;
|
||||
typedef unsigned long ULONG;
|
||||
typedef unsigned long DWORD;
|
||||
|
||||
|
||||
/* Error code */
|
||||
typedef enum {
|
||||
JDR_OK = 0, /* 0: Succeeded */
|
||||
JDR_INTR, /* 1: Interrupted by output function */
|
||||
JDR_INP, /* 2: Device error or wrong termination of input stream */
|
||||
JDR_MEM1, /* 3: Insufficient memory pool for the image */
|
||||
JDR_MEM2, /* 4: Insufficient stream input buffer */
|
||||
JDR_PAR, /* 5: Parameter error */
|
||||
JDR_FMT1, /* 6: Data format error (may be damaged data) */
|
||||
JDR_FMT2, /* 7: Right format but not supported */
|
||||
JDR_FMT3 /* 8: Not supported JPEG standard */
|
||||
} JRESULT;
|
||||
|
||||
|
||||
|
||||
/* Rectangular structure */
|
||||
typedef struct {
|
||||
WORD left, right, top, bottom;
|
||||
} JRECT;
|
||||
|
||||
|
||||
|
||||
/* Decompressor object structure */
|
||||
typedef struct JDEC JDEC;
|
||||
struct JDEC {
|
||||
UINT dctr; /* Number of bytes available in the input buffer */
|
||||
BYTE* dptr; /* Current data read ptr */
|
||||
BYTE* inbuf; /* Bit stream input buffer */
|
||||
BYTE dmsk; /* Current bit in the current read byte */
|
||||
BYTE scale; /* Output scaling ratio */
|
||||
BYTE msx, msy; /* MCU size in unit of block (width, height) */
|
||||
BYTE qtid[3]; /* Quantization table ID of each component */
|
||||
SHORT dcv[3]; /* Previous DC element of each component */
|
||||
WORD nrst; /* Restart inverval */
|
||||
UINT width, height; /* Size of the input image (pixel) */
|
||||
BYTE* huffbits[2][2]; /* Huffman bit distribution tables [id][dcac] */
|
||||
WORD* huffcode[2][2]; /* Huffman code word tables [id][dcac] */
|
||||
BYTE* huffdata[2][2]; /* Huffman decoded data tables [id][dcac] */
|
||||
LONG* qttbl[4]; /* Dequaitizer tables [id] */
|
||||
void* workbuf; /* Working buffer for IDCT and RGB output */
|
||||
BYTE* mcubuf; /* Working buffer for the MCU */
|
||||
void* pool; /* Pointer to available memory pool */
|
||||
UINT sz_pool; /* Size of momory pool (bytes available) */
|
||||
UINT (*infunc)(JDEC*, BYTE*, UINT);/* Pointer to jpeg stream input function */
|
||||
void* device; /* Pointer to I/O device identifiler for the session */
|
||||
};
|
||||
|
||||
|
||||
|
||||
/* TJpgDec API functions */
|
||||
JRESULT jd_prepare (JDEC*, UINT(*)(JDEC*,BYTE*,UINT), void*, UINT, void*);
|
||||
JRESULT jd_decomp (JDEC*, UINT(*)(JDEC*,void*,JRECT*), BYTE);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _TJPGDEC */
|
||||
@@ -1,5 +1,5 @@
|
||||
idf_component_register( SRCS operator.cpp tools.c trace.c
|
||||
REQUIRES _override esp_common pthread
|
||||
REQUIRES esp_common pthread
|
||||
PRIV_REQUIRES esp_http_client esp-tls
|
||||
INCLUDE_DIRS .
|
||||
)
|
||||
|
||||
@@ -294,7 +294,7 @@ void network_start() {
|
||||
}
|
||||
|
||||
static void event_logger(uint32_t state_machine, uint32_t state, uint32_t event) {
|
||||
ESP_LOGI(TAG, "Handling network manager event state Id %d->[%s]", state, event_to_string(event));
|
||||
ESP_LOGD(TAG, "Handling network manager event state Id %d->[%s]", state, event_to_string(event));
|
||||
}
|
||||
static const char * get_state_machine_result_string(state_machine_result_t result) {
|
||||
switch(result) {
|
||||
|
||||
@@ -822,7 +822,7 @@ static state_machine_result_t WIFI_CONNECTING_STATE_handler(state_machine_t* con
|
||||
network_connect_active_ssid(State_Machine);
|
||||
break;
|
||||
case EN_LOST_CONNECTION:
|
||||
if(nm->event_parameters->disconnected_event->reason == WIFI_REASON_ASSOC_LEAVE) {
|
||||
if(nm->event_parameters->disconnected_event->reason == WIFI_REASON_ASSOC_LEAVE || nm->event_parameters->disconnected_event->reason == WIFI_REASON_AUTH_EXPIRE || nm->event_parameters->disconnected_event->reason == WIFI_REASON_ASSOC_EXPIRE) {
|
||||
ESP_LOGI(TAG,"Wifi was disconnected from previous access point. Waiting to connect.");
|
||||
}
|
||||
else if(nm->event_parameters->disconnected_event->reason != WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
idf_component_register(SRC_DIRS .
|
||||
PRIV_REQUIRES esp_common wifi-manager pthread squeezelite-ota platform_console telnet display targets
|
||||
PRIV_REQUIRES _override esp_common wifi-manager pthread squeezelite-ota platform_console telnet display targets
|
||||
EMBED_FILES ../server_certs/github.pem
|
||||
LDFRAGMENTS "linker.lf"
|
||||
LDFRAGMENTS "linker.lf"
|
||||
)
|
||||
#get_target_property(ill ${COMPONENT_LIB} INTERFACE_LINK_LIBRARIES)
|
||||
#message("${COMPONENT_LIB} INTERFACE_LINK_LIBRARIES = ${ill}")
|
||||
|
||||
@@ -369,17 +369,8 @@ void register_default_nvs(){
|
||||
register_default_string_val("dhcp_tmout","8");
|
||||
register_default_string_val("target", CONFIG_TARGET);
|
||||
#ifdef CONFIG_CSPOT_SINK
|
||||
char * host_hame = config_alloc_get_default(NVS_TYPE_STR, "host_name", NULL, 0);
|
||||
register_default_string_val("enable_cspot", STR(CONFIG_CSPOT_SINK));
|
||||
cJSON * cspot_config = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(cspot_config, "deviceName", host_hame);
|
||||
cJSON_AddNumberToObject(cspot_config, "format", 1);
|
||||
cJSON_AddNumberToObject(cspot_config, "volume", 32767);
|
||||
char * cspot_config_str = cJSON_PrintUnformatted(cspot_config);
|
||||
register_default_string_val("cspot_config", cspot_config_str);
|
||||
cJSON_Delete(cspot_config);
|
||||
FREE_AND_NULL(cspot_config_str);
|
||||
FREE_AND_NULL(host_hame);
|
||||
register_default_string_val("cspot_config", "");
|
||||
#endif
|
||||
wait_for_commit();
|
||||
ESP_LOGD(TAG,"Done setting default values in nvs.");
|
||||
|
||||
@@ -63,6 +63,9 @@ sub initFirmwareDownload {
|
||||
$cb->() if $cb;
|
||||
}
|
||||
}
|
||||
elsif ($cb) {
|
||||
$cb->();
|
||||
}
|
||||
},
|
||||
sub {
|
||||
my ($http, $error) = @_;
|
||||
@@ -119,10 +122,15 @@ sub prefetchFirmware {
|
||||
|
||||
$cb->($releaseInfo, _gh2lmsUrl($url), $customFwUrl) if $cb;
|
||||
}
|
||||
elsif ($cb) {
|
||||
$cb->();
|
||||
}
|
||||
},
|
||||
sub {
|
||||
my ($http, $error) = @_;
|
||||
$log->error("Failed to get releases from Github: $error");
|
||||
|
||||
$cb->() if $cb;
|
||||
},
|
||||
{
|
||||
timeout => 10,
|
||||
|
||||
@@ -1,3 +1,55 @@
|
||||
[% IF useExtJS; extJsScripts = BLOCK %]
|
||||
<script type="text/javascript">
|
||||
Ext.onReady(function () {
|
||||
new Ext.util.TaskRunner().start({
|
||||
run: checkEq,
|
||||
interval: 1000
|
||||
});
|
||||
});
|
||||
|
||||
function checkEq() {
|
||||
var eqValues = [];
|
||||
this.lastValues = this.lastValues || [];
|
||||
|
||||
for (var x = 0; x < 10; x++) {
|
||||
eqValues[x] = Ext.get('pref_equalizer.' + x).dom.value || 0;
|
||||
}
|
||||
|
||||
if (eqValues.join() != this.lastValues.join()) {
|
||||
this.lastValues = eqValues;
|
||||
SqueezeJS.Controller.request({
|
||||
params: ['[% playerid %]', ['squeezeesp32', 'seteq', eqValues.join()]]
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
[% END; ELSIF !useExtJS; pageHeaderScripts = BLOCK %]
|
||||
<script type="text/javascript">
|
||||
setInterval(checkEq, 1000);
|
||||
|
||||
function checkEq() {
|
||||
var eqValues = [];
|
||||
this.lastValues = this.lastValues || [];
|
||||
|
||||
for (var x = 0; x < 10; x++) {
|
||||
eqValues[x] = $('pref_equalizer.' + x).value || 0;
|
||||
}
|
||||
|
||||
if (eqValues.join() != this.lastValues.join()) {
|
||||
this.lastValues = eqValues;
|
||||
new Ajax.Request('/jsonrpc.js', {
|
||||
method: 'post',
|
||||
postBody: JSON.stringify({
|
||||
id: 1,
|
||||
method: 'slim.request',
|
||||
params: ['[% playerid %]', ['squeezeesp32', 'seteq', eqValues.join()]]
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
[% END; END %]
|
||||
|
||||
[% PROCESS settings/header.html %]
|
||||
|
||||
[% WRAPPER setting title="PLUGIN_SQUEEZEESP32_FIRMWARE" desc="" %]
|
||||
@@ -59,62 +111,36 @@
|
||||
<div>[% "PLUGIN_SQUEEZEESP32_EQUALIZER_SAVE" | string %]</div>
|
||||
[% END %]
|
||||
|
||||
<script TYPE="text/javascript">
|
||||
if (Ext) {
|
||||
Ext.onReady(function () {
|
||||
new Ext.util.TaskRunner().start({
|
||||
run: checkEq,
|
||||
interval: 1000
|
||||
});
|
||||
});
|
||||
|
||||
function checkEq() {
|
||||
var eqValues = [];
|
||||
this.lastValues = this.lastValues || [];
|
||||
|
||||
for (var x = 0; x < 10; x++) {
|
||||
eqValues[x] = Ext.get('pref_equalizer.' + x).dom.value || 0;
|
||||
}
|
||||
|
||||
if (eqValues.join() != this.lastValues.join()) {
|
||||
this.lastValues = eqValues;
|
||||
SqueezeJS.Controller.request({
|
||||
params: ['[% playerid %]', ['squeezeesp32', 'seteq', eqValues.join()]]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
[% WRAPPER settingSection %]
|
||||
[% WRAPPER settingGroup title='31Hz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.0" id="pref_equalizer.0" value="[% pref_equalizer.0 %]" size="2"">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.0" id="pref_equalizer.0" value="[% pref_equalizer.0 || 0 %]" size="2"">
|
||||
[% END %]
|
||||
[% WRAPPER settingGroup title='62Hz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.1" id="pref_equalizer.1" value="[% pref_equalizer.1 %]" size="2">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.1" id="pref_equalizer.1" value="[% pref_equalizer.1 || 0 %]" size="2">
|
||||
[% END %]
|
||||
[% WRAPPER settingGroup title='125Hz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.2" id="pref_equalizer.2" value="[% pref_equalizer.2 %]" size="2">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.2" id="pref_equalizer.2" value="[% pref_equalizer.2 || 0 %]" size="2">
|
||||
[% END %]
|
||||
[% WRAPPER settingGroup title='250Hz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.3" id="pref_equalizer.3" value="[% pref_equalizer.3 %]" size="2">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.3" id="pref_equalizer.3" value="[% pref_equalizer.3 || 0 %]" size="2">
|
||||
[% END %]
|
||||
[% WRAPPER settingGroup title='500Hz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.4" id="pref_equalizer.4" value="[% pref_equalizer.4 %]" size="2">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.4" id="pref_equalizer.4" value="[% pref_equalizer.4 || 0 %]" size="2">
|
||||
[% END %]
|
||||
[% WRAPPER settingGroup title='1kHz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.5" id="pref_equalizer.5" value="[% pref_equalizer.5 %]" size="2">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.5" id="pref_equalizer.5" value="[% pref_equalizer.5 || 0 %]" size="2">
|
||||
[% END %]
|
||||
[% WRAPPER settingGroup title='2kHz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.6" id="pref_equalizer.6" value="[% pref_equalizer.6 %]" size="2">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.6" id="pref_equalizer.6" value="[% pref_equalizer.6 || 0 %]" size="2">
|
||||
[% END %]
|
||||
[% WRAPPER settingGroup title='4kHz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.7" id="pref_equalizer.7" value="[% pref_equalizer.7 %]" size="2">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.7" id="pref_equalizer.7" value="[% pref_equalizer.7 || 0 %]" size="2">
|
||||
[% END %]
|
||||
[% WRAPPER settingGroup title='8kHz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.8" id="pref_equalizer.8" value="[% pref_equalizer.8 %]" size="2">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.8" id="pref_equalizer.8" value="[% pref_equalizer.8 || 0 %]" size="2">
|
||||
[% END %]
|
||||
[% WRAPPER settingGroup title='16kHz' desc="" %]
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.9" id="pref_equalizer.9" value="[% pref_equalizer.9 %]" size="2">
|
||||
<input type="text" class="stdedit sliderInput_-13_20" name="pref_equalizer.9" id="pref_equalizer.9" value="[% pref_equalizer.9 || 0 %]" size="2">
|
||||
[% END %]
|
||||
[% END %]
|
||||
[% END %]
|
||||
|
||||
@@ -32,8 +32,8 @@ our $defaultPrefs = {
|
||||
'analogOutMode' => 0,
|
||||
'bass' => 0,
|
||||
'treble' => 0,
|
||||
'lineInAlwaysOn' => 0,
|
||||
'lineInLevel' => 50,
|
||||
'lineInAlwaysOn' => 0,
|
||||
'lineInLevel' => 50,
|
||||
'menuItem' => [qw(
|
||||
NOW_PLAYING
|
||||
BROWSE_MUSIC
|
||||
@@ -67,51 +67,66 @@ sub minBass { -13 }
|
||||
sub init {
|
||||
my $client = shift;
|
||||
my ($id, $caps) = @_;
|
||||
|
||||
|
||||
my ($depth) = $caps =~ /Depth=(\d+)/;
|
||||
$client->depth($depth || 16);
|
||||
|
||||
|
||||
if (!$handlersAdded) {
|
||||
|
||||
|
||||
# Add a handler for line-in/out status changes
|
||||
Slim::Networking::Slimproto::addHandler( LIOS => \&lineInOutStatus );
|
||||
|
||||
|
||||
# Create a new event for sending LIOS updates
|
||||
Slim::Control::Request::addDispatch(
|
||||
['lios', '_state'],
|
||||
[1, 0, 0, undef],
|
||||
);
|
||||
|
||||
|
||||
Slim::Control::Request::addDispatch(
|
||||
['lios', 'linein', '_state'],
|
||||
[1, 0, 0, undef],
|
||||
);
|
||||
|
||||
|
||||
Slim::Control::Request::addDispatch(
|
||||
['lios', 'lineout', '_state'],
|
||||
[1, 0, 0, undef],
|
||||
);
|
||||
|
||||
|
||||
$handlersAdded = 1;
|
||||
|
||||
}
|
||||
|
||||
|
||||
$client->SUPER::init(@_);
|
||||
Plugins::SqueezeESP32::FirmwareHelper::init($client);
|
||||
|
||||
main::INFOLOG && $log->is_info && $log->info("SqueezeESP player connected: " . $client->id);
|
||||
}
|
||||
}
|
||||
|
||||
sub initPrefs {
|
||||
my $client = shift;
|
||||
|
||||
|
||||
$sprefs->client($client)->init($defaultPrefs);
|
||||
|
||||
$prefs->client($client)->init( {
|
||||
|
||||
$prefs->client($client)->init( {
|
||||
equalizer => [(0) x 10],
|
||||
artwork => undef,
|
||||
} );
|
||||
|
||||
$prefs->setValidate({
|
||||
validator => sub {
|
||||
my ($pref, $new, $params, $old, $client) = @_;
|
||||
|
||||
$new ||= [(0) x 10];
|
||||
|
||||
foreach (0..9) {
|
||||
return 0 if $new->[$_] < $client->minBass;
|
||||
return 0 if $new->[$_] > $client->maxBass;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
}, 'equalizer');
|
||||
|
||||
$client->SUPER::initPrefs;
|
||||
}
|
||||
|
||||
@@ -121,15 +136,15 @@ sub power {
|
||||
|
||||
my $res = $client->SUPER::power($on, @_);
|
||||
return $res unless defined $on;
|
||||
|
||||
|
||||
if ($on) {
|
||||
$client->update_artwork(1);
|
||||
} else {
|
||||
$client->clear_artwork(1);
|
||||
}
|
||||
|
||||
|
||||
return $res;
|
||||
}
|
||||
}
|
||||
|
||||
# Allow the player to define it's display width (and probably more)
|
||||
sub playerSettingsFrame {
|
||||
@@ -162,16 +177,16 @@ sub playerSettingsFrame {
|
||||
sub bass {
|
||||
my ($client, $new) = @_;
|
||||
my $value = $client->SUPER::bass($new);
|
||||
|
||||
|
||||
$client->update_equalizer($value, [2, 1, 3]) if defined $new;
|
||||
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
sub treble {
|
||||
my ($client, $new) = @_;
|
||||
my $value = $client->SUPER::treble($new);
|
||||
|
||||
|
||||
$client->update_equalizer($value, [8, 9, 7]) if defined $new;
|
||||
|
||||
return $value;
|
||||
@@ -189,8 +204,8 @@ sub send_equalizer {
|
||||
sub update_equalizer {
|
||||
my ($client, $value, $index) = @_;
|
||||
return if $client->tone_update;
|
||||
|
||||
my $equalizer = $prefs->client($client)->get('equalizer');
|
||||
|
||||
my $equalizer = $prefs->client($client)->get('equalizer');
|
||||
$equalizer->[$index->[0]] = $value;
|
||||
$equalizer->[$index->[1]] = int($value / 2 + 0.5);
|
||||
$equalizer->[$index->[2]] = int($value / 4 + 0.5);
|
||||
@@ -203,7 +218,7 @@ sub update_tones {
|
||||
$client->tone_update(1);
|
||||
$sprefs->client($client)->set('bass', int(($equalizer->[1] * 2 + $equalizer->[2] + $equalizer->[3] * 4) / 7 + 0.5));
|
||||
$sprefs->client($client)->set('treble', int(($equalizer->[7] * 4 + $equalizer->[8] + $equalizer->[9] * 2) / 7 + 0.5));
|
||||
$client->tone_update(0);
|
||||
$client->tone_update(0);
|
||||
}
|
||||
|
||||
sub update_artwork {
|
||||
@@ -212,7 +227,7 @@ sub update_artwork {
|
||||
|
||||
my $artwork = $cprefs->get('artwork') || return;
|
||||
return unless $artwork->{'enable'} && $client->display->isa("Plugins::SqueezeESP32::Graphics");
|
||||
|
||||
|
||||
my $header = pack('Nnn', $artwork->{'enable'}, $artwork->{'x'}, $artwork->{'y'});
|
||||
$client->sendFrame( grfa => \$header );
|
||||
$client->display->update;
|
||||
@@ -267,7 +282,7 @@ sub clear_artwork {
|
||||
if ((!$artwork->{'x'} && !$artwork->{'y'}) || $force) {
|
||||
$client->sendFrame(grfa => \("\x00"x4));
|
||||
$client->display->update;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,7 +299,7 @@ sub config_artwork {
|
||||
sub reconnect {
|
||||
my $client = shift;
|
||||
$client->SUPER::reconnect(@_);
|
||||
|
||||
|
||||
$client->pluginData('artwork_md5', '');
|
||||
$client->config_artwork if $client->display->isa("Plugins::SqueezeESP32::Graphics");
|
||||
$client->send_equalizer;
|
||||
@@ -323,18 +338,18 @@ sub lineOutConnected {
|
||||
|
||||
sub lineInOutStatus {
|
||||
my ( $client, $data_ref ) = @_;
|
||||
|
||||
|
||||
my $state = unpack 'n', $$data_ref;
|
||||
|
||||
my $oldState = {
|
||||
in => $client->lineInConnected(),
|
||||
out => $client->lineOutConnected(),
|
||||
};
|
||||
|
||||
|
||||
Slim::Networking::Slimproto::voltage( $client, $state );
|
||||
|
||||
Slim::Control::Request::notifyFromArray( $client, [ 'lios', $state ] );
|
||||
|
||||
|
||||
if ($oldState->{in} != $client->lineInConnected()) {
|
||||
Slim::Control::Request::notifyFromArray( $client, [ 'lios', 'linein', $client->lineInConnected() ] );
|
||||
if ( Slim::Utils::PluginManager->isEnabled('Slim::Plugin::LineIn::Plugin')) {
|
||||
|
||||
@@ -3,7 +3,7 @@ package Plugins::SqueezeESP32::PlayerSettings;
|
||||
use strict;
|
||||
use base qw(Slim::Web::Settings);
|
||||
use JSON::XS::VersionOneAndTwo;
|
||||
use List::Util qw(first);
|
||||
use List::Util qw(first min max);
|
||||
|
||||
use Slim::Utils::Log;
|
||||
use Slim::Utils::Prefs;
|
||||
@@ -79,9 +79,10 @@ sub handler {
|
||||
|
||||
if ($client->can('depth') && $client->depth == 16) {
|
||||
my $equalizer = $cprefs->get('equalizer');
|
||||
for my $i (0 .. $#{$equalizer}) {
|
||||
$equalizer->[$i] = $paramRef->{"pref_equalizer.$i"} || 0;
|
||||
foreach (0 .. 9) {
|
||||
$equalizer->[$_] = min($client->maxBass, max($client->minBass, $paramRef->{"pref_equalizer.$_"} || 0))
|
||||
}
|
||||
$equalizer = [ splice(@$equalizer, 0, 10) ];
|
||||
$cprefs->set('equalizer', $equalizer);
|
||||
$client->update_tones($equalizer);
|
||||
}
|
||||
@@ -97,6 +98,7 @@ sub handler {
|
||||
$paramRef->{'pref_equalizer'} = $cprefs->get('equalizer') if $client->can('depth') && $client->depth == 16;
|
||||
$paramRef->{'player_ip'} = $client->ip;
|
||||
|
||||
require Plugins::SqueezeESP32::FirmwareHelper;
|
||||
Plugins::SqueezeESP32::FirmwareHelper::initFirmwareDownload($client, sub {
|
||||
my ($currentFWInfo, $newFWUrl, $customFwUrl) = @_;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user