Files
tactility_apps/Apps/BookPlayer/main/Source/main.c
T
2026-09-02 10:30:35 -04:00

1303 lines
48 KiB
C

#include <tt_app.h>
#include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h>
#include <tt_app_alertdialog.h>
#include <tactility/device.h>
#include <tactility/drivers/audio_stream.h>
#include <lvgl/fonts.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "cJSON.h"
#ifdef ESP_PLATFORM
#include <esp_heap_caps.h>
#endif
#define MINIMP3_IMPLEMENTATION
#define MINIMP3_NO_SIMD
#include "minimp3.h"
#define TAG "BookPlayer"
#define MP3_INPUT_BUFFER_SIZE 16384
#define MAX_BOOKS 32
#define MAX_PATH 256
#define MAX_TITLE 128
#define MAX_AUTHOR 128
#define MAX_LVGL_IMAGE_PATH 1024
#define PICKER_COVER_LOAD_DELAY_MS 250
typedef enum {
STATE_IDLE,
STATE_PLAYING,
STATE_PAUSED
} PlaybackState;
typedef struct {
char slug[MAX_PATH];
char title[MAX_TITLE];
char author[MAX_AUTHOR];
} BookMetadata;
typedef struct {
struct Device* stream_dev;
AudioStreamHandle stream_handle;
PlaybackState state;
int volume;
// Book picker list data
BookMetadata books[MAX_BOOKS];
int book_count;
int selected_book;
lv_coord_t picker_drag_start_x;
bool picker_dragging;
bool picker_dragged;
// Currently loaded book details
char current_book_slug[MAX_PATH];
cJSON* manifest_root;
cJSON* pages_array;
int page_count;
int current_page;
int last_pct;
// UI elements
AppHandle app;
// Keep the decoded cover on a dedicated back sibling. The picker controls
// are a separate transparent sibling above it, mirroring the player image
// first / chrome second composition without invalidating the cover for UI
// updates.
lv_obj_t* picker_background;
lv_obj_t* picker_wrapper;
lv_obj_t* picker_cover;
lv_obj_t* picker_touch_area;
lv_obj_t* lbl_picker_title;
lv_obj_t* lbl_picker_author;
lv_obj_t* btn_picker_play;
lv_obj_t* lbl_picker_status;
lv_obj_t* player_wrapper;
lv_obj_t* header_bar;
lv_obj_t* ctrl_bar;
lv_obj_t* lbl_book_title;
lv_obj_t* img_page;
lv_obj_t* lbl_indicator;
lv_obj_t* bar_progress;
lv_obj_t* btn_play_pause;
lv_obj_t* btn_prev;
lv_obj_t* btn_next;
// Audio State
char current_audio_path[512];
char picker_cover_path[MAX_LVGL_IMAGE_PATH];
char player_image_path[MAX_LVGL_IMAGE_PATH];
lv_timer_t* picker_cover_timer;
uint8_t* audio_buf; // Shared MP3 input and WAV buffer
mp3d_sample_t* pcm_buf; // MP3 decoded pcm buffer
// Currently-open output stream format (so we can reuse it across page
// changes instead of tearing the codec down/recreating it every page).
uint32_t stream_rate;
uint8_t stream_channels;
uint8_t stream_bits;
// Page navigation stops the decoder task but keeps a compatible output
// stream open for the next page.
bool keep_stream_on_stop;
TaskHandle_t playback_task_handle;
} AppCtx;
typedef struct __attribute__((packed)) {
char riff[4];
uint32_t overall_size;
char wave[4];
char fmt_chunk_marker[4];
uint32_t length_of_fmt;
uint16_t format_type;
uint16_t channels;
uint32_t sample_rate;
uint32_t byterate;
uint16_t block_align;
uint16_t bits_per_sample;
char data_chunk_header[4];
uint32_t data_size;
} WavHeader;
static AppCtx g_ctx;
/* ─── Forward Declarations ─── */
static void update_ui(AppCtx* ctx);
static void wait_for_playback_task_to_exit(AppCtx* ctx, bool keep_stream_open);
static void load_page(AppCtx* ctx, int page_index, bool start_audio);
static void return_to_picker(AppCtx* ctx);
static void audio_playback_task(void* arg);
static void play_mp3(AppCtx* ctx);
static void play_wav(AppCtx* ctx);
static void scan_books(AppCtx* ctx);
static bool select_picker_book(AppCtx* ctx, int index);
static void open_selected_book(AppCtx* ctx, bool start_audio);
static void clear_picker_cover(AppCtx* ctx);
static void schedule_picker_cover_load(AppCtx* ctx);
static void cancel_picker_cover_load(AppCtx* ctx);
/* ─── Audio-stream helpers ─── */
// The flashed firmware exports the legacy device_find_* lookup API; the newer
// device_get_* (out-param) API is not yet exported on 0.8.0-dev, so calling it
// fails at load with "missing symbol". The newer SDK headers dropped the legacy
// declarations, so declare them here (symbols are resolved at runtime by the ELF
// loader against the flashed firmware).
extern struct Device* device_find_by_name(const char* name);
extern struct Device* device_find_first_by_type(const struct DeviceType* type);
static bool find_audio_stream_device(AppCtx* ctx) {
struct Device* dev = device_find_by_name("audio-stream");
if (dev) {
ctx->stream_dev = dev;
return true;
}
dev = device_find_first_by_type(&AUDIO_STREAM_TYPE);
if (dev) {
ctx->stream_dev = dev;
return true;
}
return false;
}
static void close_stream_if_open(AppCtx* ctx) {
if (ctx->stream_handle) {
audio_stream_close(ctx->stream_handle);
ctx->stream_handle = NULL;
ctx->stream_rate = 0;
ctx->stream_channels = 0;
ctx->stream_bits = 0;
}
}
static bool open_output_stream(AppCtx* ctx, uint32_t sample_rate, uint8_t channels, uint8_t bits) {
// Reuse the already-open stream when the format hasn't changed. This keeps the
// codec alive across page changes, avoiding the audible pop caused by closing and
// re-initialising the audio hardware on every page turn.
if (ctx->stream_handle && ctx->stream_rate == sample_rate
&& ctx->stream_channels == channels && ctx->stream_bits == bits) {
return true;
}
close_stream_if_open(ctx);
if (!ctx->stream_dev) return false;
struct AudioStreamConfig cfg = {
.sample_rate = sample_rate,
.bits_per_sample = bits,
.channels = channels
};
error_t err = audio_stream_open_output(ctx->stream_dev, &cfg, &ctx->stream_handle);
if (err != ERROR_NONE) {
ESP_LOGE(TAG, "audio_stream_open_output failed: %d (rate=%u ch=%u)", err, (unsigned)sample_rate, channels);
ctx->stream_handle = NULL;
return false;
}
ctx->stream_rate = sample_rate;
ctx->stream_channels = channels;
ctx->stream_bits = bits;
ESP_LOGI(TAG, "audio_stream output opened: %u Hz %u ch %u-bit", (unsigned)sample_rate, channels, bits);
return true;
}
/* ─── UI Helper to update status labels & button states ─── */
static void update_ui(AppCtx* ctx) {
if (!ctx->btn_play_pause) return;
lv_obj_t* lbl_play = lv_obj_get_child(ctx->btn_play_pause, 0);
// Prev button state
if (ctx->current_page <= 0) {
lv_obj_add_state(ctx->btn_prev, LV_STATE_DISABLED);
} else {
lv_obj_clear_state(ctx->btn_prev, LV_STATE_DISABLED);
}
// Next button state
if (ctx->current_page >= ctx->page_count - 1) {
lv_obj_add_state(ctx->btn_next, LV_STATE_DISABLED);
} else {
lv_obj_clear_state(ctx->btn_next, LV_STATE_DISABLED);
}
switch (ctx->state) {
case STATE_PLAYING:
if (lbl_play) lv_label_set_text(lbl_play, LV_SYMBOL_PAUSE " Pause");
break;
case STATE_PAUSED:
if (lbl_play) lv_label_set_text(lbl_play, LV_SYMBOL_PLAY " Play");
break;
case STATE_IDLE:
default:
if (lbl_play) lv_label_set_text(lbl_play, LV_SYMBOL_PLAY " Play");
lv_bar_set_value(ctx->bar_progress, 0, LV_ANIM_OFF);
break;
}
}
/* ─── Read entire file to string ─── */
static char* read_full_file(const char* filepath) {
FILE* file = fopen(filepath, "rb");
if (!file) {
ESP_LOGE(TAG, "Failed to open file: %s", filepath);
return NULL;
}
fseek(file, 0, SEEK_END);
long size = ftell(file);
if (size <= 0) {
fclose(file);
return NULL;
}
fseek(file, 0, SEEK_SET);
char* buf = malloc(size + 1);
if (!buf) {
fclose(file);
return NULL;
}
size_t read_bytes = fread(buf, 1, size, file);
buf[read_bytes] = '\0';
fclose(file);
return buf;
}
/* ─── Auto-advance logic using LVGL Timer on main thread ─── */
static void on_auto_advance_timer(lv_timer_t* timer) {
AppCtx* ctx = (AppCtx*)lv_timer_get_user_data(timer);
if (ctx->current_page + 1 < ctx->page_count) {
load_page(ctx, ctx->current_page + 1, true);
}
}
static void handle_audio_finished(AppCtx* ctx) {
if (ctx->current_page + 1 < ctx->page_count) {
lv_timer_t* timer = lv_timer_create(on_auto_advance_timer, 0, ctx);
lv_timer_set_repeat_count(timer, 1);
} else {
ctx->state = STATE_IDLE;
update_ui(ctx);
}
}
/* ─── Helper to wait for playback thread to terminate safely ─── */
static void wait_for_playback_task_to_exit(AppCtx* ctx, bool keep_stream_open) {
if (ctx->playback_task_handle != NULL) {
ctx->keep_stream_on_stop = keep_stream_open;
ctx->state = STATE_IDLE;
while (ctx->playback_task_handle != NULL) {
tt_lvgl_unlock();
vTaskDelay(pdMS_TO_TICKS(10));
tt_lvgl_lock(portMAX_DELAY);
}
ctx->keep_stream_on_stop = false;
}
}
/* ─── Load Page Content (Image, Caption, Audio path) ─── */
static void load_image_from_page(AppCtx* ctx, cJSON* page, lv_obj_t* image,
char* lv_img_path, size_t lv_img_path_size) {
cJSON* img_item = cJSON_GetObjectItem(page, "image");
if (lv_img_path && lv_img_path_size > 0) lv_img_path[0] = '\0';
if (img_item && img_item->valuestring) {
char img_path[512];
snprintf(img_path, sizeof(img_path), "/sdcard/books/%s/%s", ctx->current_book_slug, img_item->valuestring);
FILE* img_file = fopen(img_path, "rb");
if (img_file) {
fclose(img_file);
if (!lv_img_path || lv_img_path_size == 0) {
lv_image_set_src(image, LV_SYMBOL_IMAGE);
return;
}
#ifdef ESP_PLATFORM
snprintf(lv_img_path, lv_img_path_size, "A:%s", img_path);
#else
snprintf(lv_img_path, lv_img_path_size, "A:/%s", img_path);
#endif
lv_image_set_src(image, lv_img_path);
return;
}
ESP_LOGW(TAG, "Image file not found: %s", img_path);
}
lv_image_set_src(image, LV_SYMBOL_IMAGE);
}
static void load_page(AppCtx* ctx, int page_index, bool start_audio) {
wait_for_playback_task_to_exit(ctx, true);
if (page_index < 0 || page_index >= ctx->page_count) return;
ctx->current_page = page_index;
ctx->last_pct = -1;
cJSON* page = cJSON_GetArrayItem(ctx->pages_array, page_index);
if (!page) return;
cJSON* snd_item = cJSON_GetObjectItem(page, "audio");
load_image_from_page(ctx, page, ctx->img_page,
ctx->player_image_path, sizeof(ctx->player_image_path));
// Update Page index indicator
char ind_buf[32];
snprintf(ind_buf, sizeof(ind_buf), "%d / %d", page_index + 1, ctx->page_count);
lv_label_set_text(ctx->lbl_indicator, ind_buf);
// Save audio path
if (snd_item && snd_item->valuestring) {
snprintf(ctx->current_audio_path, sizeof(ctx->current_audio_path), "/sdcard/books/%s/%s", ctx->current_book_slug, snd_item->valuestring);
} else {
ctx->current_audio_path[0] = '\0';
}
update_ui(ctx);
// Start playback if requested and valid
if (start_audio && ctx->current_audio_path[0] != '\0') {
FILE* audio_file = fopen(ctx->current_audio_path, "rb");
if (audio_file) {
fclose(audio_file);
ctx->state = STATE_PLAYING;
update_ui(ctx);
xTaskCreate(audio_playback_task, "audio_play", 8192, ctx, 5, &ctx->playback_task_handle);
} else {
ESP_LOGE(TAG, "Audio file not found: %s", ctx->current_audio_path);
const char* buttons[] = {"OK"};
tt_app_alertdialog_start("Playback Error", "The narration audio file is missing.", buttons, 1);
ctx->state = STATE_IDLE;
update_ui(ctx);
}
} else {
ctx->state = STATE_IDLE;
update_ui(ctx);
}
}
/* ─── Return to Book Picker Screen ─── */
static void return_to_picker(AppCtx* ctx) {
wait_for_playback_task_to_exit(ctx, false);
close_stream_if_open(ctx);
if (ctx->manifest_root) {
cJSON_Delete(ctx->manifest_root);
ctx->manifest_root = NULL;
ctx->pages_array = NULL;
}
lv_obj_add_flag(ctx->player_wrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->picker_background, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->picker_wrapper, LV_OBJ_FLAG_HIDDEN);
}
/* ─── Task Selection (MP3 or WAV) ─── */
static void audio_playback_task(void* arg) {
AppCtx* ctx = (AppCtx*)arg;
size_t len = strlen(ctx->current_audio_path);
bool is_wav = false;
if (len > 4 && strcasecmp(ctx->current_audio_path + len - 4, ".wav") == 0) {
is_wav = true;
}
if (is_wav) {
play_wav(ctx);
} else {
play_mp3(ctx);
}
}
/* ─── MP3 Decoder Routine (audio-stream) ─── */
static void play_mp3(AppCtx* ctx) {
vTaskDelay(pdMS_TO_TICKS(400));
FILE* file = fopen(ctx->current_audio_path, "rb");
if (!file) {
ESP_LOGE(TAG, "Failed to open file: %s", ctx->current_audio_path);
tt_lvgl_lock(portMAX_DELAY);
ctx->state = STATE_IDLE;
update_ui(ctx);
tt_lvgl_unlock();
ctx->playback_task_handle = NULL;
vTaskDelete(NULL);
return;
}
fseek(file, 0, SEEK_END);
size_t file_size = ftell(file);
fseek(file, 0, SEEK_SET);
size_t bytes_read_total = 0;
#ifdef ESP_PLATFORM
mp3dec_t* decoder = (mp3dec_t*)heap_caps_malloc(sizeof(mp3dec_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
#else
mp3dec_t* decoder = (mp3dec_t*)malloc(sizeof(mp3dec_t));
#endif
if (!decoder) {
ESP_LOGE(TAG, "Failed to allocate MP3 decoder!");
fclose(file);
ctx->playback_task_handle = NULL;
vTaskDelete(NULL);
return;
}
mp3dec_init(decoder);
size_t buffered_bytes = 0;
bool eof = false;
int sample_rate = 0;
int channels = 0;
ESP_LOGI(TAG, "Starting MP3 playback via audio-stream: %s (%d bytes)", ctx->current_audio_path, file_size);
while (ctx->state != STATE_IDLE) {
if (ctx->state == STATE_PAUSED) {
if (ctx->stream_handle) {
close_stream_if_open(ctx);
sample_rate = 0;
channels = 0;
}
vTaskDelay(pdMS_TO_TICKS(50));
continue;
}
// Fill buffer
if (!eof && buffered_bytes < MP3_INPUT_BUFFER_SIZE) {
size_t to_read = MP3_INPUT_BUFFER_SIZE - buffered_bytes;
size_t read_bytes = fread(ctx->audio_buf + buffered_bytes, 1, to_read, file);
buffered_bytes += read_bytes;
bytes_read_total += read_bytes;
if (read_bytes == 0) eof = true;
}
if (buffered_bytes == 0 && eof) {
ESP_LOGI(TAG, "Reached MP3 EOF");
break;
}
// Decode one frame
mp3dec_frame_info_t info;
memset(&info, 0, sizeof(info));
int samples = mp3dec_decode_frame(decoder, ctx->audio_buf, (int)buffered_bytes, ctx->pcm_buf, &info);
if (info.frame_bytes <= 0) {
if (eof) break;
memmove(ctx->audio_buf, ctx->audio_buf + 1, --buffered_bytes);
continue;
}
size_t consumed = (size_t)info.frame_bytes;
buffered_bytes -= consumed;
memmove(ctx->audio_buf, ctx->audio_buf + consumed, buffered_bytes);
if (samples > 0) {
// Open/reopen stream on format change
if (sample_rate != info.hz || channels != info.channels) {
if (!open_output_stream(ctx, (uint32_t)info.hz, (uint8_t)info.channels, 16)) {
ESP_LOGE(TAG, "Failed to open audio stream for MP3: %d Hz %d ch", info.hz, info.channels);
break;
}
sample_rate = info.hz;
channels = info.channels;
}
// Adjust volume without altering the start or end of the narration.
int vol = ctx->volume;
int16_t* samples_ptr = (int16_t*)ctx->pcm_buf;
size_t sample_count = (size_t)samples * info.channels;
for (size_t i = 0; i < sample_count; ++i) {
int32_t scaled = (int32_t)samples_ptr[i] * vol / 100;
samples_ptr[i] = (int16_t)scaled;
}
// Write via audio_stream (resampled to native 44100 internally)
size_t offset = 0;
size_t data_size = sample_count * sizeof(int16_t);
bool write_err = false;
while (offset < data_size && ctx->state == STATE_PLAYING) {
size_t written = 0;
error_t err = audio_stream_write(ctx->stream_handle, (uint8_t*)ctx->pcm_buf + offset, data_size - offset, &written, pdMS_TO_TICKS(1000));
if (err != ERROR_NONE || written == 0) {
ESP_LOGE(TAG, "audio_stream_write error: %d", err);
write_err = true;
break;
}
offset += written;
}
if (write_err) break;
}
// Update Progress Bar
if (file_size > 0) {
int pct = (int)((bytes_read_total - buffered_bytes) * 100 / file_size);
if (pct < 0) pct = 0;
if (pct > 100) pct = 100;
if (pct != ctx->last_pct) {
ctx->last_pct = pct;
tt_lvgl_lock(portMAX_DELAY);
lv_bar_set_value(ctx->bar_progress, pct, LV_ANIM_OFF);
tt_lvgl_unlock();
}
}
taskYIELD();
}
fclose(file);
bool stopped_externally = (ctx->state == STATE_IDLE);
if (stopped_externally && !ctx->keep_stream_on_stop) {
// App exit and returning to the picker release the output device.
close_stream_if_open(ctx);
}
if (!stopped_externally) {
tt_lvgl_lock(portMAX_DELAY);
handle_audio_finished(ctx);
tt_lvgl_unlock();
}
#ifdef ESP_PLATFORM
heap_caps_free(decoder);
#else
free(decoder);
#endif
ctx->playback_task_handle = NULL;
vTaskDelete(NULL);
}
/* ─── WAV Decoder Routine (audio-stream) ─── */
static void play_wav(AppCtx* ctx) {
vTaskDelay(pdMS_TO_TICKS(400));
FILE* file = fopen(ctx->current_audio_path, "rb");
if (!file) {
ESP_LOGE(TAG, "Failed to open WAV: %s", ctx->current_audio_path);
tt_lvgl_lock(portMAX_DELAY);
ctx->state = STATE_IDLE;
update_ui(ctx);
tt_lvgl_unlock();
ctx->playback_task_handle = NULL;
vTaskDelete(NULL);
return;
}
WavHeader header;
if (fread(&header, 1, sizeof(WavHeader), file) != sizeof(WavHeader)) {
ESP_LOGE(TAG, "Failed to read WAV header");
fclose(file);
tt_lvgl_lock(portMAX_DELAY);
ctx->state = STATE_IDLE;
update_ui(ctx);
tt_lvgl_unlock();
ctx->playback_task_handle = NULL;
vTaskDelete(NULL);
return;
}
if (strncmp(header.riff, "RIFF", 4) != 0 || strncmp(header.wave, "WAVE", 4) != 0) {
ESP_LOGE(TAG, "Invalid WAV signature");
fclose(file);
tt_lvgl_lock(portMAX_DELAY);
ctx->state = STATE_IDLE;
update_ui(ctx);
tt_lvgl_unlock();
ctx->playback_task_handle = NULL;
vTaskDelete(NULL);
return;
}
size_t data_size = header.data_size;
if (data_size == 0) {
fseek(file, 0, SEEK_END);
data_size = ftell(file) - sizeof(WavHeader);
fseek(file, sizeof(WavHeader), SEEK_SET);
}
if (!open_output_stream(ctx, header.sample_rate, header.channels, header.bits_per_sample)) {
ESP_LOGE(TAG, "Failed to open audio stream for WAV: %u Hz %u ch", (unsigned)header.sample_rate, header.channels);
fclose(file);
tt_lvgl_lock(portMAX_DELAY);
ctx->state = STATE_IDLE;
update_ui(ctx);
tt_lvgl_unlock();
ctx->playback_task_handle = NULL;
vTaskDelete(NULL);
return;
}
ESP_LOGI(TAG, "Starting WAV via audio-stream: %s (%u Hz, %u ch)", ctx->current_audio_path, (unsigned int)header.sample_rate, (unsigned int)header.channels);
size_t total_played = 0;
bool stream_open = true;
while (total_played < data_size && ctx->state != STATE_IDLE) {
if (ctx->state == STATE_PAUSED) {
if (stream_open) {
close_stream_if_open(ctx);
stream_open = false;
}
vTaskDelay(pdMS_TO_TICKS(50));
continue;
}
if (!stream_open) {
if (!open_output_stream(ctx, header.sample_rate, header.channels, header.bits_per_sample)) break;
stream_open = true;
}
size_t to_read = (data_size - total_played < MP3_INPUT_BUFFER_SIZE) ? (data_size - total_played) : MP3_INPUT_BUFFER_SIZE;
size_t read_bytes = fread(ctx->audio_buf, 1, to_read, file);
if (read_bytes == 0) break;
// Adjust volume without altering the start or end of the narration.
int vol = ctx->volume;
int16_t* samples_ptr = (int16_t*)ctx->audio_buf;
size_t sample_count = read_bytes / sizeof(int16_t);
for (size_t i = 0; i < sample_count; ++i) {
int32_t scaled = (int32_t)samples_ptr[i] * vol / 100;
samples_ptr[i] = (int16_t)scaled;
}
// Write via audio_stream
size_t offset = 0;
bool write_err = false;
while (offset < read_bytes && ctx->state == STATE_PLAYING) {
size_t written = 0;
error_t err = audio_stream_write(ctx->stream_handle, ctx->audio_buf + offset, read_bytes - offset, &written, pdMS_TO_TICKS(500));
if (err != ERROR_NONE || written == 0) {
ESP_LOGE(TAG, "audio_stream WAV write error: %d", err);
write_err = true;
break;
}
offset += written;
}
if (write_err) break;
total_played += read_bytes;
int pct = (int)((total_played * 100) / data_size);
if (pct < 0) pct = 0;
if (pct > 100) pct = 100;
if (pct != ctx->last_pct) {
ctx->last_pct = pct;
tt_lvgl_lock(portMAX_DELAY);
lv_bar_set_value(ctx->bar_progress, pct, LV_ANIM_OFF);
tt_lvgl_unlock();
}
taskYIELD();
}
fclose(file);
bool stopped_externally = (ctx->state == STATE_IDLE);
if (stopped_externally && !ctx->keep_stream_on_stop) {
// App exit and returning to the picker release the output device.
close_stream_if_open(ctx);
}
if (!stopped_externally) {
tt_lvgl_lock(portMAX_DELAY);
handle_audio_finished(ctx);
tt_lvgl_unlock();
}
ctx->playback_task_handle = NULL;
vTaskDelete(NULL);
}
/* ─── Full-screen book picker ─── */
static bool select_picker_book(AppCtx* ctx, int index) {
if (index < 0 || index >= ctx->book_count) return false;
if (ctx->manifest_root) {
cJSON_Delete(ctx->manifest_root);
ctx->manifest_root = NULL;
ctx->pages_array = NULL;
}
BookMetadata* book = &ctx->books[index];
strncpy(ctx->current_book_slug, book->slug, sizeof(ctx->current_book_slug) - 1);
ctx->current_book_slug[sizeof(ctx->current_book_slug) - 1] = '\0';
char manifest_path[512];
snprintf(manifest_path, sizeof(manifest_path), "/sdcard/books/%s/manifest.json", book->slug);
char* json_str = read_full_file(manifest_path);
if (!json_str) {
const char* buttons[] = {"OK"};
tt_app_alertdialog_start("Read Error", "Failed to open the book manifest.", buttons, 1);
return false;
}
ctx->manifest_root = cJSON_Parse(json_str);
free(json_str);
if (!ctx->manifest_root) {
const char* buttons[] = {"OK"};
tt_app_alertdialog_start("JSON Error", "The book manifest is not formatted correctly.", buttons, 1);
return false;
}
ctx->pages_array = cJSON_GetObjectItem(ctx->manifest_root, "pages");
if (!ctx->pages_array || !cJSON_IsArray(ctx->pages_array)) {
const char* buttons[] = {"OK"};
tt_app_alertdialog_start("Format Error", "No pages found in book manifest.", buttons, 1);
cJSON_Delete(ctx->manifest_root);
ctx->manifest_root = NULL;
ctx->pages_array = NULL;
return false;
}
ctx->page_count = cJSON_GetArraySize(ctx->pages_array);
if (ctx->page_count <= 0) {
const char* buttons[] = {"OK"};
tt_app_alertdialog_start("Format Error", "The book does not have pages.", buttons, 1);
cJSON_Delete(ctx->manifest_root);
ctx->manifest_root = NULL;
ctx->pages_array = NULL;
return false;
}
ctx->selected_book = index;
lv_label_set_text(ctx->lbl_picker_title, book->title);
lv_label_set_text(ctx->lbl_picker_author, book->author[0] ? book->author : "");
char picker_status[64];
snprintf(picker_status, sizeof(picker_status), "%d / %d - Tap sides or swipe", index + 1, ctx->book_count);
lv_label_set_text(ctx->lbl_picker_status, picker_status);
schedule_picker_cover_load(ctx);
return true;
}
static void clear_picker_cover(AppCtx* ctx) {
if (!ctx->picker_cover) return;
// Release the previous file-backed source before its stable path buffer is
// reused. The symbol fallback has no file decoder or SD resource attached.
lv_image_set_src(ctx->picker_cover, LV_SYMBOL_IMAGE);
ctx->picker_cover_path[0] = '\0';
}
static void on_picker_cover_timer(lv_timer_t* timer) {
AppCtx* ctx = (AppCtx*)lv_timer_get_user_data(timer);
if (!ctx) return;
// The timer is one-shot and LVGL will dispose it after this callback.
// Clear the stored pointer first so a subsequent selection cannot delete a
// timer that is already being finalized.
ctx->picker_cover_timer = NULL;
if (!ctx->pages_array || !ctx->picker_cover) return;
cJSON* first_page = cJSON_GetArrayItem(ctx->pages_array, 0);
if (!first_page) return;
load_image_from_page(ctx, first_page, ctx->picker_cover,
ctx->picker_cover_path, sizeof(ctx->picker_cover_path));
}
static void schedule_picker_cover_load(AppCtx* ctx) {
cancel_picker_cover_load(ctx);
clear_picker_cover(ctx);
// Loading a full SD PNG from onShow has rebooted the S3 before LVGL's first
// event-loop pass. The player performs this same load from a user event;
// defer the picker equivalent until its UI is live and stable.
ctx->picker_cover_timer = lv_timer_create(on_picker_cover_timer, PICKER_COVER_LOAD_DELAY_MS, ctx);
if (ctx->picker_cover_timer) {
lv_timer_set_repeat_count(ctx->picker_cover_timer, 1);
} else {
ESP_LOGE(TAG, "Failed to schedule picker cover image load");
}
}
static void cancel_picker_cover_load(AppCtx* ctx) {
if (ctx->picker_cover_timer) {
lv_timer_delete(ctx->picker_cover_timer);
ctx->picker_cover_timer = NULL;
}
}
static void open_selected_book(AppCtx* ctx, bool start_audio) {
if (!ctx->manifest_root || ctx->page_count <= 0) return;
BookMetadata* book = &ctx->books[ctx->selected_book];
lv_label_set_text(ctx->lbl_book_title, book->title);
// Switch views
cancel_picker_cover_load(ctx);
lv_obj_add_flag(ctx->picker_background, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(ctx->picker_wrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->player_wrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->header_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->ctrl_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->bar_progress, LV_OBJ_FLAG_HIDDEN);
load_page(ctx, 0, start_audio);
}
static void change_picker_book(AppCtx* ctx, int index) {
if (index < 0 || index >= ctx->book_count || index == ctx->selected_book) return;
select_picker_book(ctx, index);
}
static void on_picker_touch(lv_event_t* e) {
AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
lv_event_code_t code = lv_event_get_code(e);
lv_indev_t* indev = lv_indev_active();
if (!ctx || !indev || ctx->book_count == 0) return;
lv_point_t point;
lv_indev_get_point(indev, &point);
if (code == LV_EVENT_PRESSED) {
ctx->picker_drag_start_x = point.x;
ctx->picker_dragging = true;
ctx->picker_dragged = false;
} else if (code == LV_EVENT_PRESSING && ctx->picker_dragging) {
int dx = point.x - ctx->picker_drag_start_x;
const int threshold = 28;
if (abs(dx) >= threshold) {
int steps = dx / threshold;
int next_index = ctx->selected_book - steps; // swipe left advances
if (next_index < 0) next_index = 0;
if (next_index >= ctx->book_count) next_index = ctx->book_count - 1;
if (next_index != ctx->selected_book) {
change_picker_book(ctx, next_index);
ctx->picker_dragged = true;
}
ctx->picker_drag_start_x = point.x;
}
} else if (code == LV_EVENT_RELEASED || code == LV_EVENT_PRESS_LOST) {
ctx->picker_dragging = false;
} else if (code == LV_EVENT_CLICKED) {
if (ctx->picker_dragged) {
ctx->picker_dragged = false;
return;
}
if (point.x < lv_obj_get_width(ctx->picker_touch_area) / 2) {
change_picker_book(ctx, ctx->selected_book - 1);
} else {
change_picker_book(ctx, ctx->selected_book + 1);
}
}
}
static void on_picker_play_click(lv_event_t* e) {
AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
open_selected_book(ctx, true);
}
static void on_picker_close_click(lv_event_t* e) {
(void)e;
// Follow the normal external-app lifecycle so onHide releases the pending
// cover timer, file-backed image sources, manifest, and audio buffers.
tt_app_stop();
}
/* ─── Scan Books ─── */
static void scan_books(AppCtx* ctx) {
ctx->book_count = 0;
DIR* dir = opendir("/sdcard/books");
if (!dir) {
ESP_LOGE(TAG, "Failed to scan books: /sdcard/books folder missing.");
lv_label_set_text(ctx->lbl_picker_status, "No SD card or books directory found.");
return;
}
struct dirent* entry;
while ((entry = readdir(dir)) != NULL && ctx->book_count < MAX_BOOKS) {
if (entry->d_name[0] == '.') continue;
char manifest_path[512];
snprintf(manifest_path, sizeof(manifest_path), "/sdcard/books/%s/manifest.json", entry->d_name);
char* json_str = read_full_file(manifest_path);
if (json_str) {
cJSON* root = cJSON_Parse(json_str);
free(json_str);
if (root) {
cJSON* title_item = cJSON_GetObjectItem(root, "title");
cJSON* author_item = cJSON_GetObjectItem(root, "author");
BookMetadata* book = &ctx->books[ctx->book_count];
strncpy(book->slug, entry->d_name, sizeof(book->slug) - 1);
if (title_item && title_item->valuestring) {
strncpy(book->title, title_item->valuestring, sizeof(book->title) - 1);
} else {
strncpy(book->title, entry->d_name, sizeof(book->title) - 1);
}
if (author_item && author_item->valuestring) {
strncpy(book->author, author_item->valuestring, sizeof(book->author) - 1);
} else {
book->author[0] = '\0';
}
cJSON_Delete(root);
ctx->book_count++;
}
}
}
closedir(dir);
if (ctx->book_count == 0) {
lv_label_set_text(ctx->lbl_picker_status, "No book manifest.json files found.");
return;
}
// Bubble sort by title
for (int i = 0; i < ctx->book_count - 1; i++) {
for (int j = 0; j < ctx->book_count - i - 1; j++) {
if (strcmp(ctx->books[j].title, ctx->books[j + 1].title) > 0) {
BookMetadata temp = ctx->books[j];
ctx->books[j] = ctx->books[j + 1];
ctx->books[j + 1] = temp;
}
}
}
lv_obj_remove_flag(ctx->btn_picker_play, LV_OBJ_FLAG_HIDDEN);
select_picker_book(ctx, 0);
}
/* ─── Player Control Events ─── */
static void on_play_pause_click(lv_event_t* e) {
AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
if (ctx->current_audio_path[0] == '\0') return;
if (ctx->state == STATE_IDLE) {
ctx->state = STATE_PLAYING;
update_ui(ctx);
xTaskCreate(audio_playback_task, "audio_play", 8192, ctx, 5, &ctx->playback_task_handle);
} else if (ctx->state == STATE_PLAYING) {
ctx->state = STATE_PAUSED;
update_ui(ctx);
} else if (ctx->state == STATE_PAUSED) {
ctx->state = STATE_PLAYING;
update_ui(ctx);
}
}
static void on_prev_click(lv_event_t* e) {
AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
if (ctx->current_page > 0) {
bool was_playing = (ctx->state == STATE_PLAYING);
load_page(ctx, ctx->current_page - 1, was_playing);
}
}
static void on_next_click(lv_event_t* e) {
AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
if (ctx->current_page < ctx->page_count - 1) {
bool was_playing = (ctx->state == STATE_PLAYING);
load_page(ctx, ctx->current_page + 1, was_playing);
}
}
static void on_image_click(lv_event_t* e) {
AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
if (!ctx) return;
bool is_hidden = lv_obj_has_flag(ctx->header_bar, LV_OBJ_FLAG_HIDDEN);
if (is_hidden) {
lv_obj_remove_flag(ctx->header_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->ctrl_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->bar_progress, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag(ctx->header_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(ctx->ctrl_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(ctx->bar_progress, LV_OBJ_FLAG_HIDDEN);
}
}
static void on_back_click(lv_event_t* e) {
AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
return_to_picker(ctx);
}
/* ─── App Lifecycle ─── */
static void onShowApp(AppHandle app, void* data, lv_obj_t* parent) {
memset(&g_ctx, 0, sizeof(g_ctx));
g_ctx.app = app;
g_ctx.volume = 80;
// Allocate shared audio buffers
#ifdef ESP_PLATFORM
g_ctx.audio_buf = (uint8_t*)heap_caps_malloc(MP3_INPUT_BUFFER_SIZE, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
g_ctx.pcm_buf = (mp3d_sample_t*)heap_caps_malloc(MINIMP3_MAX_SAMPLES_PER_FRAME * sizeof(mp3d_sample_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
#else
g_ctx.audio_buf = (uint8_t*)malloc(MP3_INPUT_BUFFER_SIZE);
g_ctx.pcm_buf = (mp3d_sample_t*)malloc(MINIMP3_MAX_SAMPLES_PER_FRAME * sizeof(mp3d_sample_t));
#endif
// Find audio-stream device (provides resampling to native 44100)
if (!find_audio_stream_device(&g_ctx)) {
ESP_LOGE(TAG, "audio-stream device not found! Tried 'audio-stream' name and AUDIO_STREAM_TYPE");
}
// Create dual layouts.
// 1. The picker cover lives in its own back sibling. Keep all picker UI
// and touch objects in the transparent foreground sibling above so changing
// a title/status/button does not force the PNG-backed image through that
// overlay's redraw path.
g_ctx.picker_background = lv_obj_create(parent);
lv_obj_set_size(g_ctx.picker_background, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_border_width(g_ctx.picker_background, 0, 0);
lv_obj_set_style_pad_all(g_ctx.picker_background, 0, 0);
lv_obj_set_style_pad_gap(g_ctx.picker_background, 0, 0);
lv_obj_set_style_bg_color(g_ctx.picker_background, lv_color_hex(0x1E1E2E), 0);
lv_obj_set_style_bg_opa(g_ctx.picker_background, LV_OPA_COVER, 0);
lv_obj_remove_flag(g_ctx.picker_background, LV_OBJ_FLAG_SCROLLABLE);
g_ctx.picker_cover = lv_image_create(g_ctx.picker_background);
lv_obj_align(g_ctx.picker_cover, LV_ALIGN_CENTER, 0, 0);
lv_obj_set_style_bg_opa(g_ctx.picker_cover, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_all(g_ctx.picker_cover, 0, 0);
lv_obj_set_style_border_width(g_ctx.picker_cover, 0, 0);
lv_obj_remove_flag(g_ctx.picker_cover, LV_OBJ_FLAG_SCROLLABLE);
g_ctx.picker_wrapper = lv_obj_create(parent);
lv_obj_set_size(g_ctx.picker_wrapper, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_border_width(g_ctx.picker_wrapper, 0, 0);
lv_obj_set_style_pad_all(g_ctx.picker_wrapper, 0, 0);
lv_obj_set_style_pad_gap(g_ctx.picker_wrapper, 0, 0);
lv_obj_set_style_bg_opa(g_ctx.picker_wrapper, LV_OPA_TRANSP, 0);
lv_obj_remove_flag(g_ctx.picker_wrapper, LV_OBJ_FLAG_SCROLLABLE);
g_ctx.picker_touch_area = lv_obj_create(g_ctx.picker_wrapper);
lv_obj_set_size(g_ctx.picker_touch_area, LV_PCT(100), LV_PCT(100));
lv_obj_align(g_ctx.picker_touch_area, LV_ALIGN_CENTER, 0, 0);
lv_obj_set_style_bg_opa(g_ctx.picker_touch_area, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(g_ctx.picker_touch_area, 0, 0);
lv_obj_set_style_pad_all(g_ctx.picker_touch_area, 0, 0);
lv_obj_remove_flag(g_ctx.picker_touch_area, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(g_ctx.picker_touch_area, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_PRESSED, &g_ctx);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_PRESSING, &g_ctx);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_RELEASED, &g_ctx);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_PRESS_LOST, &g_ctx);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_CLICKED, &g_ctx);
lv_obj_t* picker_title_panel = lv_obj_create(g_ctx.picker_wrapper);
lv_obj_set_size(picker_title_panel, LV_PCT(100), 68);
lv_obj_align(picker_title_panel, LV_ALIGN_TOP_MID, 0, 0);
lv_obj_set_style_bg_color(picker_title_panel, lv_color_hex(0x11111B), 0);
lv_obj_set_style_bg_opa(picker_title_panel, LV_OPA_60, 0);
lv_obj_set_style_border_width(picker_title_panel, 0, 0);
lv_obj_set_style_pad_all(picker_title_panel, 0, 0);
lv_obj_remove_flag(picker_title_panel, LV_OBJ_FLAG_SCROLLABLE);
g_ctx.lbl_picker_title = lv_label_create(picker_title_panel);
lv_obj_set_width(g_ctx.lbl_picker_title, LV_PCT(86));
lv_obj_align(g_ctx.lbl_picker_title, LV_ALIGN_TOP_MID, 0, 10);
lv_obj_set_style_text_align(g_ctx.lbl_picker_title, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(g_ctx.lbl_picker_title, lv_color_hex(0xFFFFFF), 0);
lv_obj_set_style_text_font(g_ctx.lbl_picker_title, lvgl_get_text_font(FONT_SIZE_LARGE), 0);
lv_label_set_long_mode(g_ctx.lbl_picker_title, LV_LABEL_LONG_WRAP);
g_ctx.lbl_picker_author = lv_label_create(picker_title_panel);
lv_obj_set_width(g_ctx.lbl_picker_author, LV_PCT(86));
lv_obj_align(g_ctx.lbl_picker_author, LV_ALIGN_TOP_MID, 0, 42);
lv_obj_set_style_text_align(g_ctx.lbl_picker_author, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(g_ctx.lbl_picker_author, lv_color_hex(0xE0E0E8), 0);
lv_label_set_long_mode(g_ctx.lbl_picker_author, LV_LABEL_LONG_DOT);
g_ctx.lbl_picker_status = lv_label_create(g_ctx.picker_wrapper);
lv_obj_set_width(g_ctx.lbl_picker_status, LV_PCT(86));
lv_obj_align(g_ctx.lbl_picker_status, LV_ALIGN_BOTTOM_MID, 0, -54);
lv_obj_set_style_text_align(g_ctx.lbl_picker_status, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(g_ctx.lbl_picker_status, lv_color_hex(0xF5F5FA), 0);
g_ctx.btn_picker_play = lv_button_create(g_ctx.picker_wrapper);
lv_obj_set_size(g_ctx.btn_picker_play, 58, 42);
lv_obj_align(g_ctx.btn_picker_play, LV_ALIGN_BOTTOM_MID, 0, -10);
lv_obj_set_style_radius(g_ctx.btn_picker_play, 21, 0);
lv_obj_set_style_bg_color(g_ctx.btn_picker_play, lv_color_hex(0x89B4FA), 0);
lv_obj_set_style_text_color(g_ctx.btn_picker_play, lv_color_hex(0x11111B), 0);
lv_obj_t* lbl_picker_play = lv_label_create(g_ctx.btn_picker_play);
lv_label_set_text(lbl_picker_play, LV_SYMBOL_PLAY);
lv_obj_center(lbl_picker_play);
lv_obj_add_event_cb(g_ctx.btn_picker_play, on_picker_play_click, LV_EVENT_CLICKED, &g_ctx);
lv_obj_add_flag(g_ctx.btn_picker_play, LV_OBJ_FLAG_HIDDEN);
// A dedicated side exit control leaves the center cover, top title panel,
// and bottom play target clear while reserving its own small touch area.
lv_obj_t* btn_picker_close = lv_button_create(g_ctx.picker_wrapper);
lv_obj_set_size(btn_picker_close, 42, 42);
lv_obj_align(btn_picker_close, LV_ALIGN_RIGHT_MID, -8, 0);
lv_obj_set_style_radius(btn_picker_close, 21, 0);
lv_obj_set_style_bg_color(btn_picker_close, lv_color_hex(0xD64545), 0);
lv_obj_set_style_text_color(btn_picker_close, lv_color_hex(0xFFFFFF), 0);
lv_obj_t* lbl_picker_close = lv_label_create(btn_picker_close);
lv_label_set_text(lbl_picker_close, LV_SYMBOL_CLOSE);
lv_obj_center(lbl_picker_close);
lv_obj_add_event_cb(btn_picker_close, on_picker_close_click, LV_EVENT_CLICKED, &g_ctx);
// 2. Player Screen wrapper (hidden on start)
g_ctx.player_wrapper = lv_obj_create(parent);
lv_obj_set_size(g_ctx.player_wrapper, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_border_width(g_ctx.player_wrapper, 0, 0);
lv_obj_set_style_pad_all(g_ctx.player_wrapper, 0, 0);
lv_obj_set_style_pad_gap(g_ctx.player_wrapper, 0, 0);
lv_obj_set_style_bg_color(g_ctx.player_wrapper, lv_color_hex(0x1E1E2E), 0);
lv_obj_remove_flag(g_ctx.player_wrapper, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(g_ctx.player_wrapper, LV_OBJ_FLAG_HIDDEN);
g_ctx.img_page = lv_image_create(g_ctx.player_wrapper);
lv_obj_align(g_ctx.img_page, LV_ALIGN_CENTER, 0, 0);
lv_obj_set_style_bg_opa(g_ctx.img_page, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_all(g_ctx.img_page, 0, 0);
lv_obj_set_style_border_width(g_ctx.img_page, 0, 0);
lv_obj_remove_flag(g_ctx.img_page, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(g_ctx.img_page, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_event_cb(g_ctx.img_page, on_image_click, LV_EVENT_CLICKED, &g_ctx);
g_ctx.header_bar = lv_obj_create(g_ctx.player_wrapper);
lv_obj_t* header_bar = g_ctx.header_bar;
lv_obj_set_size(header_bar, LV_PCT(100), 36);
lv_obj_align(header_bar, LV_ALIGN_TOP_MID, 0, 0);
lv_obj_set_style_radius(header_bar, 0, 0);
lv_obj_set_style_bg_color(header_bar, lv_color_hex(0x11111B), 0);
lv_obj_set_style_bg_opa(header_bar, LV_OPA_COVER, 0);
lv_obj_set_style_border_color(header_bar, lv_color_hex(0x313244), 0);
lv_obj_set_style_border_width(header_bar, 1, LV_PART_MAIN);
lv_obj_remove_flag(header_bar, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* btn_back = lv_button_create(header_bar);
lv_obj_set_size(btn_back, 44, 26);
lv_obj_align(btn_back, LV_ALIGN_LEFT_MID, 0, 0);
lv_obj_set_style_radius(btn_back, 6, 0);
lv_obj_set_style_bg_color(btn_back, lv_color_hex(0x313244), 0);
lv_obj_t* lbl_back = lv_label_create(btn_back);
lv_label_set_text(lbl_back, LV_SYMBOL_LEFT);
lv_obj_center(lbl_back);
lv_obj_add_event_cb(btn_back, on_back_click, LV_EVENT_CLICKED, &g_ctx);
g_ctx.lbl_book_title = lv_label_create(header_bar);
lv_obj_align(g_ctx.lbl_book_title, LV_ALIGN_CENTER, 0, 0);
lv_obj_set_width(g_ctx.lbl_book_title, 180);
lv_obj_set_style_text_align(g_ctx.lbl_book_title, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(g_ctx.lbl_book_title, lv_color_hex(0xCDD6F4), 0);
lv_label_set_long_mode(g_ctx.lbl_book_title, LV_LABEL_LONG_DOT);
g_ctx.lbl_indicator = lv_label_create(header_bar);
lv_obj_align(g_ctx.lbl_indicator, LV_ALIGN_RIGHT_MID, 0, 0);
lv_obj_set_style_text_color(g_ctx.lbl_indicator, lv_color_hex(0xA6ADC8), 0);
lv_label_set_text(g_ctx.lbl_indicator, "1 / 1");
g_ctx.ctrl_bar = lv_obj_create(g_ctx.player_wrapper);
lv_obj_t* ctrl_bar = g_ctx.ctrl_bar;
lv_obj_set_size(ctrl_bar, LV_PCT(100), 40);
lv_obj_align(ctrl_bar, LV_ALIGN_BOTTOM_MID, 0, 0);
lv_obj_set_style_radius(ctrl_bar, 0, 0);
lv_obj_set_style_bg_color(ctrl_bar, lv_color_hex(0x11111B), 0);
lv_obj_set_style_bg_opa(ctrl_bar, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(ctrl_bar, 0, 0);
lv_obj_set_style_pad_all(ctrl_bar, 0, 0);
lv_obj_set_style_pad_gap(ctrl_bar, 0, 0);
lv_obj_set_flex_flow(ctrl_bar, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(ctrl_bar, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_remove_flag(ctrl_bar, LV_OBJ_FLAG_SCROLLABLE);
g_ctx.bar_progress = lv_bar_create(g_ctx.player_wrapper);
lv_obj_set_size(g_ctx.bar_progress, LV_PCT(100), 4);
lv_obj_align_to(g_ctx.bar_progress, ctrl_bar, LV_ALIGN_OUT_TOP_MID, 0, 0);
lv_bar_set_range(g_ctx.bar_progress, 0, 100);
lv_bar_set_value(g_ctx.bar_progress, 0, LV_ANIM_OFF);
lv_obj_set_style_bg_color(g_ctx.bar_progress, lv_color_hex(0x45475A), LV_PART_MAIN);
lv_obj_set_style_bg_color(g_ctx.bar_progress, lv_color_hex(0x89B4FA), LV_PART_INDICATOR);
g_ctx.btn_prev = lv_button_create(ctrl_bar);
lv_obj_set_size(g_ctx.btn_prev, 54, 30);
lv_obj_set_style_radius(g_ctx.btn_prev, 15, 0);
lv_obj_set_style_bg_color(g_ctx.btn_prev, lv_color_hex(0x313244), 0);
lv_obj_t* lbl_prev = lv_label_create(g_ctx.btn_prev);
lv_label_set_text(lbl_prev, LV_SYMBOL_PREV);
lv_obj_center(lbl_prev);
lv_obj_add_event_cb(g_ctx.btn_prev, on_prev_click, LV_EVENT_CLICKED, &g_ctx);
g_ctx.btn_play_pause = lv_button_create(ctrl_bar);
lv_obj_set_size(g_ctx.btn_play_pause, 94, 30);
lv_obj_set_style_radius(g_ctx.btn_play_pause, 15, 0);
lv_obj_set_style_bg_color(g_ctx.btn_play_pause, lv_color_hex(0x89B4FA), 0);
lv_obj_set_style_text_color(g_ctx.btn_play_pause, lv_color_hex(0x11111B), 0);
lv_obj_t* lbl_play_btn = lv_label_create(g_ctx.btn_play_pause);
lv_label_set_text(lbl_play_btn, LV_SYMBOL_PLAY " Play");
lv_obj_center(lbl_play_btn);
lv_obj_add_event_cb(g_ctx.btn_play_pause, on_play_pause_click, LV_EVENT_CLICKED, &g_ctx);
g_ctx.btn_next = lv_button_create(ctrl_bar);
lv_obj_set_size(g_ctx.btn_next, 54, 30);
lv_obj_set_style_radius(g_ctx.btn_next, 15, 0);
lv_obj_set_style_bg_color(g_ctx.btn_next, lv_color_hex(0x313244), 0);
lv_obj_t* lbl_next = lv_label_create(g_ctx.btn_next);
lv_label_set_text(lbl_next, LV_SYMBOL_NEXT);
lv_obj_center(lbl_next);
lv_obj_add_event_cb(g_ctx.btn_next, on_next_click, LV_EVENT_CLICKED, &g_ctx);
// Initial load
g_ctx.state = STATE_IDLE;
update_ui(&g_ctx);
scan_books(&g_ctx);
}
static void onHideApp(AppHandle app, void* data) {
wait_for_playback_task_to_exit(&g_ctx, false);
close_stream_if_open(&g_ctx);
cancel_picker_cover_load(&g_ctx);
clear_picker_cover(&g_ctx);
if (g_ctx.img_page) {
lv_image_set_src(g_ctx.img_page, LV_SYMBOL_IMAGE);
g_ctx.player_image_path[0] = '\0';
}
if (g_ctx.manifest_root) {
cJSON_Delete(g_ctx.manifest_root);
g_ctx.manifest_root = NULL;
g_ctx.pages_array = NULL;
}
#ifdef ESP_PLATFORM
if (g_ctx.audio_buf) {
heap_caps_free(g_ctx.audio_buf);
g_ctx.audio_buf = NULL;
}
if (g_ctx.pcm_buf) {
heap_caps_free(g_ctx.pcm_buf);
g_ctx.pcm_buf = NULL;
}
#else
if (g_ctx.audio_buf) {
free(g_ctx.audio_buf);
g_ctx.audio_buf = NULL;
}
if (g_ctx.pcm_buf) {
free(g_ctx.pcm_buf);
g_ctx.pcm_buf = NULL;
}
#endif
}
int main(int argc, char* argv[]) {
tt_app_register((AppRegistration) {
.onShow = onShowApp,
.onHide = onHideApp
});
return 0;
}