Skip to content

Commit

Permalink
🎉 Released VidGear Stable v0.3.3 [#411]
Browse files Browse the repository at this point in the history
This update significantly enhances Vidgear's capabilities, ensuring better performance, broader compatibility, and improved user experience. The introduction of the Picamera2 API support, enhanced error handling, and detailed documentation updates are pivotal in making Vidgear more robust and user-friendly.

====================

### New Features ✨
- **PiGear:**
    + Official Support for Picamera2 API backend (Fixes #342)
        * This massive update brings official support for the new Picamera2 API, unlocking powerful features for Raspberry Pi Camera Modules and limited USB camera support. 
        * **Seamless Python wrapper:** A robust wrapper around Picamera2 API library simplifies integration with minimal code changes for existing PiGear users.
        * **Enhanced camera control:** Leverages libcamera API under the hood for Raspberry Pi Camera Modules.
        * **Existing compatibility:** Maintains compatibility with PiGear's existing super-charged multi-threaded and colorspace manipulation framework.
        * **Proper Resource management:** Ensures proper resource release during PiGear termination.
        * **USB camera support (limited):** Provides basic functionality for USB webcams. PiGear could accurately differentiates between USB and Raspberry Pi cameras using metadata.
        * **Backward compatibility:** Seamlessly switches to the legacy Picamera library backend if Picamera2 is unavailable.
        * **Standalone functionalities:** Standalone functionalities for both legacy `picamera` and newer `picamera2` backends for clarity.
        * **Advanced optional parameters handling:** Handles camera configurational parameters and user-defined settings for various camera types.
            * **New optional configurational parameters:** Currently Supports "sensor", "format", "controls", "transform", "stride", "buffer_count", and "queue" with sanity checks. Seperated Raspberry Pi camera module exclusive and Unified USB cameras supported optional parameters.
            * **New user-defined optional parameters:** Such as `auto_align_output_config`, `enable_verbose_logs`, and more.
- **StreamGear:**
    * Introduced new `-enable_force_termination` attribute for immediate FFmpeg process termination.
- **Helper:**
    * Added support for SRTP/RTSPS in `is_valid_url` function (Fixes #410)
        + Enhanced `is_valid_url` in `helper.py` to recognize and support both `rtsp` and `rtsps` protocols. (Suggested by @jonra1993)
        + SRTP/RTSPS extends RTSP/RTP to encrypt video and audio data using the same ciphers as HTTPS, typically AES with a 128-bit key length.
    * Added a custom deprecated decorator to mark deprecated functions and parameters to display a warning message when a deprecated one is used.
- **Docs:**
    * Overhauled mkdocs theme.
        + Added `unrecognized_links: ignore` to `mkdocs.yml` for validations.
        + Added custom admonition icons to mkdocs.yml 
        + Added new `git-authors` plugin in mkdocs.yml 
        + Added new tables markdown extension in mkdocs.yml 
        + Added custom fences to `pymdownx.superfences` markdown extension. 
        + Added `line_spans: __span` and `pygments_lang_class: true` parameters to `pymdownx.highlight` markdown extension. 
        + Added `normalize_issue_symbols: true` to `pymdownx.magiclink` markdown extension.
        + Added new mkdocs feature dependency `mkdocs-git-authors-plugin`.
    * Added the use of new `-enable_force_termination` parameter.
    * Added a new FAQ entry about the deprecated `rgb_mode` parameter.
    * Added new `screengear_error11.png` asset.
- **CI:**
    * Added test cases for `import_dependency_safe` function to validate different scenarios and error handling in `import_dependency_safe`.


### Updates/Improvements ⚡️
- Core: 
    * Improved exception handling for module imports: 
        + Updated `import_dependency_safe` in `helper.py`:
            * Added specific handling for `ModuleNotFoundError`.
            * Included original exception in `ImportError` for better error tracing.
            * Enhanced logging to include exception traceback when error is set to "log".
        + Enhanced `import_core_dependency` in `__init__.py`:
            * Added specific handling for `ModuleNotFoundError`.
            * Included original exception in `ImportError` for better error tracing.
    * Improved colorspace handling in videocapture gears:
        + Logged a warning and discarded invalid colorspace values instead of raising an exception.
        + Consolidated colorspace logging into a single line using a ternary operation.
- Asyncio:
    * Replaced deprecated Starlette's `on_shutdown` parameter with an async context manager `lifespan` in WebGear and WebGear_RTC APIs. (Fixes #397)
        + Moved shutdown logic for VideoGear and peer RTC connections to this new `lifespan` context manager.
        + Added new `contextlib` import for using `asynccontextmanager`.
- NetGear_Async API:
    * Modified `__init__` method to handle event loop more robustly:
        + Try to get the running event loop using `asyncio.get_running_loop()`
        + If no running event loop found, create a new one with `asyncio.new_event_loop()`
        + Log if creating a new event loop
    * Changed launch method to use `self.loop.create_task()` instead of `asyncio.ensure_future()`
        + Ensures the task is created using the correct event loop instance.
    * Moved the event loop initialization code to an earlier point before setting event loop policy to ensure it is set up correctly before selecting `WindowsSelectorEventLoop` policy.
        + On Windows, vidgear requires the `WindowsSelectorEventLoop`, but Python 3.8 and above defaults to the `ProactorEventLoop` which is not compatible.
    * Removed redundant python version check to set `WindowsSelectorEventLoop` policy, as minimum supported version is already `3.8`.
    * Move event loop setup and policy assignment to the beginning of `__init__` before zmq Context creation.
    * Refactored return data handling.
- StreamGear:
    * Updated `close()` methods for handling gracefully signal interruptions based on different operating systems with device audio streams.
    * Deprecated `terminate()` method, introducing `close()` for safer process termination.
    * Enhanced stream copy support in Single Source mode (Fixes #396).
        + Moved settings for "-vf" and "-aspect" inside conditional blocks.
        + Added warnings and discarded these parameters in stream copy mode.
        + Ignored stream copy parameter in Real-time Frames Mode or Custom Streams with appropriate warnings.
        + Updated `-acodec` handling:
            * Default to `aac` for Custom Streams.
            * Use stream copy (`-acodec copy`) for input video’s audio when Custom Streams are disabled.
        + Refined `-livestream` parameter usage to Real-time Frames Mode only.
        + Adjusted video and audio bitrate assignment to skip when stream copy is enabled.
        + Improved log message for `-clear_prev_assets` parameter.
    * Restricted `-livestream` parameter to Real-time Frames Mode only.
        + Disabled live streaming for video files and updated relevant logging.
    * Enhanced warning messages and clarified description.
- PiGear:
    * Logging optimization with warning for common `libcamera` messages.
    * Lowered `framerate` minimum value to `0.0`.
    * Moved `sensor` optional parameter to commonly supported picamera2 configurational parameters.
    * Removed unsupported `bit_depth` optional parameters.
    * Updated PiGear API tagline and introduction.
- NetGear: 
    * Enhanced logging and error handling for secure mode.
    * Logged Authenticator start/stop events.
    * Handled socket session expiration more gracefully in `recv_handler`.
    * Ensured proper termination of the ZMQ context and socket when closing the NetGear instance.
- WebGear:
    * Enhanced error messages for WebGear auto-generation workflow (Fixes #403)
        + Updated `homepage`, `not_found`, and `server_error` methods to include more detailed JSON error messages.
        + Added specific error and message prefixes to improve clarity.
- WebGear_RTC:
    * Optimized peer connection closure to avoid redundant closures.
    * Reduced unnecessary logging by only logging ICE connection state changes when they are not in a "failed" state.
- WriteGear:
    * Simplified the logic for formatting output parameters.
    * Improved error handling in `execute_ffmpeg_cmd` method:
        + Raised `ValueError` with descriptive messages for `BrokenPipeError` or `IOError`.
        + Updated error handling per PEP 409 to preserve original exception context or suppress it based on logging settings.
- CamGear:
    * Removed GStreamer support check.
    * Improved readability of livestream warning logs.
- Setup.py:
    * Dropped legacy picamera dependency in `setup.py`.
    * Updated setup.py to use the latest `pyzmq` version to address installation issues (Fixes #399).
- Helper:
    * Added patch for substring index bug in `get_supported_demuxers` helper method.
    * Updated `extract_time` helper function regex to handle milliseconds.
- Docs:
    * Update StreamGear documentation:
        + Updated documentation to deprecated `terminate()` method, and introducing `close()` for safer process termination.
        + Improved the overview section's description and wording.
        + Updated usage examples for both Single-Source Mode and Real-time Frames Mode.
        + Updated StreamGear usage examples for device audio input.
        + Refactored sections for Live Streaming usage.
            * Added warning for unsupported `-livestream` parameter in Single-Source Mode.
        + Added a tip box on benefits of using stream copy (`-vcodec copy`) for faster HLS/DASH transcoding.
            * Highlighted limitations of stream copy, including incompatibility with Real-time Frames Mode and Custom Streams.
            * Clarified automatic audio stream copy (`-acodec copy`) usage with input video’s audio stream.
        + Updated usage example for device video source.
        + Addressed deprecation of the `terminate()` method in favor of the new `close()` method.
        + Updated respective notices for the deprecated `terminate()` method and `rgb_mode` parameter.
        + Added a deprecation warning admonition for the `rgb_mode` parameter in the `stream()` method.
        + Removed the obsolete usage example for deprecation RGB mode with StreamGear.
        + Added documentation and usage of the new `-enable_force_termination` parameter.
        + Modified the warning message to mention that forced termination can cause corrupted output in certain scenarios.
        + Updated the docstring for the `stream()` method and `transcode_source()` method.
        + Refactored the StreamGear API Parameters documentation to enhance clarity and readability.
        + Refined the description of the `-streams` attribute of the StreamGear API.
    * Update PiGear documentation:
        + Added a warning advising users to disable common `libcamera` messages when logging is disabled.
        + Updated Picamera2 installation instructions _(including `apt`, `pip`, pre-installation on Raspberry Pi images, and compatibility warnings)_
        + Moved legacy Picamera library installation instructions to an admonition.
        + Removed Importing section from overview to avoid confusion.
    * Update NetGear documentation:
        + Added Admonition for warning users about the Client's end must run before the Server's end to establish a secure connection in Secure Mode.
        + Added warning log for potential issues with `flag=1` (NOBLOCK). (Fixes #390)
            * Changed default value of `copy` to `True` in NetGear API documentation.
        + Noted that `track` option is ignored when `copy=True`.
    * Update WriteGear documentationL
        + Updated the documentation for the `-disable_force_termination` parameter.
    * Update `README.md`:
        + Replaced deprecated options (`frame_jpeg_quality`, `frame_jpeg_optimize`, `frame_jpeg_progressive`) with their newer equivalents (`jpeg_compression_quality,` `jpeg_compression_fastdct`, `jpeg_compression_fastupsample`) in WebGear usage example.
    * Update `mkdocs.yml`:
        + Set `edit_uri` for GitHub edit links.
        + Add new theme features like content actions, tooltips, etc.
        + Update palette settings for light/dark mode.
        + Enable new markdown extensions.
        + Add custom javascript hook support.
        + Migrated to new Google Analytics 4.
        + Replaced depreciated `materialx `with supported emoji extension.
        + Replaced permalink icon with default one.
        + Change system mode toggle icon and name in `mkdocs.yml`.
    * Improved overall documentation quality by added detailed explanations, practical examples, following best practices, and clearer usage patterns.
    * Updated sections, code examples, admonitions, and comments for better readability, consistency, and precision.
    * Added missing version contributors to `changelog.md`.
    * Added new icons to make headings more readable.
    * Replaced unsupported admonitions with supported ones.
    * Removed all custom admonition icons and color CSS from `custom.css`.
    * Removed Twitter section from help and docs site metadata.
    * Updated Zenodo badge and BibTeX entry.
    * Added workaround for 'AttributeError: 'DXCamera' object has no attribute 'is_capturing'' error on Windows.
    * Remove script tags from `main.html` and use a custom hook for adding javascripts on certain pages.
    * Refactored all APIs and bonus examples to use `linenums` and `hl_lines` which makes it easier to highlight specific lines in code blocks.
    * Removed Gitter community chat sidecard JS file.
    * Redefined spacing between sections.
    * Add failure warning in various docs about `picamera` incompatibility on 64-bit OS.
    * Update announcement icon in `main.html`.
    * Remove `site.webmanifest` file.
- Maintenance:
    * Improved logging, parameter validation, and added descriptive dialogs across various APIs.
    * Moved logging enablement before version logging for consistency in vidgear APIs.
    * Removed redundant boolean assignment for various APIs internal logging.
    * Simplified conditional statements and assignments using short-circuiting, Boolean operations, and ternary operators across various APIs and tests.
    * Refactored vidgear code to improve readability, maintainability, and performance.
    * Added `.cache` directory to `.gitignore`, 
    * Updated vidgear library version to `v0.3.3`.
    * Improved code efficiency with short-circuiting and formatting.
    * Updated logging practices to be more developer-friendly.
    * Removed unnecessary parentheses and type checks.
    * Removed unused imports.
    * Updated code comments.
- CI:
    * Temporarily removed PiGear API from code coverage due to hardware limitations.
    * Deprecated custom `event_loop` fixture overrides in WebGear_RTC and NetGear_Async tests
        + Removed redundant `pytest.mark.asyncio` decorators from several test functions. 
    * Add a new `event_loop_policy` fixture for pytest to override the event loop policy:
        + Added new recommended approach of using `pytest.mark.asyncio(scope="module")` to mark all WebGear_RTC and NetGear_Async tests as asynchronous and utilize the same event loop throughout the module.
        + Log the event loop being used for debugging.
    * Updated NetGear unit tests to reflect the new default for `copy`.
    * Ensured coverage for `raise`, `log`, `silent`, and unknown error types.
    * Improved parameterized test cases to support floating point values.
    * Updated StreamGear tests to use the new `close()` method instead of the deprecated terminate() method.
    * Updated tests of various APIs for better coverage and reliability.
    * Enabled `kill=True` in `close()` in NetGear Tests.
    * Removed pinned `cryptography==38.0.4` dependency.
    * Remove unused imports and code cleanup.
    * Rearranged the dependencies.


### Breaking Updates/Changes 💥
- StreamGear:
    * Deprecated `terminate()` method and introduce `close()` method.
        + The `terminate()` method in StreamGear is now deprecated and will be removed in a future release. Developers should use the new `close()` method instead, which provides a more descriptive name like in  WriteGear API for terminating StreamGear processes safely.
    * Deprecated `rgb_mode` parameter in `stream()` method.
        + This parameter will be removed in a future version, and only BGR format frames will be supported.
    * Restricted -livestream parameter to Real-time Frames Mode only.
        + Live streaming is intended for low-latency streaming of real-time frames, where chunks contain only the most recent frames. It doesn't make sense when streaming from a video file, as the entire file can be streamed normally without the need for live streaming.



### Bug-fixes 🐛
- PiGear:
    * Modify PiGear class behavior when `enforce_legacy_picamera=True` on unsupported system
        + Instead of silently disabling `picamera2` API directly, PiGear now raises an error if `picamera` is unavailable or unsupported
        + Prevented incorrect initialization of `PiGear` class on unsupported 64-bit OS systems.
    * Fixed `UnboundLocalError` bug for 'picamera2' variable assigment.
    * Fixed `UnboundLocalError` bug for 'queue' variable assignment.
    * Fixed colorspace typo bug.
- StreamGear:
    * Fixed incompatibility of stream copy with Real-time Frames Mode.
        + Added warnings and discarded `-vcodec copy` when using this mode.
    * Removed non-essential aspect ratio parameter to prevent unwanted distortions (Fixes #385).
    * Moved handle streaming format to beginning to fix 'StreamGear' object has no attribute '_StreamGear__format' bug.
- NetGear: 
    * Fixed Secure Mode failing to work on conflicting ZMQ Contexts:
        + Handled "Address in use" error more gracefully and disabled secure mode if errors occur.
        + Improved handling of ZMQ Authenticator and Certificates.
    * Fixed `msg_json` undefined when terminating context in the `recv_handler` method.
- CamGear:
    * Fixed logging condition for yt-dlp (Fixes #394) 
        + Updated `no_warnings` parameter in `CamGear` to be `False` when logging is enabled and `True` otherwise.
- Docs:
    * Replaced buggy kofi widget with a button image in `index.md`.
    * Fixed Ko-fi sponsorship heart hover effect in footer 
        + Replaced `twemoji` heart emoji with `heart-pulse` fontawesome SVG  
    * Fixed titles and indentations in various admonitions.
    * Fixed various issues in code comments, and hyperlinks URLs. 
    * Fixed typos, formatting, code highlighting, and grammar inconsistencies.
    * Fixed minor typo in `js_hook.py`.
- CI:
    * Fixed simplejpeg and opencv not compatible with `numpy==2.x.x` versions.
        + Pinned `numpy<2.0.0` in all CI envs.
    * Fixed expected duration value in parameterized test case from `8` to `8.44` since `test_extract_time` function now supports floating point values.
    * Fixed `test_secure_mode` NetGear test:
        + Added `"127.0.0.1"` address to allow common endpoint for connection.
        + Added `"jpeg_compression":False` to disable frame compression, allowing frame to be the same while assertion.
    * Fixed `pip install` hash bug in Azure Pipelines CI.
    * Fixed various typos and code issues in tests.
    * Fixed invalid escape sequence in testcase string.
    * Fixed python environment bugs in `appveyor.yml`.
  • Loading branch information
abhiTronix authored Jun 22, 2024
2 parents be6f3f0 + 0677976 commit 5f4127b
Show file tree
Hide file tree
Showing 118 changed files with 5,615 additions and 3,263 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/ci_linux.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ jobs:
chmod +x scripts/bash/install_opencv.sh
- name: install pip_dependencies
run: |
pip install -U pip wheel numpy
pip install -U .[asyncio]
pip install -U pip wheel
pip install "numpy<2.0.0"
pip install -U .[asyncio] six httpx yt_dlp paramiko
pip uninstall opencv-python -y
pip install -U flake8 six codecov httpx pytest pytest-asyncio pytest-cov yt_dlp mpegdash paramiko m3u8 async-asgi-testclient
pip install -U flake8 codecov pytest pytest-asyncio pytest-cov mpegdash m3u8 async-asgi-testclient
pip install -U deffcode
pip install cryptography==38.0.4
if: success()
- name: run prepare_dataset_script
run: bash scripts/bash/prepare_dataset.sh
Expand Down
18 changes: 12 additions & 6 deletions .github/workflows/deploy_docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ jobs:
if: success()
- name: install_dependencies
run: |
pip install -U mkdocs mkdocs-material mkdocs-git-revision-date-localized-plugin mkdocs-minify-plugin mkdocs-exclude mike mkdocstrings mkdocstrings-python-legacy
pip install -U mkdocs mkdocs-material mkdocs-git-revision-date-localized-plugin mkdocs-minify-plugin
pip install -U mkdocs-exclude mike mkdocstrings mkdocstrings-python-legacy
pip install -U mkdocs-git-authors-plugin
pip install jinja2==3.0.*
if: success()
- name: git configure
Expand All @@ -65,7 +67,7 @@ jobs:
- name: mike deploy docs release
run: |
echo "${{ env.NAME_RELEASE }}"
mike deploy --push --update-aliases --no-redirect ${{ env.NAME_RELEASE }} ${{ env.RELEASE_NAME }} --title=${{ env.RELEASE_NAME }}
mike deploy --push --update-aliases --alias-type=copy ${{ env.NAME_RELEASE }} ${{ env.RELEASE_NAME }} --title=${{ env.RELEASE_NAME }}
env:
NAME_RELEASE: "v${{ env.RELEASE_NAME }}-release"
if: success()
Expand All @@ -88,7 +90,9 @@ jobs:
if: success()
- name: install_dependencies
run: |
pip install -U mkdocs mkdocs-material mkdocs-git-revision-date-localized-plugin mkdocs-minify-plugin mkdocs-exclude mike mkdocstrings mkdocstrings-python-legacy
pip install -U mkdocs mkdocs-material mkdocs-git-revision-date-localized-plugin mkdocs-minify-plugin
pip install -U mkdocs-exclude mike mkdocstrings mkdocstrings-python-legacy
pip install -U mkdocs-git-authors-plugin
pip install jinja2==3.0.*
if: success()
- name: git configure
Expand All @@ -106,7 +110,7 @@ jobs:
- name: mike deploy docs stable
run: |
echo "${{ env.NAME_STABLE }}"
mike deploy --push --update-aliases --no-redirect ${{ env.NAME_STABLE }} latest --title=latest
mike deploy --push --update-aliases --alias-type=copy ${{ env.NAME_STABLE }} latest --title=latest
mike set-default --push latest
env:
NAME_STABLE: "v${{ env.RELEASE_NAME }}-stable"
Expand All @@ -131,7 +135,9 @@ jobs:
if: success()
- name: install_dependencies
run: |
pip install -U mkdocs mkdocs-material mkdocs-git-revision-date-localized-plugin mkdocs-minify-plugin mkdocs-exclude mike mkdocstrings mkdocstrings-python-legacy
pip install -U mkdocs mkdocs-material mkdocs-git-revision-date-localized-plugin mkdocs-minify-plugin
pip install -U mkdocs-exclude mike mkdocstrings mkdocstrings-python-legacy
pip install -U mkdocs-git-authors-plugin
pip install jinja2==3.0.*
if: success()
- name: git configure
Expand All @@ -149,7 +155,7 @@ jobs:
- name: mike deploy docs dev
run: |
echo "Releasing ${{ env.NAME_DEV }}"
mike deploy --push --update-aliases --no-redirect ${{ env.NAME_DEV }} dev --title=dev
mike deploy --push --update-aliases --alias-type=copy ${{ env.NAME_DEV }} dev --title=dev
env:
NAME_DEV: "v${{ env.RELEASE_NAME }}-dev"
if: success()
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ venv
Pipfile.lock
env3.*
env
.cache
.coverage
coverage.xml
.netlify
Expand Down
71 changes: 40 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ limitations under the License.

&nbsp;

VidGear is a **High-Performance Video Processing Python Library** that provides an easy-to-use, highly extensible, thoroughly optimised **Multi-Threaded + Asyncio API Framework** on top of many state-of-the-art specialized libraries like _[OpenCV][opencv], [FFmpeg][ffmpeg], [ZeroMQ][zmq], [picamera][picamera], [starlette][starlette], [yt_dlp][yt_dlp], [pyscreenshot][pyscreenshot], [dxcam][dxcam], [aiortc][aiortc] and [python-mss][mss]_ serving at its backend, and enable us to flexibly exploit their internal parameters and methods, while silently delivering **robust error-handling and real-time performance 🔥**
VidGear is a **High-Performance Video Processing Python Library** that provides an easy-to-use, highly extensible, thoroughly optimised **Multi-Threaded + Asyncio API Framework** on top of many state-of-the-art specialized libraries like _[OpenCV][opencv], [FFmpeg][ffmpeg], [ZeroMQ][zmq], [picamera2][picamera2], [starlette][starlette], [yt_dlp][yt_dlp], [pyscreenshot][pyscreenshot], [dxcam][dxcam], [aiortc][aiortc] and [python-mss][mss]_ serving at its backend, and enable us to flexibly exploit their internal parameters and methods, while silently delivering **robust error-handling and real-time performance 🔥**

VidGear primarily focuses on simplicity, and thereby lets programmers and software developers to easily integrate and perform Complex Video Processing Tasks, in just a few lines of code.

Expand Down Expand Up @@ -122,7 +122,7 @@ Each API is designed exclusively to handle/control/process different data-specif
**A. Video-Capture Gears:**

- [**CamGear:**](#camgear) Multi-Threaded API targeting various IP-USB-Cameras/Network-Streams/Streaming-Sites-URLs.
- [**PiGear:**](#pigear) Multi-Threaded API targeting various Raspberry-Pi Camera Modules.
- [**PiGear:**](#pigear) Multi-Threaded API targeting various Camera Modules and _(limited)_ USB cameras on Raspberry Pis :grapes:.
- [**ScreenGear:**](#screengear) High-performance API targeting rapid Screencasting Capabilities.
- [**VideoGear:**](#videogear) Common Video-Capture API with internal [Video Stabilizer](https://abhitronix.github.io/vidgear/latest/gears/stabilizer/overview/) wrapper.

Expand Down Expand Up @@ -265,27 +265,35 @@ stream_stab.stop()
<img src="https://abhitronix.github.io/vidgear/latest/assets/images/picam2.webp" alt="PiGear" width="50%" />
</p>

> _PiGear is similar to CamGear but made to support various Raspberry Pi Camera Modules _(such as [OmniVision OV5647 Camera Module][ov5647-picam] and [Sony IMX219 Camera Module][imx219-picam])_._
> _PiGear is a specialized API similar to the [CamGear API](#camgear) but optimized for **Raspberry Pi :grapes: Boards**, offering comprehensive **support for camera modules** _(e.g., [OmniVision OV5647 Camera Module][ov5647-picam], [Sony IMX219 Camera Module][imx219-picam])_, along with **limited compatibility for USB cameras**._
PiGear provides a flexible multi-threaded framework around complete [picamera](https://picamera.readthedocs.io/en/release-1.13/index.html) python library, and provide us the ability to exploit almost all of its parameters like `brightness, saturation, sensor_mode, iso, exposure, etc.` effortlessly. Furthermore, PiGear also supports multiple camera modules, such as in the case of Raspberry-Pi Compute Module IO boards.
PiGear implements a seamless and robust wrapper around the [picamera2][picamera2] python library, simplifying integration with minimal code changes and ensuring a smooth transition for developers already familiar with the Picamera2 API. PiGear leverages the `libcamera` API under the hood with multi-threading, providing high-performance :fire:, enhanced control and functionality for Raspberry Pi camera modules.

PiGear handles common configuration parameters and non-standard settings for various camera types, simplifying the integration process. PiGear currently supports PiCamera2 API parameters such as `sensor`, `controls`, `transform`, and `format` etc., with internal type and sanity checks for robust performance.

While primarily focused on Raspberry Pi camera modules, PiGear also provides **basic functionality for USB webcams** only with Picamera2 API, along with the ability to accurately differentiate between USB and Raspberry Pi cameras using metadata.

PiGear seamlessly switches to the legacy [picamera][picamera] library if the `picamera2` library is unavailable, ensuring seamless backward compatibility. For this, PiGear also provides a flexible multi-threaded framework around complete `picamera` API, allowing developers to effortlessly exploit a wide range of parameters, such as `brightness`, `saturation`, `sensor_mode`, `iso`, `exposure`, and more.

Furthermore, PiGear supports the use of multiple camera modules, including those found on Raspberry Pi Compute Module IO boards and USB cameras _(only with Picamera2 API)_.

Best of all, PiGear contains **Threaded Internal Timer** - that silently keeps active track of any frozen-threads/hardware-failures and exit safely, if any does occur. That means that if you're running PiGear API in your script and someone accidentally pulls the Camera-Module cable out, instead of going into possible kernel panic, API will exit safely to save resources.

**Code to open picamera stream with variable parameters in PiGear API:**
**Code to open picamera2 stream with variable parameters in PiGear API:**

```python
# import required libraries
from vidgear.gears import PiGear
from libcamera import Transform
import cv2

# add various Picamera tweak parameters to dictionary
# formulate various Picamera2 API
# configurational parameters
options = {
"hflip": True,
"exposure_mode": "auto",
"iso": 800,
"exposure_compensation": 15,
"awb_mode": "horizon",
"sensor_mode": 0,
"controls": {"Brightness": 0.5, "ExposureValue": 2.0},
"transform": Transform(hflip=1),
"sensor": {"output_size": (480, 320)}, # will override `resolution`
"format": "RGB888", # 8-bit BGR
}

# open pi video stream with defined parameters
Expand Down Expand Up @@ -316,7 +324,6 @@ cv2.destroyAllWindows()

# safely close video stream
stream.stop()

```

### PiGear API Guide:
Expand Down Expand Up @@ -420,21 +427,21 @@ In addition to this, WriteGear also provides flexible access to [**OpenCV's Vide
<img src="https://abhitronix.github.io/vidgear/latest/assets/images/streamgear_flow.webp" alt="NetGear API" width=80%/>
</p>

> _StreamGear automates transcoding workflow for generating Ultra-Low Latency, High-Quality, Dynamic & Adaptive Streaming Formats (such as MPEG-DASH and Apple HLS) in just few lines of python code._
> _StreamGear streamlines and simplifies the transcoding workflow to generate Ultra-Low Latency, High-Quality, Dynamic & Adaptive Streaming Formats like MPEG-DASH and Apple HLS with just a few lines of Python code, allowing developers to focus on their application logic rather than dealing with the complexities of transcoding and chunking media files._
StreamGear provides a standalone, highly extensible, and flexible wrapper around [**FFmpeg**][ffmpeg] multimedia framework for generating chunked-encoded media segments of the content.
StreamGear API provides a standalone, highly extensible, and flexible wrapper around the [**FFmpeg**](https://ffmpeg.org/) multimedia framework for generating chunk-encoded media segments from your multimedia content effortlessly.

SteamGear is an out-of-the-box solution for transcoding source videos/audio files & real-time video frames and breaking them into a sequence of multiple smaller chunks/segments of suitable lengths. These segments make it possible to stream videos at different quality levels _(different bitrates or spatial resolutions)_ and can be switched in the middle of a video from one quality level to another – if bandwidth permits – on a per-segment basis. A user can serve these segments on a web server that makes it easier to download them through HTTP standard-compliant GET requests.
With StreamGear, you can transcode source video/audio files and real-time video frames into a sequence of multiple smaller chunks/segments of suitable lengths. These segments facilitate streaming at different quality levels _(bitrates or spatial resolutions)_ and allow for seamless switching between quality levels during playback based on available bandwidth. You can serve these segments on a web server, making them easily accessible via standard **HTTP GET** requests.

SteamGear currently supports [**MPEG-DASH**](https://www.encoding.com/mpeg-dash/) _(Dynamic Adaptive Streaming over HTTP, ISO/IEC 23009-1)_ and [**Apple HLS**](https://developer.apple.com/documentation/http_live_streaming) _(HTTP Live Streaming)_. But, Multiple DRM support is yet to be implemented.
SteamGear currently supports both [**MPEG-DASH**](https://www.encoding.com/mpeg-dash/) _(Dynamic Adaptive Streaming over HTTP, ISO/IEC 23009-1)_ and [**Apple HLS**](https://developer.apple.com/documentation/http_live_streaming) _(HTTP Live Streaming)_.

SteamGear also creates a Manifest file _(such as MPD in-case of DASH)_ or a Master Playlist _(such as M3U8 in-case of Apple HLS)_ besides segments that describe these segment information _(timing, URL, media characteristics like video resolution and bit rates)_ and is provided to the client before the streaming session.
Additionally, StreamGear generates a manifest file _(such as MPD for DASH)_ or a master playlist _(such as M3U8 for Apple HLS)_ alongside the segments. These files contain essential segment information, _including timing, URLs, and media characteristics like video resolution and adaptive bitrates_. They are provided to the client before the streaming session begins.

**StreamGear primarily works in two Independent Modes for transcoding which serves different purposes:**

- **Single-Source Mode:** In this mode, StreamGear **transcodes entire video file** _(as opposed to frame-by-frame)_ into a sequence of multiple smaller chunks/segments for streaming. This mode works exceptionally well when you're transcoding long-duration lossless videos(with audio) for streaming that required no interruptions. But on the downside, the provided source cannot be flexibly manipulated or transformed before sending onto FFmpeg Pipeline for processing. **_Learn more about this mode [here ➶][ss-mode-doc]_**
- **Single-Source Mode 💿 :** In this mode, StreamGear **transcodes entire video file** _(as opposed to frame-by-frame)_ into a sequence of multiple smaller chunks/segments for streaming. This mode works exceptionally well when you're transcoding long-duration lossless videos(with audio) for streaming that required no interruptions. But on the downside, the provided source cannot be flexibly manipulated or transformed before sending onto FFmpeg Pipeline for processing. **_Learn more about this mode [here ➶][ss-mode-doc]_**

- **Real-time Frames Mode:** In this mode, StreamGear directly **transcodes frame-by-frame** _(as opposed to a entire video file)_, into a sequence of multiple smaller chunks/segments for streaming. This mode works exceptionally well when you desire to flexibility manipulate or transform [`numpy.ndarray`](https://numpy.org/doc/1.18/reference/generated/numpy.ndarray.html#numpy-ndarray) frames in real-time before sending them onto FFmpeg Pipeline for processing. But on the downside, audio has to added manually _(as separate source)_ for streams. **_Learn more about this mode [here ➶][rtf-mode-doc]_**
- **Real-time Frames Mode 🎞️ :** In this mode, StreamGear directly **transcodes frame-by-frame** _(as opposed to a entire video file)_, into a sequence of multiple smaller chunks/segments for streaming. This mode works exceptionally well when you desire to flexibility manipulate or transform [`numpy.ndarray`](https://numpy.org/doc/1.18/reference/generated/numpy.ndarray.html#numpy-ndarray) frames in real-time before sending them onto FFmpeg Pipeline for processing. But on the downside, audio has to added manually _(as separate source)_ for streams. **_Learn more about this mode [here ➶][rtf-mode-doc]_**

### StreamGear API Guide:

Expand Down Expand Up @@ -508,9 +515,9 @@ from vidgear.gears.asyncio import WebGear
# various performance tweaks
options = {
"frame_size_reduction": 40,
"frame_jpeg_quality": 80,
"frame_jpeg_optimize": True,
"frame_jpeg_progressive": False,
"jpeg_compression_quality": 80,
"jpeg_compression_fastdct": True,
"jpeg_compression_fastupsample": False,
}

# initialize WebGear app
Expand Down Expand Up @@ -650,7 +657,7 @@ It is something I am doing with my own free time. But so much more needs to be d

Here is a Bibtex entry you can use to cite this project in a publication:

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.8174694.svg)](https://doi.org/10.5281/zenodo.8174694)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.8332548.svg)](https://doi.org/10.5281/zenodo.8332548)

```BibTeX
@software{vidgear,
Expand All @@ -660,18 +667,19 @@ Here is a Bibtex entry you can use to cite this project in a publication:
Christian Hollinger and
Ian Max Andolina and
Vincent Boivin and
enarche-ahn and
Kyle Ahn and
freol35241 and
Benjamin Lowe and
Mickaël Schoentgen and
Renaud Bouckenooghe},
title = {abhiTronix/vidgear: VidGear v0.3.1},
month = jul,
Renaud Bouckenooghe and
Ibtsam Ahmad},
title = {abhiTronix/vidgear: VidGear Stable v0.3.2},
month = sep,
year = 2023,
publisher = {Zenodo},
version = {vidgear-0.3.1},
doi = {10.5281/zenodo.8174694},
url = {https://doi.org/10.5281/zenodo.8174694}
version = {vidgear-0.3.2},
doi = {10.5281/zenodo.8332548},
url = {https://doi.org/10.5281/zenodo.8332548}
}
```

Expand Down Expand Up @@ -807,5 +815,6 @@ External URLs
[zmq-req-rep]: https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/patterns/client_server.html
[zmq-pub-sub]: https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/patterns/pubsub.html
[zmq-pull-push]: https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/patterns/pushpull.html#push-pull
[picamera2]:https://github.com/raspberrypi/picamera2
[picamera-setting]: https://picamera.readthedocs.io/en/release-1.13/quickstart.html
[webrtc]: https://webrtc.org/
5 changes: 3 additions & 2 deletions appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,10 @@ install:
- "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
- "python --version"
- "python -m pip install --upgrade pip wheel"
- "python -m pip install .[asyncio] six codecov httpx pytest-cov pytest-asyncio yt_dlp aiortc paramiko m3u8 async-asgi-testclient"
- cmd: python -m pip install "numpy<2.0.0"
- "python -m pip install --upgrade .[asyncio] six httpx yt_dlp aiortc"
- "python -m pip install --upgrade pytest codecov pytest-cov pytest-asyncio m3u8 async-asgi-testclient paramiko"
- "python -m pip install --upgrade deffcode"
- "python -m pip install cryptography==38.0.4"
- "python -m pip install https://github.com/abhiTronix/python-mpegdash/releases/download/0.3.0-dev2/mpegdash-0.3.0.dev2-py3-none-any.whl"
- cmd: chmod +x scripts/bash/prepare_dataset.sh
- cmd: bash scripts/bash/prepare_dataset.sh
Expand Down
10 changes: 5 additions & 5 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ steps:
displayName: "Prepare dataset"
- script: |
python -m pip install --upgrade pip wheel
pip install --upgrade .[asyncio] six codecov yt_dlp httpx mpegdash paramiko m3u8 async-asgi-testclient
pip install --upgrade deffcode
pip install cryptography==38.0.4
pip install --upgrade pytest pytest-asyncio pytest-cov pytest-azurepipelines
python -m pip install -U pip wheel
python -m pip install "numpy<2.0.0"
python -m pip install -U .[asyncio] yt_dlp httpx six paramiko
python -m pip install -U codecov pytest pytest-asyncio pytest-cov mpegdash m3u8 async-asgi-testclient
python -m pip install -U deffcode
displayName: "Install pip dependencies"
- script: |
Expand Down
Loading

0 comments on commit 5f4127b

Please sign in to comment.