Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow aborting loading audio #4017

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

ibash
Copy link
Contributor

@ibash ibash commented Feb 7, 2025

Short description

This change makes loadAudio optionally take an AbortSignal which can be used to abort loading.
We use this to prevent a race condition where the wrong audio might be loading into wavesurfer.

Implementation details

Passing through an AbortSignal. After any async call it needs to be checked with throwIfAborted. Not my favorite, but is effective.

How to test it

Easiest is to add some delays in loadAudio and then try aborting.

Add manual delays throughout loadAudio with:

await new Promise((r) => setTimeout(r, 5000))

Then call loadAudio passing in a signal and aborting it.

Screenshots

Checklist

  • This PR is covered by e2e tests
  • It introduces no breaking API changes

Summary by CodeRabbit

  • New Features
    • Enhanced the audio playback experience by enabling the ability to cancel ongoing audio loading operations.
    • Improved error handling ensures that if an audio load is interrupted, the system responds more promptly and smoothly.

This change makes loadAudio optionally take an AbortSignal which can be
used to abort loading.

We use this to prevent a race condition where the wrong audio might be
loading into wavesurfer.
Copy link

coderabbitai bot commented Feb 7, 2025

Walkthrough

This pull request enhances the WaveSurfer class by introducing an optional AbortSignal parameter into the asynchronous audio loading methods. The loadAudio method now includes multiple checkpoints for aborting operations using signal?.throwIfAborted(), while the load and loadBlob methods are updated to pass the signal parameter to loadAudio. The changes improve error handling and allow audio loading processes to be canceled when needed.

Changes

File Change Summary
src/wavesurfer.ts Modified method signatures of loadAudio, load, and loadBlob to include an optional AbortSignal parameter. loadAudio now checks for abortion at key steps using signal?.throwIfAborted().

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant WaveSurfer
    participant AbortSignal

    Caller->>WaveSurfer: load(url, ..., signal)
    WaveSurfer->>WaveSurfer: Begin fetching audio blob
    alt Check after fetch
        AbortSignal-->>WaveSurfer: throwIfAborted()
        WaveSurfer->>Caller: Abort error thrown
    else
        WaveSurfer->>WaveSurfer: Set duration & decode audio data
        alt Check after decoding
            AbortSignal-->>WaveSurfer: throwIfAborted()
            WaveSurfer->>Caller: Abort error thrown
        else
            WaveSurfer->>Caller: Return loaded audio
        end
    end
Loading

Poem

I'm a bunny hopping through the code maze,
With abort signals lighting up my busy ways.
Audio loads, yet can be canceled on the go,
In my field of code, smooth operations flow.
Hoppy bytes abound in each new line I sow!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/wavesurfer.ts

Oops! Something went wrong! :(

ESLint: 9.17.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/wavesurfer.ts (1)

431-434: Consider using the provided signal for fetch operations.

The code creates a new AbortController when none is provided, but it could potentially reuse the provided signal for fetch operations to ensure consistent abort behavior.

Consider this implementation:

 if (window.AbortController && !fetchParams.signal) {
-  this.abortController = new AbortController()
-  fetchParams.signal = this.abortController?.signal
+  this.abortController = signal ? undefined : new AbortController()
+  fetchParams.signal = signal || this.abortController?.signal
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 605fe78 and e7ffb8a.

📒 Files selected for processing (1)
  • src/wavesurfer.ts (5 hunks)
🔇 Additional comments (3)
src/wavesurfer.ts (3)

421-421: LGTM! The signal parameter is properly added to method signatures.

The optional AbortSignal parameter is consistently added to all three methods: loadAudio, load, and loadBlob.

Also applies to: 487-488, 497-498


489-491: LGTM! Error handling is properly maintained.

The signal parameter is correctly forwarded to loadAudio while maintaining the existing error handling pattern.

Also applies to: 499-501


437-437: Verify abort signal checks after async operations.

The abort signal checks are strategically placed after each async operation:

  1. After fetching the blob
  2. After getting the audio duration
  3. Before and after decoding the audio data

This ensures that the loading process can be aborted at any point during these potentially time-consuming operations.

Let's verify the abort signal usage with a test script:

Also applies to: 459-459, 474-476

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check for consistent abort signal usage patterns in the codebase

# Look for other async operations that might need abort signal checks
rg -A 5 "await.*\(" --type ts

# Look for existing abort signal usage patterns
rg "signal\?\.throwIfAborted\(\)" --type ts

Length of output: 3886


Abort Signal Usage Verification in Audio Loading Operations

Based on the grep output:

• The abort signal check ("signal?.throwIfAborted()") is confirmed immediately after fetching the blob.
• It is also used after the blob’s arrayBuffer conversion and after decoding the audio data.
• While the review comment noted a signal check after retrieving the audio duration, our current search output does not conclusively show a check immediately following that duration promise. However, all other abort checks for the async operations in question are correctly placed.

Overall, the abort signal checks are consistently applied after the major async operations in wavesurfer.ts. You may want to confirm that any async operation that could be long-running—such as fetching or decoding—is safeguarded by an abort check if intended. In this case, the placement matches the intended strategy described in the review comment.

@katspaugh
Copy link
Owner

You can already pass an abort signal in the fetchParams option. See https://wavesurfer.xyz/docs/types/wavesurfer.WaveSurferOptions

Or is it not sufficient for your use case?

@ibash
Copy link
Contributor Author

ibash commented Feb 8, 2025

We're using a singleton wavesurfer instance and loading different audio into it. When the second call to loadAudio happens we need to make sure no side effects from the first call get propagated out. Calling throwIfAborted after each async hop is the most fool-proof way of doing that. Though it's definitely possible that we could do a work around by unsubscribing / resubscribing any event listeners.

@katspaugh
Copy link
Owner

Ah, so you aren't even interested in aborting the actual fetch or decoding process, only in interrupting the whole thing in between those async processes as if they threw?

@@ -434,6 +434,8 @@ class WaveSurfer extends Player<WaveSurferEvents> {
}
const onProgress = (percentage: number) => this.emit('loading', percentage)
blob = await Fetcher.fetchBlob(url, onProgress, fetchParams)
Copy link
Owner

@katspaugh katspaugh Feb 10, 2025

Choose a reason for hiding this comment

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

Since there's a bit of an overlap with the existing fetchParams.signal, I'm thinking maybe we can use the new one for this as well?

Something like:

Suggested change
blob = await Fetcher.fetchBlob(url, onProgress, fetchParams)
blob = await Fetcher.fetchBlob(url, onProgress, {
...fetchParams,
signal: signal ?? fetchParams?.signal
})

Then if you abort it, it will also abort the fetching.

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.

2 participants