Skip to content

[codex] Add first-party audio playback API - #97

Closed
Quick104 wants to merge 1 commit into
mainfrom
codex/feat-first-party-audio-api
Closed

Quick104 wants to merge 1 commit into
mainfrom
codex/feat-first-party-audio-api

Conversation

@Quick104

@Quick104 Quick104 commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add first-party Silo audio playback endpoints for audiobook sessions, progress sync, session close, per-track streaming, and bookmarks.
  • Return cumulative audiobook timelines with ordered tracks, global chapters, resume position, artwork metadata, and direct/AAC playback modes.
  • Document the new audio API contract for Apple and future client parity.

Validation

  • go test ./internal/api/handlers ./internal/api
  • git diff --check

Notes

go test ./internal/playback currently fails on origin/main in the NVENC fake-FFmpeg tests (signal: killed in TestFFmpegSupportsNVENCCachesByFFmpegPath and TestFFmpegSupportsNVENCSmokeProbeUsesSafeFrameDimensions). The detector/test files match origin/main, so that failure is separate from this PR.

Summary by CodeRabbit

  • New Features

    • Added audiobook playback functionality with session management (start, sync, close).
    • Added resume position tracking to remember where users left off in audiobooks.
    • Added bookmark management enabling users to mark, save, and organize key positions within audiobooks.
    • Added audio track streaming for seamless playback delivery.
  • Documentation

    • Added comprehensive Audio API documentation specifying playback session contracts, authentication requirements, endpoint specifications, and bookmark operations.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2bfa5100-6f75-459f-ba45-bb1573c7d3fb

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/feat-first-party-audio-api

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/audio-api.md`:
- Around line 10-12: Update the docs to state that bookmark reads also require
the active profile headers: mention that the GET
/api/v1/audio/items/{content_id}/bookmarks endpoint enforces
apimw.RequireProfile (same as the write endpoints), so clients must include the
active profile headers used by first-party clients when performing bookmark
reads as well as writes.

In `@internal/api/handlers/audio_test.go`:
- Around line 149-152: After decoding into audioPlaybackResponse 'start' (from
json.Unmarshal of startRec.Body.Bytes()), add assertions that the start playback
actually succeeded before testing expiry: assert the HTTP status of startRec is
success (e.g., 200), assert start.SessionID (or the field name in
audioPlaybackResponse for session id) is non-empty, and fail the test with
t.Fatalf or t.Fatalf-like message if those checks fail so later 404 assertions
can't mask a failed start; update the test around variables startRec and start
to include these explicit checks.

In `@internal/api/handlers/audio.go`:
- Around line 305-307: The parsed seek value from strconv.ParseFloat can be
"Inf" and must be rejected before passing to remux; update the block that sets
seek (the parsed variable in the handler that assigns to seek and later calls
remux) to only accept finite, non-negative values by checking that the parsed
float is not infinite or NaN (use math.IsInf(parsed, 0) and math.IsNaN(parsed)
or equivalent) in addition to parsed >= 0, and only then assign to seek.
- Around line 273-283: The handler currently ignores JSON decode errors and
persistence errors then always deletes the session; change it to validate and
handle failures: check the error returned by
json.NewDecoder(r.Body).Decode(&req) and return a 400 if decoding fails; when
isFiniteNonNegative(req.Position) is true compute duration (falling back to
session.TotalSeconds), call persistProgress and check its error—if
persistProgress returns an error respond with a 500 (and do NOT call
deleteSession) so the caller sees the failure; only call
deleteSession(session.ID) after successful persist or when there was no position
to persist. Reference audioProgressRequest, isFiniteNonNegative,
persistProgress, deleteSession, and session.TotalSeconds in your edits.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e6d9e3e7-1df7-4717-8d6a-be7458aee149

📥 Commits

Reviewing files that changed from the base of the PR and between 7c268f8 and e3a5f09.

📒 Files selected for processing (4)
  • docs/audio-api.md
  • internal/api/handlers/audio.go
  • internal/api/handlers/audio_test.go
  • internal/api/router.go

Comment thread docs/audio-api.md
Comment on lines +10 to +12
All endpoints require normal Silo user authentication. Playback start, sync,
close, and bookmark writes also require the active profile headers used by the
first-party clients.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Document the profile requirement for bookmark reads, not only writes.

The current router enforces apimw.RequireProfile for GET /api/v1/audio/items/{content_id}/bookmarks too (see internal/api/router.go, Lines 1784-1791). This section only mentions bookmark writes, which can mislead client implementers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/audio-api.md` around lines 10 - 12, Update the docs to state that
bookmark reads also require the active profile headers: mention that the GET
/api/v1/audio/items/{content_id}/bookmarks endpoint enforces
apimw.RequireProfile (same as the write endpoints), so clients must include the
active profile headers used by first-party clients when performing bookmark
reads as well as writes.

