Skip to content

feat: Swift Package Manager support for iOS and macOS - #1142

Merged
hiroshihorie merged 10 commits into
mainfrom
hiroshi/swift-package-manager
Aug 3, 2026
Merged

hiroshihorie merged 10 commits into
mainfrom
hiroshi/swift-package-manager

Conversation

@hiroshihorie

@hiroshihorie hiroshihorie commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

What

Adds Swift Package Manager support for the iOS and macOS plugins, following the Flutter SPM plugin convention:

  • ios/livekit_client/Package.swift and macos/livekit_client/Package.swift, with Sources/livekit_client/ symlink trees into shared_swift/ (and the iOS broadcast files in ios/Classes/), so the existing sources stay the single source of truth.
  • The packages depend on flutter_webrtc's Swift package (../flutter_webrtc, resolved by the Flutter tool) and consume its flutter-webrtc and WebRTC products. Reusing flutter_webrtc's WebRTC binary target keeps a single copy of the xcframework in the package graph, mirroring how the podspecs share the WebRTC-SDK pod today.
  • The example app's Xcode projects get the SPM integration committed (package reference, product dependency, prepare pre-action in the Runner scheme), matching what flutter would generate.

CocoaPods is unchanged: podspecs and Classes/ are untouched, and apps with SPM disabled keep building through pods.

Depends on

Testing

With Flutter 3.44.1 (SPM on by default) and a local dependency_overrides pointing flutter_webrtc at the PR 2062 branch:

  • flutter build macos --debug and flutter build ios --debug --simulator of the example both succeed.
  • Both plugins compile as Swift packages (verified LiveKitPlugin / FlutterWebRTCPlugin symbols in the app binaries) with exactly one embedded WebRTC.framework.
  • permission_handler_apple has no SPM support and keeps building through CocoaPods in hybrid mode.

Note for local testing: the Flutter tool copies plugins that declare SwiftPM dependencies on other plugins into the app's build directory with rsync. With the example app living inside this repo that copy recurses into itself (flutter_tools bug, to be filed upstream). Workaround is to make example/build a symlink to a directory outside the repo before building.


Update 2026-08-03

flutter_webrtc 1.6.0 shipped with Swift Package Manager support, so this PR is unblocked:

  • Bumped the pinned flutter_webrtc to 1.6.0 and removed the need for any local overrides. Verified the example builds via SPM against the released package from pub.dev, including the versioned pub cache path rewrite.
  • Added a CI step to the iOS and macOS jobs that symlinks example/build outside the repository, working around the Flutter tool's rsync recursion when a plugin with SwiftPM plugin dependencies hosts its own example app (upstream flutter_tools bug, to be filed).
  • Merged main (RPC tester, data stream fix, Dart 3.13 fixes).

Adds ios/livekit_client and macos/livekit_client Swift packages using
the Flutter SPM plugin layout. Sources are symlinks into shared_swift
and ios/Classes so they stay the single source of truth. CocoaPods
integration is unchanged and both podspecs keep working as before.

The packages depend on flutter_webrtc's Swift package for the WebRTC
framework, mirroring the podspec dependency. Requires a flutter_webrtc
release that includes its own SPM support (PR 2062).
…S projects

Mirrors the changes flutter's automatic SPM migration makes (package
reference, product dependency, and the prepare pre-action in the Runner
scheme). Committing them avoids the migration step at build time, which
currently fails to validate projects whose plugins declare SwiftPM
dependencies on other plugins. CocoaPods phases are untouched so the
example still builds with SPM disabled.
hiroshihorie added a commit to flutter-webrtc/flutter-webrtc that referenced this pull request Jul 29, 2026
Restructure plugin sources from Classes/ into the Flutter SPM convention
flutter_webrtc/Sources/flutter_webrtc/ with public headers under
include/flutter_webrtc/. Source symlinks into common/darwin/Classes are
preserved so it remains the single source of truth.

- Add ios/flutter_webrtc/Package.swift and
macos/flutter_webrtc/Package.swift,
  both pulling WebRTC 144.7559.04 directly via .binaryTarget against the
xcframework release asset (bypasses webrtc-sdk/Specs Package.swift,
which
  declares .visionOS(.v26) under swift-tools 5.9 and fails to compile).
- Update both podspecs to point at the new Sources/ layout and add
  USER_HEADER_SEARCH_PATHS so quoted #import "Foo.h" keeps resolving.
- Drop the broken stub macos/Package.swift in favor of the new location.
- Example: deintegrate CocoaPods from macOS (all macOS deps are
SPM-ready)
  and from iOS after removing permission_handler and gallery_saver_plus
  from pubspec and the two samples that referenced them, since neither
  ships a Package.swift upstream.

Verified with Flutter 3.41 + Xcode 26.5: flutter build macos and an
xcodebuild iphonesimulator build of the example both succeed.

close #2045, close #2027

---

## Update 2026-07-29 (takeover by @hiroshihorie)

Changes since the original description:

