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

improve combine sinks #14

Draft
wants to merge 5 commits into
base: dev
Choose a base branch
from
Draft

improve combine sinks #14

wants to merge 5 commits into from

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Jan 22, 2025

closes #7

Summary by CodeRabbit

  • New Features

    • Enhanced sound server detection capabilities
    • Added support for identifying active sound server (PipeWire, PulseAudio, ALSA)
    • Improved sink management and retrieval logic
  • Bug Fixes

    • Implemented robust error handling for sound server detection
    • Added retry mechanism for sink retrieval
  • Refactor

    • Modularized script functionality
    • Updated sink combination process for better compatibility

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

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.

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

Walkthrough

The combine-sinks script has been modified to enhance its functionality and error handling. It now includes a constant for retrieving the first non-system user's username and a function to detect the active sound server (PipeWire, PulseAudio, or ALSA). New functions have been added for logging, sink retrieval, and checking for the "auto_null" sink. The retry logic for obtaining sinks has been encapsulated in a dedicated function, with the main logic updated to adapt to different sound server environments.

Changes

File Changes
combine-sinks - Added detect_sound_server() function to identify active sound server
- Introduced OVOS_USER constant for username retrieval
- Created log_message() for centralized logging
- Added get_sinks() to retrieve sinks based on sound server
- Implemented wait_for_auto_null() to check for "auto_null" sink
- Developed retry_get_sinks() for multiple sink retrieval attempts

Sequence Diagram

sequenceDiagram
    participant Script as combine-sinks
    participant SoundServer as Sound Server
    
    Script->>SoundServer: detect_sound_server()
    SoundServer-->>Script: Return active server type
    
    Script->>SoundServer: get_sinks()
    SoundServer-->>Script: Return available sinks
    
    alt No Sinks Found
        Script->>Script: retry_get_sinks()
        Script->>SoundServer: Retry get_sinks()
    end
    
    Script->>Script: wait_for_auto_null()
    Script->>SoundServer: Create Combined Sink
Loading

Poem

🎵 In the realm of audio's dance,
A script that leaps with every chance,
Sinks combine with rabbit's might,
PipeWire, PulseAudio in sight!
Modularity hops along, 🐰
A symphony of code so strong! 🎧


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
Contributor

@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: 3

🔭 Outside diff range comments (1)
combine-sinks (1)

Line range hint 8-9: Replace hardcoded user ID with dynamic user detection.

The environment variables use a hardcoded user ID (1000), while the script later dynamically detects the user with OVOS_USER. This inconsistency could cause issues on systems where the first non-system user has a different ID.

Apply this diff to use the dynamically detected user ID:

-export PULSE_RUNTIME_PATH="/run/user/1000/pulse/"
-export XDG_RUNTIME_DIR="/run/user/1000/"
+export PULSE_RUNTIME_PATH="/run/user/$(id -u "$OVOS_USER")/pulse/"
+export XDG_RUNTIME_DIR="/run/user/$(id -u "$OVOS_USER")/"
🧹 Nitpick comments (2)
combine-sinks (2)

91-99: Make sleep duration configurable and implement PipeWire auto_null check.

The function uses a hardcoded sleep duration and lacks proper PipeWire implementation.

Apply this diff to improve the implementation:

+# Constants
+WAIT_DURATION=3  # Configurable sleep duration in seconds
+
 wait_for_auto_null() {
     if [ "$SOUND_SERVER" == "pulse" ] && pactl list short sinks | grep -q "auto_null"; then
         log_message "auto_null sink exists, still booting? Sleeping for 3 seconds..."
-        sleep 3
+        sleep "$WAIT_DURATION"
     elif [ "$SOUND_SERVER" == "pipewire" ]; then
-        echo "TODO"
-        sleep 3
+        if wpctl status | grep -q "auto_null"; then
+            log_message "auto_null sink exists in PipeWire, still booting? Sleeping for $WAIT_DURATION seconds..."
+            sleep "$WAIT_DURATION"
+        fi
     fi
 }

Line range hint 1-174: Consider implementing sound server abstraction.

While the script's modularity has improved, the sound server-specific logic is scattered throughout the code. Consider implementing a more structured approach:

  1. Create separate functions for each sound server operation
  2. Use a configuration file for system-specific settings
  3. Implement proper service detection and fallback mechanisms

Example structure:

# Sound server interface functions
pulse_get_sinks() { ... }
pipewire_get_sinks() { ... }
pulse_create_combined_sink() { ... }
pipewire_create_combined_sink() { ... }

# Generic interface
get_sinks() {
    case "$SOUND_SERVER" in
        pulse) pulse_get_sinks ;;
        pipewire) pipewire_get_sinks ;;
        *) return 1 ;;
    esac
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c768ef8 and b7cc5b1.

📒 Files selected for processing (1)
  • combine-sinks (4 hunks)
🔇 Additional comments (1)
combine-sinks (1)

68-71: Remove or utilize the unused card name constants.

The card name constants are defined but never used in the script. Either remove them if they're not needed or implement the intended functionality.

Run this script to confirm they're unused:

Comment on lines +162 to 164
elif [ "$SOUND_SERVER" == "pipewire" ]; then
echo "TODO"
fi
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement PipeWire combined sink creation.

