Fix audiobook player

This commit is contained in:
acx10
2026-01-31 15:55:42 -07:00
parent 830bb5e9de
commit b6057588f6
4 changed files with 310 additions and 131 deletions
@@ -16,10 +16,15 @@ import java.nio.file.Path;
@Service
public class FileStreamingService {
private static final int BUFFER_SIZE = 8192;
private static final long MAX_CHUNK_SIZE = 2 * 1024 * 1024;
private static final int BUFFER_SIZE = 64 * 1024;
public void streamWithRangeSupport(
Path filePath,
String contentType,
HttpServletRequest request,
HttpServletResponse response
) throws IOException {
public void streamWithRangeSupport(Path filePath, String contentType, HttpServletRequest request, HttpServletResponse response) throws IOException {
if (!Files.exists(filePath)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
return;
@@ -29,29 +34,55 @@ public class FileStreamingService {
String rangeHeader = request.getHeader("Range");
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Cache-Control", "no-store");
response.setHeader("Content-Disposition", "inline");
response.setContentType(contentType);
response.setHeader("Cache-Control", "public, max-age=3600");
// -------------------------
// HEAD
// -------------------------
if ("HEAD".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader(
"Content-Range",
"bytes 0-" + (fileSize - 1) + "/" + fileSize
);
response.setContentLengthLong(fileSize);
return;
}
try {
// -------------------------
// NO RANGE
// -------------------------
if (rangeHeader == null) {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLengthLong(fileSize);
streamBytes(filePath, 0, fileSize - 1, response.getOutputStream());
} else {
RangeInfo range = parseRange(rangeHeader, fileSize);
if (range == null) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
response.setHeader("Content-Range", "bytes */" + fileSize);
return;
}
long contentLength = range.end - range.start + 1;
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setContentLengthLong(contentLength);
response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + fileSize);
streamBytes(filePath, range.start, range.end, response.getOutputStream());
return;
}
// -------------------------
// RANGE
// -------------------------
Range range = parseRange(rangeHeader, fileSize);
if (range == null) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
response.setHeader("Content-Range", "bytes */" + fileSize);
return;
}
long length = range.end - range.start + 1;
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader(
"Content-Range",
"bytes " + range.start + "-" + range.end + "/" + fileSize
);
response.setContentLengthLong(length);
streamBytes(filePath, range.start, range.end, response.getOutputStream());
} catch (IOException e) {
if (isClientDisconnect(e)) {
log.debug("Client disconnected during streaming: {}", e.getMessage());
@@ -61,90 +92,89 @@ public class FileStreamingService {
}
}
boolean isClientDisconnect(IOException e) {
if (e instanceof SocketTimeoutException) {
return true;
}
String message = e.getMessage();
if (message == null) {
String className = e.getClass().getSimpleName();
return className.contains("Timeout") || className.contains("Closed");
}
return message.contains("Connection reset") ||
message.contains("Broken pipe") ||
message.contains("connection was aborted") ||
message.contains("An established connection was aborted") ||
message.contains("SocketTimeout") ||
message.contains("timed out");
}
RangeInfo parseRange(String rangeHeader, long fileSize) {
if (!rangeHeader.startsWith("bytes=")) {
// ------------------------------------------------------------
// RANGE PARSER — RFC 7233 compliant
// ------------------------------------------------------------
Range parseRange(String header, long size) {
if (header == null || !header.startsWith("bytes=")) {
return null;
}
String rangeSpec = rangeHeader.substring(6).trim();
String[] ranges = rangeSpec.split(",");
if (ranges.length == 0) {
return null;
}
String value = header.substring(6).trim();
String[] parts = value.split(",", 2);
String range = parts[0].trim();
String range = ranges[0].trim();
String[] parts = range.split("-", -1);
if (parts.length != 2) {
return null;
}
int dash = range.indexOf('-');
if (dash < 0) return null;
try {
long start, end;
if (parts[0].isEmpty()) {
long suffix = Long.parseLong(parts[1]);
start = Math.max(0, fileSize - suffix);
end = fileSize - 1;
} else if (parts[1].isEmpty()) {
start = Long.parseLong(parts[0]);
end = Math.min(start + MAX_CHUNK_SIZE - 1, fileSize - 1);
} else {
start = Long.parseLong(parts[0]);
end = Long.parseLong(parts[1]);
// suffix-byte-range-spec: "-<length>"
if (dash == 0) {
long suffix = Long.parseLong(range.substring(1));
if (suffix <= 0) return null;
suffix = Math.min(suffix, size);
return new Range(size - suffix, size - 1);
}
if (start < 0 || start >= fileSize || end < start) {
return null;
long start = Long.parseLong(range.substring(0, dash));
// open-ended: "<start>-"
if (dash == range.length() - 1) {
if (start >= size) return null;
return new Range(start, size - 1);
}
end = Math.min(end, fileSize - 1);
// "<start>-<end>"
long end = Long.parseLong(range.substring(dash + 1));
if (start > end || start >= size) return null;
end = Math.min(end, size - 1);
return new Range(start, end);
return new RangeInfo(start, end);
} catch (NumberFormatException e) {
return null;
}
}
private void streamBytes(Path filePath, long start, long end, OutputStream outputStream) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile(filePath.toFile(), "r")) {
// ------------------------------------------------------------
// STREAM BYTES
// ------------------------------------------------------------
private void streamBytes(Path path, long start, long end, OutputStream out)
throws IOException {
try (RandomAccessFile raf = new RandomAccessFile(path.toFile(), "r")) {
raf.seek(start);
long bytesToRead = end - start + 1;
long remaining = end - start + 1;
byte[] buffer = new byte[BUFFER_SIZE];
long totalRead = 0;
while (totalRead < bytesToRead) {
int toRead = (int) Math.min(buffer.length, bytesToRead - totalRead);
int read = raf.read(buffer, 0, toRead);
if (read == -1) {
break;
}
outputStream.write(buffer, 0, read);
totalRead += read;
while (remaining > 0) {
int read = raf.read(buffer, 0, (int) Math.min(buffer.length, remaining));
if (read == -1) break;
out.write(buffer, 0, read);
remaining -= read;
}
outputStream.flush();
out.flush();
}
}
record RangeInfo(long start, long end) {}
}
// ------------------------------------------------------------
// DISCONNECT DETECTION
// ------------------------------------------------------------
boolean isClientDisconnect(IOException e) {
if (e instanceof SocketTimeoutException) return true;
String msg = e.getMessage();
if (msg == null) return false;
return msg.contains("Broken pipe")
|| msg.contains("Connection reset")
|| msg.contains("connection was aborted")
|| msg.contains("An established connection was aborted")
|| msg.contains("SocketTimeout")
|| msg.contains("timed out");
}
record Range(long start, long end) {}
}
@@ -182,7 +182,7 @@ class FileStreamingServiceTest {
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
verify(response).setHeader("Cache-Control", "public, max-age=3600");
verify(response).setHeader("Cache-Control", "no-store");
}
// ==================== parseRange tests ====================
@@ -8,13 +8,11 @@
<!-- Hidden audio element -->
<audio
#audioElement
[src]="audioSrc"
(loadedmetadata)="onAudioLoaded()"
(timeupdate)="onTimeUpdate()"
(progress)="onProgress()"
(ended)="onAudioEnded()"
(error)="onAudioError()"
preload="none"
></audio>
<!-- Header -->
@@ -55,7 +55,8 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
private pageTitle = inject(PageTitleService);
isLoading = true;
audioLoading = true;
audioLoading = false;
audioInitialized = false;
bookId!: number;
audiobookInfo!: AudiobookInfo;
@@ -145,29 +146,13 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
this.resetState();
this.isLoading = true;
const audiobookInfo$ = this.audiobookService.getAudiobookInfo(this.bookId);
const book$ = this.bookService.getBookByIdFromAPI(this.bookId, false);
forkJoin([audiobookInfo$, book$]).subscribe({
next: ([info, book]) => {
this.audiobookService.getAudiobookInfo(this.bookId).subscribe({
next: (info) => {
this.audiobookInfo = info;
this.pageTitle.setBookPageTitle(book);
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/cover/${this.bookId}?token=${encodeURIComponent(token || '')}`;
this.coverUrl = this.audiobookService.getEmbeddedCoverUrl(this.bookId);
if (book.audiobookProgress) {
this.savedPosition = book.audiobookProgress.positionMs
? book.audiobookProgress.positionMs / 1000
: 0;
}
if (info.folderBased && info.tracks && info.tracks.length > 0) {
const trackIndex = book.audiobookProgress?.trackIndex ?? 0;
this.currentTrackIndex = trackIndex;
this.loadTrack(trackIndex, false);
const track = info.tracks[trackIndex];
// Prepare the source URL but don't load it yet
this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, 0);
const track = info.tracks[0];
if (track?.durationMs) {
this.duration = track.durationMs / 1000;
}
@@ -178,14 +163,15 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
}
}
// Load cover URLs
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/cover/${this.bookId}?token=${encodeURIComponent(token || '')}`;
this.coverUrl = this.audiobookService.getEmbeddedCoverUrl(this.bookId);
this.isLoading = false;
this.audioLoading = false;
if (this.savedPosition > 0) {
this.currentTime = this.savedPosition;
}
this.loadBookmarks();
// Load book details in parallel (for progress, title, etc.) - non-blocking
this.loadBookDetails(info);
},
error: () => {
this.messageService.add({
@@ -194,22 +180,77 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
detail: 'Failed to load audiobook'
});
this.isLoading = false;
this.audioLoading = false;
}
});
}
private loadBookDetails(info: AudiobookInfo): void {
this.bookService.getBookByIdFromAPI(this.bookId, false)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: (book) => {
this.pageTitle.setBookPageTitle(book);
if (book.audiobookProgress) {
this.savedPosition = book.audiobookProgress.positionMs
? book.audiobookProgress.positionMs / 1000
: 0;
// If audio is already loaded, seek to saved position
const audio = this.audioElement?.nativeElement;
if (audio && audio.readyState >= 1 && this.savedPosition > 0) {
audio.currentTime = this.savedPosition;
this.currentTime = this.savedPosition;
}
// Handle track index for folder-based audiobooks
if (info.folderBased && info.tracks && info.tracks.length > 0) {
const trackIndex = book.audiobookProgress?.trackIndex ?? 0;
if (trackIndex !== this.currentTrackIndex) {
this.currentTrackIndex = trackIndex;
this.loadTrack(trackIndex, false);
const track = info.tracks[trackIndex];
if (track?.durationMs) {
this.duration = track.durationMs / 1000;
}
}
}
}
if (this.savedPosition > 0) {
this.currentTime = this.savedPosition;
}
},
error: () => {
// Non-critical - audiobook can still play without book details
}
});
this.loadBookmarks();
}
private loadTrack(index: number, showLoading = true): void {
if (!this.audiobookInfo.tracks || index < 0 || index >= this.audiobookInfo.tracks.length) {
return;
}
this.currentTrackIndex = index;
this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, index);
this.audioLoading = showLoading;
this.buffered = 0;
const track = this.audiobookInfo.tracks[index];
if (track?.durationMs) {
this.duration = track.durationMs / 1000;
}
// Only set the audio source if already initialized
if (this.audioInitialized) {
this.audioLoading = showLoading;
const audio = this.audioElement?.nativeElement;
if (audio) {
audio.src = this.audioSrc;
audio.load();
}
}
}
private resetState(): void {
@@ -222,7 +263,8 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
this.savedPosition = 0;
this.currentTrackIndex = 0;
this.audioSrc = '';
this.audioLoading = true;
this.audioLoading = false;
this.audioInitialized = false;
this.showTrackList = false;
this.coverUrl = undefined;
@@ -380,6 +422,36 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
const audio = this.audioElement?.nativeElement;
if (!audio) return;
// Initialize audio on first play
if (!this.audioInitialized) {
this.audioLoading = true;
this.audioInitialized = true;
audio.src = this.audioSrc;
audio.load();
// Wait for enough data to play
const playWhenReady = () => {
audio.removeEventListener('canplay', playWhenReady);
audio.play();
this.isPlaying = true;
this.startProgressSaveInterval();
this.updateMediaSessionPlaybackState();
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.resumeSession(Math.round(this.currentTime * 1000));
} else {
this.audiobookSessionService.startSession(
this.bookId,
Math.round(this.currentTime * 1000),
this.playbackRate,
this.audiobookInfo?.bookFileId,
this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined
);
}
};
audio.addEventListener('canplay', playWhenReady);
return;
}
if (this.isPlaying) {
audio.pause();
this.stopProgressSaveInterval();
@@ -499,10 +571,25 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
}
selectTrack(track: AudiobookTrack): void {
this.loadTrack(track.index);
this.currentTrackIndex = track.index;
this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, track.index);
this.currentTime = 0;
this.savedPosition = 0;
this.buffered = 0;
const trackInfo = this.audiobookInfo.tracks?.[track.index];
if (trackInfo?.durationMs) {
this.duration = trackInfo.durationMs / 1000;
}
this.showTrackList = false;
const audio = this.audioElement?.nativeElement;
if (audio) {
this.audioLoading = true;
this.audioInitialized = true;
audio.src = this.audioSrc;
audio.load();
}
setTimeout(() => {
this.audioElement?.nativeElement?.play();
this.isPlaying = true;
@@ -522,15 +609,23 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
selectChapter(chapter: AudiobookChapter): void {
const audio = this.audioElement?.nativeElement;
if (audio) {
audio.currentTime = chapter.startTimeMs / 1000;
this.currentTime = chapter.startTimeMs / 1000;
this.showTrackList = false;
this.updateMediaSessionMetadata();
if (!this.isPlaying) {
if (!audio) return;
// Initialize audio if not yet done
if (!this.audioInitialized) {
this.audioLoading = true;
this.audioInitialized = true;
audio.src = this.audioSrc;
audio.load();
const seekAndPlay = () => {
audio.removeEventListener('canplay', seekAndPlay);
audio.currentTime = chapter.startTimeMs / 1000;
this.currentTime = chapter.startTimeMs / 1000;
audio.play();
this.isPlaying = true;
this.startProgressSaveInterval();
this.updateMediaSessionMetadata();
this.updateMediaSessionPlaybackState();
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.resumeSession(chapter.startTimeMs);
@@ -540,6 +635,28 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
this.audiobookInfo?.bookFileId
);
}
};
audio.addEventListener('canplay', seekAndPlay);
this.showTrackList = false;
return;
}
audio.currentTime = chapter.startTimeMs / 1000;
this.currentTime = chapter.startTimeMs / 1000;
this.showTrackList = false;
this.updateMediaSessionMetadata();
if (!this.isPlaying) {
audio.play();
this.isPlaying = true;
this.startProgressSaveInterval();
this.updateMediaSessionPlaybackState();
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.resumeSession(chapter.startTimeMs);
} else {
this.audiobookSessionService.startSession(
this.bookId, chapter.startTimeMs, this.playbackRate,
this.audiobookInfo?.bookFileId
);
}
}
}
@@ -876,23 +993,57 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
}
goToBookmark(bookmark: BookMark): void {
const audio = this.audioElement?.nativeElement;
if (!audio) return;
const targetPosition = (bookmark.positionMs || 0) / 1000;
// Initialize audio if not yet done
if (!this.audioInitialized) {
if (this.audiobookInfo.folderBased && bookmark.trackIndex !== undefined && bookmark.trackIndex !== null) {
this.currentTrackIndex = bookmark.trackIndex;
this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, bookmark.trackIndex);
}
this.audioLoading = true;
this.audioInitialized = true;
audio.src = this.audioSrc;
audio.load();
const seekAndPlay = () => {
audio.removeEventListener('canplay', seekAndPlay);
audio.currentTime = targetPosition;
this.currentTime = targetPosition;
audio.play();
this.isPlaying = true;
this.startProgressSaveInterval();
const positionMs = bookmark.positionMs || 0;
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.resumeSession(positionMs);
} else {
this.audiobookSessionService.startSession(
this.bookId, positionMs, this.playbackRate,
this.audiobookInfo?.bookFileId,
this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined
);
}
};
audio.addEventListener('canplay', seekAndPlay);
this.showBookmarkList = false;
return;
}
if (this.audiobookInfo.folderBased && bookmark.trackIndex !== undefined && bookmark.trackIndex !== null) {
if (bookmark.trackIndex !== this.currentTrackIndex) {
this.loadTrack(bookmark.trackIndex);
this.savedPosition = (bookmark.positionMs || 0) / 1000;
this.savedPosition = targetPosition;
} else {
const audio = this.audioElement?.nativeElement;
if (audio && bookmark.positionMs) {
audio.currentTime = bookmark.positionMs / 1000;
this.currentTime = bookmark.positionMs / 1000;
}
audio.currentTime = targetPosition;
this.currentTime = targetPosition;
}
} else {
const audio = this.audioElement?.nativeElement;
if (audio && bookmark.positionMs) {
audio.currentTime = bookmark.positionMs / 1000;
this.currentTime = bookmark.positionMs / 1000;
}
audio.currentTime = targetPosition;
this.currentTime = targetPosition;
}
this.showBookmarkList = false;