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

feat(spectrogram): add logarithmic, bark and erb scales #3976

Merged
merged 1 commit into from
Dec 28, 2024

Conversation

Dabolus
Copy link
Contributor

@Dabolus Dabolus commented Dec 27, 2024

Short description

This PR is my attempt to add support for more Y scales when rendering spectrograms. To reach feature parity with Audacity, only the Period scale is missing, but I couldn't find much information on it, so I left it out for now.

Resolves #1648

Implementation details

I made the function used to create the Mel filter bank generic to make it usable also for different scales and I added all the other common spectrogram scales. The output is not perfect, but I think it's not too bad either. Any suggestion to improve it is more than welcome. I also added some typings to make it easier to work with the plugin (types only, no breaking changes)

How to test it

Run yarn start, go to the "Spectrogram" example and change the scale property from mel to logarithmic, bark, or erb.

Screenshots

Logarithmic

image

Bark

image

ERB

image

Checklist

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

Summary by CodeRabbit

  • New Features

    • Expanded frequency scaling options in the Spectrogram plugin to include 'logarithmic', 'bark', and 'erb'.
    • Enhanced functionality for audio frequency analysis and visualization through new filter bank methods.
  • Bug Fixes

    • Improved type safety with updated method signatures for better compatibility and performance.

Copy link

coderabbitai bot commented Dec 27, 2024

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.

examples/spectrogram.js

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.

Walkthrough

The pull request enhances the Spectrogram plugin in wavesurfer.js by expanding frequency scaling options. The changes introduce support for multiple frequency scales including linear, logarithmic, Mel, Bark, and ERB scales. This modification allows more flexible audio frequency visualization by adding new methods for filter bank creation and scale conversions in the SpectrogramPlugin class, with corresponding updates to type definitions and configuration options.

Changes

File Change Summary
examples/spectrogram.js Updated scale configuration to support multiple frequency scale options
src/plugins/spectrogram.ts - Added TypeScript typings for FFT class
- Expanded scale property in plugin options
- Implemented new methods for filter bank creation
- Added frequency scale conversion methods

Sequence Diagram

sequenceDiagram
    participant User
    participant SpectrogramPlugin
    participant FFT
    User->>SpectrogramPlugin: Configure with scale option
    SpectrogramPlugin->>FFT: Calculate Spectrum
    SpectrogramPlugin->>SpectrogramPlugin: Create Filter Bank
    SpectrogramPlugin->>SpectrogramPlugin: Convert Frequencies
    SpectrogramPlugin->>User: Render Spectrogram
Loading

Assessment against linked issues

Objective Addressed Explanation
Logarithmic Y-axis scale [#1648]

Poem

🐰 Frequencies dance, scales unfurl wide,
From linear to log, a spectral ride!
Mel, Bark, and ERB join the show,
Wavesurfer's magic begins to grow! 🎵
A rabbit's song of sonic delight! 🎶

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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: 2

🧹 Nitpick comments (3)
src/plugins/spectrogram.ts (3)

559-579: Efficiently constructed filter bank.
Using createFilterBank with parameterized functions (hzToScale, scaleToHz) is a neat approach, reducing repetitive code for different scales. Watch out for fractional indexing around line 570 to avoid out-of-bounds array writes on j+1.


597-607: Bark scale formula.
Modifying bark inline to adjust for the under/over edges is functional but slightly obscures the original parameter. Consider using an intermediate variable to avoid rewriting the function argument in place.


Line range hint 653-714: Potential memory overhead with repeated slicing.
In the getFrequencies method, repeatedly slicing large channelData arrays in a loop may incur performance overhead. Consider reusing a typed array buffer to avoid generating new slices each iteration.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b44f52b and ec92428.

📒 Files selected for processing (2)
  • examples/spectrogram.js (1 hunks)
  • src/plugins/spectrogram.ts (12 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/plugins/spectrogram.ts

[error] 215-215: Shouldn't redeclare 'FFT'. Consider to delete it or rename it.

'FFT' is defined here:

(lint/suspicious/noRedeclare)

🔇 Additional comments (7)
src/plugins/spectrogram.ts (6)

124-124: Consider verifying window function usage and FFT correctness.
The new calculateSpectrum method includes windowing and FFT logic. Ensure that the supplied window function and buffer sizes align correctly with project requirements, as subtle off-by-one or overlap issues may introduce artifacts in the spectrogram.


263-268: Good documentation on scale types.
The added comments describing logarithmic, bark, and ERB scales provide clarity and align with psychoacoustical concepts. This helps users understand the new frequency scaling capabilities.


302-323: Private fields look appropriate for plugin state.
These new private fields (e.g., frequenciesDataUrl, canvas, spectrCc, etc.) centralize the plugin’s configuration and rendering references. This organization should improve maintainability.


386-388: Filter bank allocation per scale.
Declaring distinct numbers of filters (numLogFilters, numBarkFilters, numErbFilters) provides flexibility across scales. Validate these defaults in practice to ensure they produce insightful spectrogram data.


489-489: Updated drawSpectrogram signature.
Switching to a more explicit drawSpectrogram(frequenciesData: Uint8Array[][]): void clarifies expected data structures. This will help consumers of this method understand the correct input format.


798-813: Labeling partial scales.
The switch statement for the scale-based frequency labeling is comprehensive. Confirm that the computed label frequencies match user expectations (e.g., the bark or ERB scale range).

examples/spectrogram.js (1)

21-21: Inform users of newly supported scales.
Adding 'logarithmic', 'bark', and 'erb' options in the comment is helpful. This ensures that developers experimenting with the spectrogram example can quickly switch scales without referencing documentation elsewhere.

src/plugins/spectrogram.ts Show resolved Hide resolved
src/plugins/spectrogram.ts Show resolved Hide resolved
Copy link
Owner

@katspaugh katspaugh left a comment

Choose a reason for hiding this comment

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

Amazing! Thanks much!

@katspaugh katspaugh merged commit fbef7b3 into katspaugh:main Dec 28, 2024
4 checks passed
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.

Logarithm scale on Y axis in Spectrogram plugin
2 participants