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

Fix incorrect y-axis labeling of spectrogram #4011

Merged
merged 1 commit into from
Jan 26, 2025

Conversation

lucastheis
Copy link
Contributor

@lucastheis lucastheis commented Jan 25, 2025

Short description

Unfortunately the y-axis labels of the spectrogram are still incorrect. I am mostly to blame as I had used and sent some faulty test files to @jonom (#3796) such that the linear labels ended up off by a factor of 2.

This PR also improves the implementation for nonlinear scales. The previous approach did not seem to work unless frequencyMax matches half the buffer's sampling rate.

This PR's implementation still does not work when numMelFilters (or numLogFilters, etc.) is different from fftSamples / 2, so I changed these values for now so that the spectrogram and labels are aligned.

Implementation details

  • Correct some multiplication factors so that the frequency labels are no longer off by a factor of 2
  • Take into account nonlinear scaling when cropping spectrogram (for frequencyMin/frequencyMax)

How to test it

I added examples/audio/1khz.mp3 and a basic Cypress test to check if the 1 kHz label is where you'd want it.

Screenshots

Before:

1 kHz, scale: linear, frequencyMax: 5000, fftSamples: 1024, height: 256
image

1 kHz, scale: mel, frequencyMax: 5000, fftSamples: 1024, height: 256
image

1 kHz, scale: erb, frequencyMax: 5000, fftSamples: 1024, height: 256
image

8 kHz, scale: linear, frequencyMax: 20000, fftSamples: 1024, height: 256
image

1 kHz, scale: linear, frequencyMax: 5000, fftSamples: 1024, height: 256, frequencyMin: 500
image

After:

1 kHz, scale: linear, frequencyMax: 5000, fftSamples: 1024, height: 256
image

1 kHz, scale: mel, frequencyMax: 5000, fftSamples: 1024, height: 256
image

1 kHz, scale: erb, frequencyMax: 5000, fftSamples: 1024, height: 256
image

8 kHz, scale: linear, frequencyMax: 20000, fftSamples: 1024, height: 256
image

1 kHz, scale: linear, frequencyMax: 5000, fftSamples: 1024, height: 256, frequencyMin: 500
image

Checklist

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced spectrogram visualization with support for multiple frequency scales (linear, mel, log, bark, erbs)
    • Improved frequency range handling in spectrogram rendering
  • Bug Fixes

    • Corrected frequency scaling calculations for more accurate spectrogram representation
  • Tests

    • Added comprehensive test cases to verify spectrogram rendering across different scale types

Copy link

coderabbitai bot commented Jan 25, 2025

Warning

Rate limit exceeded

@lucastheis has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 16 minutes and 49 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 5c7a0ac and 5c4171a.

⛔ Files ignored due to path filters (1)
  • examples/audio/1khz.mp3 is excluded by !**/*.mp3
📒 Files selected for processing (2)
  • cypress/e2e/spectrogram.cy.js (2 hunks)
  • src/plugins/spectrogram.ts (8 hunks)

Walkthrough

This pull request introduces comprehensive improvements to the spectrogram functionality in WaveSurfer. The changes focus on frequency scaling and visualization, updating the SpectrogramPlugin to support more accurate frequency range representations. A new Cypress test suite is added to validate the rendering of frequency labels across different scale types, ensuring robust testing of the spectrogram plugin's capabilities.

Changes

File Change Summary
cypress/e2e/spectrogram.cy.js Added scales constant with ['linear', 'mel', 'log', 'bark', 'erbs'] and new test case to verify frequency label rendering
src/plugins/spectrogram.ts - Updated frequency max scaling to samplerate/2
- Modified filter count initializations to use fftSamples/2
- Added hzToScale and scaleToHz methods
- Enhanced spectrogram rendering logic

Sequence Diagram

sequenceDiagram
    participant Test as Cypress Test
    participant WaveSurfer as WaveSurfer
    participant Spectrogram as SpectrogramPlugin

    Test->>WaveSurfer: Initialize with scale type
    WaveSurfer->>Spectrogram: Configure plugin
    Spectrogram-->>WaveSurfer: Apply frequency scaling
    WaveSurfer-->>Test: Render spectrogram
    Test->>Test: Validate snapshot
Loading

Possibly related PRs

Suggested reviewers

  • katspaugh

Poem

🎵 Frequencies dance, scales unfurl wide
A spectrogram's canvas, where sound waves reside
From linear to mel, log to bark's embrace
Our plugin now sings with newfound grace! 🐰🎨


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.

@lucastheis lucastheis changed the title Fix incorrect labeling of spectrogram Fix incorrect y-axis labeling of spectrogram Jan 25, 2025
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: 1

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

387-392: Reevaluate default filter sizes
Allocating fftSamples / 2 filters for mel/log/bark/erb might be excessive for some use cases and can impact performance. Consider making these configurable or adjusting them based on real-world scenarios.


545-551: Minor comment typo
"freqwMax" should likely be "freqMax."

- // Only relevant if `freqwMax > freqFrom`
+ // Only relevant if `freqMax > freqFrom`
cypress/e2e/spectrogram.cy.js (1)

86-114: Solid coverage of scale tests
Iterating through multiple scale types is a great testing approach. However, note the 'erbs' vs. 'erb' issue, which can invalidate the intended test.

Would you like assistance in harmonizing the test suite with the plugin’s recognized scale types and possibly opening a new issue for extended scale support?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ef522ee and 5c7a0ac.

⛔ Files ignored due to path filters (1)
  • examples/audio/1khz.mp3 is excluded by !**/*.mp3
📒 Files selected for processing (2)
  • cypress/e2e/spectrogram.cy.js (2 hunks)
  • src/plugins/spectrogram.ts (8 hunks)
🔇 Additional comments (12)
src/plugins/spectrogram.ts (12)

258-258: Documentation alignment
The updated docstring clarifies that frequencyMax should be set to the Nyquist frequency (samplerate/2), which aligns well with the revised scaling logic.


509-510: Clear statement on raw data range
The comment succinctly clarifies that the raw frequenciesData covers up to half the sample rate (Nyquist).


512-513: Straightforward min/max handling
Referencing frequencyMin and frequencyMax here is direct and clear, aiding readability.


521-526: Background fill beyond Nyquist
Filling the unused canvas area with the last colormap color is a reasonable solution if freqMax exceeds the actual data range.


537-537: Vertical indexing
Subtracting from bitmapHeight - 1 flips the rows correctly, ensuring the top row corresponds to higher frequencies.


666-678: Implicit linear scale
Falling back to return hz when this.scale is neither 'mel', 'logarithmic', 'bark', nor 'erb' effectively handles the 'linear' case.


680-692: Consistent inverse scaling
The scaleToHz method mirrors the logic in hzToScale, ensuring proper two-way conversion for each scale.


713-713: Sensible default for frequencyMax
Defaulting to buffer.sampleRate / 2 aligns with standard audio processing assumptions around Nyquist frequency.


796-798: Accurate label interpolation
Interpolating between scaleMin and scaleMax in scale-space ensures frequency labels match the selected scale.


851-851: Good use of getLabelFrequency
This leverages your new scale logic for frequency labeling. No issues here.


556-558: Validate cropping height
Ensure that (rMax1 - rMin) remains non-negative—otherwise, the cropped bitmap could have an invalid height.

✅ Verification successful

Height calculation is mathematically guaranteed to be non-negative
Since rMin is derived from freqMin and rMax1 is clamped to be ≤ 1, the expression (rMax1 - rMin) is guaranteed to be non-negative due to the monotonic nature of the frequency scaling function.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Investigate any usage pattern of rMin/rMax1 that might produce negative dimensions:
rg --context 5 'rMax1|rMin'

Length of output: 3851


560-566: Avoid potential division by zero
rMax can become zero or negative if freqMax ≤ 0. Consider clamping or adding a guard to prevent runtime errors.

cypress/e2e/spectrogram.cy.js Outdated 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.

Thanks!

@katspaugh katspaugh merged commit bb62616 into katspaugh:main Jan 26, 2025
3 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.

2 participants