The PipeWire implementation for creating combined sinks is missing, which makes the script non-functional for PipeWire users.

Apply this diff to add PipeWire support:

     elif [ "$SOUND_SERVER" == "pipewire" ]; then
-        echo "TODO"
+        # Remove existing combined sink if present
+        wpctl destroy auto_combined 2>/dev/null || true
+        
+        # Create new combined sink
+        if ! wpctl create-sink auto_combined slaves="$SINKS"; then
+            log_message "Failed to create combined sink"
+            exit 1
+        fi
+        
+        # Set as default if creation successful
+        if wpctl status | grep -q "auto_combined"; then
+            wpctl set-default-sink auto_combined
+            log_message "Combined sink created with outputs: $SINKS"
+        else
+            log_message "Combined sink creation failed"
+            exit 1
+        fi
     fi
📝 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
elif [ "$SOUND_SERVER" == "pipewire" ]; then
echo "TODO"
fi
elif [ "$SOUND_SERVER" == "pipewire" ]; then
# Remove existing combined sink if present
wpctl destroy auto_combined 2>/dev/null || true
# Create new combined sink
if ! wpctl create-sink auto_combined slaves="$SINKS"; then
log_message "Failed to create combined sink"
exit 1
fi
# Set as default if creation successful
if wpctl status | grep -q "auto_combined"; then
wpctl set-default-sink auto_combined
log_message "Combined sink created with outputs: $SINKS"
else
log_message "Combined sink creation failed"
exit 1
fi
fi

Copy link
Contributor

@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

🔭 Outside diff range comments (1)
combine-sinks (1)

Line range hint 8-9: Use OVOS_USER variable for environment paths.

The environment variables are hardcoded with user ID 1000, which might not match the actual user. Consider using the OVOS_USER variable consistently.

Apply this diff to make the paths dynamic:

-export PULSE_RUNTIME_PATH="/run/user/1000/pulse/"
-export XDG_RUNTIME_DIR="/run/user/1000/"
+export PULSE_RUNTIME_PATH="/run/user/$(id -u "$OVOS_USER")/pulse/"
+export XDG_RUNTIME_DIR="/run/user/$(id -u "$OVOS_USER")/"
♻️ Duplicate comments (3)
combine-sinks (3)

19-33: 🛠️ Refactor suggestion

Enhance sound server detection reliability.

The current detection only checks if commands exist but doesn't verify if the services are actually running.

Apply this diff to improve detection reliability:

 detect_sound_server() {
     # Check if PipeWire is installed
-    if command -v pipewire > /dev/null; then
+    if pgrep -x pipewire >/dev/null; then
         echo "pipewire"
     # Check if PulseAudio is installed
-    elif command -v pulseaudio > /dev/null; then
+    elif pgrep -x pulseaudio >/dev/null; then
         echo "pulse"
     # Check if ALSA is available
     elif command -v aplay > /dev/null && command -v amixer > /dev/null; then
         echo "alsa"
     else
         echo "No sound server detected"
         exit 1
     fi
 }

68-75: ⚠️ Potential issue

Implement PipeWire sink detection.

The get_sinks function returns "TODO" for PipeWire, which will break the sink combination logic.

Apply this diff to add PipeWire support:

 get_sinks() {
     if [ "$SOUND_SERVER" == "pulse" ]; then
         pactl list short sinks | awk '{print $2}' | grep -v 'auto_combined' | grep -v 'auto_null' | tr '\n' ',' | sed 's/,$//'
     elif [ "$SOUND_SERVER" == "pipewire" ]; then
-        echo "TODO"
+        wpctl status | grep -A1 "Sinks:" | tail -n1 | awk '{print $2}' | tr '\n' ',' | sed 's/,$//'
     fi
 }

149-151: ⚠️ Potential issue

Implement PipeWire combined sink creation.

The PipeWire implementation for creating combined sinks is missing, which makes the script non-functional for PipeWire users.

Apply this diff to add PipeWire support:

     elif [ "$SOUND_SERVER" == "pipewire" ]; then
-        echo "TODO"
+        # Remove existing combined sink if present
+        wpctl destroy auto_combined 2>/dev/null || true
+        
+        # Create new combined sink
+        if ! wpctl create-sink auto_combined slaves="$SINKS"; then
+            log_message "Failed to create combined sink"
+            exit 1
+        fi
+        
+        # Set as default if creation successful
+        if wpctl status | grep -q "auto_combined"; then
+            wpctl set-default-sink auto_combined
+            log_message "Combined sink created with outputs: $SINKS"
+        else
+            log_message "Combined sink creation failed"
+            exit 1
+        fi
     fi
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b7cc5b1 and 2e2bb47.

📒 Files selected for processing (1)
  • combine-sinks (3 hunks)
🔇 Additional comments (3)
combine-sinks (3)

88-99: LGTM! Well-implemented retry logic.

The retry mechanism is well-structured with proper logging and retry count.


101-110: LGTM! Good logging implementation.

The main logic properly handles both sound servers with appropriate logging.


157-161: LGTM! Comprehensive logging after actions.

The final logging properly captures the state for both sound servers.

@JarbasAl JarbasAl marked this pull request as draft January 23, 2025 00:20
This was referenced Jan 23, 2025
JarbasAl and others added 2 commits January 23, 2025 01:14
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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.

combine output sink
1 participant