aboutsummaryrefslogtreecommitdiff
path: root/patches/0002-yp3-M4B-chapters-Down-Left-Right-chapter-title-marke.patch
diff options
context:
space:
mode:
Diffstat (limited to 'patches/0002-yp3-M4B-chapters-Down-Left-Right-chapter-title-marke.patch')
-rw-r--r--patches/0002-yp3-M4B-chapters-Down-Left-Right-chapter-title-marke.patch968
1 files changed, 968 insertions, 0 deletions
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
+