aboutsummaryrefslogtreecommitdiff
path: root/patches
diff options
context:
space:
mode:
authorYP3 Audiobook <noreply@example.invalid>2026-11-25 17:45:43 -0500
committerYP3 Audiobook <noreply@example.invalid>2026-11-25 17:45:43 -0500
commit013e3857a1c6480dfd241fb14b36c55b0421939e (patch)
tree59b3aa16d4f658eb7b76e5dfbc475c3a408507c7 /patches
downloadyp3-audiobook-firmware-013e3857a1c6480dfd241fb14b36c55b0421939e.tar.gz
initial commit
Diffstat (limited to 'patches')
-rw-r--r--patches/0001-yp3-audiobook-resume-save-on-pause-periodically-per-.patch386
-rw-r--r--patches/0002-yp3-M4B-chapters-Down-Left-Right-chapter-title-marke.patch968
-rw-r--r--patches/0003-yp3-next-chapter-title-in-the-next-track-tokens.patch90
3 files changed, 1444 insertions, 0 deletions
diff --git a/patches/0001-yp3-audiobook-resume-save-on-pause-periodically-per-.patch b/patches/0001-yp3-audiobook-resume-save-on-pause-periodically-per-.patch
new file mode 100644
index 0000000..007e110
--- /dev/null
+++ b/patches/0001-yp3-audiobook-resume-save-on-pause-periodically-per-.patch
@@ -0,0 +1,386 @@
+From 7482c8a3508e68ccd705d12e2291d402bb011351 Mon Sep 17 00:00:00 2001
+From: YP3 Audiobook <noreply@example.invalid>
+Date: Wed, 25 Nov 2026 20:11:27 +0000
+Subject: [PATCH 1/3] yp3: audiobook resume (save on pause/periodically,
+ per-file bookmarks, defaults)
+
+---
+ apps/bookmark.c | 87 +++++++++++++++++++++++++++++++++---
+ apps/bookmark.h | 3 ++
+ apps/filetree.c | 9 ++++
+ apps/playback.c | 30 +++++++++++++
+ apps/settings.c | 12 +++++
+ apps/settings.h | 3 ++
+ apps/settings_list.c | 38 +++++++++++++---
+ firmware/export/config/yp3.h | 7 +++
+ 8 files changed, 177 insertions(+), 12 deletions(-)
+
+diff --git a/apps/bookmark.c b/apps/bookmark.c
+index 4bb97a15..a6790c7f 100644
+--- a/apps/bookmark.c
++++ b/apps/bookmark.c
+@@ -144,7 +144,8 @@ static long long_token(const char **s)
+ /*-------------------------------------------------------------------------*/
+ static bool bookmark_get_playlist_and_track_hash(const char *bookmark,
+ uint32_t *pl_hash,
+- uint32_t *track_hash)
++ uint32_t *track_hash,
++ bool per_track)
+ {
+ *pl_hash = 0;
+ *track_hash = 0;
+@@ -163,7 +164,7 @@ static bool bookmark_get_playlist_and_track_hash(const char *bookmark,
+ track = pl_end + 1;
+ get_hash(pl_start, pl_hash, pl_len);
+
+- if (global_settings.usemrb == BOOKMARK_ONE_PER_TRACK)
++ if (per_track)
+ {
+ get_hash(track, track_hash, strlen(track));
+ }
+@@ -322,12 +323,26 @@ static bool add_bookmark(const char* bookmark_file_name,
+ || (global_settings.usemrb == BOOKMARK_ONE_PER_TRACK)))
+ {
+
+- if (bookmark_get_playlist_and_track_hash(bookmark, &pl_hash, &pl_track_hash))
++ bool per_track = (global_settings.usemrb == BOOKMARK_ONE_PER_TRACK);
++ if (bookmark_get_playlist_and_track_hash(bookmark, &pl_hash,
++ &pl_track_hash, per_track))
+ {
+ comp_playlist = true;
+- comp_track = (global_settings.usemrb == BOOKMARK_ONE_PER_TRACK);
++ comp_track = per_track;
+ }
+ }
++#ifdef HAVE_AUDIOBOOK_RESUME
++ /* A folder's bookmark file keeps one bookmark per file: the newest
++ place in each book. Upstream adds one on every stop and keeps them
++ all, and autoload took the newest whichever file was picked. */
++ else if (!most_recent &&
++ bookmark_get_playlist_and_track_hash(bookmark, &pl_hash,
++ &pl_track_hash, true))
++ {
++ comp_playlist = true;
++ comp_track = true;
++ }
++#endif
+
+ logf("adding bookmark to %s [%s]", fnamebuf, bookmark);
+ /* Writing the new bookmark to the begining of the temp file */
+@@ -357,7 +372,8 @@ static bool add_bookmark(const char* bookmark_file_name,
+ if (comp_playlist)
+ {
+ if (bookmark_get_playlist_and_track_hash(global_temp_buffer,
+- &bm_pl_hash, &bm_pl_track_hash))
++ &bm_pl_hash, &bm_pl_track_hash,
++ comp_track))
+ {
+ equal = (pl_hash == bm_pl_hash);
+ if (equal && comp_track)
+@@ -1333,6 +1349,67 @@ int bookmark_autoload(const char* file)
+ }
+ }
+
++#ifdef HAVE_AUDIOBOOK_RESUME
++/* The track a bookmark line names, without its folder. */
++static const char *bookmark_track_name(const char *bookmark)
++{
++ const char *track = strrchr(bookmark, ';');
++ const char *slash;
++
++ if (!track)
++ return NULL;
++ track++;
++ slash = strrchr(track, '/');
++ return slash ? slash + 1 : track;
++}
++
++/* ----------------------------------------------------------------------- */
++/* Autoload for a file picked in the browser: resume that file at its own */
++/* bookmark in its folder's bookmark file, so each book in a folder keeps */
++/* its place. A file with no bookmark there plays from its start. */
++/* Autoload "ask" keeps the upstream list. */
++/* ----------------------------------------------------------------------- */
++int bookmark_autoload_track(const char* dir, const char* track_path)
++{
++ static char line[MAX_BOOKMARK_SIZE];
++ char bm_filename[MAX_PATH];
++ const char *want;
++ bool found = false;
++ int fd;
++
++ if (global_settings.autoloadbookmark != BOOKMARK_YES)
++ return bookmark_autoload(dir);
++
++ if (!generate_bookmark_file_name(bm_filename, sizeof(bm_filename), dir, -1))
++ return BOOKMARK_DONT_RESUME;
++
++ fd = open(bm_filename, O_RDONLY);
++ if (fd < 0)
++ return BOOKMARK_DONT_RESUME;
++
++ want = strrchr(track_path, '/');
++ want = want ? want + 1 : track_path;
++
++ /* newest first */
++ while (read_line(fd, line, sizeof(line)) > 0)
++ {
++ const char *track = bookmark_track_name(line);
++ if (track && !strcmp(track, want) &&
++ parse_bookmark(NULL, 0, line, NULL, false))
++ {
++ found = true;
++ break;
++ }
++ }
++ close(fd);
++
++ if (!found)
++ return BOOKMARK_DONT_RESUME;
++ logf("autoload %s from %s", want, bm_filename);
++ return play_bookmark(line) ? BOOKMARK_DO_RESUME : BOOKMARK_DONT_RESUME;
++}
++#endif /* HAVE_AUDIOBOOK_RESUME */
++
+ /* ----------------------------------------------------------------------- */
+ /* This function loads the bookmark information into the resume memory. */
+ /* This is an interface function. */
+diff --git a/apps/bookmark.h b/apps/bookmark.h
+index 192e577c..392488d7 100644
+--- a/apps/bookmark.h
++++ b/apps/bookmark.h
+@@ -40,6 +40,9 @@ bool bookmark_autobookmark(bool prompt_ok);
+ bool bookmark_create_menu(void);
+ bool bookmark_mrb_load(void);
+ int bookmark_autoload(const char* file);
++#ifdef HAVE_AUDIOBOOK_RESUME
++int bookmark_autoload_track(const char* dir, const char* track_path);
++#endif
+ bool bookmark_load(const char* file, bool autoload);
+ bool bookmark_exists(void);
+ bool bookmark_is_bookmarkable_state(void);
+diff --git a/apps/filetree.c b/apps/filetree.c
+index efbdbf72..e11036df 100644
+--- a/apps/filetree.c
++++ b/apps/filetree.c
+@@ -610,7 +610,16 @@ int ft_enter(struct tree_context* c)
+
+ case FILE_ATTR_AUDIO:
+ {
++#ifdef HAVE_AUDIOBOOK_RESUME
++ /* Picking a file replaces what is playing: keep that
++ book's place first (upstream only bookmarks on stop),
++ then resume the picked file at its own bookmark. */
++ if (audio_status() && !global_settings.party_mode)
++ bookmark_autobookmark(false);
++ int res = bookmark_autoload_track(c->currdir, buf);
++#else
+ int res = bookmark_autoload(c->currdir);
++#endif
+ if (res == BOOKMARK_CANCEL || res == BOOKMARK_DO_RESUME)
+ break;
+
+diff --git a/apps/playback.c b/apps/playback.c
+index 5e09ae3e..bc5f91c4 100644
+--- a/apps/playback.c
++++ b/apps/playback.c
+@@ -1807,6 +1807,25 @@ static void audio_playlist_track_change(void)
+ playlist_update_resume_info(id3);
+ }
+
++#ifdef HAVE_AUDIOBOOK_RESUME
++static long audiobook_next_save_tick;
++
++/* Store the playing position as the resume point and have it written out
++ soon. Upstream refreshes it only at track changes and stop, so in a
++ long single-file audiobook a crash or dead battery went back to the
++ start of the file. */
++static void audiobook_save_position(void)
++{
++ struct mp3entry *id3 = valid_mp3entry(id3_get(PLAYING_ID3));
++
++ audiobook_next_save_tick = current_tick + AUDIOBOOK_RESUME_SAVE_TICKS;
++ if (!id3 || !id3->elapsed)
++ return;
++ playlist_update_resume_info(id3);
++ status_save_now();
++}
++#endif /* HAVE_AUDIOBOOK_RESUME */
++
+ /* Change the data for the next track and send the event */
+ static void audio_update_and_announce_next_track(const struct mp3entry *id3_next)
+ {
+@@ -3694,6 +3713,11 @@ static void audio_on_pause(bool pause)
+ play_status = pause ? PLAY_PAUSED : PLAY_PLAYING;
+ iap_on_play_status(play_status);
+
++#ifdef HAVE_AUDIOBOOK_RESUME
++ if (pause && !ff_rw_mode)
++ audiobook_save_position();
++#endif
++
+ if (!pause && codec_skip_pending)
+ {
+ /* Actually do the skip that is due - resets the status flag */
+@@ -4202,6 +4226,12 @@ void audio_playback_handler(struct queue_event *ev)
+ break;
+ } /* end switch */
+
++#ifdef HAVE_AUDIOBOOK_RESUME
++ if (play_status == PLAY_PLAYING && !ff_rw_mode &&
++ TIME_AFTER(current_tick, audiobook_next_save_tick))
++ audiobook_save_position();
++#endif
++
+ switch (filling)
+ {
+ /* Active states */
+diff --git a/apps/settings.c b/apps/settings.c
+index ef77a799..62620cc8 100644
+--- a/apps/settings.c
++++ b/apps/settings.c
+@@ -748,6 +748,18 @@ void status_save(bool force)
+ register_storage_idle_func(flush_global_status_callback);
+ }
+
++#ifdef HAVE_AUDIOBOOK_RESUME
++/* Write the resume point at the next storage idle, skipping the 15 minute
++ * throttle: playback calls this on pause and every
++ * AUDIOBOOK_RESUME_SAVE_TICKS while playing, so a crash, RESET or a dead
++ * battery loses at most that much of a long single-file audiobook. */
++void status_save_now(void)
++{
++ next_status_update_tick = current_tick - 1;
++ register_storage_idle_func(flush_global_status_callback);
++}
++#endif
++
+ int settings_save(void)
+ {
+ logf("%s", __func__);
+diff --git a/apps/settings.h b/apps/settings.h
+index a67981dc..9a6b67ef 100644
+--- a/apps/settings.h
++++ b/apps/settings.h
+@@ -262,6 +262,9 @@ void settings_load(void) INIT_ATTR;
+ bool settings_load_config(const char* file, bool apply);
+
+ void status_save(bool force);
++#ifdef HAVE_AUDIOBOOK_RESUME
++void status_save_now(void);
++#endif
+ int settings_save(void);
+
+ /* defines for the options paramater */
+diff --git a/apps/settings_list.c b/apps/settings_list.c
+index e0eda5e7..4f5e2f58 100644
+--- a/apps/settings_list.c
++++ b/apps/settings_list.c
+@@ -324,6 +324,22 @@ static const char off[] = "off";
+ static const char off_on[] = "off,on";
+ static const char off_on_ask[] = "off,on,ask";
+ static const char off_number_spell[] = "off,number,spell";
++/* Defaults for an audiobook player (HAVE_AUDIOBOOK_RESUME): bookmark every
++ * book on stop, power-off and switching books, resume a picked file at its
++ * bookmark, start in the book that was playing, rewind a little on resume,
++ * and step 30 s on Left/Right. */
++#ifdef HAVE_AUDIOBOOK_RESUME
++#define AUDIOBOOK_DEFAULT(audiobook, upstream) (audiobook)
++#else
++#define AUDIOBOOK_DEFAULT(audiobook, upstream) (upstream)
++#endif
++/* "start in screen": previous, root, files, [db,] wps... */
++#ifdef HAVE_TAGCACHE
++#define AUDIOBOOK_START_WPS 4
++#else
++#define AUDIOBOOK_START_WPS 3
++#endif
++
+ static const int timeout_sec_common[] = {-1,0,1,2,3,4,5,6,7,8,9,10,15,20,25,30,
+ 45,60,90,120,180,240,300,600,900,1200,
+ 1500,1800,2700,3600,4500,5400,6300,7200};
+@@ -1706,7 +1722,8 @@ const struct settings_list settings[] = {
+ ID2P(LANG_OFF), ID2P(LANG_ON), ID2P(LANG_ASK)),
+ /* bookmarks */
+ CHOICE_SETTING(0, autocreatebookmark, LANG_BOOKMARK_SETTINGS_AUTOCREATE,
+- BOOKMARK_NO, "autocreate bookmarks",
++ AUDIOBOOK_DEFAULT(BOOKMARK_YES, BOOKMARK_NO),
++ "autocreate bookmarks",
+ "off,on,ask,recent only - on,recent only - ask", NULL, 5,
+ ID2P(LANG_SET_BOOL_NO), ID2P(LANG_SET_BOOL_YES),
+ ID2P(LANG_ASK), ID2P(LANG_BOOKMARK_SETTINGS_RECENT_ONLY_YES),
+@@ -1714,11 +1731,13 @@ const struct settings_list settings[] = {
+ OFFON_SETTING(0, autoupdatebookmark, LANG_BOOKMARK_SETTINGS_AUTOUPDATE,
+ false, "autoupdate bookmarks", NULL),
+ CHOICE_SETTING(0, autoloadbookmark, LANG_BOOKMARK_SETTINGS_AUTOLOAD,
+- BOOKMARK_NO, "autoload bookmarks", off_on_ask, NULL, 3,
++ AUDIOBOOK_DEFAULT(BOOKMARK_YES, BOOKMARK_NO),
++ "autoload bookmarks", off_on_ask, NULL, 3,
+ ID2P(LANG_SET_BOOL_NO), ID2P(LANG_SET_BOOL_YES),
+ ID2P(LANG_ASK)),
+ CHOICE_SETTING(0, usemrb, LANG_BOOKMARK_SETTINGS_MAINTAIN_RECENT_BOOKMARKS,
+- BOOKMARK_NO, "use most-recent-bookmarks",
++ AUDIOBOOK_DEFAULT(BOOKMARK_ONE_PER_TRACK, BOOKMARK_NO),
++ "use most-recent-bookmarks",
+ "off,on,unique only,one per track", NULL, 4, ID2P(LANG_SET_BOOL_NO),
+ ID2P(LANG_SET_BOOL_YES),
+ ID2P(LANG_BOOKMARK_SETTINGS_ONE_PER_PLAYLIST),
+@@ -2226,7 +2245,8 @@ const struct settings_list settings[] = {
+ OFFON_SETTING(0, bt_autoconnect, LANG_BLUETOOTH_AUTOCONNECT, true,
+ "bluetooth auto-connect", NULL),
+ #endif
+- INT_SETTING(F_TIME_SETTING, pause_rewind, LANG_PAUSE_REWIND, 0,
++ INT_SETTING(F_TIME_SETTING, pause_rewind, LANG_PAUSE_REWIND,
++ AUDIOBOOK_DEFAULT(2, 0),
+ "rewind duration on pause", UNIT_SEC, 0, 15, 1,
+ formatter_time_unit_0_is_off, getlang_time_unit_0_is_off, NULL),
+ #if CONFIG_TUNER
+@@ -2287,12 +2307,15 @@ const struct settings_list settings[] = {
+ NULL),
+ #endif
+ TABLE_SETTING_LIST(F_TIME_SETTING | F_ALLOW_ARBITRARY_VALS, skip_length,
+- LANG_SKIP_LENGTH, 0, "skip length",
++ LANG_SKIP_LENGTH, AUDIOBOOK_DEFAULT(30, 0), "skip length",
+ "outro,track",
+ UNIT_SEC, formatter_time_unit_0_is_skip_track,
+ getlang_time_unit_0_is_skip_track, NULL,
+ 25, timeout_sec_common),
+- CHOICE_SETTING(F_CB_ON_SELECT_ONLY, start_in_screen, LANG_START_SCREEN, 1,
++ CHOICE_SETTING(F_CB_ON_SELECT_ONLY, start_in_screen, LANG_START_SCREEN,
++ /* audiobook: "Resume Playback" (main menu without
++ anything to resume) */
++ AUDIOBOOK_DEFAULT(AUDIOBOOK_START_WPS, 1),
+ "start in screen", "previous,root,files,"
+ #ifdef HAVE_TAGCACHE
+ #define START_DB_COUNT 1
+@@ -2561,7 +2584,8 @@ const struct settings_list settings[] = {
+
+ #endif /* HAVE_HOTKEY */
+
+- INT_SETTING(F_TIME_SETTING, resume_rewind, LANG_RESUME_REWIND, 0,
++ INT_SETTING(F_TIME_SETTING, resume_rewind, LANG_RESUME_REWIND,
++ AUDIOBOOK_DEFAULT(5, 0),
+ "resume rewind", UNIT_SEC, 0, 60, 5,
+ formatter_time_unit_0_is_off, getlang_time_unit_0_is_off, NULL),
+ CUSTOM_SETTING(0, root_menu_customized,
+diff --git a/firmware/export/config/yp3.h b/firmware/export/config/yp3.h
+index d43aa9ed..07614b6b 100644
+--- a/firmware/export/config/yp3.h
++++ b/firmware/export/config/yp3.h
+@@ -250,6 +250,13 @@
+ * a whole 40 KiB frame of heap, and cabbiev2's two left playback without
+ * its buffer (OOM panic). Skins keep their colours, fonts and icons. */
+ #define HAVE_NO_BACKDROP_FILES
++/* Audiobook player: the resume point is written on pause and every
++ * AUDIOBOOK_RESUME_SAVE_TICKS while playing (not just at track changes and
++ * stop), each book in a folder keeps its own bookmark, switching books
++ * bookmarks the one playing, and the defaults bookmark and resume
++ * (apps/playback.c, bookmark.c, filetree.c, settings_list.c). */
++#define HAVE_AUDIOBOOK_RESUME
++#define AUDIOBOOK_RESUME_SAVE_TICKS (60 * HZ)
+ /* No surround: its 31 KB delay buffer comes out of the playback buffer,
+ * which then stayed shrunk (stutter until a reset) */
+ #define HAVE_NO_SURROUND
+--
+2.56.1
+
diff --git a/patches/0002-yp3-M4B-chapters-Down-Left-Right-chapter-title-marke.patch b/patches/0002-yp3-M4B-chapters-Down-Left-Right-chapter-title-marke.patch
new file mode 100644
index 0000000..11b3410
--- /dev/null
+++ b/patches/0002-yp3-M4B-chapters-Down-Left-Right-chapter-title-marke.patch
@@ -0,0 +1,968 @@
+From 648bf22824c28ed4c432bf5312d25082ef8d2364 Mon Sep 17 00:00:00 2001
+From: YP3 Audiobook <noreply@example.invalid>
+Date: Wed, 25 Nov 2026 20:28:42 +0000
+Subject: [PATCH 2/3] yp3: M4B chapters (Down+Left/Right, chapter title,
+ markers, list)
+
+---
+ apps/SOURCES | 3 +
+ apps/action.h | 4 +
+ apps/chapters.c | 644 ++++++++++++++++++++++++++++
+ apps/chapters.h | 38 ++
+ apps/gui/skin_engine/skin_display.c | 11 +
+ apps/gui/skin_engine/skin_tokens.c | 30 ++
+ apps/gui/wps.c | 10 +
+ apps/keymaps/keymap-yp3.c | 11 +-
+ apps/onplay.c | 22 +
+ apps/settings_list.c | 4 +-
+ firmware/export/config/yp3.h | 5 +
+ 11 files changed, 780 insertions(+), 2 deletions(-)
+ create mode 100644 apps/chapters.c
+ create mode 100644 apps/chapters.h
+
+diff --git a/apps/SOURCES b/apps/SOURCES
+index af692315..ed0f5be7 100644
+--- a/apps/SOURCES
++++ b/apps/SOURCES
+@@ -7,6 +7,9 @@ alarm_menu.c
+ #endif
+ abrepeat.c
+ bookmark.c
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++chapters.c
++#endif
+ core_keymap.c
+ debug_menu.c
+ filetypes.c
+diff --git a/apps/action.h b/apps/action.h
+index 03a3a084..c382838a 100644
+--- a/apps/action.h
++++ b/apps/action.h
+@@ -191,6 +191,10 @@ enum {
+ ACTION_WPS_ABSETB_NEXTDIR, /* you shouldnt want to change dir in ab-mode */
+ ACTION_WPS_ABRESET,
+ ACTION_WPS_HOTKEY,
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++ ACTION_WPS_CHAPTERPREV,
++ ACTION_WPS_CHAPTERNEXT,
++#endif
+
+ /* list and tree page up/down */
+ ACTION_LISTTREE_PGUP,/* optional */
+diff --git a/apps/chapters.c b/apps/chapters.c
+new file mode 100644
+index 00000000..9b483653
+--- /dev/null
++++ b/apps/chapters.c
+@@ -0,0 +1,644 @@
++/* SPDX-License-Identifier: GPL-2.0-or-later */
++/* Audiobook chapters of the playing file.
++ *
++ * MP4/M4B files carry chapters one of two ways, often both:
++ * - a Nero 'chpl' atom in moov/udta (ffmpeg writes it): up to 255
++ * entries of a start time in 100 ns units and a title;
++ * - a QuickTime chapter track: the audio track's tref/chap names a text
++ * track whose samples are the titles (a 16-bit length, then the text)
++ * and whose sample times are the starts (iTunes, Audible conversions).
++ * 'chpl' is used when present, else the chapter track.
++ *
++ * Only the start times and where each title is in the file are kept, for
++ * the one track loaded (8 bytes a chapter, CHAPTERS_MAX at most): titles
++ * are read from the file when shown. Everything here runs in the UI
++ * thread (it opens files). */
++
++#include <stdio.h>
++#include <string.h>
++#include "string-extra.h"
++#include <stdint.h>
++#include "config.h"
++#include "system.h"
++#include "file.h"
++#include "rbunicode.h"
++#include "metadata.h"
++#include "audio.h"
++#include "playback.h"
++#include "playlist.h"
++#include "misc.h"
++#include "screen_access.h"
++#include "list.h"
++#include "root_menu.h"
++#include "logf.h"
++#include "chapters.h"
++
++#define CHAPTERS_MAX 255
++#define TITLE_MAX 96 /* bytes of a title read from the file */
++
++#define FOURCC(a,b,c,d) (((uint32_t)(a) << 24) | ((b) << 16) | ((c) << 8) | (d))
++
++static uint32_t ch_start[CHAPTERS_MAX]; /* ms */
++static uint32_t ch_title[CHAPTERS_MAX]; /* file offset of the title's length
++ field; 0: no title */
++static int ch_count;
++static bool ch_qt_titles; /* 16-bit title lengths, else 8 */
++static char ch_path[MAX_PATH]; /* the file they are from */
++static int ch_last_index = -1; /* chapters_changed() */
++static int ch_title_index = -1; /* cur_title holds this one */
++static char cur_title[TITLE_MAX + 1];
++
++/* --- a small buffered reader: the atoms are walked with many tiny reads --- */
++
++static struct
++{
++ int fd;
++ uint32_t pos; /* file offset of buf[0] */
++ int len, i;
++ bool err;
++ unsigned char buf[256];
++} rd;
++
++static void rd_seek(uint32_t off)
++{
++ if (rd.len && off >= rd.pos && off < rd.pos + rd.len)
++ {
++ rd.i = off - rd.pos;
++ return;
++ }
++ if (lseek(rd.fd, off, SEEK_SET) != (off_t)off)
++ rd.err = true;
++ rd.pos = off;
++ rd.len = rd.i = 0;
++}
++
++static unsigned rd_u8(void)
++{
++ if (rd.i >= rd.len)
++ {
++ rd.pos += rd.len;
++ rd.i = 0;
++ rd.len = read(rd.fd, rd.buf, sizeof(rd.buf));
++ if (rd.len <= 0)
++ {
++ rd.len = 0;
++ rd.err = true;
++ return 0;
++ }
++ }
++ return rd.buf[rd.i++];
++}
++
++static uint32_t rd_u16(void)
++{
++ uint32_t v = rd_u8() << 8;
++ return v | rd_u8();
++}
++
++static uint32_t rd_u32(void)
++{
++ uint32_t v = rd_u16() << 16;
++ return v | rd_u16();
++}
++
++static uint64_t rd_u64(void)
++{
++ uint64_t v = (uint64_t)rd_u32() << 32;
++ return v | rd_u32();
++}
++
++static uint32_t rd_tell(void)
++{
++ return rd.pos + rd.i;
++}
++
++/* --- atoms --- */
++
++struct atom
++{
++ uint32_t type;
++ uint32_t data; /* offset of its contents */
++ uint32_t end; /* offset just past it */
++};
++
++/* The atom at *pos, if it lies within end; *pos moves past it. */
++static bool atom_next(uint32_t *pos, uint32_t end, struct atom *a)
++{
++ uint64_t size;
++ uint32_t hdr = 8;
++
++ if (rd.err || *pos >= end || end - *pos < 8)
++ return false;
++ rd_seek(*pos);
++ size = rd_u32();
++ a->type = rd_u32();
++ if (size == 1)
++ {
++ size = rd_u64();
++ hdr = 16;
++ }
++ else if (size == 0)
++ size = end - *pos; /* to the end of its parent */
++ if (rd.err || size < hdr || size > (uint64_t)(end - *pos))
++ return false;
++ a->data = *pos + hdr;
++ a->end = *pos + (uint32_t)size;
++ *pos = a->end;
++ return true;
++}
++
++static bool atom_find(uint32_t start, uint32_t end, uint32_t type,
++ struct atom *a)
++{
++ uint32_t pos = start;
++ while (atom_next(&pos, end, a))
++ if (a->type == type)
++ return true;
++ return false;
++}
++
++/* A path of nested atoms, e.g. "mdia" "minf" "stbl". */
++static bool atom_path(const struct atom *parent, const uint32_t *types,
++ int n, struct atom *a)
++{
++ uint32_t start = parent->data, end = parent->end;
++ for (int i = 0; i < n; i++)
++ {
++ if (!atom_find(start, end, types[i], a))
++ return false;
++ start = a->data;
++ end = a->end;
++ }
++ return true;
++}
++
++/* --- Nero chapters: moov/udta/chpl --- */
++
++static int read_chpl(const struct atom *chpl)
++{
++ int n, count = 0;
++
++ /* version (1 byte), flags (3), version 1: 4 reserved, count (1) */
++ rd_seek(chpl->data);
++ rd_seek(chpl->data + (rd_u8() != 0 ? 8 : 4));
++ n = rd_u8();
++ for (int i = 0; i < n && count < CHAPTERS_MAX; i++)
++ {
++ uint64_t start = rd_u64(); /* 100 ns units */
++ uint32_t title = rd_tell();
++ uint32_t len = rd_u8();
++ if (rd.err || title + 1 + len > chpl->end)
++ break;
++ rd_seek(title + 1 + len);
++ ch_start[count] = (uint32_t)(start / 10000);
++ ch_title[count] = title;
++ count++;
++ }
++ ch_qt_titles = false;
++ return count;
++}
++
++/* --- QuickTime chapter track --- */
++
++static uint32_t trak_id(const struct atom *trak)
++{
++ struct atom a;
++ if (!atom_find(trak->data, trak->end, FOURCC('t','k','h','d'), &a))
++ return 0;
++ rd_seek(a.data);
++ if (rd_u8() == 1)
++ rd_seek(a.data + 4 + 16); /* 64-bit creation/modification times */
++ else
++ rd_seek(a.data + 4 + 8);
++ return rd_u32();
++}
++
++/* The track the audio track names as its chapters (tref/chap), 0: none */
++static uint32_t chapter_track_id(const struct atom *moov)
++{
++ uint32_t pos = moov->data;
++ struct atom trak, a;
++ static const uint32_t chap_path[] =
++ { FOURCC('t','r','e','f'), FOURCC('c','h','a','p') };
++
++ while (atom_next(&pos, moov->end, &trak))
++ {
++ if (trak.type != FOURCC('t','r','a','k'))
++ continue;
++ if (atom_path(&trak, chap_path, 2, &a) && a.end - a.data >= 4)
++ {
++ rd_seek(a.data);
++ return rd_u32();
++ }
++ }
++ return 0;
++}
++
++static int read_chapter_track(const struct atom *trak)
++{
++ static const uint32_t mdhd_path[] =
++ { FOURCC('m','d','i','a'), FOURCC('m','d','h','d') };
++ static const uint32_t stbl_path[] =
++ { FOURCC('m','d','i','a'), FOURCC('m','i','n','f'),
++ FOURCC('s','t','b','l') };
++ struct atom mdhd, stbl, stts, stsc, stsz, stco;
++ uint32_t timescale, n_stts, n_stsc, n_chunks, n_sizes, fixed_size;
++ bool co64;
++ int count = 0;
++
++ if (!atom_path(trak, mdhd_path, 2, &mdhd) ||
++ !atom_path(trak, stbl_path, 3, &stbl))
++ return 0;
++ rd_seek(mdhd.data);
++ rd_seek(mdhd.data + (rd_u8() == 1 ? 4 + 16 : 4 + 8));
++ timescale = rd_u32();
++
++ if (!atom_find(stbl.data, stbl.end, FOURCC('s','t','t','s'), &stts) ||
++ !atom_find(stbl.data, stbl.end, FOURCC('s','t','s','c'), &stsc) ||
++ !atom_find(stbl.data, stbl.end, FOURCC('s','t','s','z'), &stsz))
++ return 0;
++ co64 = !atom_find(stbl.data, stbl.end, FOURCC('s','t','c','o'), &stco);
++ if (co64 &&
++ !atom_find(stbl.data, stbl.end, FOURCC('c','o','6','4'), &stco))
++ return 0;
++ if (!timescale || rd.err)
++ return 0;
++
++ /* start times: the sample durations added up */
++ rd_seek(stts.data + 4);
++ n_stts = rd_u32();
++ uint64_t t = 0;
++ for (uint32_t e = 0; e < n_stts && count < CHAPTERS_MAX && !rd.err; e++)
++ {
++ uint32_t n = rd_u32(), delta = rd_u32();
++ for (uint32_t k = 0; k < n && count < CHAPTERS_MAX; k++)
++ {
++ ch_start[count++] = (uint32_t)(t * 1000 / timescale);
++ t += delta;
++ }
++ }
++
++ /* where each sample (title) is: chunks from stsc/stco, sizes from stsz */
++ rd_seek(stsz.data + 4);
++ fixed_size = rd_u32();
++ n_sizes = rd_u32();
++ rd_seek(stsc.data + 4);
++ n_stsc = rd_u32();
++ rd_seek(stco.data + 4);
++ n_chunks = rd_u32();
++ if (rd.err || !n_stsc)
++ return 0;
++ if (!fixed_size && (uint32_t)count > n_sizes)
++ count = n_sizes;
++
++ /* stsc: runs of chunks (first chunk, samples per chunk, description) */
++ uint32_t stsc_i = 0, per_chunk = 0, next_first = 0;
++ int s = 0;
++ for (uint32_t chunk = 1; chunk <= n_chunks && s < count; chunk++)
++ {
++ while (chunk >= next_first && stsc_i < n_stsc)
++ {
++ /* entry stsc_i starts here: take its count, find the next */
++ rd_seek(stsc.data + 8 + 12 * stsc_i + 4);
++ per_chunk = rd_u32();
++ stsc_i++;
++ if (stsc_i < n_stsc)
++ {
++ rd_seek(stsc.data + 8 + 12 * stsc_i);
++ next_first = rd_u32();
++ }
++ else
++ next_first = UINT32_MAX;
++ }
++
++ uint64_t off;
++ if (co64)
++ {
++ rd_seek(stco.data + 8 + 8 * (chunk - 1));
++ off = rd_u64();
++ }
++ else
++ {
++ rd_seek(stco.data + 8 + 4 * (chunk - 1));
++ off = rd_u32();
++ }
++ for (uint32_t k = 0; k < per_chunk && s < count; k++, s++)
++ {
++ uint32_t size = fixed_size;
++ if (!size)
++ {
++ rd_seek(stsz.data + 12 + 4 * s);
++ size = rd_u32();
++ }
++ ch_title[s] = (off < UINT32_MAX && size >= 2) ? (uint32_t)off : 0;
++ off += size;
++ }
++ if (rd.err)
++ return 0;
++ }
++ for (; s < count; s++)
++ ch_title[s] = 0;
++ ch_qt_titles = true;
++ return count;
++}
++
++static int read_chapters(const char *path)
++{
++ struct atom moov, a;
++ uint32_t pos = 0, size;
++ int count = 0;
++
++ memset(&rd, 0, sizeof(rd));
++ rd.fd = open(path, O_RDONLY);
++ if (rd.fd < 0)
++ return 0;
++ off_t fsize = ffilesize(rd.fd);
++ size = fsize > 0 ? (uint32_t)fsize : 0;
++
++ /* the top level: mdat is skipped by its size, moov may come after it */
++ bool found = false;
++ while (atom_next(&pos, size, &moov))
++ {
++ if (moov.type == FOURCC('m','o','o','v'))
++ {
++ found = true;
++ break;
++ }
++ }
++
++ if (found)
++ {
++ static const uint32_t chpl_path[] =
++ { FOURCC('u','d','t','a'), FOURCC('c','h','p','l') };
++ if (atom_path(&moov, chpl_path, 2, &a))
++ count = read_chpl(&a);
++
++ if (count == 0)
++ {
++ uint32_t id = chapter_track_id(&moov);
++ uint32_t p = moov.data;
++ struct atom trak;
++ while (id && atom_next(&p, moov.end, &trak))
++ {
++ if (trak.type == FOURCC('t','r','a','k') && trak_id(&trak) == id)
++ {
++ count = read_chapter_track(&trak);
++ break;
++ }
++ }
++ }
++ }
++ close(rd.fd);
++
++ /* sane: from 0, in order */
++ for (int i = 1; i < count; i++)
++ {
++ if (ch_start[i] < ch_start[i - 1])
++ {
++ count = i;
++ break;
++ }
++ }
++ if (count > 0)
++ ch_start[0] = 0;
++ logf("chapters: %d in %s", count, path);
++ return count;
++}
++
++/* --- interface --- */
++
++int chapters_update(const struct mp3entry *id3)
++{
++ if (!id3 || !id3->path[0])
++ return 0;
++ if (!strcmp(id3->path, ch_path))
++ return ch_count;
++
++ strmemccpy(ch_path, id3->path, sizeof(ch_path));
++ ch_count = 0;
++ ch_last_index = -1;
++ ch_title_index = -1;
++ switch (id3->codectype)
++ {
++ case AFMT_MP4_AAC:
++ case AFMT_MP4_AAC_HE:
++ case AFMT_MP4_ALAC:
++ ch_count = read_chapters(id3->path);
++ break;
++ default:
++ break;
++ }
++ return ch_count;
++}
++
++int chapters_index(unsigned long elapsed)
++{
++ int lo = 0, hi = ch_count - 1;
++ if (ch_count <= 0)
++ return -1;
++ while (lo < hi) /* the last chapter starting at or before elapsed */
++ {
++ int mid = (lo + hi + 1) / 2;
++ if (ch_start[mid] <= elapsed)
++ lo = mid;
++ else
++ hi = mid - 1;
++ }
++ return lo;
++}
++
++unsigned long chapters_start(int i)
++{
++ return (i >= 0 && i < ch_count) ? ch_start[i] : 0;
++}
++
++/* Cut a UTF-8 string after its last whole character. */
++static void utf8_trim(char *s, size_t len)
++{
++ size_t i = len;
++ while (i > 0 && ((unsigned char)s[i - 1] & 0xc0) == 0x80)
++ i--; /* continuation bytes */
++ if (i > 0 && ((unsigned char)s[i - 1] & 0x80))
++ {
++ unsigned char lead = s[i - 1];
++ size_t need = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : 2;
++ if (len - (i - 1) < need)
++ len = i - 1; /* a cut-off last character */
++ }
++ s[len] = '\0';
++}
++
++const char *chapters_title(int i, char *buf, size_t size)
++{
++ static unsigned char raw[TITLE_MAX];
++ int fd;
++
++ if (!size)
++ return buf;
++ buf[0] = '\0';
++ if (i >= 0 && i < ch_count && ch_title[i] &&
++ (fd = open(ch_path, O_RDONLY)) >= 0)
++ {
++ unsigned char lenbuf[2];
++ int lenbytes = ch_qt_titles ? 2 : 1;
++ if (lseek(fd, ch_title[i], SEEK_SET) == (off_t)ch_title[i] &&
++ read(fd, lenbuf, lenbytes) == lenbytes)
++ {
++ int len = ch_qt_titles ? (lenbuf[0] << 8 | lenbuf[1]) : lenbuf[0];
++ len = MIN(len, (int)sizeof(raw));
++ len = read(fd, raw, len);
++ if (len >= 2 && ((raw[0] == 0xfe && raw[1] == 0xff) ||
++ (raw[0] == 0xff && raw[1] == 0xfe)))
++ {
++ /* UTF-16 with a byte order mark */
++ bool be = raw[0] == 0xfe;
++ unsigned char *out = (unsigned char *)buf;
++ unsigned char *end = out + size - 1;
++ for (int k = 2; k + 1 < len; k += 2)
++ {
++ unsigned long c = be ? (raw[k] << 8 | raw[k + 1])
++ : (raw[k + 1] << 8 | raw[k]);
++ if (c >= 0xd800 && c < 0xe000)
++ c = '?'; /* no surrogate pairs here */
++ if (end - out < 3)
++ break;
++ out = utf8encode(c, out);
++ }
++ *out = '\0';
++ }
++ else if (len > 0)
++ {
++ len = MIN(len, (int)size - 1);
++ memcpy(buf, raw, len);
++ utf8_trim(buf, len);
++ }
++ }
++ close(fd);
++ }
++ /* trim spaces and line ends some tools leave */
++ size_t n = strlen(buf);
++ while (n && (buf[n - 1] == ' ' || buf[n - 1] == '\r' || buf[n - 1] == '\n'))
++ buf[--n] = '\0';
++ if (!buf[0])
++ snprintf(buf, size, "Chapter %d", i + 1);
++ return buf;
++}
++
++const char *chapters_current_title(const struct mp3entry *id3)
++{
++ if (chapters_update(id3) <= 0)
++ return NULL;
++ int i = chapters_index(id3->elapsed);
++ if (i != ch_title_index)
++ {
++ chapters_title(i, cur_title, sizeof(cur_title));
++ ch_title_index = i;
++ }
++ return cur_title;
++}
++
++bool chapters_changed(const struct mp3entry *id3)
++{
++ if (chapters_update(id3) <= 0)
++ return false;
++ int i = chapters_index(id3->elapsed);
++ if (i == ch_last_index)
++ return false;
++ ch_last_index = i;
++ return true;
++}
++
++void chapters_draw_markers(struct screen *display, unsigned long length,
++ int x, int y, int w, int h)
++{
++ unsigned long secs = length / 1000;
++ if (ch_count < 2 || !secs)
++ return;
++ display->set_drawmode(DRMODE_COMPLEMENT);
++ for (int i = 1; i < ch_count; i++)
++ {
++ unsigned long at = ch_start[i] / 1000;
++ if (at >= secs)
++ break;
++ display->vline(x + (int)((unsigned long long)w * at / secs), y, y + h - 1);
++ }
++}
++
++static void seek_to(unsigned long ms)
++{
++ audio_pre_ff_rewind();
++ audio_ff_rewind(ms);
++}
++
++void chapters_skip(const struct mp3entry *id3, int direction,
++ unsigned long threshold)
++{
++ if (!id3)
++ return;
++
++ if (chapters_update(id3) > 0)
++ {
++ unsigned long elapsed = id3->elapsed;
++ int i = chapters_index(elapsed);
++ if (direction < 0)
++ {
++ /* restart this chapter, or the one before at its start */
++ if (elapsed < ch_start[i] + threshold && i > 0)
++ i--;
++ seek_to(ch_start[i]);
++ }
++ else if (i + 1 < ch_count)
++ seek_to(ch_start[i + 1]);
++ else
++ system_sound_play(SOUND_TRACK_NO_MORE); /* stay in this book */
++ return;
++ }
++
++ /* no chapters inside: a book in several files, one per chapter */
++ if (direction < 0)
++ {
++ if (id3->elapsed < threshold && playlist_check(-1))
++ audio_prev();
++ else
++ seek_to(0);
++ }
++ else if (playlist_check(1))
++ audio_next();
++ else
++ system_sound_play(SOUND_TRACK_NO_MORE);
++}
++
++static const char *chapter_list_name(int item, void *data,
++ char *buf, size_t size)
++{
++ (void)data;
++ char title[TITLE_MAX + 1];
++ unsigned long s = ch_start[item] / 1000;
++ chapters_title(item, title, sizeof(title));
++ if (s >= 3600)
++ snprintf(buf, size, "%lu:%02lu:%02lu %s",
++ s / 3600, s / 60 % 60, s % 60, title);
++ else
++ snprintf(buf, size, "%lu:%02lu %s", s / 60, s % 60, title);
++ return buf;
++}
++
++int chapters_browse(void)
++{
++ struct mp3entry *id3 = audio_current_track();
++ struct simplelist_info info;
++ char title[32];
++
++ if (chapters_update(id3) <= 0)
++ return 0;
++ snprintf(title, sizeof(title), "Chapters (%d)", ch_count);
++ simplelist_info_init(&info, title, ch_count, NULL);
++ info.get_name = chapter_list_name;
++ info.selection = chapters_index(id3->elapsed);
++ info.hide_theme = false;
++ simplelist_show_list(&info);
++ if (info.selection < 0 || info.selection >= ch_count)
++ return 0;
++ seek_to(ch_start[info.selection]);
++ return GO_TO_WPS;
++}
+diff --git a/apps/chapters.h b/apps/chapters.h
+new file mode 100644
+index 00000000..14e4d709
+--- /dev/null
++++ b/apps/chapters.h
+@@ -0,0 +1,38 @@
++/* SPDX-License-Identifier: GPL-2.0-or-later */
++/* Chapters inside the playing audiobook file (MP4/M4B: a Nero 'chpl' list
++ * or a QuickTime chapter text track). See chapters.c. */
++#ifndef _CHAPTERS_H_
++#define _CHAPTERS_H_
++
++#include <stdbool.h>
++#include <stddef.h>
++#include "metadata.h"
++
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++struct screen;
++
++/* Chapters of this track, read from its file the first time it is asked
++ * for (UI thread only: file I/O). 0: none. */
++int chapters_update(const struct mp3entry *id3);
++/* The chapter playing at elapsed (ms) of the loaded track. */
++int chapters_index(unsigned long elapsed);
++unsigned long chapters_start(int i);
++/* Chapter i's title (from the file; "Chapter N" without one) in buf. */
++const char *chapters_title(int i, char *buf, size_t size);
++/* The playing chapter's title, cached. */
++const char *chapters_current_title(const struct mp3entry *id3);
++/* True once each time the playing chapter changes (skin refresh). */
++bool chapters_changed(const struct mp3entry *id3);
++/* Ticks at the chapter starts on a progress bar. */
++void chapters_draw_markers(struct screen *display, unsigned long length,
++ int x, int y, int w, int h);
++/* Previous (-1) / next (1) chapter of the playing track; without chapters,
++ * the previous / next file. Previous restarts the chapter unless it began
++ * less than threshold ms ago. */
++void chapters_skip(const struct mp3entry *id3, int direction,
++ unsigned long threshold);
++/* The chapter list (WPS context menu): GO_TO_WPS after a jump, else 0. */
++int chapters_browse(void);
++#endif
++
++#endif /* _CHAPTERS_H_ */
+diff --git a/apps/gui/skin_engine/skin_display.c b/apps/gui/skin_engine/skin_display.c
+index a2ae149c..6828b536 100644
+--- a/apps/gui/skin_engine/skin_display.c
++++ b/apps/gui/skin_engine/skin_display.c
+@@ -55,6 +55,7 @@
+ #endif
+
+ #include "cuesheet.h"
++#include "chapters.h"
+ #include "playback.h"
+ #include "backdrop.h"
+ #include "viewport.h"
+@@ -96,6 +97,11 @@ void skin_update(enum skinnable_screens skin, enum screen_type screen,
+ * This is also safe for skined screen which dont use the id3 */
+ struct mp3entry *id3 = get_wps_state()->id3;
+ bool cuesheet_update = (id3 != NULL ? cuesheet_subtrack_changed(id3) : false);
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++ /* a new chapter title */
++ if (skin == WPS && id3 != NULL && chapters_changed(id3))
++ cuesheet_update = true;
++#endif
+ if (cuesheet_update)
+ skin_request_full_update(skin);
+
+@@ -381,6 +387,11 @@ void draw_progressbar(struct gui_wps *gwps, struct skin_viewport* skin_viewport,
+ if (id3->cuesheet)
+ cue_draw_markers(display, id3->cuesheet, id3->length,
+ x, y+1, width, height-2);
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++ else if (id3 == get_wps_state()->id3 && chapters_update(id3) > 1)
++ chapters_draw_markers(display, id3->length,
++ x, y+1, width, height-2);
++#endif
+ }
+ #if 0 /* disable for now CONFIG_TUNER */
+ else if (in_radio_screen() || (get_radio_status() != FMRADIO_OFF))
+diff --git a/apps/gui/skin_engine/skin_tokens.c b/apps/gui/skin_engine/skin_tokens.c
+index e80d9550..98d854ce 100644
+--- a/apps/gui/skin_engine/skin_tokens.c
++++ b/apps/gui/skin_engine/skin_tokens.c
+@@ -34,6 +34,7 @@
+ #include "sound.h"
+ #include "debug.h"
+ #include "cuesheet.h"
++#include "chapters.h"
+ #include "replaygain.h"
+ #include "core_alloc.h"
+ #include "abrepeat.h"
+@@ -849,6 +850,35 @@ static const char *try_id3_token(struct wps_token *token, int offset,
+ }
+
+ struct wps_state *state = get_wps_state();
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++ /* An audiobook with chapters: the title is the chapter's, the track
++ number the chapter's of all, the album the book's if it has none */
++ if (id3 && id3 == state->id3 && !token->next && offset == 0 &&
++ chapters_update(id3) > 0)
++ {
++ out_text = NULL;
++ switch (token->type)
++ {
++ case SKIN_TOKEN_METADATA_TRACK_TITLE:
++ out_text = chapters_current_title(id3);
++ break;
++ case SKIN_TOKEN_METADATA_TRACK_NUMBER:
++ snprintf(buf, buf_size, "%d/%d",
++ chapters_index(id3->elapsed) + 1,
++ chapters_update(id3));
++ out_text = buf;
++ break;
++ case SKIN_TOKEN_METADATA_ALBUM:
++ if (!id3->album || !*id3->album)
++ out_text = id3->title;
++ break;
++ default:
++ break;
++ }
++ if (out_text)
++ goto free_id3_outtext;
++ }
++#endif
+ if (id3 && id3 == state->id3 && id3->cuesheet)
+ {
+ out_text = get_cuesheetid3_token(token, id3,
+diff --git a/apps/gui/wps.c b/apps/gui/wps.c
+index 12fda688..714a44a4 100644
+--- a/apps/gui/wps.c
++++ b/apps/gui/wps.c
+@@ -48,6 +48,7 @@
+ #include "playback.h"
+ #include "splash.h"
+ #include "cuesheet.h"
++#include "chapters.h"
+ #include "ata_idle_notify.h"
+ #include "root_menu.h"
+ #include "backdrop.h"
+@@ -988,6 +989,15 @@ long gui_wps_show(void)
+ change_dir(-1);
+ }
+ break;
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++ case ACTION_WPS_CHAPTERPREV:
++ case ACTION_WPS_CHAPTERNEXT:
++ chapters_skip(state->id3,
++ button == ACTION_WPS_CHAPTERNEXT ? 1 : -1,
++ DEFAULT_SKIP_THRESH);
++ update = true;
++ break;
++#endif
+ /* menu key functions */
+ case ACTION_WPS_MENU:
+ gwps_leave_wps(true);
+diff --git a/apps/keymaps/keymap-yp3.c b/apps/keymaps/keymap-yp3.c
+index 09aa33ca..444bd47c 100644
+--- a/apps/keymaps/keymap-yp3.c
++++ b/apps/keymaps/keymap-yp3.c
+@@ -24,7 +24,10 @@ static const struct button_mapping lists[] = {
+ { ACTION_STD_MENU, BUTTON_UP|BUTTON_LEFT, BUTTON_NONE },
+ LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_STD)
+ };
+-/* Now Playing: Up acts on release so that holding it can stop. */
++/* Now Playing: Up acts on release so that holding it can stop. Left/Right
++ * tapped hop (Skip Length), held seek; Down+Left / Down+Right (the lower
++ * corners) go to the previous / next chapter, so Down turns the volume
++ * down on release, or the combo would lower it too. */
+ static const struct button_mapping wps[] = {
+ { ACTION_WPS_PLAY, BUTTON_SELECT|BUTTON_REL, BUTTON_SELECT },
+ { ACTION_WPS_CONTEXT, BUTTON_SELECT|BUTTON_REPEAT, BUTTON_SELECT },
+@@ -37,7 +40,13 @@ static const struct button_mapping wps[] = {
+ BUTTON_RIGHT|BUTTON_REPEAT },
+ { ACTION_WPS_VOLUP, BUTTON_UP|BUTTON_REL, BUTTON_UP },
+ { ACTION_WPS_STOP, BUTTON_UP|BUTTON_REPEAT, BUTTON_UP },
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++ { ACTION_WPS_VOLDOWN, BUTTON_DOWN|BUTTON_REL, BUTTON_DOWN },
++ { ACTION_WPS_CHAPTERPREV, BUTTON_DOWN|BUTTON_LEFT, BUTTON_NONE },
++ { ACTION_WPS_CHAPTERNEXT, BUTTON_DOWN|BUTTON_RIGHT, BUTTON_NONE },
++#else
+ { ACTION_WPS_VOLDOWN, BUTTON_DOWN, BUTTON_NONE },
++#endif
+ { ACTION_WPS_VOLDOWN, BUTTON_DOWN|BUTTON_REPEAT, BUTTON_NONE },
+ { ACTION_WPS_MENU, BUTTON_UP|BUTTON_LEFT, BUTTON_NONE },
+ LAST_ITEM_IN_LIST
+diff --git a/apps/onplay.c b/apps/onplay.c
+index 04278fe7..384a8376 100644
+--- a/apps/onplay.c
++++ b/apps/onplay.c
+@@ -57,6 +57,7 @@
+ #include "tagtree.h"
+ #endif
+ #include "cuesheet.h"
++#include "chapters.h"
+ #include "statusbar-skinned.h"
+ #include "pitchscreen.h"
+ #include "viewport.h"
+@@ -839,6 +840,24 @@ static int view_cue_item_callback(int action,
+ MENUITEM_FUNCTION(view_cue_item, 0, ID2P(LANG_BROWSE_CUESHEET),
+ view_cue, view_cue_item_callback, Icon_NOICON);
+
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++/* The playing audiobook's chapters, first in the context menu */
++static int chapters_item_callback(int action,
++ const struct menu_item_ex *this_item,
++ struct gui_synclist *this_list)
++{
++ (void)this_item;
++ (void)this_list;
++ if (action == ACTION_REQUEST_MENUITEM &&
++ chapters_update(audio_current_track()) <= 0)
++ return ACTION_EXIT_MENUITEM;
++ return action;
++}
++MENUITEM_FUNCTION(chapters_item, MENU_FUNC_CHECK_RETVAL,
++ (unsigned char *)"Chapters",
++ chapters_browse, chapters_item_callback, Icon_NOICON);
++#endif
++
+
+ static int browse_id3_wrapper(void)
+ {
+@@ -1250,6 +1269,9 @@ static int onplaymenu_callback(int action,
+ /* used when onplay() is called in the CONTEXT_WPS context */
+ MAKE_ONPLAYMENU( wps_onplay_menu, ID2P(LANG_ONPLAY_MENU_TITLE),
+ onplaymenu_callback, Icon_Audio,
++#ifdef HAVE_AUDIOBOOK_CHAPTERS
++ &chapters_item,
++#endif
+ &wps_playlist_menu, &cat_playlist_menu,
+ &sound_settings, &playback_settings,
+ #ifdef HAVE_TAGCACHE
+diff --git a/apps/settings_list.c b/apps/settings_list.c
+index 4f5e2f58..b029aab0 100644
+--- a/apps/settings_list.c
++++ b/apps/settings_list.c
+@@ -2521,7 +2521,9 @@ const struct settings_list settings[] = {
+ list_kinetic_load_from_cfg, list_kinetic_write_to_cfg,
+ list_kinetic_is_default, list_kinetic_set_default),
+ #endif
+- OFFON_SETTING(0, prevent_skip, LANG_PREVENT_SKIPPING, false, "prevent track skip", NULL),
++ /* audiobook: Left/Right never leave the book (the chapter keys do) */
++ OFFON_SETTING(0, prevent_skip, LANG_PREVENT_SKIPPING,
++ AUDIOBOOK_DEFAULT(true, false), "prevent track skip", NULL),
+ OFFON_SETTING(0, rewind_across_tracks, LANG_REWIND_ACROSS_TRACKS, false, "rewind across tracks", NULL),
+ #ifdef HAVE_PITCHCONTROL
+ OFFON_SETTING(0, pitch_mode_semitone, LANG_SEMITONE, false,
+diff --git a/firmware/export/config/yp3.h b/firmware/export/config/yp3.h
+index 07614b6b..d3e5742d 100644
+--- a/firmware/export/config/yp3.h
++++ b/firmware/export/config/yp3.h
+@@ -257,6 +257,11 @@
+ * (apps/playback.c, bookmark.c, filetree.c, settings_list.c). */
+ #define HAVE_AUDIOBOOK_RESUME
+ #define AUDIOBOOK_RESUME_SAVE_TICKS (60 * HZ)
++/* Chapters inside M4B/MP4 files (apps/chapters.c): Down+Left / Down+Right
++ * in Now Playing go to the previous / next chapter (or file, in a book
++ * without them), the title shows the chapter, the progress bar marks
++ * them, and the context menu lists them. */
++#define HAVE_AUDIOBOOK_CHAPTERS
+ /* No surround: its 31 KB delay buffer comes out of the playback buffer,
+ * which then stayed shrunk (stutter until a reset) */
+ #define HAVE_NO_SURROUND
+--
+2.56.1
+
diff --git a/patches/0003-yp3-next-chapter-title-in-the-next-track-tokens.patch b/patches/0003-yp3-next-chapter-title-in-the-next-track-tokens.patch
new file mode 100644
index 0000000..2613f36
--- /dev/null
+++ b/patches/0003-yp3-next-chapter-title-in-the-next-track-tokens.patch
@@ -0,0 +1,90 @@
+From 4a31d205984cb0ffa1d2381213b09d695adbd49d Mon Sep 17 00:00:00 2001
+From: YP3 Audiobook <noreply@example.invalid>
+Date: Wed, 25 Nov 2026 20:39:34 +0000
+Subject: [PATCH 3/3] yp3: next chapter title in the next-track tokens
+
+---
+ apps/chapters.c | 18 ++++++++++++++++++
+ apps/chapters.h | 2 ++
+ apps/gui/skin_engine/skin_tokens.c | 9 +++++++++
+ 3 files changed, 29 insertions(+)
+
+diff --git a/apps/chapters.c b/apps/chapters.c
+index 9b483653..d8306f5b 100644
+--- a/apps/chapters.c
++++ b/apps/chapters.c
+@@ -47,6 +47,8 @@ static char ch_path[MAX_PATH]; /* the file they are from */
+ static int ch_last_index = -1; /* chapters_changed() */
+ static int ch_title_index = -1; /* cur_title holds this one */
+ static char cur_title[TITLE_MAX + 1];
++static int ch_next_index = -1; /* next_title holds this one */
++static char next_title[TITLE_MAX + 1];
+
+ /* --- a small buffered reader: the atoms are walked with many tiny reads --- */
+
+@@ -418,6 +420,7 @@ int chapters_update(const struct mp3entry *id3)
+ ch_count = 0;
+ ch_last_index = -1;
+ ch_title_index = -1;
++ ch_next_index = -1;
+ switch (id3->codectype)
+ {
+ case AFMT_MP4_AAC:
+@@ -537,6 +540,21 @@ const char *chapters_current_title(const struct mp3entry *id3)
+ return cur_title;
+ }
+
++const char *chapters_next_title(const struct mp3entry *id3)
++{
++ if (chapters_update(id3) <= 0)
++ return NULL;
++ int i = chapters_index(id3->elapsed) + 1;
++ if (i >= ch_count)
++ return NULL;
++ if (i != ch_next_index)
++ {
++ chapters_title(i, next_title, sizeof(next_title));
++ ch_next_index = i;
++ }
++ return next_title;
++}
++
+ bool chapters_changed(const struct mp3entry *id3)
+ {
+ if (chapters_update(id3) <= 0)
+diff --git a/apps/chapters.h b/apps/chapters.h
+index 14e4d709..3bc633c6 100644
+--- a/apps/chapters.h
++++ b/apps/chapters.h
+@@ -21,6 +21,8 @@ unsigned long chapters_start(int i);
+ const char *chapters_title(int i, char *buf, size_t size);
+ /* The playing chapter's title, cached. */
+ const char *chapters_current_title(const struct mp3entry *id3);
++/* The next chapter's title, cached; NULL in the last chapter. */
++const char *chapters_next_title(const struct mp3entry *id3);
+ /* True once each time the playing chapter changes (skin refresh). */
+ bool chapters_changed(const struct mp3entry *id3);
+ /* Ticks at the chapter starts on a progress bar. */
+diff --git a/apps/gui/skin_engine/skin_tokens.c b/apps/gui/skin_engine/skin_tokens.c
+index 98d854ce..4c1fbffb 100644
+--- a/apps/gui/skin_engine/skin_tokens.c
++++ b/apps/gui/skin_engine/skin_tokens.c
+@@ -878,6 +878,15 @@ static const char *try_id3_token(struct wps_token *token, int offset,
+ if (out_text)
+ goto free_id3_outtext;
+ }
++ /* "next track" title: the next chapter's, until the last chapter */
++ else if ((token->next || offset == 1) && state->id3 &&
++ token->type == SKIN_TOKEN_METADATA_TRACK_TITLE &&
++ chapters_update(state->id3) > 0)
++ {
++ out_text = chapters_next_title(state->id3);
++ if (out_text)
++ goto free_id3_outtext;
++ }
+ #endif
+ if (id3 && id3 == state->id3 && id3->cuesheet)
+ {
+--
+2.56.1
+