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 @Service
public class FileStreamingService { public class FileStreamingService {
private static final int BUFFER_SIZE = 8192; private static final int BUFFER_SIZE = 64 * 1024;
private static final long MAX_CHUNK_SIZE = 2 * 1024 * 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)) { if (!Files.exists(filePath)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found"); response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
return; return;
@@ -29,29 +34,55 @@ public class FileStreamingService {
String rangeHeader = request.getHeader("Range"); String rangeHeader = request.getHeader("Range");
response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Cache-Control", "no-store");
response.setHeader("Content-Disposition", "inline");
response.setContentType(contentType); 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 { try {
// -------------------------
// NO RANGE
// -------------------------
if (rangeHeader == null) { if (rangeHeader == null) {
response.setStatus(HttpServletResponse.SC_OK); response.setStatus(HttpServletResponse.SC_OK);
response.setContentLengthLong(fileSize); response.setContentLengthLong(fileSize);
streamBytes(filePath, 0, fileSize - 1, response.getOutputStream()); streamBytes(filePath, 0, fileSize - 1, response.getOutputStream());
} else { return;
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());
} }
// -------------------------
// 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) { } catch (IOException e) {
if (isClientDisconnect(e)) { if (isClientDisconnect(e)) {
log.debug("Client disconnected during streaming: {}", e.getMessage()); log.debug("Client disconnected during streaming: {}", e.getMessage());
@@ -61,90 +92,89 @@ public class FileStreamingService {
} }
} }
boolean isClientDisconnect(IOException e) { // ------------------------------------------------------------
if (e instanceof SocketTimeoutException) { // RANGE PARSER — RFC 7233 compliant
return true; // ------------------------------------------------------------
} Range parseRange(String header, long size) {
if (header == null || !header.startsWith("bytes=")) {
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=")) {
return null; return null;
} }
String rangeSpec = rangeHeader.substring(6).trim(); String value = header.substring(6).trim();
String[] ranges = rangeSpec.split(","); String[] parts = value.split(",", 2);
if (ranges.length == 0) { String range = parts[0].trim();
return null;
}
String range = ranges[0].trim(); int dash = range.indexOf('-');
String[] parts = range.split("-", -1); if (dash < 0) return null;
if (parts.length != 2) {
return null;
}
try { try {
long start, end; // suffix-byte-range-spec: "-<length>"
if (dash == 0) {
if (parts[0].isEmpty()) { long suffix = Long.parseLong(range.substring(1));
long suffix = Long.parseLong(parts[1]); if (suffix <= 0) return null;
start = Math.max(0, fileSize - suffix); suffix = Math.min(suffix, size);
end = fileSize - 1; return new Range(size - suffix, size - 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]);
} }
if (start < 0 || start >= fileSize || end < start) { long start = Long.parseLong(range.substring(0, dash));
return null;
// 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) { } catch (NumberFormatException e) {
return null; 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); raf.seek(start);
long bytesToRead = end - start + 1; long remaining = end - start + 1;
byte[] buffer = new byte[BUFFER_SIZE]; byte[] buffer = new byte[BUFFER_SIZE];
long totalRead = 0;
while (totalRead < bytesToRead) { while (remaining > 0) {
int toRead = (int) Math.min(buffer.length, bytesToRead - totalRead); int read = raf.read(buffer, 0, (int) Math.min(buffer.length, remaining));
int read = raf.read(buffer, 0, toRead); if (read == -1) break;
if (read == -1) { out.write(buffer, 0, read);
break; remaining -= read;
}
outputStream.write(buffer, 0, read);
totalRead += 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); 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 ==================== // ==================== parseRange tests ====================
@@ -8,13 +8,11 @@
<!-- Hidden audio element --> <!-- Hidden audio element -->
<audio <audio
#audioElement #audioElement
[src]="audioSrc"
(loadedmetadata)="onAudioLoaded()" (loadedmetadata)="onAudioLoaded()"
(timeupdate)="onTimeUpdate()" (timeupdate)="onTimeUpdate()"
(progress)="onProgress()" (progress)="onProgress()"
(ended)="onAudioEnded()" (ended)="onAudioEnded()"
(error)="onAudioError()" (error)="onAudioError()"
preload="none"
></audio> ></audio>
<!-- Header --> <!-- Header -->
@@ -55,7 +55,8 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
private pageTitle = inject(PageTitleService); private pageTitle = inject(PageTitleService);
isLoading = true; isLoading = true;
audioLoading = true; audioLoading = false;
audioInitialized = false;
bookId!: number; bookId!: number;
audiobookInfo!: AudiobookInfo; audiobookInfo!: AudiobookInfo;
@@ -145,29 +146,13 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
this.resetState(); this.resetState();
this.isLoading = true; this.isLoading = true;
const audiobookInfo$ = this.audiobookService.getAudiobookInfo(this.bookId); this.audiobookService.getAudiobookInfo(this.bookId).subscribe({
const book$ = this.bookService.getBookByIdFromAPI(this.bookId, false); next: (info) => {
forkJoin([audiobookInfo$, book$]).subscribe({
next: ([info, book]) => {
this.audiobookInfo = 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) { if (info.folderBased && info.tracks && info.tracks.length > 0) {
const trackIndex = book.audiobookProgress?.trackIndex ?? 0; // Prepare the source URL but don't load it yet
this.currentTrackIndex = trackIndex; this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, 0);
this.loadTrack(trackIndex, false); const track = info.tracks[0];
const track = info.tracks[trackIndex];
if (track?.durationMs) { if (track?.durationMs) {
this.duration = track.durationMs / 1000; 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.isLoading = false;
this.audioLoading = false;
if (this.savedPosition > 0) { // Load book details in parallel (for progress, title, etc.) - non-blocking
this.currentTime = this.savedPosition; this.loadBookDetails(info);
}
this.loadBookmarks();
}, },
error: () => { error: () => {
this.messageService.add({ this.messageService.add({
@@ -194,22 +180,77 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
detail: 'Failed to load audiobook' detail: 'Failed to load audiobook'
}); });
this.isLoading = false; 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 { private loadTrack(index: number, showLoading = true): void {
if (!this.audiobookInfo.tracks || index < 0 || index >= this.audiobookInfo.tracks.length) { if (!this.audiobookInfo.tracks || index < 0 || index >= this.audiobookInfo.tracks.length) {
return; return;
} }
this.currentTrackIndex = index; this.currentTrackIndex = index;
this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, index); this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, index);
this.audioLoading = showLoading;
this.buffered = 0; this.buffered = 0;
const track = this.audiobookInfo.tracks[index]; const track = this.audiobookInfo.tracks[index];
if (track?.durationMs) { if (track?.durationMs) {
this.duration = track.durationMs / 1000; 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 { private resetState(): void {
@@ -222,7 +263,8 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
this.savedPosition = 0; this.savedPosition = 0;
this.currentTrackIndex = 0; this.currentTrackIndex = 0;
this.audioSrc = ''; this.audioSrc = '';
this.audioLoading = true; this.audioLoading = false;
this.audioInitialized = false;
this.showTrackList = false; this.showTrackList = false;
this.coverUrl = undefined; this.coverUrl = undefined;
@@ -380,6 +422,36 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
const audio = this.audioElement?.nativeElement; const audio = this.audioElement?.nativeElement;
if (!audio) return; 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) { if (this.isPlaying) {
audio.pause(); audio.pause();
this.stopProgressSaveInterval(); this.stopProgressSaveInterval();
@@ -499,10 +571,25 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
} }
selectTrack(track: AudiobookTrack): void { 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.currentTime = 0;
this.savedPosition = 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; this.showTrackList = false;
const audio = this.audioElement?.nativeElement;
if (audio) {
this.audioLoading = true;
this.audioInitialized = true;
audio.src = this.audioSrc;
audio.load();
}
setTimeout(() => { setTimeout(() => {
this.audioElement?.nativeElement?.play(); this.audioElement?.nativeElement?.play();
this.isPlaying = true; this.isPlaying = true;
@@ -522,15 +609,23 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
selectChapter(chapter: AudiobookChapter): void { selectChapter(chapter: AudiobookChapter): void {
const audio = this.audioElement?.nativeElement; const audio = this.audioElement?.nativeElement;
if (audio) { if (!audio) return;
audio.currentTime = chapter.startTimeMs / 1000;
this.currentTime = chapter.startTimeMs / 1000; // Initialize audio if not yet done
this.showTrackList = false; if (!this.audioInitialized) {
this.updateMediaSessionMetadata(); this.audioLoading = true;
if (!this.isPlaying) { 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(); audio.play();
this.isPlaying = true; this.isPlaying = true;
this.startProgressSaveInterval(); this.startProgressSaveInterval();
this.updateMediaSessionMetadata();
this.updateMediaSessionPlaybackState(); this.updateMediaSessionPlaybackState();
if (this.audiobookSessionService.isSessionActive()) { if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.resumeSession(chapter.startTimeMs); this.audiobookSessionService.resumeSession(chapter.startTimeMs);
@@ -540,6 +635,28 @@ export class AudiobookReaderComponent implements OnInit, OnDestroy {
this.audiobookInfo?.bookFileId 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 { 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 (this.audiobookInfo.folderBased && bookmark.trackIndex !== undefined && bookmark.trackIndex !== null) {
if (bookmark.trackIndex !== this.currentTrackIndex) { if (bookmark.trackIndex !== this.currentTrackIndex) {
this.loadTrack(bookmark.trackIndex); this.loadTrack(bookmark.trackIndex);
this.savedPosition = (bookmark.positionMs || 0) / 1000; this.savedPosition = targetPosition;
} else { } else {
const audio = this.audioElement?.nativeElement; audio.currentTime = targetPosition;
if (audio && bookmark.positionMs) { this.currentTime = targetPosition;
audio.currentTime = bookmark.positionMs / 1000;
this.currentTime = bookmark.positionMs / 1000;
}
} }
} else { } else {
const audio = this.audioElement?.nativeElement; audio.currentTime = targetPosition;
if (audio && bookmark.positionMs) { this.currentTime = targetPosition;
audio.currentTime = bookmark.positionMs / 1000;
this.currentTime = bookmark.positionMs / 1000;
}
} }
this.showBookmarkList = false; this.showBookmarkList = false;