#include #include #include #include #include #include #include #include #include #include #include #include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_log.h" #define MINIMP3_IMPLEMENTATION #define MINIMP3_NO_SIMD #include "minimp3.h" #define TAG "Mp3Player" #define MP3_INPUT_BUFFER_SIZE 16384 typedef enum { STATE_IDLE, STATE_PLAYING, STATE_PAUSED } PlaybackState; typedef struct { struct Device* stream_dev; AudioStreamHandle stream_handle; char filepath[512]; PlaybackState state; AppHandle app_handle; // UI elements lv_obj_t* lbl_title; lv_obj_t* lbl_status; lv_obj_t* bar_progress; lv_obj_t* btn_play_pause; lv_obj_t* btn_stop; // Playback state variables FILE* file; mp3dec_t decoder; uint8_t* input_buf; mp3d_sample_t* pcm_buf; size_t buffered_bytes; bool eof; int volume; int sample_rate; int channels; // Progress calculation size_t file_size; size_t bytes_read_total; int pos_sec; int total_sec; long total_decoded_samples; int start_pos_sec; // from bundle bool finished_naturally; TaskHandle_t playback_task_handle; } AppCtx; static AppCtx g_ctx; /* ─── Update UI ─── */ static void update_ui(AppCtx* ctx) { if (!ctx->lbl_status) return; switch (ctx->state) { case STATE_PLAYING: lv_label_set_text(ctx->lbl_status, "Playing..."); lv_label_set_text(lv_obj_get_child(ctx->btn_play_pause, 0), LV_SYMBOL_PAUSE " Pause"); lv_obj_clear_state(ctx->btn_play_pause, LV_STATE_DISABLED); lv_obj_clear_state(ctx->btn_stop, LV_STATE_DISABLED); break; case STATE_PAUSED: lv_label_set_text(ctx->lbl_status, "Paused"); lv_label_set_text(lv_obj_get_child(ctx->btn_play_pause, 0), LV_SYMBOL_PLAY " Play"); lv_obj_clear_state(ctx->btn_play_pause, LV_STATE_DISABLED); lv_obj_clear_state(ctx->btn_stop, LV_STATE_DISABLED); break; case STATE_IDLE: default: if (ctx->filepath[0] != '\0') { lv_label_set_text(ctx->lbl_status, "Ready"); lv_obj_clear_state(ctx->btn_play_pause, LV_STATE_DISABLED); } else { lv_label_set_text(ctx->lbl_status, "No file loaded"); lv_obj_add_state(ctx->btn_play_pause, LV_STATE_DISABLED); } lv_label_set_text(lv_obj_get_child(ctx->btn_play_pause, 0), LV_SYMBOL_PLAY " Play"); lv_obj_add_state(ctx->btn_stop, LV_STATE_DISABLED); lv_bar_set_value(ctx->bar_progress, 0, LV_ANIM_OFF); break; } } /* ─── Playback Task ─── */ static void mp3_playback_task(void* arg) { AppCtx* ctx = (AppCtx*)arg; ctx->file = fopen(ctx->filepath, "rb"); if (!ctx->file) { ESP_LOGE(TAG, "Failed to open file: %s", ctx->filepath); tt_lvgl_lock(portMAX_DELAY); ctx->state = STATE_IDLE; lv_label_set_text(ctx->lbl_status, "Error: File not found"); update_ui(ctx); tt_lvgl_unlock(); ctx->playback_task_handle = NULL; vTaskDelete(NULL); return; } fseek(ctx->file, 0, SEEK_END); ctx->file_size = ftell(ctx->file); fseek(ctx->file, 0, SEEK_SET); ctx->bytes_read_total = 0; ctx->pos_sec = 0; ctx->total_sec = 0; ctx->total_decoded_samples = 0; ctx->finished_naturally = false; // Handle ID3 and resume seek (like DiscoveryMountain) uint8_t id3hdr[10]; long id3_skip = 0; if (fread(id3hdr,1,10,ctx->file)==10 && memcmp(id3hdr,"ID3",3)==0) { int id3size = (id3hdr[6]&0x7F)<<21 | (id3hdr[7]&0x7F)<<14 | (id3hdr[8]&0x7F)<<7 | (id3hdr[9]&0x7F); id3_skip = id3size + 10; fseek(ctx->file, id3_skip, SEEK_SET); } else { fseek(ctx->file, 0, SEEK_SET); } long file_data_size = ctx->file_size - id3_skip; if (file_data_size>0) ctx->total_sec = (int)(file_data_size / 16000); // rough estimate if (ctx->start_pos_sec > 5) { long seek_bytes = (long)ctx->start_pos_sec * 16000; if (seek_bytes < file_data_size) { fseek(ctx->file, id3_skip + seek_bytes, SEEK_SET); ctx->total_decoded_samples = (long)ctx->start_pos_sec * 16000; ctx->pos_sec = ctx->start_pos_sec; ESP_LOGI(TAG, "Resuming %s from %d sec", ctx->filepath, ctx->start_pos_sec); } } mp3dec_init(&ctx->decoder); ctx->buffered_bytes = 0; ctx->eof = false; ctx->sample_rate = 0; ctx->channels = 0; ctx->stream_handle = NULL; ESP_LOGI(TAG, "Starting MP3 playback: %s (size: %d bytes) resume=%d", ctx->filepath, ctx->file_size, ctx->start_pos_sec); while (ctx->state != STATE_IDLE) { if (ctx->state == STATE_PAUSED) { if (ctx->stream_handle != NULL) { // Close stream immediately on pause to stop DMA audio_stream_close(ctx->stream_handle); ctx->stream_handle = NULL; // Clear cached format to force re-open on resume ctx->sample_rate = 0; ctx->channels = 0; } vTaskDelay(pdMS_TO_TICKS(50)); continue; } // Fill input buffer if (!ctx->eof && ctx->buffered_bytes < MP3_INPUT_BUFFER_SIZE) { size_t to_read = MP3_INPUT_BUFFER_SIZE - ctx->buffered_bytes; size_t read_bytes = fread(ctx->input_buf + ctx->buffered_bytes, 1, to_read, ctx->file); ctx->buffered_bytes += read_bytes; ctx->bytes_read_total += read_bytes; if (read_bytes == 0) { ctx->eof = true; } } if (ctx->buffered_bytes == 0 && ctx->eof) { ESP_LOGI(TAG, "Reached EOF"); break; } // Decode one frame mp3dec_frame_info_t info; memset(&info, 0, sizeof(info)); int samples = mp3dec_decode_frame(&ctx->decoder, ctx->input_buf, (int)ctx->buffered_bytes, ctx->pcm_buf, &info); if (info.frame_bytes <= 0) { if (ctx->eof) { break; } // Move 1 byte forward to resync memmove(ctx->input_buf, ctx->input_buf + 1, --ctx->buffered_bytes); continue; } size_t consumed = (size_t)info.frame_bytes; ctx->buffered_bytes -= consumed; memmove(ctx->input_buf, ctx->input_buf + consumed, ctx->buffered_bytes); if (samples > 0) { ctx->total_decoded_samples += samples; if (info.hz > 0) { ctx->pos_sec = ctx->total_decoded_samples / info.hz; // Update total_sec estimate if needed if (ctx->total_sec == 0 && ctx->file_size > 0) { // rough estimate already done, but keep } } // Configure audio-stream if format changed if (ctx->sample_rate != info.hz || ctx->channels != info.channels) { if (ctx->stream_handle != NULL) { audio_stream_close(ctx->stream_handle); ctx->stream_handle = NULL; } struct AudioStreamConfig config = { .sample_rate = (uint32_t)info.hz, .bits_per_sample = 16, .channels = (uint8_t)info.channels }; error_t err = audio_stream_open_output(ctx->stream_dev, &config, &ctx->stream_handle); if (err != ERROR_NONE) { ESP_LOGE(TAG, "Failed to open audio stream: %d", err); break; } ctx->sample_rate = info.hz; ctx->channels = info.channels; ESP_LOGI(TAG, "Audio stream opened: %d Hz, %d channels", info.hz, info.channels); } // Adjust volume (after resampler) 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; } // Play audio via audio-stream (resampled to native 44100) 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(500)); if (err != ERROR_NONE || written == 0) { ESP_LOGE(TAG, "Audio stream write failed: %d", err); write_err = true; break; } offset += written; } if (write_err) { break; } } // Update progress UI if (ctx->file_size > 0) { int pct = (int)((ctx->bytes_read_total - ctx->buffered_bytes) * 100 / ctx->file_size); if (pct < 0) pct = 0; if (pct > 100) pct = 100; tt_lvgl_lock(portMAX_DELAY); lv_bar_set_value(ctx->bar_progress, pct, LV_ANIM_OFF); tt_lvgl_unlock(); } } fclose(ctx->file); ctx->file = NULL; if (ctx->pos_sec > 0 && ctx->total_sec >0 && ctx->pos_sec >= ctx->total_sec - 10) { // Finished naturally, clear resume ctx->pos_sec = 0; ctx->finished_naturally = true; } else { ctx->finished_naturally = false; } // Close audio stream to clean up DMA / resampler task if (ctx->stream_handle != NULL) { audio_stream_close(ctx->stream_handle); ctx->stream_handle = NULL; } ESP_LOGI(TAG, "Playback task finished pos=%d total=%d naturally=%d", ctx->pos_sec, ctx->total_sec, ctx->finished_naturally); tt_lvgl_lock(portMAX_DELAY); ctx->state = STATE_IDLE; update_ui(ctx); tt_lvgl_unlock(); ctx->playback_task_handle = NULL; vTaskDelete(NULL); } /* ─── Callbacks ─── */ static void on_play_pause_click(lv_event_t* e) { AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e); if (ctx->filepath[0] == '\0') return; if (ctx->state == STATE_IDLE) { ctx->state = STATE_PLAYING; update_ui(ctx); xTaskCreate(mp3_playback_task, "mp3_play", 6144, ctx, 6, &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_stop_click(lv_event_t* e) { AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e); if (ctx->state == STATE_IDLE) return; ctx->state = STATE_IDLE; update_ui(ctx); } /* ─── App Lifecycle ─── */ static void onShowApp(AppHandle app, void* data, lv_obj_t* parent) { memset(&g_ctx, 0, sizeof(g_ctx)); g_ctx.volume = 80; g_ctx.app_handle = app; // Allocate memory buffers g_ctx.input_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)); // Find audio-stream device with retry (seen "not found" when launched from DM) for (int tries=0; tries<5; tries++) { struct Device* dev = device_find_by_name("audio-stream"); if (dev) { g_ctx.stream_dev = dev; break; } dev = device_find_first_by_type(&AUDIO_STREAM_TYPE); if (dev) { g_ctx.stream_dev = dev; break; } ESP_LOGW(TAG, "Audio-stream not found, retry %d/5", tries); vTaskDelay(pdMS_TO_TICKS(200)); } if (!g_ctx.stream_dev) { ESP_LOGE(TAG, "Audio-stream device not found after retries!"); } else { ESP_LOGI(TAG, "Found audio-stream device %p", g_ctx.stream_dev); } // Parse launch parameters BundleHandle bundle = tt_app_get_parameters(app); bool has_file_param = false; if (bundle) { char file_param[512] = {0}; if (tt_bundle_opt_string(bundle, "file", file_param, sizeof(file_param)) || tt_bundle_opt_string(bundle, "path", file_param, sizeof(file_param)) || tt_bundle_opt_string(bundle, "filepath", file_param, sizeof(file_param))) { // Safely resolve SD card path if (strncmp(file_param, "/sdcard", 7) == 0) { strncpy(g_ctx.filepath, file_param, sizeof(g_ctx.filepath) - 1); g_ctx.filepath[sizeof(g_ctx.filepath)-1]=0; } else { if (file_param[0] == '/') { size_t needed = 7 + strlen(file_param) + 1; if (needed <= sizeof(g_ctx.filepath)) { strcpy(g_ctx.filepath, "/sdcard"); strcat(g_ctx.filepath, file_param); } else { strncpy(g_ctx.filepath, file_param, sizeof(g_ctx.filepath)-1); g_ctx.filepath[sizeof(g_ctx.filepath)-1]=0; } } else { size_t needed = 8 + strlen(file_param) + 1; if (needed <= sizeof(g_ctx.filepath)) { strcpy(g_ctx.filepath, "/sdcard/"); strcat(g_ctx.filepath, file_param); } else { strncpy(g_ctx.filepath, file_param, sizeof(g_ctx.filepath)-1); g_ctx.filepath[sizeof(g_ctx.filepath)-1]=0; } } } has_file_param = true; } int32_t pos = 0; if (tt_bundle_opt_int32(bundle, "pos_sec", &pos) || tt_bundle_opt_int32(bundle, "position", &pos) || tt_bundle_opt_int32(bundle, "timestamp", &pos)) { g_ctx.start_pos_sec = pos; } int32_t vol = 0; if (tt_bundle_opt_int32(bundle, "volume", &vol)) { g_ctx.volume = vol; } } // For direct testing from Launcher without bundle (user request: run mp3 player with episode on sd) // Use a known existing file on SD card if no file param provided if (!has_file_param) { // Try to find first mp3 in /sdcard/dm/ // For quick test, use a hardcoded existing file from logs const char *test_files[] = { "/sdcard/dm/462_Gadgets_Escape_S01E02.mp3", "/sdcard/dm/463_Discovering_Discovery_Mountain_S01E01.mp3", "/sdcard/download/test2.mp3", "/sdcard/download/test.mp3" }; for (int i=0; i<4; i++) { struct stat st; if (stat(test_files[i], &st)==0 && st.st_size>1024) { strncpy(g_ctx.filepath, test_files[i], sizeof(g_ctx.filepath)-1); g_ctx.filepath[sizeof(g_ctx.filepath)-1]=0; ESP_LOGI(TAG, "No file param, using test file %s", g_ctx.filepath); has_file_param = true; break; } } } // ─── UI Layout ─── lv_obj_t* toolbar = tt_lvgl_toolbar_create_for_app(parent, app); lv_obj_align(toolbar, LV_ALIGN_TOP_MID, 0, 0); // Player Card (rounded box) lv_obj_t* card = lv_obj_create(parent); lv_obj_set_size(card, lv_pct(90), lv_pct(70)); lv_obj_align(card, LV_ALIGN_CENTER, 0, 15); lv_obj_set_style_radius(card, 15, 0); lv_obj_set_style_bg_color(card, lv_color_hex(0x1E1E2E), 0); lv_obj_set_style_border_color(card, lv_color_hex(0x313244), 0); lv_obj_set_style_border_width(card, 2, 0); lv_obj_set_flex_flow(card, LV_FLEX_FLOW_COLUMN); lv_obj_set_flex_align(card, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); lv_obj_set_style_pad_all(card, 15, 0); lv_obj_set_style_pad_gap(card, 15, 0); // Audio Icon lv_obj_t* icon = lv_label_create(card); lv_label_set_text(icon, LV_SYMBOL_AUDIO); lv_obj_set_style_text_color(icon, lv_color_hex(0x89B4FA), 0); // Track Title g_ctx.lbl_title = lv_label_create(card); lv_obj_set_width(g_ctx.lbl_title, lv_pct(95)); lv_obj_set_style_text_align(g_ctx.lbl_title, LV_TEXT_ALIGN_CENTER, 0); lv_obj_set_style_text_color(g_ctx.lbl_title, lv_color_hex(0xCDD6F4), 0); if (g_ctx.filepath[0] != '\0') { const char* last_slash = strrchr(g_ctx.filepath, '/'); const char* filename = last_slash ? last_slash + 1 : g_ctx.filepath; lv_label_set_text(g_ctx.lbl_title, filename); lv_label_set_long_mode(g_ctx.lbl_title, LV_LABEL_LONG_SCROLL_CIRCULAR); } else { lv_label_set_text(g_ctx.lbl_title, "No File Parameter"); } // Playback Status g_ctx.lbl_status = lv_label_create(card); lv_obj_set_style_text_color(g_ctx.lbl_status, lv_color_hex(0xA6ADC8), 0); // Progress Bar g_ctx.bar_progress = lv_bar_create(card); lv_obj_set_size(g_ctx.bar_progress, lv_pct(85), 8); 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); // Controls Container lv_obj_t* ctrl_box = lv_obj_create(card); lv_obj_remove_style_all(ctrl_box); lv_obj_set_size(ctrl_box, lv_pct(90), 45); lv_obj_set_flex_flow(ctrl_box, LV_FLEX_FLOW_ROW); lv_obj_set_flex_align(ctrl_box, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); // Play/Pause Button g_ctx.btn_play_pause = lv_btn_create(ctrl_box); lv_obj_set_size(g_ctx.btn_play_pause, 100, 36); lv_obj_set_style_radius(g_ctx.btn_play_pause, 18, 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 = lv_label_create(g_ctx.btn_play_pause); lv_label_set_text(lbl_play, LV_SYMBOL_PLAY " Play"); lv_obj_center(lbl_play); lv_obj_add_event_cb(g_ctx.btn_play_pause, on_play_pause_click, LV_EVENT_CLICKED, &g_ctx); // Stop Button g_ctx.btn_stop = lv_btn_create(ctrl_box); lv_obj_set_size(g_ctx.btn_stop, 100, 36); lv_obj_set_style_radius(g_ctx.btn_stop, 18, 0); lv_obj_set_style_bg_color(g_ctx.btn_stop, lv_color_hex(0xF38BA8), 0); lv_obj_set_style_text_color(g_ctx.btn_stop, lv_color_hex(0x11111B), 0); lv_obj_t* lbl_stop = lv_label_create(g_ctx.btn_stop); lv_label_set_text(lbl_stop, LV_SYMBOL_STOP " Stop"); lv_obj_center(lbl_stop); lv_obj_add_event_cb(g_ctx.btn_stop, on_stop_click, LV_EVENT_CLICKED, &g_ctx); if (!g_ctx.stream_dev) { lv_label_set_text(g_ctx.lbl_status, "Error: Audio Not Found"); lv_obj_add_state(g_ctx.btn_play_pause, LV_STATE_DISABLED); lv_obj_add_state(g_ctx.btn_stop, LV_STATE_DISABLED); } else if (!g_ctx.input_buf || !g_ctx.pcm_buf) { lv_label_set_text(g_ctx.lbl_status, "Error: Out of Memory"); lv_obj_add_state(g_ctx.btn_play_pause, LV_STATE_DISABLED); lv_obj_add_state(g_ctx.btn_stop, LV_STATE_DISABLED); } else { g_ctx.state = STATE_IDLE; update_ui(&g_ctx); // Auto-play if a file parameter was provided if (g_ctx.filepath[0] != '\0') { g_ctx.state = STATE_PLAYING; update_ui(&g_ctx); xTaskCreate(mp3_playback_task, "mp3_play", 6144, &g_ctx, 6, &g_ctx.playback_task_handle); } } } static void onHideApp(AppHandle app, void* data) { (void)app; (void)data; ESP_LOGI(TAG, "onHide start pos_sec=%d", g_ctx.pos_sec); if (g_ctx.state != STATE_IDLE) { g_ctx.state = STATE_IDLE; } int tries=0; while (g_ctx.playback_task_handle != NULL && tries<50) { vTaskDelay(pdMS_TO_TICKS(50)); tries++; if (tries%10==0) { ESP_LOGI(TAG, "onHide waiting for playback task %d/50", tries); } } if (g_ctx.playback_task_handle != NULL) { ESP_LOGW(TAG, "Playback task stuck, force deleting"); vTaskDelete(g_ctx.playback_task_handle); g_ctx.playback_task_handle = NULL; } ESP_LOGI(TAG, "Playback task stopped, closing audio stream"); // Close audio stream BEFORE allocating result bundle to free internal heap (seen crash on close) if (g_ctx.stream_handle != NULL) { audio_stream_close(g_ctx.stream_handle); g_ctx.stream_handle = NULL; vTaskDelay(pdMS_TO_TICKS(100)); // let DMA free } if (g_ctx.input_buf) { free(g_ctx.input_buf); g_ctx.input_buf = NULL; } if (g_ctx.pcm_buf) { free(g_ctx.pcm_buf); g_ctx.pcm_buf = NULL; } size_t free_internal = heap_caps_get_free_size(MALLOC_CAP_INTERNAL); ESP_LOGI(TAG, "Heap after free buffers: internal=%d", free_internal); // Return timestamp result - minimal to avoid OOM and timeout // Only allocate bundle if heap > 8KB, and only put 1-2 ints if (free_internal > 6000) { BundleHandle result = tt_bundle_alloc(); if (result) { tt_bundle_put_int32(result, "pos_sec", g_ctx.pos_sec); tt_bundle_put_int32(result, "timestamp", g_ctx.pos_sec); tt_app_set_result(g_ctx.app_handle, APP_RESULT_OK, result); ESP_LOGI(TAG, "Set result bundle pos_sec=%d", g_ctx.pos_sec); } else { ESP_LOGW(TAG, "Bundle alloc failed, returning OK without data"); tt_app_set_result(g_ctx.app_handle, APP_RESULT_OK, NULL); } } else { ESP_LOGW(TAG, "Low heap %d, returning OK without bundle", free_internal); tt_app_set_result(g_ctx.app_handle, APP_RESULT_OK, NULL); } ESP_LOGI(TAG, "onHide returning pos_sec=%d total_sec=%d finished=%d", g_ctx.pos_sec, g_ctx.total_sec, g_ctx.finished_naturally); } int main(int argc, char* argv[]) { tt_app_register((AppRegistration) { .onShow = onShowApp, .onHide = onHideApp }); return 0; }