Comment on lines +149 to +152
var start audioPlaybackResponse
if err := json.Unmarshal(startRec.Body.Bytes(), &start); err != nil {
t.Fatalf("decode start: %v", err)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Assert successful playback start before asserting expiry behavior.

Line 149 decodes the response, but the test never checks that start playback succeeded first. If start fails (or session_id is empty), the later 404 can still pass and mask the real failure mode.

Suggested patch
 	startRec := httptest.NewRecorder()
 	handler.HandleStartPlayback(startRec, startReq)
+	if startRec.Code != http.StatusOK {
+		t.Fatalf("start status = %d body=%s", startRec.Code, startRec.Body.String())
+	}
 	var start audioPlaybackResponse
 	if err := json.Unmarshal(startRec.Body.Bytes(), &start); err != nil {
 		t.Fatalf("decode start: %v", err)
 	}
+	if start.SessionID == "" {
+		t.Fatalf("missing session_id in start response")
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var start audioPlaybackResponse
if err := json.Unmarshal(startRec.Body.Bytes(), &start); err != nil {
t.Fatalf("decode start: %v", err)
}
startRec := httptest.NewRecorder()
handler.HandleStartPlayback(startRec, startReq)
if startRec.Code != http.StatusOK {
t.Fatalf("start status = %d body=%s", startRec.Code, startRec.Body.String())
}
var start audioPlaybackResponse
if err := json.Unmarshal(startRec.Body.Bytes(), &start); err != nil {
t.Fatalf("decode start: %v", err)
}
if start.SessionID == "" {
t.Fatalf("missing session_id in start response")
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/audio_test.go` around lines 149 - 152, After decoding
into audioPlaybackResponse 'start' (from json.Unmarshal of
startRec.Body.Bytes()), add assertions that the start playback actually
succeeded before testing expiry: assert the HTTP status of startRec is success
(e.g., 200), assert start.SessionID (or the field name in audioPlaybackResponse
for session id) is non-empty, and fail the test with t.Fatalf or t.Fatalf-like
message if those checks fail so later 404 assertions can't mask a failed start;
update the test around variables startRec and start to include these explicit
checks.

Comment on lines +273 to +283
var req audioProgressRequest
_ = json.NewDecoder(r.Body).Decode(&req)
if isFiniteNonNegative(req.Position) {
duration := req.Duration
if duration <= 0 {
duration = session.TotalSeconds
}
position := clampFloat(req.Position, 0, duration)
_ = h.persistProgress(r.Context(), session.UserID, session.ProfileID, session.ContentID, position, duration)
}
h.deleteSession(session.ID)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don’t silently drop final progress sync failures on close.

Line 274 ignores bad request bodies, and Line 281 ignores persistence errors; then Line 283 deletes the session and returns 204. That can lose final progress with no retry signal.

Suggested fix
 import (
 	"context"
 	"encoding/json"
 	"errors"
 	"fmt"
+	"io"
 	"math"
 	"net/http"
@@
 func (h *AudioHandler) HandleClosePlayback(w http.ResponseWriter, r *http.Request) {
 	session, ok := h.sessionForRequest(w, r)
 	if !ok {
 		return
 	}
 	var req audioProgressRequest
-	_ = json.NewDecoder(r.Body).Decode(&req)
+	if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
+		writeError(w, http.StatusBadRequest, "bad_request", "Invalid request body")
+		return
+	}
 	if isFiniteNonNegative(req.Position) {
 		duration := req.Duration
 		if duration <= 0 {
 			duration = session.TotalSeconds
 		}
 		position := clampFloat(req.Position, 0, duration)
-		_ = h.persistProgress(r.Context(), session.UserID, session.ProfileID, session.ContentID, position, duration)
+		if err := h.persistProgress(r.Context(), session.UserID, session.ProfileID, session.ContentID, position, duration); err != nil {
+			writeError(w, http.StatusInternalServerError, "internal_error", "Failed to sync audio progress")
+			return
+		}
 	}
 	h.deleteSession(session.ID)
 	w.WriteHeader(http.StatusNoContent)
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/audio.go` around lines 273 - 283, The handler currently
ignores JSON decode errors and persistence errors then always deletes the
session; change it to validate and handle failures: check the error returned by
json.NewDecoder(r.Body).Decode(&req) and return a 400 if decoding fails; when
isFiniteNonNegative(req.Position) is true compute duration (falling back to
session.TotalSeconds), call persistProgress and check its error—if
persistProgress returns an error respond with a 500 (and do NOT call
deleteSession) so the caller sees the failure; only call
deleteSession(session.ID) after successful persist or when there was no position
to persist. Reference audioProgressRequest, isFiniteNonNegative,
persistProgress, deleteSession, and session.TotalSeconds in your edits.

Comment on lines +305 to +307
if raw := r.URL.Query().Get("seek"); raw != "" {
if parsed, err := strconv.ParseFloat(raw, 64); err == nil && parsed >= 0 {
seek = parsed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reject non-finite seek values.

strconv.ParseFloat accepts "Inf", so Line 306 can pass a non-finite seek into remux. Gate it with the same finite/non-negative check you already use elsewhere.

Suggested fix
-		if raw := r.URL.Query().Get("seek"); raw != "" {
-			if parsed, err := strconv.ParseFloat(raw, 64); err == nil && parsed >= 0 {
+		if raw := r.URL.Query().Get("seek"); raw != "" {
+			if parsed, err := strconv.ParseFloat(raw, 64); err == nil && isFiniteNonNegative(parsed) {
 				seek = parsed
 			}
 		}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/audio.go` around lines 305 - 307, The parsed seek value
from strconv.ParseFloat can be "Inf" and must be rejected before passing to
remux; update the block that sets seek (the parsed variable in the handler that
assigns to seek and later calls remux) to only accept finite, non-negative
values by checking that the parsed float is not infinite or NaN (use
math.IsInf(parsed, 0) and math.IsNaN(parsed) or equivalent) in addition to
parsed >= 0, and only then assign to seek.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant