这是indexloc提供的服务,不要输入任何密码
Skip to content

Fix: Safe camera detection for macOS (M1/M2) to prevent OpenCV AVX/th… #1236

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

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

Conversation

brynwhyman
Copy link

@brynwhyman brynwhyman commented May 8, 2025

This PR addresses a crash I had to work around when launching on Apple Silicon (M1/M2/M3). The issue stemmed from OpenCV's threaded camera enumeration causing a fatal error due to AVX instruction mismatches or GIL violations.

  • Replaces the original get_available_cameras() logic with a safe fallback for macOS that avoids multithreaded access and AVX instruction usage.
  • Adds platform-specific logging to help users understand what's detected.
  • Retains the original Windows-specific logic (via pygrabber) for full cross-platform compatibility.

Tested on:

  • macOS 14.4.1 (Apple M2)
  • Python 3.10
  • Camera detection succeeded and GUI preview works without crash

Let me know if you'd like help extending this further. Thanks!

Summary by Sourcery

Implement a safe camera detection mechanism for macOS and Unix-like systems to prevent crashes related to OpenCV threading and AVX instructions

New Features:

  • Implemented a safe fallback camera detection method for macOS and Unix systems

Bug Fixes:

  • Fixed camera detection crash on Apple Silicon (M1/M2/M3) platforms
  • Resolved OpenCV threading and AVX instruction compatibility issues on macOS

Enhancements:

  • Simplified camera detection logic for non-Windows platforms
  • Added platform-specific logging for camera detection

Copy link
Contributor

sourcery-ai bot commented May 8, 2025

Reviewer's Guide

This pull request modifies the get_available_cameras() function in modules/ui.py to prevent crashes on Apple Silicon (macOS) by introducing a simplified camera detection strategy. For macOS and other Unix-like systems, it now exclusively attempts to access the default camera (index 0) via cv2.VideoCapture(0), thereby avoiding multithreaded operations and potential AVX instruction issues inherent in the previous, more exhaustive camera probing. The Windows-specific camera detection using pygrabber is largely retained, but its OpenCV fallback for cases where no cameras are found by pygrabber has been removed. Logging for camera detection has also been updated to be more platform-specific.

File-Level Changes

Change Details Files
Implemented a safer, simplified camera detection method for macOS and Linux systems.
  • Replaced iterative multi-camera probing with a direct check for the default camera (index 0) to prevent crashes related to multithreading/AVX instructions on Apple Silicon.
  • Updated the docstring of get_available_cameras to describe the new approach.
modules/ui.py
Streamlined the camera detection process for Windows.
  • Removed the OpenCV-based fallback from the Windows camera detection logic.
modules/ui.py
Enhanced diagnostic logging during camera detection.
  • Added new informational logs for the Unix camera detection path.
  • Revised error log messages to be more specific for both Windows and Unix platforms.
modules/ui.py
Refactored import statements within get_available_cameras.
  • Moved cv2 and platform imports to be local to the function scope.
modules/ui.py

Possibly linked issues

  • #-1: PR changes camera detection on macOS to fix OpenCV initialization failure reported in the issue.
  • #0: The PR fixes the webcam detection problem on Apple Silicon described in the issue by changing the camera detection logic.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @brynwhyman - I've reviewed your changes - here's some feedback:

  • Camera detection on Linux is now limited to index 0; consider retaining multi-index probing for Linux if the original crash was macOS-specific.
  • The OpenCV fallback for Windows camera detection (when pygrabber finds no devices) appears to have been removed; please clarify if this was intentional.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 801 to +805
def get_available_cameras():
"""Returns a list of available camera names and indices."""
"""
Safe camera detection for macOS and Unix-like systems that avoids threading and AVX crashes.
Returns a tuple of (camera_indices, camera_names).
"""
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion: Clarify behavior differences across platforms in the docstring.

Also note that on Windows the function enumerates devices via DirectShow; add this to the docstring to distinguish platform strategies.

Suggested change
def get_available_cameras():
"""Returns a list of available camera names and indices."""
"""
Safe camera detection for macOS and Unix-like systems that avoids threading and AVX crashes.
Returns a tuple of (camera_indices, camera_names).
"""
def get_available_cameras():
"""
Safe camera detection that avoids threading and AVX crashes.
On macOS and Unix-like systems, it utilizes a safe detection mechanism to list available cameras.
On Windows, devices are enumerated via DirectShow.
Returns a tuple of (camera_indices, camera_names).
"""

return camera_indices, camera_names
# macOS or Linux
try:
print("[Info] Safely checking for available cameras...")
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion: Use a logging framework instead of print statements.

A logging framework provides configurable levels and outputs, improving maintainability and configurability of debug and error messages in production.

Suggested implementation:

import logging
# (other imports below)
            logging.error(f"[Camera Detection Error - Windows]: {e}")
        logging.info("Safely checking for available cameras...")
            logging.warning("Default camera (index 0) not available.")
        logging.error(f"[Camera Detection Error - Unix]: {e}")

Please ensure that the logging configuration (level, formatting, etc.) is set up in your application so that these logging calls behave as expected. If there is an existing logging setup in your code base, this configuration might already be in place.

@brynwhyman
Copy link
Author

Likely solves this issue too: #1166

@brynwhyman
Copy link
Author

Should I make the changes suggested by the bot?

@arturo-lr-dev
Copy link

arturo-lr-dev commented May 20, 2025

tryed on M4 and seem that didn't work.

Seems the camera is loading but the UI doesn't show anything

Log:
DEPRECATION WARNING: The system version of Tk is deprecated and may be removed in a future release. Please don't rely on it. Set TK_SILENCE_DEPRECATION=1 to suppress this warning.
[Info] Safely checking for available cameras...

Version apple: 15.5
Python 3.10.13

Solved: Just use python 3.10.16

Now I have the fps problems

@brynwhyman
Copy link
Author

@arturo-lr-dev thanks for testing.

Now I have the fps problems

Is this something that exists when trying to install from the main branch too? Wondering if it's an issue with this PR or not

@arturo-lr-dev
Copy link

@brynwhyman it happens with both branches, i think is not a problem of this branch

@ridhoperdana
Copy link

tryed on M4 and seem that didn't work.

Seems the camera is loading but the UI doesn't show anything

Log: DEPRECATION WARNING: The system version of Tk is deprecated and may be removed in a future release. Please don't rely on it. Set TK_SILENCE_DEPRECATION=1 to suppress this warning. [Info] Safely checking for available cameras...

Version apple: 15.5 Python 3.10.13

Solved: Just use python 3.10.16

Now I have the fps problems

Hi, i am using the same python version and the same mac version. I got blank view of the UI
Screenshot 2025-06-10 at 16 51 19

the log doesnt show any error (except the SSL)

(venv) ➜  Deep-Live-Cam git:(main) ✗ python3.10 run.py --execution-provider coreml
/Users/ridhoperdana/workspace/Deep-Live-Cam/venv/lib/python3.10/site-packages/albumentations/check_version.py:147: UserWarning: Error fetching version info <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1007)>
  data = fetch_version_info()
DEPRECATION WARNING: The system version of Tk is deprecated and may be removed in a future release. Please don't rely on it. Set TK_SILENCE_DEPRECATION=1 to suppress this warning.
[Info] Safely checking for available cameras...

do you ever got the same issue?

@arturo-lr-dev

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.

3 participants