- Caught up with main (twice), no conflicts beyond CHANGELOG.
- Bumped the Package.swift binary targets from WebRTC 144.7559.04 to
144.7559.09 to match the podspecs. The mute mode APIs merged from main
only exist in .09, so the old pin no longer compiled. This also fixes
the `isPlatformVoiceProcessingAllowed` error reported in the comments.
- Exported the WebRTC binary target as a library product so dependent
plugins (livekit_client, see livekit/client-sdk-flutter#1142) can reuse
it instead of declaring a colliding second copy.
- Restored `permission_handler` to the example. permission_handler_apple
9.4.10 now ships a Package.swift, so it no longer blocks the CocoaPods
free example. `gallery_saver_plus` stays removed (no SPM support
upstream), a replacement using `gal` can land separately.
- Removed the leftover `ios/Classes` and `macos/Classes` platform view
symlinks that came back through merges. The podspecs point at the
`Sources/` layout, so they were dead.
- Synced the podspec versions with pubspec (1.5.2).
- CI: the iOS and macOS jobs now build the example with both SPM and
CocoaPods, and a new job checks the WebRTC-SDK version stays in sync
across the two podspecs and two Package.swift files.
- Docs: CHANGELOG entry and a README section on Swift Package Manager
support.
- Documented in macos/Package.swift why ScreenCaptureKit ends up weak
linked (verified LC_LOAD_WEAK_DYLIB in the built app), matching the
podspec's weak_frameworks.

The CI blocker mentioned in the comments (flutter/flutter#186054) was
fixed in Flutter 3.44.2, and all jobs are green in both dependency
manager modes.

Verified with Flutter 3.44.1 + Xcode 26.6: example builds for macOS and
iOS simulator via SPM and via CocoaPods, and livekit_client consumes
this branch successfully through both SPM and CocoaPods on both
platforms.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com>
The Flutter tool copies plugins that declare SwiftPM dependencies on
other plugins into the app build directory with rsync. The example app
lives inside the plugin repo, so that copy would recurse into its own
output. Symlink example/build into RUNNER_TEMP before building.
@hiroshihorie
hiroshihorie marked this pull request as ready for review August 3, 2026 08:03
devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

The manual SPM integration was committed from a working tree where a
hybrid pod install had already trimmed the phase. Restore it from main
so the checked in projects stay correct for CocoaPods only builds and
the pbxproj diff is purely additive.
@hiroshihorie
hiroshihorie merged commit 4ac8674 into main Aug 3, 2026
15 checks passed
@hiroshihorie
hiroshihorie deleted the hiroshi/swift-package-manager branch August 3, 2026 09:32
@hiroshihorie hiroshihorie mentioned this pull request Aug 3, 2026
hiroshihorie added a commit that referenced this pull request Aug 3, 2026
## What

Folds the pending changesets into the 2.10.0 release. Version propagated
by `scripts/create_version.dart`, all version checks pass, `.changes/`
emptied.

## Changelog

* Added: Swift Package Manager support for iOS and macOS. CocoaPods
remains fully supported. (#1142)
* Added: `ScreenSelectDialog.show` and
`Hardware.requestCapturePermission` so apps can start screen share
without importing flutter_webrtc (#1147)
* Fixed: Compile errors on Dart 3.13 where nullable publish options are
no longer promoted across await (#1146)
* Fixed: Omit data stream totalLength when size is unknown (#1141)
* Fixed: Harden the example RPC tester (#1085)

Minor bump driven by the SPM and screen share additions.

## Why now

Dart 3.13 (Flutter 3.47 beta, soon stable) fails to compile every
published livekit_client, so #1146 needs to ship before 3.47 lands. The
screen share helpers unblock livekit/components-flutter#52, which
removes the flutter_webrtc pin conflict that downgrades users to
livekit_client 2.6.1 (livekit/components-flutter#49).

## After merge

Tag `v2.10.0` to publish. First run of the reworked publish workflow
from #1140 (tag guard, pin-warning-only validation gate, forced
publish).

Downstream: components-flutter #52 switches to `livekit_client:
^2.10.0`, then a components release and an agent-starter-flutter bump.
shivanshtalwar0 added a commit to januscaler/flutter-webrtc that referenced this pull request Nov 13, 2026
* WebRTC v144.7559.04 (#2040)

* Fix for java.lang.IllegalStateException: MediaStreamTrack has been disposed. in android when app is swipe killed after webrtc session (#2033)

Instead of throwing error below
## before this fix
<details>
<summary>Error</summary>
D/FlutterWebRTCPlugin(14635): streamDispose(): audio track already
disposed, skipping
W/FlutterWebRTCPlugin(14635): dispose(): error disposing media stream
W/FlutterWebRTCPlugin(14635): java.lang.IllegalStateException:
MediaStreamTrack has been disposed.
W/FlutterWebRTCPlugin(14635): at
org.webrtc.MediaStreamTrack.checkMediaStreamTrackExists(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:14)
W/FlutterWebRTCPlugin(14635): at
org.webrtc.MediaStreamTrack.getNativeMediaStreamTrack(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:1)
W/FlutterWebRTCPlugin(14635): at
org.webrtc.AudioTrack.getNativeAudioTrack(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:1)
W/FlutterWebRTCPlugin(14635): at
org.webrtc.MediaStream.removeTrack(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:3)
W/FlutterWebRTCPlugin(14635): at
org.webrtc.MediaStream.dispose(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:21)
W/FlutterWebRTCPlugin(14635): at
com.cloudwebrtc.webrtc.MethodCallHandlerImpl.dispose(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:26)
W/FlutterWebRTCPlugin(14635): at
com.cloudwebrtc.webrtc.FlutterWebRTCPlugin.stopListening(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:3)
W/FlutterWebRTCPlugin(14635): at
com.cloudwebrtc.webrtc.FlutterWebRTCPlugin.onDetachedFromEngine(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:1)
W/FlutterWebRTCPlugin(14635): at
ha.c.a(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:109)
W/FlutterWebRTCPlugin(14635): at
ga.h.f(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:158)
W/FlutterWebRTCPlugin(14635): at
ga.d.onDestroy(r8-map-id-45b5861c0d00c6ac231d617c95780bf88af2e5cadeaf5f07124b8c55825e2bc0:19)
W/FlutterWebRTCPlugin(14635): at
android.app.Activity.performDestroy(Activity.java:9612)
W/FlutterWebRTCPlugin(14635): at
android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1578)
W/FlutterWebRTCPlugin(14635): at
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:6554)
W/FlutterWebRTCPlugin(14635): at
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:6599)
W/FlutterWebRTCPlugin(14635): at
android.app.servertransaction.DestroyActivityItem.execute(DestroyActivityItem.java:52)
W/FlutterWebRTCPlugin(14635): at
android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:63)
W/FlutterWebRTCPlugin(14635): at
android.app.servertransaction.TransactionExecutor.executeLifecycleItem(TransactionExecutor.java:169)
W/FlutterWebRTCPlugin(14635): at
android.app.servertransaction.TransactionExecutor.executeTransactionItems(TransactionExecutor.java:101)
W/FlutterWebRTCPlugin(14635): at
android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:80)
W/FlutterWebRTCPlugin(14635): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2987)
W/FlutterWebRTCPlugin(14635): at
android.os.Handler.dispatchMessageImpl(Handler.java:142)
W/FlutterWebRTCPlugin(14635): at
android.os.Handler.dispatchMessage(Handler.java:125)
W/FlutterWebRTCPlugin(14635): at
android.os.Looper.loopOnce(Looper.java:269)
W/FlutterWebRTCPlugin(14635): at android.os.Looper.loop(Looper.java:367)
W/FlutterWebRTCPlugin(14635): at
android.app.ActivityThread.main(ActivityThread.java:9333)
W/FlutterWebRTCPlugin(14635): at java.lang.reflect.Method.invoke(Native
Method)
W/FlutterWebRTCPlugin(14635): at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:566)
W/FlutterWebRTCPlugin(14635): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:929)
D/FlutterWebRTCPlugin(14635): Stopping the audio manager...

</details>

## after this fix
it  silently logs
```
D/FlutterWebRTCPlugin(15353): streamDispose(): audio track already disposed, skipping
D/FlutterWebRTCPlugin(15353): Stopping the audio manager...
```
without this crash is reported in play store whenever app is swipe
killed after webrtc session

* Fix handling of `KeyDerivationAlgorithm` option (#2049)

Currently on the flutter side, you can set a Key Derivation Algorithm,
but the value is not actually passed to libwebrtc. This correctly parses
the option.


Also tweaking the function `KeyDerivationAlgorithmFromInt` to properly
return `libwebrtc::KeyDerivationAlgorithm` as opposed to the currently
used `libwebrtc::FrameCryptorAlgorithm`

* Fix Android screen capture after orientation changes (#2048)

This fixes Android screen capture frames after device orientation
changes.

Problem:
When an Android device is used as screen-capture host and rotates from
portrait to landscape or back, the remote viewer can receive frames with
black areas, wrong offset, or squashed content. The existing
implementation calls `VirtualDisplay.resize(...)`, but in some devices
this does not fully realign the capture surface/buffer.

Fix:
When the capture format changes, release the existing `VirtualDisplay`
and recreate it using the already authorized `MediaProjection`. This
avoids asking for screen-capture permission again and produces correctly
sized frames after rotation.

Also initialize `oldWidth` and `oldHeight` when capture starts, so the
first frame does not trigger an unnecessary recreate.

Tested:
- Android tablet Samsung SM-T510 as screen-capture host
- iPhone viewer
- Portrait -> landscape -> portrait rotation during active WebRTC
session
- No additional Android screen-capture prompt shown
<img width="585" height="1266" alt="before_horizontal"
src="https://github.com/user-attachments/assets/a0088ab8-e380-4832-b789-59261bcbad4e"
/>
<img width="585" height="1266" alt="before_vertical_after_horizontal"
src="https://github.com/user-attachments/assets/3723c9ee-a697-40d3-8bba-a715044bb356"
/>

Co-authored-by: Matteo Annibali <m.annibali@entersrl.it>

* fix(android): guard muxer writes against codec-config and invalid sample buffers (#2031)

## Summary

This change adds defensive checks before writing encoded samples into
`MediaMuxer` during Android recording shutdown/drain.

## What changed

- Ignore `BUFFER_FLAG_CODEC_CONFIG` buffers
- Skip samples with invalid `offset` / `size`
- Clamp video presentation timestamps to non-negative values

## Why

Without these guards, some recordings can fail during stop/drain with
errors
similar to:

- `bufferInfo must specify a valid buffer offset, size and presentation
time`

These buffers should not be written as regular media samples.

## Expected result

- Cleaner stop path for Android recordings
- Fewer muxer exceptions at the end of recording
- More reliable mp4 finalization

Co-authored-by: yuhan <yunhan@uni-ubi.com>

* fix(android): make VideoFileRenderer more tolerant on Qualcomm/Hisi encoders (#2030)

## Summary

This change makes Android local recording more tolerant on devices where
`MediaCodec.configure(...)` fails for H264 surface encoding, especially
on some
Qualcomm-based devices.

## What changed

- Keep the video `MediaFormat` minimal for surface input encoding
- Avoid forcing `MediaFormat.KEY_PROFILE` on `OMX.qcom.*` and
`OMX.hisi.video.encoder.avc`
- Deduplicate candidate resolutions
- Stop retrying encoder initialization on every frame after all configs
fail
- Fall back to a standalone EGL context if shared context setup fails

## Why

On affected devices, the recorder repeatedly fails during encoder
configuration
with logs similar to:

- `configureCodec returning error -38`
- `MediaCodec configure failed with err 0x80001001`
- `Failed to configure and start encoder with any supported
configuration`

Because initialization is retried from `onFrame(...)`, this can also
cause
severe UI jank and repeated logs.

## Expected result

- Recorder can start successfully on more Android devices
- Failed hardware encoder setups stop retrying indefinitely
- Recording failures no longer degrade UI responsiveness as badly

## Notes

This patch is intentionally conservative and only changes Android
recording
behavior in `VideoFileRenderer`.

Co-authored-by: yuhan <yunhan@uni-ubi.com>

* fix(android): prevent CameraAccessException on concurrent video calls (#2013)

### Context

On Android, opening the same physical camera device twice from one
process triggers the Camera2
winner-takes-all rule: `cameraserver` disconnects the first session
synchronously at the HAL
level, then delivers `onDisconnected` asynchronously - after the HAL
pipeline is already
destroyed.

`CameraCaptureSessionImpl.onDisconnected` (line 805) unconditionally
calls `close()` (line 579)
-> `stopRepeating()` (line 1448) -> `cancelRequest()`, which returns
`ENOSYS (-38)` because the
pipeline no longer exists. This propagates as `CameraAccessException:
CAMERA_ERROR (3)`.

A concrete scenario: two consecutive incoming video calls - call 1
active with camera held, call
2 arriving a few seconds later. The second `getUserMedia(video)`
requests the same camera ID
while call 1's session is still live.

**Reproducible on any Android device including stock Pixel (AOSP) - not
an OEM-specific issue.**
Confirmed on Samsung Galaxy Cover 5, Xiaomi, and Pixel.

---

### What this PR covers

#### Single datasource + fan-out (`getUserVideo`)

Before opening a new camera, `getUserVideo()` scans `mVideoCapturers`
for an existing primary
entry for the same camera. If found, it returns a shared `VideoTrack`
derived from the existing
`VideoSource` via `buildSharedVideoTrack()` - no `startCapture()`, no
new camera connect.
`cameraserver` sees a single client; `onDisconnected` is never
triggered; `ENOSYS` is
structurally impossible.

Camera matching: when the caller passes an explicit `deviceId`, the
check matches by exact
`cameraName == deviceId` (handles multi-camera devices with multiple
back cameras). Without
`deviceId`, falls back to facing-direction match via `isFrontFacing`.

#### New `buildSharedVideoTrack()` method

Creates a secondary `VideoTrack` from the existing `VideoSource` of a
primary entry. The new
`VideoCapturerInfoEx` entry has `capturer = null` and `primaryTrackId`
pointing to the primary,
so the rest of the lifecycle code knows it does not own the camera
session. Returns the same
track settings structure as the primary path, including `facingMode`.

#### `removeVideoCapturer()` - shared track lifecycle

Reworked to handle three cases:

1. **Shared track removed** - entry is unregistered; the underlying
capturer keeps running.
2. **Primary removed while shared tracks exist** - one shared track is
promoted to primary
(receives `capturer`, `cameraEventsHandler`, `SurfaceTextureHelper`);
remaining shared tracks
   are re-pointed to the new primary. Camera keeps running.
3. **Primary removed, no shared tracks** - capturer is stopped and
disposed normally (existing
   behavior).

#### `switchCamera()` - shared track support

Shared entries have `capturer = null`. `switchCamera` now resolves to
the primary entry via
`primaryTrackId` before accessing `capturer`, and handles a missing
entry with an explicit error
instead of a NullPointerException.

#### `reStartCamera()` - skip shared entries

Shared entries have no `capturer`. `reStartCamera` now skips entries
where `primaryTrackId` is
set, avoiding a NullPointerException when the camera is re-opened after
interruption.

#### `VideoCapturerInfoEx` - new fields

| Field | Purpose |
|---|---|
| `videoSource` | The `VideoSource` backing this track; shared across
primary and all its shared entries |
| `primaryTrackId` | Non-null on shared entries; points to the primary
entry that owns the capturer |
| `facingMode` | "user" / "environment" / null; resolved at open time,
propagated to shared entries |

---

### Files changed

| File | Changes |
|---|---|
| `android/src/main/java/com/cloudwebrtc/webrtc/GetUserMediaImpl.java` |
reuse check in getUserVideo, buildSharedVideoTrack (new),
removeVideoCapturer lifecycle, switchCamera primary resolution,
reStartCamera shared-track skip, VideoCapturerInfoEx fields |

---

### Logcat (expected output with reuse active)

```
W  getUserMedia(video): camera already active (track=b5435b4b-...), reusing VideoSource to prevent concurrent camera access
D  buildSharedVideoTrack: created shared track 39f26460-... from primary b5435b4b-...
```

No `CameraAccessException`, no `ENOSYS (-38)`. WebRTC ICE flow proceeds
normally.
`switchCamera` works on both lines.

* Fix android screen capture rotation (#2055)

- Resize the existing VirtualDisplay instead of releasing/recreating it
on orientation changes.
- Advertise H264 decoder support with at least level 4.1
(profile-level-id ...29) to allow higher-resolution iOS screen streams
on Android.

---------

Co-authored-by: Matteo Annibali <m.annibali@entersrl.it>

* Fix Windows CI for VS 2026 (#2059)

* chore: Refactoring the CMake binary download process for Win/Linux. (#2061)

## Summary

Refactor `third_party/CMakeLists.txt` so the prebuilt libwebrtc download
is driven by build context instead of hardcoded strings.

- Move `binary_version` and `download_url` (base) into
`third_party/libwebrtc_version.ini`; CMake parses the INI at configure
time.
- Auto-detect the target OS (`win` / `linux`) from `CMAKE_SYSTEM_NAME`
and the arch (`x64` / `arm64`) from `CMAKE_GENERATOR_PLATFORM` on
Windows or `FLUTTER_TARGET_PLATFORM` / `CMAKE_SYSTEM_PROCESSOR` on
Linux/eLinux.
- Compose the release asset as `libwebrtc-<os>-<arch>-release.zip` and
cache each variant separately under `third_party/downloads/`.
- Normalize the extracted layout: stage into a temp dir and force-rename
the top-level folder to `libwebrtc/`, regardless of what the archive
uses.

Bumping libwebrtc now only requires editing `libwebrtc_version.ini`.

* chore(example): update generated Flutter project files (#2064)

* fix(desktop): map echoCancellation/noiseSuppression/autoGainControl constraints to RTCAudioOptions (#2068)

Fixes #2067

## Problem

Since 1.2.1 the software APM (AEC/NS/AGC) is unconditionally enabled on
Linux/Windows/eLinux. The `echoCancellation`, `noiseSuppression`, and
`autoGainControl` constraint keys are parsed into an
`RTCMediaConstraints` object that is then silently discarded.
`CreateAudioSource` is called without an `RTCAudioOptions` argument, so
all three processing stages default to `true` regardless of the Dart
caller's intent.

`getSettings()` also hardcoded `true` for all three flags, masking the
issue.

## Fix

- Add `getAudioProcessingFlag()`: resolves a boolean flag from all three
constraint shapes — flat W3C key, `mandatory` sub-map, `optional` list
entries (the format the LiveKit SDK and others use).
- Populate an `RTCAudioOptions` struct from the resolved values and pass
it to `CreateAudioSource`.
- For the `audio: true` (boolean) path, keep all processing on to
preserve existing behaviour.
- Report the actual constraint values in `getSettings()`.

Only `common/cpp/src/flutter_media_stream.cc` is changed — shared by
Linux, Windows, and eLinux.

## Test procedure

1. On Linux (Ubuntu with PipeWire or PulseAudio), call `getUserMedia`
with `echoCancellation: false`.
2. Play audio through speakers while recording — echo should be audible
in the captured stream.
3. Repeat with `echoCancellation: true` — echo should be suppressed by
the software AEC.
4. Verify `track.getSettings()['echoCancellation']` returns the value
passed in the constraint.

Co-authored-by: Alfredo Bautista <a.bautista@saltosystems.com>

* Added loopback capture for windows to capture application and desktop audio (#2060)

This pull request introduces system audio (loopback) capture support
during screen sharing, primarily for Windows (using WASAPI Application
Loopback), and lays the groundwork for future Linux support. It adds a
platform-independent `LoopbackCapturer` interface, integrates audio
capture into the screen sharing workflow, and ensures proper resource
management. On non-supported platforms, loopback capture is safely
disabled.

**System audio (loopback) capture support:**

* Added a platform-independent `LoopbackCapturer` interface
(`loopback_capturer.h`), with a factory function to create
platform-specific implementations. On Windows, this uses WASAPI
Application Loopback; on Linux, a stub is provided that returns
`nullptr` (`loopback_capturer.h`, `linux/loopback_capturer_factory.cc`,
`windows/application_loopback_capturer.h`).
[[1]](diffhunk://#diff-c61b759304746ce959be4a2603edd9a98b6777a1b37f2f414390efacfc937228R1-R56)
[[2]](diffhunk://#diff-02f86122d83785dcba9db75085bff3e66e9389c426c50ca197fc61b89ceee982R1-R12)
[[3]](diffhunk://#diff-daf6ce9f55f173527709cc834abe01194d27d3787e1b45361248c9c04aa8b5beR1-R101)
* Integrated loopback audio capture into the `FlutterScreenCapture`
class, including new member variables for managing the capturer and
audio source (`flutter_screen_capture.h`).
[[1]](diffhunk://#diff-ada695c099855f6866a021d043aed319d273665da3630a3fad10240c14882675R7-R11)
[[2]](diffhunk://#diff-ada695c099855f6866a021d043aed319d273665da3630a3fad10240c14882675R61-R66)

**Screen sharing workflow improvements:**

* Updated `GetDisplayMedia` to support an `"audio"` constraint: if
enabled, initializes and starts loopback audio capture, creates a custom
audio source, and attaches the audio track to the media stream. Handles
both success and failure cases gracefully (`flutter_screen_capture.cc`).
* Ensured that loopback capture is stopped and resources are released
when screen sharing is stopped (`flutter_screen_capture.cc`).

**Build system updates:**

* Updated CMake files to include new source files and link necessary
system libraries for Windows and Linux builds (`windows/CMakeLists.txt`,
`linux/CMakeLists.txt`).
[[1]](diffhunk://#diff-67b8036ebec555bc48b9ed2fdf146e80ebfea01c32d9daec8d3aa70a70ec1b1fR32)
[[2]](diffhunk://#diff-67b8036ebec555bc48b9ed2fdf146e80ebfea01c32d9daec8d3aa70a70ec1b1fR57-R63)
[[3]](diffhunk://#diff-25b4e52755fc75324470232b071995ac62664f1532efcf33ce81cdc49b8c64f5R31)

**Minor code cleanup:**

* Suppressed an unnecessary debug print and marked unused parameters in
thumbnail capture (`flutter_screen_capture.cc`).
[[1]](diffhunk://#diff-42fc9abc81eee02107819b93ce0528374fd4c8463a5b3d2e85f625ed3b58cb28L64-R64)
[[2]](diffhunk://#diff-42fc9abc81eee02107819b93ce0528374fd4c8463a5b3d2e85f625ed3b58cb28R168-R169)

For full functionality it depends on PR in libwebrtc
(webrtc-sdk/libwebrtc#140)

Fixes issues:
#1919

---------

Co-authored-by: Tom Träskbäck <tom.traskback@gmail.com>
Co-authored-by: CloudWebRTC <duanweiwei1982@gmail.com>

* feat(audio): allow embedders to own audio session management (#2069)

## Motivation

When FlutterWebRTC is embedded alongside another SDK that wants to own
the platform audio session (e.g. LiveKit) — the `AVAudioSession`
category/mode/route on iOS, or the audio mode/focus/routing on Android —
FlutterWebRTC's own session management conflicts with it.

This PR adds an **opt-in** way for an embedder to take over, with **no
behavior change** for anyone who doesn't opt in.

## What's added

**1. Disable FlutterWebRTC's own audio session management**

- iOS: `+ [FlutterWebRTCPlugin setAudioSessionManagementEnabled:]`
- Android:
`AudioSwitchManager.setAudioSessionManagementEnabled(boolean)`

When disabled, FlutterWebRTC no longer touches the `AVAudioSession` /
`AudioSwitch` (category, mode, focus, routing, speaker). Microphone mute
is intentionally left working. On Android the `AudioSwitch` is now
created lazily and is never created while disabled.

**2. Expose the audio device module delegate (darwin)**

- `+ [FlutterWebRTCPlugin setAudioDeviceModuleObserver:]`

Lets an embedder receive the audio engine lifecycle callbacks
(`willEnableEngine` / `didDisableEngine` / …) and drive audio-session
policy from real engine events. Held weakly and wired onto the peer
connection factory's audio device module at creation time; only
overrides the observer when one is registered.

## Compatibility

Both switches default to **enabled** (`YES` / `true`), so existing
consumers are unaffected. They are process-global statics intended to be
set once from native code (e.g. another plugin's registration) before
any audio operation.

## Usage

```objc
// iOS — from the embedding plugin's registration, before any audio op:
[FlutterWebRTCPlugin setAudioSessionManagementEnabled:NO];
[FlutterWebRTCPlugin setAudioDeviceModuleObserver:myDelegate];
```

```java
// Android
AudioSwitchManager.setAudioSessionManagementEnabled(false);
```

## Other

Bumps `com.github.davidliu:audioswitch` to `039a35a…`, the revision that
exposes `CommDeviceAudioSwitch`, to align with downstream consumers.

## Platforms

iOS + Android (management switch); iOS/darwin (ADM delegate hook). macOS
unchanged.

* Enable platform rendering for macOS (#2058)

* Enable platform rendering for macOS.
* Organize code for iOS / macOS.

* feat(android): expose the peer connection factory to embedders (#2077)

## What

Adds a public `getPeerConnectionFactory()` accessor on the Android
`FlutterWebRTCPlugin`, forwarding to the existing factory held by
`MethodCallHandlerImpl`.

## Why

Native plugins that interop with flutter_webrtc sometimes need the
shared `PeerConnectionFactory` to call factory-scoped WebRTC APIs. On
iOS this is already possible since `FlutterWebRTCPlugin` exposes
`peerConnectionFactory` as a public property, but on Android the factory
is private to the method call handler. This adds the missing counterpart
so both platforms behave the same.

Concrete example: WebRTC-SDK exposes engine-wide state on the factory
(e.g. `PeerConnectionFactory.getAudioProcessingState()` in 144.7559.09),
and the LiveKit Flutter SDK reads it through this accessor.

## Notes

- 5 lines + 1 import, no behavior change, nothing else touched.
- `getPeerConnectionFactory()` on `MethodCallHandlerImpl` already
exists, this only makes it reachable from the plugin instance.

* chore(android): support AGP 9 built-in Kotlin (#2075)

## What this does

Migrates the Android plugin to AGP 9's built-in Kotlin while keeping
older toolchains building:

- Apply the **Kotlin Gradle Plugin only when built-in Kotlin is
inactive** — AGP < 9, or AGP 9 with `android.builtInKotlin=false`. When
AGP 9's built-in Kotlin is active it registers the `kotlin` extension
itself and rejects KGP, so applying it is skipped.
- Set the JVM target through the `kotlin { compilerOptions {} }` DSL
**when the extension supports it** (KGP 1.9+ / AGP 9 built-in Kotlin),
falling back to the legacy `kotlinOptions` DSL otherwise.
- Bump the standalone buildscript fallbacks (AGP 7.1.1 → 8.1.0, KGP
1.8.10 → 2.1.0) so they're self-consistent.
- Drop the explicit `kotlin-stdlib-jdk7` dependency; KGP and AGP 9
built-in Kotlin add the standard library automatically.

## Why the conditional logic

The plugin is consumed by apps across a wide range of Flutter / AGP /
Kotlin versions, so two compatibility points shape the config:

- **Kotlin Gradle Plugin version.** The `kotlin { compilerOptions {} }`
DSL requires KGP 1.9+ — `KotlinAndroidProjectExtension.compilerOptions`
doesn't exist before then. Flutter app templates before 3.29 still
declare Kotlin 1.8.22, so the plugin feature-detects `compilerOptions`
and falls back to `kotlinOptions`. Without that fallback, those apps
fail at configuration with:
  ```
> Could not find method compilerOptions() for arguments [...] on
extension 'kotlin'
  ```
- **`android.builtInKotlin` flag.** Flutter currently ships AGP 9 with
`android.builtInKotlin=false` by default (flutter/flutter#183910) —
built-in Kotlin off, KGP still required. Gating on the AGP major version
alone would skip `kotlin-android` there and leave the module with no
`kotlin` extension:
  ```
  > Extension with name 'kotlin' does not exist.
  ```
So the plugin gates on whether built-in Kotlin is *actually active*
(`agpMajor >= 9 && android.builtInKotlin != false`).

## Testing

`flutter build apk --debug`, plugin consumed by an example / probe app:

| Flutter | App toolchain | Path exercised | Result |
|---|---|---|---|
| 3.44.1 | AGP 8.6.0, KGP 2.1.0 | `compilerOptions` DSL | ✅ |
| 3.41.6 | AGP 8.6.0, KGP 1.8.22 | `kotlinOptions` fallback | ✅ |
| 3.44.1 | AGP 9.0.1, `builtInKotlin=false` (template default) | applies
KGP | ✅ |
| 3.41.6 | KGP 1.8.22, unguarded `compilerOptions` (control) | — | ❌ —
confirms the fallback is needed |
| 3.44.1 | AGP 9.0.1 `builtInKotlin=false`, AGP-version-only gate
(control) | — | ❌ — confirms the `builtInKotlin` gate is needed |

Built-in-Kotlin-*active* (`android.builtInKotlin=true`) is not reachable
on shipping Flutter yet: Flutter 3.44.1's Gradle plugin auto-applies
`kotlin-android` to Kotlin-source modules, which collides with it. For
that future path the gate skips KGP and the `kotlin { compilerOptions {}
}` DSL drives the JVM target.

Supersedes #2063. Fixes #2053, closes #2056.

* chore(deps): bump WebRTC-SDK to 144.7559.09 and libwebrtc to m144.7559.09 (#2078)

## What

Bumps all prebuilt WebRTC binaries to the M144.7559.09 line, built from
webrtc-sdk/webrtc@b1800a61db8320af5c14456c13622d8b85b1ed39:

- **Android** (maven `io.github.webrtc-sdk:android`): `144.7559.04` →
`144.7559.09`
- **iOS / macOS** (CocoaPods `WebRTC-SDK`): `144.7559.04` →
`144.7559.09`
- **Windows / Linux** (prebuilt libwebrtc via
`third_party/libwebrtc_version.ini`): `libwebrtc.m144.7559.02` →
`libwebrtc.m144.7559.09` — first bump through the ini mechanism from
#2061

Coming from `.04`, this picks up the runtime audio processing options
API (webrtc-sdk/webrtc#247) and the factory-owned audio processing state
v2 (webrtc-sdk/webrtc#254), among everything else in `.05`–`.09`.

## API migration

One ADM property was renamed in 144.7559.09:
`RTCAudioDeviceModule.isVoiceProcessingEnabled` is now
`isPlatformVoiceProcessingAllowed`. The single call site is migrated;
the Dart-facing `isVoiceProcessingEnabled` method-channel name is
unchanged. Other WebRTC-SDK consumers using the old property will need
the same one-line change when they bump.

## Draft until

- [x] CocoaPods `WebRTC-SDK 144.7559.09` on trunk
- [x] maven `io.github.webrtc-sdk:android:144.7559.09` published
(webrtc-sdk/android#49)
- [x] `libwebrtc.m144.7559.09` release assets attached

All artifacts are published — ready for review.

* macos: use the AVAudioEngine audio device module (#2082)

## What

Switches the macOS audio device module from CoreAudio
(`audioDeviceModuleType` 0) to AVAudioEngine
(`RTCAudioDeviceModuleTypeAudioEngine`), matching iOS.

## Why the CoreAudio fallback existed

macOS moved to CoreAudio in #1990 to avoid an
`AVAudioIONodeImpl::SetOutputFormat` sample-rate assertion that fired
when the microphone toggled during screen share (#1986, #1990):

```
required condition is false: format.sampleRate == hwFormat.sampleRate
```

## Why it's safe to revert now

That crash predates the audio engine stability work in WebRTC-SDK
**144.7559.04+** — specifically webrtc-sdk/webrtc#228, which added
`@try/@catch` guards around all `connect:to:format:` calls (the
`IsFormatSampleRateAndChannelCountValid` crashes), replaced hardware
voice-processing property reads with state-based checks (an
`EXC_BAD_ACCESS` source), and fixed engine recreate / buffer-stop
ordering.

Verified locally on **144.7559.09**: with an active ScreenCaptureKit
session, toggling the microphone on/off repeatedly and switching input
devices produced no `SetOutputFormat` assertion and no crash report
(previously a reliable repro).

## Payoff

Brings macOS to parity with iOS: enables Apple platform voice processing
(AEC/NS/AGC) and the audio processing options API on macOS, instead of
software-only APM.

## Note

Requires WebRTC-SDK 144.7559.04+ (this repo is on .09). Draft pending
broader hardware validation — macOS audio hardware varies, and the
original crash was sample-rate-mismatch driven (e.g. 24kHz↔48kHz on
Bluetooth headset transitions).

* release: 1.5.0 (#2081)

Rolls up everything since 1.4.1 — see CHANGELOG for the full list.
Highlights:

- macOS platform rendering (#2058) and iOS AVAudioEngine ADM (#2009)
- WebRTC-SDK 144.7559.09 / libwebrtc.m144.7559.09 across all platforms
(#2078)
- AGP 9 built-in Kotlin support (#2075)
- Android factory accessor for embedders (#2077)
- Windows loopback capture (#2060)

After merge: tag and `flutter pub publish` per the usual flow.

* fix: stop gitignoring checked-in third_party source

The root .gitignore ignored all of third_party/, but CMakeLists.txt,
libwebrtc_version.ini, and svpng/ are checked in and required at build
time (and shipped in the published package). dart pub publish treats
checked-in-but-gitignored files as a warning and fails the automated
publish (exit 65). Narrow the ignore to the build-time artifact
directories (downloads/, libwebrtc/) so the tracked source is clean.

* fix: call SetRecordingDevice(0) when no sourceId is supplied (#2072)

**Problem**

When `getUserMedia` is called without a `sourceId` constraint, the
fallback path enters `if (sourceId == "")` at
[`flutter_media_stream.cc:235`](https://github.com/Noobidoo/flutter-webrtc/blob/3054cffda98ab1feaa5126c84b2c43173968a929/common/cpp/src/flutter_media_stream.cc#L235),
fetches the default device name and GUID, but never calls
`SetRecordingDevice(0)`. No recording device is explicitly selected,
which can cause the wrong device to be used or no audio to be captured.

**Fix**

Add `base_->audio_device_->SetRecordingDevice(0)` to the fallback block
to ensure the default recording device is selected.

Fixes #2071

* feat(android): add fullScreenOnly option to requestCapturePermission (force entire-screen on API 34+) (#2079)

Resolves #2080

## Summary

On Android 14 (API 34+), the `MediaProjection` consent dialog lets the
user choose between sharing a **single app** or the **entire screen**.
Some apps (remote support, screen mirroring) only support full-screen
capture and the single-app option is confusing/unusable for them.

This adds an opt-in `fullScreenOnly` flag to
`Helper.requestCapturePermission()`. When `true` and running on API 34+,
the screen-capture intent is created with
`MediaProjectionConfig.createConfigForDefaultDisplay()`, which forces
entire-screen capture and removes the single-app option from the consent
dialog.

```dart
// only offer entire-screen capture on Android 14+
await Helper.requestCapturePermission(fullScreenOnly: true);
```

## Details

- **Opt-in, non-breaking**: defaults to `false`, so existing callers and
the `getDisplayMedia` path are unchanged.
- **API-gated**: the `MediaProjectionConfig` branch only runs on
`Build.VERSION_CODES.UPSIDE_DOWN_CAKE` (API 34) and above; older
versions fall back to the existing `createScreenCaptureIntent()`.
- **No effect on macOS**: the flag is threaded only through the Android
`MediaProjection` path.
- Flag flows: `helper.dart` → `MethodCallHandlerImpl` (`fullScreenOnly`
arg, null-safe) → `GetUserMediaImpl.requestCapturePermission` →
`screenRequestPermissions` (a backward-compatible 1-arg overload
delegates to `false`) → Fragment args → `requestStart`.

## Testing

Built and verified on an Android 16 (API 36) emulator:
- `fullScreenOnly: true` → consent dialog defaults to "entire screen"
and the single-app option is disabled ("not supported by this app").
- `fullScreenOnly: false` (default) → unchanged user-choice dialog.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* chore(android): bump audioswitch to 039a35ae (#2084)

## What

Bumps `com.github.davidliu:audioswitch` from `89582c47` to `039a35ae` —
the revision pinned by the [LiveKit Android
SDK](https://github.com/livekit/client-sdk-android/blob/main/gradle/libs.versions.toml).

## What the 4 commits in between bring

- `CommDeviceAudioSwitch` (davidliu/audioswitch#7): routing via the
Android 12+ Communication Device API (`setCommunicationDevice`),
replacing the deprecated `setSpeakerphoneOn`/`startBluetoothSco` path on
modern devices
- Fix: selected audio device not updating when a wired headset is
plugged in (davidliu/audioswitch#6)
- `CommDeviceAudioSwitch` matched to previous earpiece/wired behavior
(davidliu/audioswitch#8)
- Crash guard when unregistering communication device listeners
(davidliu/audioswitch#9)

## Why now

Gradle resolves a single audioswitch revision per app classpath, and
SHA-pinned JitPack versions compare string-wise — so an app combining
flutter_webrtc with another plugin pinning `039a35ae` (e.g. the LiveKit
Flutter SDK) can end up with whichever string sorts higher, losing
classes the newer revision provides. Aligning everyone on the same
revision removes the ambiguity.

flutter_webrtc itself only uses `AudioSwitch` and `AudioDevice`, both
unchanged across this range — no code changes needed.

* fix(android): recreate texture surface when frame size changes (#2085)

## Problem

On Android, when a subscribed video upgrades to a higher simulcast
layer, the rendered video stays blurry even once 720p frames arrive.
Repro: subscribe while the publisher starts on a low layer → renderer
initializes at the low resolution → layer upgrades → still blurry.

## Cause

`SurfaceTextureRenderer.onFrame` creates the EGL surface once, sized by
the **first** frame. On a later resolution change,
`updateFrameDimensionsAndReportEvents` called `producer.setSize()` — but
`TextureRegistry.SurfaceProducer`'s backing buffers are fixed-size, and
`setSize()` only takes effect for a Surface obtained **afterwards** via
`getSurface()` (the ImageReader-backed producer from the #1726 Surface
API migration). The renderer kept GL-downscaling upgraded frames into
the original low-resolution buffer, which Flutter then upscaled for
display: permanently blurry.

iOS is unaffected — its renderer delivers per-frame pixel buffers with
no fixed-size backing, matching the Android-only reports.

## Fix

When the rotated frame dimensions change, release the EGL surface,
`setSize()`, re-obtain the producer surface, and recreate the EGL
surface — the same sequence as first-frame creation. The size-change
check reuses the existing `layoutLock` dimension tracking; rotation-only
changes (which don't alter rotated dimensions) don't trigger recreation.
The now-redundant `setSize()` in `updateFrameDimensionsAndReportEvents`
is removed so surface sizing has a single owner.

## Testing

- Compiles (example apk).
- Needs runtime verification with a simulcast publisher and a subscriber
starting on a low layer (dynacast or constrained bandwidth), watching
the upgrade un-blur. Reported and reproduced by LiveKit (Android-only).

* v1.5.1 (#2087)

Patch release rolling up the four changes since `v1.5.0`.

## Changes

- **[Android] fix:** recreate the texture surface when the incoming
frame size changes, so simulcast layer upgrades no longer stay blurry
(#2085).
- **[Android] chore:** bump audioswitch to `039a35ae`, aligning with the
LiveKit Android SDK — Communication Device API support plus
wired-headset and Bluetooth fixes (#2084).
- **[Android] feat:** add `fullScreenOnly` option to
`requestCapturePermission` to force entire-screen capture on API 34+
(#2079).
- **[Darwin] fix:** call `SetRecordingDevice(0)` when no sourceId is
supplied (#2072).

## Notes

- Patch bump: all fixes plus one additive option, no breaking changes.
- `pubspec.yaml` 1.5.0 → 1.5.1; CHANGELOG dated section added.
- After merge: create the `v1.5.1` GitHub release on the merge commit;
the `v*` tag triggers the publish workflow → pub.dev.

* Fix Windows libwebrtc extraction through plugin symlinks (#2100)

## Summary

Resolve the third_party CMake directory to its real path before
downloading or extracting libwebrtc binaries.

## Why

Flutter example builds add plugins through .plugin_symlinks. On Windows,
CMake file(ARCHIVE_EXTRACT) refuses to extract through that symlink
path, causing the Windows build job to fail before compilation.

## Impact

This affects the Win/Linux libwebrtc binary cache/extraction path only.
It does not change Dart APIs or platform plugin code.

## Validation

- git diff --check

Split from flutter-webrtc/flutter-webrtc#2099 so the CI fix can be
reviewed independently.

* Expose Android audio device module (#2099)

## Summary

Expose the Android `JavaAudioDeviceModule` from `FlutterWebRTCPlugin`
through a narrow getter.

## Why

Downstream plugins that already coordinate with
`FlutterWebRTCPlugin.sharedSingleton` need access to the same ADM
instance that flutter-webrtc creates and passes into
`PeerConnectionFactory`. This lets them start/prewarm recording with
options without duplicating or replacing flutter-webrtc's ADM.

## Impact

This is an Android-only API surface for native plugin integrations. It
does not change existing Dart APIs or existing start/stop recording
behavior.

## Validation

- `git diff --check`

* v1.5.2 (#2101)

## Summary
- bump package version to 1.5.2
- add changelog entries for Android ADM exposure and Windows symlink
extraction fix

## Validation
- dart pub publish --dry-run

* feat: RTCVideoPlatformView.placeholderBuilder (#2102)

```dart
RTCVideoPlatformView(
  ...,
  placeholderBuilder: (context) {
    return const CircularProgressIndicator.adaptive();
  },
)
```

* Android: option to disable built-in hardware AEC/NS (#2104)

Adds an `androidUseHardwareAudioProcessing` init option (default `true`,
so nothing changes unless you opt in). When set to `false`, the
`JavaAudioDeviceModule` is built with the platform
`AcousticEchoCanceler`/`NoiseSuppressor` off, and the WebRTC software
APM handles echo/noise instead:

```dart
await WebRTC.initialize(options: {'androidUseHardwareAudioProcessing': false});
```

The built-in hardware AEC is unreliable on quite a few Android devices —
you get echo that AEC3 would otherwise cancel (#1433). Today the only
way to turn it off is `bypassVoiceProcessing`, but that also switches
the input to the raw `AudioSource.MIC` and forces stereo in/out — a full
raw-capture path that's overkill when all you want is for the software
APM to run on an otherwise-normal voice call. This flag leaves the audio
source (and everything else) exactly as it is and only flips the two
hardware-effect flags.

It's the same control the native LiveKit Android SDK
(`javaAudioDeviceModuleCustomizer`) and react-native-webrtc
(react-native-webrtc/react-native-webrtc#713) already expose; this
brings it to flutter_webrtc.

Tested on a Realme device whose earpiece hardware AEC leaked badly: with
the flag off, AEC3 converges and the echo clears. With it unset/`true`,
behaviour is unchanged.

* feat: expose microphone mute mode and ADM-level microphone mute (#2105)

## Description

Adds control over how the AVAudioEngine-based audio device module mutes
microphone input, and ADM-level mute APIs independent of
`MediaStreamTrack.enabled`.

Fixes #2098.

## Background

Since 1.5.0 the Darwin factory uses the AVAudioEngine audio device
module, whose default mute strategy is `voiceProcessing`
(`AVAudioInputNode.isVoiceProcessingInputMuted`). That strategy plays
the platform's mute/unmute sound effect, which is the regression
reported in #2098. The underlying WebRTC-SDK binaries (144.7559.09,
already pinned) ship alternative mute modes, but the plugin had no API
to select them.

## API

```dart
// iOS/macOS: choose the muting strategy (no-op elsewhere)
await Helper.setMicrophoneMuteMode(MicrophoneMuteMode.inputMixer);
final mode = await Helper.getMicrophoneMuteMode();

// ADM-level mute, independent of track.enabled (Darwin + Android)
await Helper.setMicrophoneMuted(true);
final muted = await Helper.isMicrophoneMuted();
```

Mute modes (Darwin only):
- `voiceProcessing` (default) — fast, keeps muted-talker detection
possible, but plays the platform mute tone.
- `inputMixer` — mutes the engine's input mixer node; fast and silent,
engine keeps running.
- `restartEngine` — restarts the engine without mic input; slower,
silent, stops mic input entirely while muted.

The default is unchanged; apps opt into the silent modes.

## Implementation notes

- Darwin: method-channel handlers call `RTCAudioDeviceModule`
`muteMode`/`setMuteMode:`/`isMicrophoneMuted`/`setMicrophoneMuted:`,
following the existing voice-processing handler pattern.
- Android: `setMicrophoneMuted` maps to
`JavaAudioDeviceModule.setMicrophoneMute` (mute mode is not applicable).
The Java ADM has no mute getter, so the plugin mirrors the last set
value for `isMicrophoneMuted`.
- Unsupported platforms: `setMicrophoneMuteMode` is a no-op and
`getMicrophoneMuteMode` returns `unknown`; web is a no-op for all four
APIs.

## Testing

- `dart analyze` clean.
- macOS and Android example builds pass against the pinned WebRTC-SDK
144.7559.09 (no native dependency bump required).

* fix: serialize data channel event queue access across threads (#2118)

Fixes #2117

The data channel's `eventSink` and `eventQueue` are written from the
WebRTC signaling thread in `sendEvent` and read from the platform thread
in `onListen`/`onCancel`, with no synchronization. On Darwin that can
hand `onListen` an array the signaling thread has just deallocated,
crashing in `objc_retain`; on Android it can throw
`ConcurrentModificationException` out of `onListen` and drop the queued
events. See the issue for the crash report and the full analysis.

### The fix

Guard every access with a per-channel lock — `@synchronized(channel)` on
Darwin, a lock object on Android — and drain the queue while the lock is
held on both platforms.

Draining inside the lock costs nothing, because delivery never blocks:
`postEvent` only dispatches to the main queue on Darwin, and
`AnyThreadSink` posts to the main looper on Android. It is also what
keeps the queued events ahead of anything the signaling thread sends
concurrently, without relying on which thread happens to deliver them.

Neither critical section acquires a second lock, so no lock-order
inversion is possible, and both hold the lock only for a pointer swap
plus a non-blocking dispatch.

`createDataChannel` resets `eventQueue` *after* attaching the delegate,
so an event the signaling thread queues in between is silently dropped —
defeating the purpose of the queue — and the reset itself races with the
signaling thread's write. The reset now happens before the delegate is
set. `didOpenDataChannel` already runs on the signaling thread and is
not affected; it is reordered the same way only so both creation paths
read alike.

Every access to these two associated objects is now either inside the
lock or before the delegate is attached, when no other thread can reach
the channel yet.

Two more instances of the same class of race are deliberately left alone
here, both in `FlutterRTCPeerConnection.m`:

* `peerConnection.eventSink` — written on the platform thread, read from
the signaling thread in 15 places.
* `peerConnection.dataChannels` — an `NSMutableDictionary` written from
the signaling thread in `didOpenDataChannel`, while the platform thread
reads and mutates it in `createDataChannel`, `dataChannelClose`,
`dataChannelSend` and others.

Both are written once per connection or per channel rather than once per
event, so they are far less exposed than the queue, and both reach well
beyond the call sites touched here. Folding them in would make this
change much harder to review; they are better addressed on their own.

### Testing

* `flutter analyze` and `flutter test` on the plugin: clean.
* `example` built for Android and macOS against this branch (macOS
compiles the same `common/darwin` sources as iOS).
* `example`'s `DataChannelLoopBackSample` run on macOS with the patch:
channels open, messages flow both ways, and repeated connect/hang-up
cycles behave as before.
* An app using `livekit_client` built for both iOS and Android with the
patch applied.
* `git clang-format --diff` reports no violations on the changed lines.

* fix(android): NPE in setFocusPoint/setExposurePoint — orientation cache is never populated (#2113)

## Description

On Android, every `Helper.setFocusPoint` / `Helper.setExposurePoint`
call crashes inside the plugin with:

```
E MethodChannel#FlutterWebRTC.Method: Failed to handle method call
E MethodChannel#FlutterWebRTC.Method: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Enum.ordinal()' on a null object reference
	at com.cloudwebrtc.webrtc.video.camera.CameraUtils.convertPointToMeteringRectangle
	at com.cloudwebrtc.webrtc.video.camera.CameraUtils.setFocusPoint
	at com.cloudwebrtc.webrtc.MethodCallHandlerImpl.onMethodCall
```

This makes tap-to-focus / tap-to-expose completely non-functional on
Android. It is hit in the wild by anything wiring viewfinder taps to
these helpers — e.g. LiveKit's `VideoTrackRenderer.onViewFinderTap`
calls both on every tap.

## Root cause

`CameraUtils`'s constructor intentionally never calls
`deviceOrientationManager.start()` (see the existing `TODO: get a proper
fix at some point` comment — registering the receiver broke
terminated-app scenarios). With the receiver never started,
`DeviceOrientationManager.getLastUIOrientation()` returns its
`lastOrientation` cache, which stays `null` forever.

`setFocusPoint`/`setExposurePoint` then pass that `null` straight into
`convertPointToMeteringRectangle(..., @NonNull DeviceOrientation
orientation)`, which calls `orientation.ordinal()` → guaranteed NPE on
every call.

## Fix

Fix at the source instead of null-guarding every caller: when the cache
is empty, `getLastUIOrientation()` now computes the *actual* current UI
orientation on demand via the already-existing `getUIOrientation()`
(real display rotation + configuration), falling back to `PORTRAIT_UP`
only when no `Activity` is attached (backgrounded/terminated) — the same
default `getUIOrientation()` itself uses for undefined configurations.

- No behaviour change for code paths where orientation change events
populate the cache (if `start()` is ever re-enabled).
- Does not re-introduce the receiver-registration problem `start()` was
disabled for.
- The method's contract tightens from `@Nullable` to `@NonNull`; its
only callers (`setFocusPoint`, `setExposurePoint`) already required
non-null.

## Testing

Reproduced on a physical Android device (MediaTek, Android 11) via
LiveKit `VideoTrackRenderer` viewfinder taps: before the patch every tap
logged the NPE above and focus never moved; with the patch applied
(pinned fork) taps produce metering rectangles and no exceptions.

Co-authored-by: Ramin <mahmudov18ramin@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>

* feat(ios,macos): add Swift Package Manager integration. (#2062)

Restructure plugin sources from Classes/ into the Flutter SPM convention
flutter_webrtc/Sources/flutter_webrtc/ with public headers under
include/flutter_webrtc/. Source symlinks into common/darwin/Classes are
preserved so it remains the single source of truth.

- Add ios/flutter_webrtc/Package.swift and
macos/flutter_webrtc/Package.swift,
  both pulling WebRTC 144.7559.04 directly via .binaryTarget against the
xcframework release asset (bypasses webrtc-sdk/Specs Package.swift,
which
  declares .visionOS(.v26) under swift-tools 5.9 and fails to compile).
- Update both podspecs to point at the new Sources/ layout and add
  USER_HEADER_SEARCH_PATHS so quoted #import "Foo.h" keeps resolving.
- Drop the broken stub macos/Package.swift in favor of the new location.
- Example: deintegrate CocoaPods from macOS (all macOS deps are
SPM-ready)
  and from iOS after removing permission_handler and gallery_saver_plus
  from pubspec and the two samples that referenced them, since neither
  ships a Package.swift upstream.

Verified with Flutter 3.41 + Xcode 26.5: flutter build macos and an
xcodebuild iphonesimulator build of the example both succeed.

close #2045, close #2027

---

## Update 2026-07-29 (takeover by @hiroshihorie)

Changes since the original description:

- Caught up with main (twice), no conflicts beyond CHANGELOG.
- Bumped the Package.swift binary targets from WebRTC 144.7559.04 to
144.7559.09 to match the podspecs. The mute mode APIs merged from main
only exist in .09, so the old pin no longer compiled. This also fixes
the `isPlatformVoiceProcessingAllowed` error reported in the comments.
- Exported the WebRTC binary target as a library product so dependent
plugins (livekit_client, see livekit/client-sdk-flutter#1142) can reuse
it instead of declaring a colliding second copy.
- Restored `permission_handler` to the example. permission_handler_apple
9.4.10 now ships a Package.swift, so it no longer blocks the CocoaPods
free example. `gallery_saver_plus` stays removed (no SPM support
upstream), a replacement using `gal` can land separately.
- Removed the leftover `ios/Classes` and `macos/Classes` platform view
symlinks that came back through merges. The podspecs point at the
`Sources/` layout, so they were dead.
- Synced the podspec versions with pubspec (1.5.2).
- CI: the iOS and macOS jobs now build the example with both SPM and
CocoaPods, and a new job checks the WebRTC-SDK version stays in sync
across the two podspecs and two Package.swift files.
- Docs: CHANGELOG entry and a README section on Swift Package Manager
support.
- Documented in macos/Package.swift why ScreenCaptureKit ends up weak
linked (verified LC_LOAD_WEAK_DYLIB in the built app), matching the
podspec's weak_frameworks.

The CI blocker mentioned in the comments (flutter/flutter#186054) was
fixed in Flutter 3.44.2, and all jobs are green in both dependency
manager modes.

Verified with Flutter 3.44.1 + Xcode 26.6: example builds for macOS and
iOS simulator via SPM and via CocoaPods, and livekit_client consumes
this branch successfully through both SPM and CocoaPods on both
platforms.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com>

* fix(iOS): remove private buttonPressed: broadcast picker selector (#2121)

## Summary

Apple's automated App Store review rejects iOS binaries containing the
non-public `RPSystemBroadcastPickerView.buttonPressed:` selector.

This replaces the private selector invocation with public UIKit APIs by
locating the picker's `UIButton` subview and sending the
`UIControlEventTouchUpInside` control event.

The automatic broadcast picker path is preserved. The existing
`broadcast-manual` behavior and remaining screen-capture implementation
are unchanged.

This follows the public-button approach adopted by LiveKit in:
https://github.com/livekit/client-sdk-swift/pull/1065

Fixes #2120.

## Changes

- Remove the `NSSelectorFromString(@"buttonPressed:")` invocation.
- Trigger the picker through `UIButton` and
`UIControlEventTouchUpInside`.
- Log a warning if the picker button cannot be found.
- Remove the unused Objective-C runtime import.
- Import UIKit explicitly.

## Verification

- `flutter analyze`
- `flutter test`
- `flutter build ios --release --no-codesign`
- Confirmed `buttonPressed:` is absent from tracked source.
- Confirmed `buttonPressed:` is absent from every Mach-O file in the
compiled iOS application.

Physical broadcast-picker activation was not tested locally.

## Scope

## Summary

Apple's automated App Store review rejects iOS binaries containing the
non-public `RPSystemBroadcastPickerView.buttonPressed:` selector.

This replaces the private selector invocation with public UIKit APIs by
locating the picker's `UIButton` subview and sending the
`UIControlEventTouchUpInside` control event.

The automatic broadcast picker path is preserved. The existing
`broadcast-manual` behavior and remaining screen-capture implementation
are unchanged.

This follows the public-button approach adopted by LiveKit in:
https://github.com/livekit/client-sdk-swift/pull/1065

Fixes #2120.

## Changes

- Remove the `NSSelectorFromString(@"buttonPressed:")` invocation.
- Trigger the picker through `UIButton` and
`UIControlEventTouchUpInside`.
- Log a warning if the picker button cannot be found.
- Remove the unused Objective-C runtime import.
- Import UIKit explicitly.

## Verification

- `flutter analyze`
- `flutter test`
- `flutter build ios --release --no-codesign`
- Confirmed `buttonPressed:` is absent from tracked source.
- Confirmed `buttonPressed:` is absent from every Mach-O file in the
compiled iOS application.

Physical broadcast-picker activation was not tested locally.

## Scope

This intentionally retains `RPSystemBroadcastPickerView` for
compatibility with iOS 26 and earlier. Migration to ScreenCaptureKit on
iOS 27 and later is outside the scope of this focused fix.

* exposing public MediaStream getStreamForId in FlutterWebRTCPlugin.java (#2109)

the same method is already exposed on the iOS implementation. i use this
method to inject a custom video track in to the MediaStream to be able
to send it through the webrtc connection.

* fix(macos): create parent directory before captureFrame writes the file (#2090)

### What

`FlutterRTCFrameCapturer` (shared by iOS/macOS) writes the captured
frame with `[imageData writeToFile:_path atomically:NO]`. When the
parent directory of `_path` does not exist the write fails with only a
generic `Failed to write to file` log.

This change creates the intermediate directories with `NSFileManager`
before the write, and makes the failure path actionable by returning a
`FlutterError` and logging whether `imageData` was nil plus the target
path.

### Why

Closes #2089. Callers that pass a not-yet-created subdirectory currently
get an opaque failure; creating the directory first matches the
expectation that `captureFrame(path)` works for a fresh path.

### Changes

- `common/darwin/Classes/FlutterRTCFrameCapturer.m`: create parent
directory before writing; clearer error/log on failure.

### Notes

- Single file, no public API change.
- Original change authored by 송건호 <ghsong@rsupport.com>; submitted via
fork.

Co-authored-by: 송건호 <ghsong@rsupport.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(android): resolve OrientationAwareScreenCapturer deadlock/ANR on stop (#2092)

### What

Removes a stop-time deadlock in `OrientationAwareScreenCapturer`.

`stopCapture()` was `public synchronized`, so it held the capturer
monitor while blocking on the `SurfaceTextureHelper` thread via
`invokeAtFrontUninterruptibly`. That thread runs `onFrame()` →
`changeCaptureFormat()` (also `synchronized`), which then re-enters the
monitor `stopCapture()` still holds → deadlock → ANR.

### Why

Closes #2091. PRs #2048 / #2055 fixed orientation/rotation correctness
in this file but left the stop-time deadlock unaddressed.

### Changes

- Drop `synchronized` from `stopCapture()`; guard with a `volatile
isStopped`/`isDisposed` flag and return early.
- `onFrame()` only enters `changeCaptureFormat()` when the target
dimensions actually change (compared against `volatile` old
width/height), removing the per-frame lock and shrinking the race
window.
- Make `oldWidth`/`oldHeight`/`isDisposed` `volatile`, add `volatile
isStopped`, and silently drop frames that arrive after stop/dispose.

### Notes

- Single file (`OrientationAwareScreenCapturer.java`).
- Original change authored by 오세진 <ohsj@rsupport.com>; submitted via
fork.

Co-authored-by: 오세진 <ohsj@rsupport.com>
Co-authored-by: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com>

* fix: skip unrecognized constraint value types in ParseConstraints (#2132)

fix: skip unrecognized constraint value types in ParseConstraints
(#2128)

**Problem**

`FlutterWebRTCBase::ParseConstraints` throws `std::bad_variant_access`
when a
constraint map entry holds a value type it does not explicitly handle
(e.g. a
null / `std::monostate` `EncodableValue`). The final `else` branch
unconditionally calls `GetValue<int>(v)`:

```cpp
} else if (TypeIs<bool>(v)) {
  value = GetValue<bool>(v) ? RTCMediaConstraints::kValueTrue
                            : RTCMediaConstraints::kValueFalse;
} else {
  value = std::to_string(GetValue<int>(v));   // throws if v is not int
}
```

When `v` is null/`std::monostate` (passed by some callers for
optional/empty
constraint fields), `GetValue<int>` throws, crashing the native side.
This was
hit on the Linux desktop path during media/screen-capture constraint
parsing.

**Fix**

Replace the final `else` branch with `continue;` so unrecognized value
types
are skipped instead of forcing a `std::get<int>`:

```cpp
} else {
  continue;
}
```

Only recognized constraints are applied; parsing no longer crashes on
empty or
unrecognized values.

### Testing

- `git clang-format` reports no violations on the changed line (Chromium
style).
- Validated in the originating Linux desktop application (Kohera, using
`livekit_client`): `getUserMedia`/`getDisplayMedia` with
null/unrecognized
  constraint values no longer crashes the native side.

Fixes #2128

Co-authored-by: Claude <noreply@anthropic.com>

Co-authored-by: Claude <noreply@anthropic.com>

* fix: prevent event channel use-after-free on peer connection cleanup (#2131)

fix: prevent event channel use-after-free on peer connection cleanup
(#2127)

**Problem**

During peer connection teardown, `RTCPeerConnectionClose` erases the
entry
from `peerconnection_observers_` immediately, but Dart's
`RTCPeerConnection`
keeps its EventChannel subscription alive until `dispose()` (which
invokes
`RTCPeerConnectionDispose`). Any event the WebRTC stack emits between
`Close`
and `Dispose` therefore hits a destroyed observer — a use-after-free.

Additionally, `~EventChannelProxyImpl` was empty, so the stream handler
could
remain registered after the proxy was destroyed, leaving dangling
callbacks.

**Fix**

- Move the `peerconnection_observers_.erase(...)` from
`RTCPeerConnectionClose`
to `RTCPeerConnectionDispose`, so the event channel survives `Close`
(until
  Dart has cancelled its subscription).
- In `~EventChannelProxyImpl`, call
`channel_->SetStreamHandler(nullptr)` to
  drop the handler on destruction and prevent dangling callbacks.

### Testing

- `git clang-format` reports no violations on the changed lines
(Chromium style).
- Validated in the originating Linux desktop application (Kohera, using
`livekit_client`): rapid connect/hang-up cycles and swipe-kill teardown
no
  longer crash on the event channel.

Fixes #2127

Co-authored-by: Claude <noreply@anthropic.com>

Co-authored-by: Claude <noreply@anthropic.com>

* fix(linux): guard texture proxy and harden desktop source enumeration (#2133)

fix(linux): guard texture proxy and harden desktop source enumeration
(#2129)

**Problem**

Linux desktop screen capture has two crash/fragility issues.

**(A) Use-after-free in the GTK texture proxy**
(`linux/flutter/core_implementations.cc`)

`fl_texture_proxy_copy_pixels` does an unguarded
`std::get<flutter::PixelBufferTexture>(*proxy->texture)`. If the texture
variant is destroyed before the proxy `GObject` is torn down (a race
during
unregister), this dereferences freed memory and crashes.
`UnregisterTexture`
also calls `fl_texture_registrar_unregister_texture` *before* nulling
`proxy->texture`, leaving a window in which the engine's copy-pixels
callback
can fire against a destroyed variant.

**(B) Fragile desktop source enumeration**
(`common/cpp/src/flutter_screen_capture.cc`)

`BuildDesktopSourcesList` calls `UpdateSourceList` with no exception
guard; on
Linux this can throw during transient desktop-enumerator failures,
aborting
the whole enumeration. `GetDisplayMedia` also errors with `"source not
found!"`
when the requested `source_id` is absent from a stale cached list, even
though
a re-enumeration would have found it.

A number of leftover `std::cout` debug statements were also present.

**Fix**

- `fl_texture_proxy_copy_pixels`: null-check `proxy->texture` before
`std::get`
  (return `TRUE` to avoid crashing the engine copy path).
- `UnregisterTexture`: null `FL_TEXTURE_PROXY(texture)->texture`
*before*
  `fl_texture_registrar_unregister_texture`, closing the race.
- `BuildDesktopSourcesList`: on `__linux__`, wrap `UpdateSourceList` in
`try/catch` so a transient failure skips that source type instead of
aborting.
- `GetDisplayMedia`: on `__linux__`, when the requested `source_id` is
not in the
  cached list, rebuild the list and retry the match. The first-available
(`sources_.front()`) fallback is only used when the caller did not
specify a
source (`source_id == "0"`); a specifically-requested source that still
isn't
found falls through to the existing `"source not found!"` error rather
than
  silently capturing the wrong surface.
- Remove the leftover debug `std::cout` statements.

### Testing

- `git clang-format` reports no violations on the changed lines
(Chromium style).
- Validated in the originating Linux desktop application (Kohera, using
`livekit_client`): rapid start/stop of screen-share capture no longer
crashes
during the texture unregister race, and transient desktop-enumerator
failures
  no longer abort source enumeration.

Fixes #2129

Co-authored-by: Claude <noreply@anthropic.com>

Co-authored-by: Claude <noreply@anthropic.com>

* fix(linux): marshal MethodResultProxy callbacks to platform thread (#2130)

fix(linux): marshal MethodResultProxy callbacks to platform thread
(#2126)

**Problem**

libwebrtc invokes PeerConnection callbacks (`setRemoteDescription`,
`createAnswer`, etc.) on worker threads. `MethodResultProxyImpl`
forwarded
these directly to Flutter's `MethodResult`, which on Linux/GTK silently
drops responses that arrive on a non-platform thread. As a result the
Dart
`Future` for the operation never resolved, so subscriber SDP
renegotiation
never completed — `livekit_client` never sent the SDP answer back to the
server and the peer connection stalled.

The sibling `EventChannelProxy` already solves this by marshalling
through
`TaskRunner` (#1795 / `1c2ff6f`), but that marshalling was never
extended to
`MethodResultProxy`.

**Fix**

Add an optional `TaskRunner*` parameter to `MethodResultProxy::Create`
(default `nullptr` so other platforms keep the current direct-call
path).
When set, `Success`/`Error`/`NotImplemented` enqueue the call onto the
platform thread via `TaskRunner::EnqueueTask`. The
`unique_ptr<MethodResult>`
is converted to `shared_ptr` for lambda capture (`std::function`
requires
copyability), and a null guard guards against double-call since the
proxy is
moved out on the first terminal call.

The Linux plugin passes its `task_runner()`; elinux and windows continue
to
call `Create` without a runner (default `nullptr`).

### Testing

- `git clang-format` reports no violations on the changed lines
(Chromium style).
- Validated in the originating Linux desktop application (Kohera, using
`livekit_client`): subscriber SDP renegotiation completes and the answer
is
  delivered where it previously hung on Linux/GTK.

Fixes #2126

Co-authored-by: Claude <noreply@anthropic.com>

Co-authored-by: Claude <noreply@anthropic.com>

* feat(linux): system-audio (loopback) capture via PulseAudio (#2115)

## What

Implements the Linux system-audio (loopback) capturer so
`getDisplayMedia({ video: true, audio: true })` streams system/desktop
audio on
Linux, the same way it already works on Windows (WASAPI) and macOS.

Before this change, `CreateLoopbackCapturer()` on Linux was a `nullptr`
stub, so
a Linux screen share silently carried no system-audio track.

## How

- **`linux/pulse_loopback_capturer.{h,cc}` (new):** uses the PulseAudio
*simple*
API to record the default output sink's `.monitor` source. The default
sink is
  resolved through a short-lived `pa_context` introspection
  (`server_info` -> `sink_info.monitor_source_name`, falling back to
  `<sink>.monitor`). A single capture thread then block-reads
  S16LE / 48 kHz / stereo frames and feeds one 10 ms frame
  (`480 * 2ch * 2 bytes = 1920` bytes) at a time to
`RTCAudioSource::CaptureFrame(..., 16, 48000, 2, 480)`, mirroring the
Windows
capturer. The blocking read self-paces to real time, so no ring buffer
is
  needed.
- **`linux/loopback_capturer_factory.cc`:** returns the Pulse capturer
under
`HAVE_LIBPULSE`; otherwise keeps the previous `nullptr` behaviour, so
the
  factory symbol is always defined for `__linux__`.
- **`linux/CMakeLists.txt`:** a guarded `pkg_check_modules(libpulse
libpulse-simple)` enables the capturer when the dev headers are present,
and
degrades to the `nullptr` stub (build still succeeds) when they are not.

### Robustness

The introspection is bounded by a 3-second steady-clock deadline and
runs the
mainloop non-blocking, so a misbehaving PulseAudio/PipeWire daemon
degrades to
"no audio track" instead of blocking the Flutter platform thread inside
`getDisplayMedia`.

### PipeWire

PipeWire ships a PulseAudio compatibility layer, so the same `libpulse`
path
covers both the PulseAudio and PipeWire stacks.

### GCC 16 note

The CMakeLists also force-includes `<cstdint>` for the plugin target
under
GCC/Clang, because the bundled libwebrtc headers (e.g. `rtc_types.h`)
use
fixed-width integer types without including `<cstdint>`, which fails to
compile
on GCC 14+/16. Happy to split…
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