main f5b6f215ff48 cached
57 files
150.8 KB
38.2k tokens
199 symbols
1 requests
Download .txt
Repository: IceDBorn/pipewire-screenaudio
Branch: main
Commit: f5b6f215ff48
Files: 57
Total size: 150.8 KB

Directory structure:
gitextract_014v53gh/

├── .editorconfig
├── .eslintrc
├── .github/
│   └── workflows/
│       └── update-changelog.yaml
├── .gitignore
├── .prettierrc.yml
├── CHANGELOG.md
├── INSTALL.md
├── LICENSE
├── README.md
├── extension/
│   ├── manifest.json
│   ├── react/
│   │   ├── .gitignore
│   │   ├── build-watcher.sh
│   │   ├── components/
│   │   │   └── nodes-table.jsx
│   │   ├── index.html
│   │   ├── index.jsx
│   │   ├── lib/
│   │   │   ├── backend.js
│   │   │   ├── hooks.js
│   │   │   ├── local-storage.js
│   │   │   └── match-node.js
│   │   ├── routes/
│   │   │   └── popup.jsx
│   │   └── vite.config.js
│   └── scripts/
│       ├── background.js
│       ├── injector.js
│       └── override-gdm.js
├── flake.nix
├── install.sh
├── native/
│   ├── .gitignore
│   ├── connector/
│   │   ├── cli.sh
│   │   └── util.sh
│   ├── connector-rs/
│   │   ├── .gitignore
│   │   ├── Cargo.toml
│   │   ├── pipewire-utils/
│   │   │   ├── .gitignore
│   │   │   ├── Cargo.toml
│   │   │   ├── examples/
│   │   │   │   ├── all-desktop-audio.rs
│   │   │   │   └── create-node.rs
│   │   │   ├── rustfmt.toml
│   │   │   └── src/
│   │   │       ├── cancellation_signal.rs
│   │   │       ├── lib.rs
│   │   │       ├── monitor.rs
│   │   │       ├── pipewire_client.rs
│   │   │       ├── pipewire_objects.rs
│   │   │       ├── proxies.rs
│   │   │       ├── roundtrip.rs
│   │   │       └── utils.rs
│   │   ├── rustfmt.toml
│   │   └── src/
│   │       ├── command.rs
│   │       ├── daemon.rs
│   │       ├── dirs.rs
│   │       ├── helpers/
│   │       │   ├── io.rs
│   │       │   └── pipewire.rs
│   │       ├── helpers.rs
│   │       ├── ipc.rs
│   │       ├── ipc_request.rs
│   │       ├── main.rs
│   │       └── monitor.rs
│   └── native-messaging-hosts/
│       └── com.icedborn.pipewirescreenaudioconnector.json
└── package.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
indent_style = tab


================================================
FILE: .eslintrc
================================================
{
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": 2020,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "env": {
    "browser": true
  },
  "globals": {
    "browser": true,
    "chrome": true
  },
  "rules": {
    "react/prop-types": "ignore"
  }
}


================================================
FILE: .github/workflows/update-changelog.yaml
================================================
# .github/workflows/update-changelog.yaml
name: "Update Changelog"

on:
  release:
    types: [released]

jobs:
  update:
    runs-on: ubuntu-latest

    permissions:
      # Give the default GITHUB_TOKEN write permission to commit and push the 
      # updated CHANGELOG back to the repository.
      # https://github.blog/changelog/2023-02-02-github-actions-updating-the-default-github_token-permissions-to-read-only/
      contents: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          ref: ${{ github.event.release.target_commitish }}

      - name: Update Changelog
        uses: stefanzweifel/changelog-updater-action@v1
        with:
          latest-version: ${{ github.event.release.tag_name }}
          release-notes: ${{ github.event.release.body }}

      - name: Commit updated CHANGELOG
        uses: stefanzweifel/git-auto-commit-action@v4
        with:
          create_branch: true
          branch: changelog-update-${{ github.event.release.tag_name }}
          commit_message: Update CHANGELOG
          file_pattern: CHANGELOG.md


================================================
FILE: .gitignore
================================================
# Prerequisites
*.d

# Compiled Object files
*.slo
*.lo
*.o
*.obj

# Precompiled Headers
*.gch
*.pch

# Compiled Dynamic libraries
*.so
*.dylib
*.dll

# Fortran module files
*.mod
*.smod

# Compiled Static libraries
*.lai
*.la
*.a
*.lib

# Executables
*.exe
*.out
*.app

# VSCodium history
.history/

# Node deps
/node_modules

/result
/pipewire-screenaudio.zip


================================================
FILE: .prettierrc.yml
================================================
useTabs: true


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## 0.4.2 - 2026-03-24

### What's Changed

* Fix node list not updating by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/123
* Fix error while removing event listeners during cleanup by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/122
* Refactor popup component into multiple hooks that each manages their own state by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/124
* Improve popup size consistency when in errored state by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/125
* Fix popup showing both scrollbars in chromium by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/126
* feat(popup): disable all desktop in firefox private windows by @jim3692 in https://github.com/IceDBorn/pipewire-screenaudio/pull/128
* rework(install): support multiple browsers by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/127
* fix(override-gdm): do not edit page title on chromium by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/129
* (update): readme deps & add reference to install.md by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/131
* fix(flake): use the new manifest introduced in cb2860b6c25c20f92794e2e59c9699e0481bb491 by @Kladki in https://github.com/IceDBorn/pipewire-screenaudio/pull/130
* fix(override-gdm): chromium detection by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/134
* readme: add Chrome Web Store url by @jim3692 in https://github.com/IceDBorn/pipewire-screenaudio/pull/135

### New Contributors

* @Kladki made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/130

**Full Changelog**: https://github.com/IceDBorn/pipewire-screenaudio/compare/0.4.1...0.4.2

## 0.4.1 - 2026-03-10

### What's Changed

* Fix detection of misconfigured native connector by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/117
* Fix version check compatibility by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/116

**Full Changelog**: https://github.com/IceDBorn/pipewire-screenaudio/compare/0.4.0...0.4.1

## 0.4.0 - 2026-03-10

### What's Changed

* Implement simple CLI wrapper for connector by @jim3692 in https://github.com/IceDBorn/pipewire-screenaudio/pull/97
* Rust rewrite by @jim3692, @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/99
* Fixing Teamspeak 6 segfault by supplying node.description in pipewire.rs by @licentiapoetica in https://github.com/IceDBorn/pipewire-screenaudio/pull/112
* Fix missing AudioCallbackDriver by @jim3692 in https://github.com/IceDBorn/pipewire-screenaudio/pull/87
* New UI based on MUI by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/71
* Frontend react rewrite by @jim3692, @IceDBorn, @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/71
* Fix injector breaking stream audio/video constraints by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/71

### New Contributors

* @Andreas02-dev made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/95
* @jvdcf-dev made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/107
* @DADA30000 made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/110
* @licentiapoetica made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/112

**Full Changelog**: https://github.com/IceDBorn/pipewire-screenaudio/compare/0.3.4...0.4.0

## 0.3.4 - 2023-10-26

![Father Gascoigne](https://s6.gifyu.com/images/S8sjU.gif)

### Fixed

- Flake installation
- Enqueued actions causing the nodes loop to stop (#61) @jim3692
- micId being "null" instead of null, causing errors
- setSelectedNode(null) always failing (#70)
- Nodes loop being stopped after sharing (#67)
- Multiple additions of dropdown listeners (#68)
- Crash when starting "All Desktop Audio" without nodes (#69) @alansartorio

## 0.3.3 - 2023-10-22

### Added

- Logging (#30) @jim3692 @alansartorio

### Fixed

- Extension reporting falsely pipewire-screenaudio is running (#37) @jim3692
- Discord workaround not working when another session is open (#44) @alansartorio
- Race condition upon linking ports (#48) @alansartorio
- Race condition upon setting nodes to share (#49) @jim3692
- Being able to hide "All Desktop Audio" (#46) @jim3692

### Changed

- Code cleanup (#29 #30) @jim3692 @alansartorio

## 0.3.2 - 2023-10-10

### Fixed

- `intToBin` not working on some Linux distros (#27) @jim3692

## 0.3.1 - 2023-08-09

### Fixed

- Discord screen-sharing not working if the user does not select a video source within 5 seconds (#20) @alansartorio

## 0.3.0 - 2023-08-08

### Added

- Information about Matrix
- Note about bugzilla report
- Switching nodes while streaming @alansartorio

### Fixed

- All Desktop Audio not working sometimes @alansartorio
- Duplicated audio occurring on Discord + Wayland @alansartorio 😱

## 0.2.1 - 2023-07-20

### Added

- NixOS flakes support and installation instructions

### Changed

- License to GPL3
- Extension icon @illuminor 💘

## 0.2.0 - 2023-07-19

We reworked the whole extension to only use bash and pipewire. This was made possible by the great work of @jim3692 💋

### Added

- Install script for the native part of the extension
- Version checks

### Changed

- Port the native part to pure bash

### Removed

- C++ and its dependencies

## 0.1.1 - 2023-07-18

### Fixed

- The injector script not applying in iframes

## 0.1.0 - 2023-07-12

### Added

- "All Desktop Audio" support @alansartorio

## 0.0.1 - 2023-07-10

Initial release


================================================
FILE: INSTALL.md
================================================
# Installation Guide

## Dependencies

### Extension UI

- Node.js
- Yarn

### Native Connector

- Cargo

## Browser Extension

You can install the extension from your browser's extension store or build and sideload it locally.

### Published Extensions

- [Firefox Add-ons](https://addons.mozilla.org/en-US/firefox/addon/pipewire-screenaudio/)
- [Chrome Web Store](https://chromewebstore.google.com/detail/pipewire-screenaudio/cbmjbapailadjabjnjnnbfdimkbdicja)

### Local Installation

- **Firefox-based browsers:**
  1.  Go to [about:debugging](about:debugging#/runtime/this-firefox) and click "Load Temporary Add-on".
  1.  Select the `manifest.json` file inside the `extension` directory in the project root
- **Chromium-based browsers:**
  1.  Go to [chrome://extensions](chrome://extensions) and click "Load unpacked".
  1.  Select the `extension` directory containing the `manifest.json` file in the project root

> **Note:** For Chromium-based browsers, after loading the extension, copy its ID and provide it to the install script when prompted.

## Native Messaging Hosts

The extension communicates with a native connector for pipewire management. For security reasons, browsers require explicit configuration specifying which extensions can interact with which binaries.

Configuration paths vary by browser. Some common locations are:

### Firefox-based Browsers

- `~/.mozilla/native-messaging-hosts` or `~/.config/mozilla/firefox/native-messaging-hosts` (Firefox)
- `~/.librewolf/native-messaging-hosts` (Librewolf)

### Chromium-based Browsers

- `~/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts` (Brave)
- `~/.config/chromium/NativeMessagingHosts` (Chromium)
- `~/.config/net.imput.helium/NativeMessagingHosts` (Helium)
- `~/.config/google-chrome/NativeMessagingHosts` (Google Chrome)

## Native Connector

- The native connector can be built from source or installed via your package manager
- The typical binary path is: `/usr/lib/pipewire-screenaudio/connector/connector-rs`

If you build the connector yourself, do not move or delete the project directory, as the binary resides within it. If you move the directory, rerun the install script to update the path.

## Uninstallation

- Remove the browser extension from your browser's extensions page
- Delete the `com.icedborn.pipewirescreenaudioconnector.json` manifest from your browser's native messaging hosts directory
- Remove the native connector binary if built from source


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# <img src="./extension/assets/icons/icon.svg" width="22" alt="Logo"> Pipewire Screenaudio

Extension to passthrough Pipewire audio to WebRTC Screenshare

Based on [virtual-mic](https://github.com/Curve/rohrkabel/tree/master/examples/virtual-mic) and [Screenshare-with-audio-on-Discord-with-Linux](https://github.com/edisionnano/Screenshare-with-audio-on-Discord-with-Linux)

## Communication

You can find us on [Matrix](https://matrix.to/#/#pipewire-screenaudio:matrix.org)

## Installation

### Packages

[![AUR](https://img.shields.io/aur/version/pipewire-screenaudio?style=for-the-badge)](https://aur.archlinux.org/packages/pipewire-screenaudio)
[![AUR](https://img.shields.io/aur/version/pipewire-screenaudio-git?style=for-the-badge)](https://aur.archlinux.org/packages/pipewire-screenaudio-git)

#### NixOS Flakes

```nix
# flake.nix

{
  inputs.pipewire-screenaudio.url = "github:IceDBorn/pipewire-screenaudio";
  # ...

  outputs = {nixpkgs, pipewire-screenaudio, ...} @ inputs: {
    nixosConfigurations.HOSTNAME = nixpkgs.lib.nixosSystem {
      specialArgs = { inherit inputs; }; # this is the important part
      modules = [
        ./configuration.nix
      ];
    };
  }
}

# configuration.nix

{inputs, pkgs, ...}: {
  environment.systemPackages = with pkgs; [
    (firefox.override { nativeMessagingHosts = [ inputs.pipewire-screenaudio.packages.${pkgs.system}.default ]; })
    # ...
  ];
}
```

### Installing from Source

#### Requirements

- cargo
- node.js
- yarn

```bash
git clone https://github.com/IceDBorn/pipewire-screenaudio.git
cd pipewire-screenaudio
bash install.sh
```

For detailed instructions check [INSTALL.md](https://github.com/IceDBorn/pipewire-screenaudio/blob/main/INSTALL.md)

## Usage

- #### Via the extension
  - Install the [extension](https://addons.mozilla.org/firefox/addon/pipewire-screenaudio)
  - Optional: Grant extension with access permissions to all sites
  - Join a WebRTC call, click the extension icon, select an audio node and share
  - Stream, your transmission should contain both audio and video

- #### Via the CLI
  - **Description:** It's used to manually call the commands that are normally called by the extension. It is meant for troubleshooting, but it could be used for integrating the connector with other apps.
  - **Usage:**
    ```bash
    bash native/connector/cli.sh COMMAND ARGUMENTS
    ```
  - **Example:**
    ```bash
    bash native/connector/cli.sh GetNodes
    ```
    ```bash
    bash native/connector/cli.sh SetSharingNode '{ "nodes": [ 10840 ] }'
    ```
    ```bash
    # All desktop audio
    bash native/connector/cli.sh SetSharingNode '{ "nodes": [ -1 ] }'
    ```
    ```bash
    # Multiple nodes
    bash native/connector/cli.sh SetSharingNode '{ "nodes": [ 10840, 10841 ] }'
    ```
  - **Environment:**
    ```bash
    DEBUG=1 # Set to enable verbose logging
    ```

### resistFingerprinting

- privacy.resistFingerprinting (enabled by default in LibreWolf, arkenfox user.js, etc.) breaks the extension. Either disable the preference or add any domains you wish to use Pipewire Screenaudio with to `privacy.resistFingerprinting.exemptedDomains` in `about:config`


================================================
FILE: extension/manifest.json
================================================
{
	"manifest_version": 3,
	"name": "Pipewire Screenaudio",
	"version": "0.4.2",

	"description": "Passthrough pipewire audio to WebRTC screenshare",

	"browser_specific_settings": {
		"gecko": {
			"id": "pipewire-screenaudio@icenjim"
		}
	},

	"action": {
		"default_popup": "react/dist/index.html"
	},

	"icons": {
		"128": "assets/icons/icon.png"
	},

	"content_scripts": [
		{
			"matches": ["<all_urls>"],
			"run_at": "document_start",
			"js": ["scripts/injector.js"],
			"all_frames": true
		}
	],

	"background": {
		"scripts": ["scripts/background.js"],
		"service_worker": "scripts/background.js"
	},

	"permissions": ["nativeMessaging", "storage"],

	"web_accessible_resources": [
		{
			"matches": ["<all_urls>"],
			"resources": ["scripts/override-gdm.js"]
		}
	]
}


================================================
FILE: extension/react/.gitignore
================================================
/dist

================================================
FILE: extension/react/build-watcher.sh
================================================
#!/usr/bin/env bash

scriptRoot="$( cd -- "$(dirname "$0")" > /dev/null 2>&1 ; pwd -P )"

cd $scriptRoot

# Watch for file changes
npx nodemon -e js,jsx --ignore ./dist/ --exec "yarn build && notify-send -i $scriptRoot/../assets/icons/icon.svg 'Pipewire Screenaudio' 'Extension rebuilt'"


================================================
FILE: extension/react/components/nodes-table.jsx
================================================
import React from "react";

import Table from "@mui/material/Table";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableBody from "@mui/material/TableBody";
import TableRow from "@mui/material/TableRow";
import TableCell from "@mui/material/TableCell";

import Paper from "@mui/material/Paper";
import Checkbox from "@mui/material/Checkbox";

export default function NodesTable({
	hasError,
	allDesktopAudio,
	nodes,
	nodeSelection,
	toggleNodes,
}) {
	const allChecked = nodes.every((node) => nodeSelection.has(node.serial));

	return (
		<TableContainer
			component={Paper}
			sx={{
				minHeight: 100,
				maxHeight: 275,
				borderRadius: 0,
			}}
		>
			<Table
				size="small"
				disabled={hasError}
			>
				<TableHead
					sx={{
						position: "sticky",
						top: 0,
						zIndex: 10,
						background: "#1e1e1e",
						borderBottom: "solid",
						borderColor: "#515151",
					}}
				>
					<TableRow>
						<TableCell>
							<Checkbox
								disabled={allDesktopAudio || hasError}
								onChange={(event) => toggleNodes(null)}
								checked={allChecked}
							/>
						</TableCell>
						<TableCell>Media</TableCell>
						<TableCell>Application</TableCell>
					</TableRow>
				</TableHead>
				<TableBody>
					{nodes.map((node) => (
						<TableRow
							key={node.mediaName}
							sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
						>
							<TableCell>
								<Checkbox
									onChange={(event) => toggleNodes([node.serial])}
									disabled={allDesktopAudio || hasError}
									checked={nodeSelection.has(node.serial)}
								/>
							</TableCell>
							<TableCell component="th" scope="row">
								<div
									style={{
										overflow: "hidden",
										width: 200,
										textOverflow: "ellipsis",
										whiteSpace: "nowrap",
									}}
								>
									{node.mediaName}
								</div>
							</TableCell>
							<TableCell>
								<div
									style={{
										overflow: "hidden",
										width: 140,
										textOverflow: "ellipsis",
										whiteSpace: "nowrap",
									}}
								>
									{node.applicationName}
								</div>
							</TableCell>
						</TableRow>
					))}
				</TableBody>
			</Table>
		</TableContainer>
	);
}


================================================
FILE: extension/react/index.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<body style="width: 500px">
		<div id="root"></div>
		<script type="module" src="/index.jsx"></script>
	</body>
</html>


================================================
FILE: extension/react/index.jsx
================================================
import { createRoot } from "react-dom/client";
import {
	createBrowserRouter,
	useSearchParams,
	RouterProvider,
} from "react-router-dom";

import "@fontsource/roboto/300.css";
import "@fontsource/roboto/400.css";
import "@fontsource/roboto/500.css";
import "@fontsource/roboto/700.css";

import { ThemeProvider, createTheme } from "@mui/material/styles";
import CssBaseline from "@mui/material/CssBaseline";

import Popup from "./routes/popup";

const darkTheme = createTheme({
	palette: {
		mode: "dark",
	},
});

const router = createBrowserRouter([
	{
		path: "/react/dist/index.html",
		element: <PageWrapper />,
	},
]);

function PageWrapper() {
	const [search] = useSearchParams();
	console.log(search);

	if (!search.has("page")) {
		return <Popup />;
	}
}

function App() {
	return (
		<ThemeProvider theme={darkTheme}>
			<CssBaseline />
			<RouterProvider router={router} basename="/react/dist/index.html" />
		</ThemeProvider>
	);
}

const rootEl = document.getElementById("root");
const root = createRoot(rootEl);
root.render(<App />);


================================================
FILE: extension/react/lib/backend.js
================================================
import { MIC_ID, readLocalStorage } from "./local-storage";

const MESSAGE_NAME = "com.icedborn.pipewirescreenaudioconnector";
const EXT_VERSION = chrome.runtime.getManifest().version;

export const ERROR_VERSION_MISMATCH = "Version Mismatch";

export const EVENT_MIC_ID_UPDATED = "onMicIdUpdated";
export const EVENT_MIC_ID_REMOVED = "onMicIdRemoved";

let isStopping = false;

function enqueueCommandToBackground(command) {
	sendMessage("enqueue-command", command);
}

async function sendNativeMessage(command, args) {
	console.log("Sent native message", { command, args });

	const response = await chrome.runtime.sendNativeMessage(MESSAGE_NAME, {
		cmd: command,
		args: args,
	});
	// support previous connector versions
	if (response.success === undefined) {
		return response;
	}
	if (!response.success) {
		throw new Error(
			`unsuccessful message response during call to ${command} with arguments ${JSON.stringify(args)}: ${response.errorMessage}`,
		);
	}
	return response.response;
}

async function sendMessage(message, command) {
	console.log("Sent message", { command, message });

	try {
		return await chrome.runtime.sendMessage({
			messageName: MESSAGE_NAME,
			message: message,
			command: command,
		});
	} catch (err) {
		console.error(
			`Failed message "${message}" with command: ${JSON.stringify(command)}`,
		);
		throw err;
	}
}

function matchVersion(a, b) {
	const aSplit = a.split(".");
	const bSplit = b.split(".");
	return aSplit[0] === bSplit[0] && aSplit[1] === bSplit[1];
}

function getNewPromise() {
	let resolvePromise, rejectPromise;
	const promise = new Promise((resolve, reject) => {
		resolvePromise = resolve;
		rejectPromise = reject;
	});

	return { promise, resolvePromise, rejectPromise };
}

function handleMessage(message) {
	console.log({ message });

	if (message === EVENT_MIC_ID_UPDATED) {
		readLocalStorage(MIC_ID).then((micId) => {
			const event = new CustomEvent(EVENT_MIC_ID_UPDATED, {
				detail: { micId },
			});
			document.dispatchEvent(event);
		});
	}

	if (message === EVENT_MIC_ID_REMOVED) {
		const event = new CustomEvent(EVENT_MIC_ID_REMOVED);
		document.dispatchEvent(event);
	}
}

chrome.runtime.onMessage.addListener(handleMessage);

export async function healthCheck() {
	const { version: nativeVersion } = await sendNativeMessage("GetVersion");

	if (!matchVersion(nativeVersion, EXT_VERSION)) {
		throw new Error(ERROR_VERSION_MISMATCH, {
			cause: {
				nativeVersion,
				extensionVersion: EXT_VERSION,
			},
		});
	}

	return true;
}

export async function getNodes() {
	return await sendNativeMessage("GetNodes");
}

export async function isPipewireScreenAudioRunning(micId) {
	return (await sendNativeMessage("IsPipewireScreenAudioRunning", { micId }))
		.isRunning;
}

export function startPipewireScreenAudio() {
	isStopping = false;
	enqueueCommandToBackground({
		cmd: "StartPipewireScreenAudio",
		maps: { outMap: [[MIC_ID, "micId"]] }, // Set the `micId` in LocalStorage to the incoming `micId`
		event: EVENT_MIC_ID_UPDATED,
	});
}

export function stopPipewireScreenAudio(micId) {
	isStopping = true;
	enqueueCommandToBackground({
		cmd: "StopPipewireScreenAudio",
		args: { micId },
		maps: { outMap: [[MIC_ID, null]] }, // Clear the `micId` in LocalStorage
		event: EVENT_MIC_ID_REMOVED,
	});
}

export function setSharingNode(nodeSerials) {
	enqueueCommandToBackground({
		cmd: "SetSharingNode",
		args: { nodes: nodeSerials },
		maps: { inMap: [[MIC_ID, "micId"]] }, // Read the `micId` from LocalStorage and pass it as the `micId` arg
	});
}

export const isChromium = () => typeof browser === "undefined";

export const isIncognito = () => {
	if (isChromium()) {
		return false;
	}

	return !!browser?.extension.inIncognitoContext;
}


================================================
FILE: extension/react/lib/hooks.js
================================================
import { useEffect, useRef, useState } from "react";
import { readLocalStorage, updateLocalStorage } from "./local-storage";

export function useDidUpdateEffect(fn, inputs) {
	const didMountRef = useRef(false);

	useEffect(() => {
		if (didMountRef.current) {
			return fn();
		}
		didMountRef.current = true;
	}, inputs);
}

export function useLocalStorage(name) {
	const [data, setData] = useState(undefined);
	const [isLoading, setIsLoading] = useState(true);

	useEffect(() => {
		readLocalStorage(name).then((val) => {
			setData(val);
			setIsLoading(false);
		});
	}, [name]);

	const setStoredData = (val) => {
		setData(val);
		updateLocalStorage(name, val);
	};

	return { isLoading, data, setData: setStoredData };
}


================================================
FILE: extension/react/lib/local-storage.js
================================================
export const SELECTED_NODES = "selectedNodes";
export const MIC_ID = "micId";
export const ALL_DESKTOP = "allDesktopAudio";

export async function readLocalStorage(name) {
	try {
		const stored = await chrome.storage.local.get(name);
		return stored[name] ?? null;
	} catch {
		return null;
	}
}

export async function updateLocalStorage(name, value) {
	await chrome.storage.local.set({ [name]: value });
}


================================================
FILE: extension/react/lib/match-node.js
================================================
export default function matchNode(a, b) {
	return (
		a.serial === b.serial &&
		a.mediaName === b.mediaName &&
		a.applicationName === b.applicationName
	);
}


================================================
FILE: extension/react/routes/popup.jsx
================================================
// TODO: Add nodes sorting
import React, { useCallback, useEffect, useState } from "react";

import Alert from "@mui/material/Alert";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import FormControlLabel from "@mui/material/FormControlLabel";
import Grid from "@mui/material/Grid";
import Paper from "@mui/material/Paper";
import Switch from "@mui/material/Switch";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";

import { useDebouncedCallback } from "use-debounce";

import {
	ERROR_VERSION_MISMATCH,
	EVENT_MIC_ID_UPDATED,
	EVENT_MIC_ID_REMOVED,
	healthCheck,
	getNodes,
	isChromium,
	isIncognito,
	isPipewireScreenAudioRunning,
	startPipewireScreenAudio,
	stopPipewireScreenAudio,
	setSharingNode,
} from "../lib/backend";

import {
	MIC_ID,
	ALL_DESKTOP,
	readLocalStorage,
	updateLocalStorage,
	SELECTED_NODES,
} from "../lib/local-storage";
import { useDidUpdateEffect, useLocalStorage } from "../lib/hooks";

import NodesTable from "../components/nodes-table";
import matchNode from "../lib/match-node";

function mapNode(node) {
	return {
		mediaName: node.properties["media.name"],
		applicationName: node.properties["application.name"],
		serial: node.properties["object.serial"],
		checked: false,
	};
}

/**
 * @param {Object} param0
 * @param {object[]} param0.nodes
 * @param {boolean} param0.areNodesLoading
 */
function useNodeSelectionState({ nodes, areNodesLoading }) {
	const {
		data: storedNodeSelection,
		setData: setStoredNodeSelection,
		isLoading,
	} = useLocalStorage(SELECTED_NODES);

	if (isLoading || areNodesLoading) return { isLoading: true };

	let nodeSelection;

	if (!nodes) {
		nodeSelection = new Set(
			(storedNodeSelection ?? []).map((node) => node.serial),
		);
	} else {
		nodeSelection = new Set(
			(storedNodeSelection ?? [])
				.filter((selectedNode) =>
					nodes.some((node) => matchNode(node, selectedNode)),
				)
				.map((node) => node.serial),
		);
	}

	/**
	 * @type {function(int[]):void}
	 */
	const toggleNodes = (serials) => {
		let newNodeSelection;
		if (serials === null) {
			const turnOn = !nodes.every((node) => nodeSelection.has(node.serial));
			newNodeSelection = new Set(
				turnOn ? nodes.map((node) => node.serial) : [],
			);
		} else {
			newNodeSelection = new Set(nodeSelection);
			for (const serial of serials) {
				if (newNodeSelection.has(serial)) {
					newNodeSelection.delete(serial);
				} else {
					newNodeSelection.add(serial);
				}
			}
		}
		setStoredNodeSelection(
			nodes.filter((node) => newNodeSelection.has(node.serial)),
		);
	};

	return { isLoading: false, nodeSelection, toggleNodes };
}

function useHealthchecks() {
	const [isLoading, setIsLoading] = useState(true);
	const [versionMatches, setVersionMatches] = useState(null);
	const [connectorConnection, setConnectorConnection] = useState(false);
	const [extensionVersion, setExtensionVersion] = useState(null);
	const [nativeVersion, setNativeVersion] = useState(null);

	useEffect(() => {
		(async () => {
			try {
				const health = await healthCheck();
				setVersionMatches(health);
				setConnectorConnection(true);
			} catch (err) {
				if (err.message === ERROR_VERSION_MISMATCH) {
					setNativeVersion(err.cause.nativeVersion);
					setExtensionVersion(err.cause.extensionVersion);
					setVersionMatches(false);
					setConnectorConnection(true);
				}
			}
			setIsLoading(false);
		})();
	}, []);

	return {
		isLoading,
		versionMatches,
		connectorConnection,
		extensionVersion,
		nativeVersion,
	};
}

/**
 * @param {Object} param0
 * @param {boolean} param0.enabled
 */
function useNodes({ enabled }) {
	const [nodes, setNodes] = useState(null);
	const [isInitialized, setIsInitialized] = useState(false);
	const [isErrored, setIsErrored] = useState(false);

	useEffect(() => {
		if (!enabled) return;

		let previousNodes = null;
		const nodesReceive = async () => {
			try {
				const n = await getNodes();
				const currentNodesStr = JSON.stringify(n);
				if (currentNodesStr !== previousNodes) setNodes(n.map(mapNode));
				previousNodes = currentNodesStr;
				setIsErrored(false);
			} catch (err) {
				console.error("error receiving nodes: ", err);
				setNodes(null);
				setIsErrored(true);
			}
			if (!isInitialized) setIsInitialized(true);
		};
		nodesReceive();

		let nodesInterval = setInterval(nodesReceive, 2000);

		return () => {
			if (nodesInterval !== null) {
				clearInterval(nodesInterval);
			}
		};
	}, [enabled]);

	return { nodes, isErrored, isInitialized };
}

/**
 * @param {Object} param0
 * @param {boolean} param0.enabled
 */
function useCurrentMicId({ enabled }) {
	const [isRunning, setIsRunning] = useState(null);
	const {
		isLoading: isLocalStorageLoading,
		data: micId,
		setData: setMicId,
	} = useLocalStorage(MIC_ID);
	const [isInitialized, setIsInitialized] = useState(false);

	const shouldListen = enabled && !isLocalStorageLoading;

	function handleMicIdUpdated(id) {
		if (!id) return;
		setMicId(id.detail.micId);
		setIsRunning(true);
	}

	function handleMicIdRemoved() {
		setMicId(null);
		setIsRunning(false);
	}

	useEffect(() => {
		if (!shouldListen) return;

		let func = async () => {
			try {
				const res = await isPipewireScreenAudioRunning(micId);
				console.log({ res, micId });
				if (!res) setMicId(null);
				setIsRunning(res);

				document.addEventListener(EVENT_MIC_ID_UPDATED, handleMicIdUpdated);
				document.addEventListener(EVENT_MIC_ID_REMOVED, handleMicIdRemoved);
			} catch (err) {
				console.error("unhandled error:", err);
			}
			setIsInitialized(true);
		};

		func();

		return () => {
			document.removeEventListener(EVENT_MIC_ID_UPDATED, handleMicIdUpdated);
			document.removeEventListener(EVENT_MIC_ID_REMOVED, handleMicIdRemoved);
		};
	}, [shouldListen]);

	return { isInitialized, micId, isRunning };
}

function useAllDesktopAudio() {
	const { isLoading, data, setData } = useLocalStorage(ALL_DESKTOP);

	return {
		isAllDesktopAudioLoading: isLoading,
		allDesktopAudio: !!data,
		setAllDesktopAudio: setData,
	};
}

export default function Popup() {
	const {
		isLoading: isHealthcheckLoading,
		connectorConnection,
		versionMatches,
		nativeVersion,
		extensionVersion,
	} = useHealthchecks();

	const {
		nodes,
		isErrored: areNodesErrored,
		isInitialized: areNodesInitialized,
	} = useNodes({
		enabled: !isHealthcheckLoading && connectorConnection,
	});
	const nodesSuccessfullyLoaded = areNodesInitialized && !areNodesErrored;

	const {
		isInitialized: isCurrentMicIdInitialized,
		isRunning,
		micId,
	} = useCurrentMicId({
		enabled: !isHealthcheckLoading && connectorConnection,
	});

	const { isAllDesktopAudioLoading, allDesktopAudio, setAllDesktopAudio } =
		useAllDesktopAudio();

	const {
		isLoading: isNodeSelectionLoading,
		nodeSelection,
		toggleNodes,
	} = useNodeSelectionState({
		nodes,
		areNodesLoading: !nodesSuccessfullyLoaded,
	});

	const debouncedSetSharingNodes = useDebouncedCallback(() => {
		setSharingNode(Array.from(nodeSelection));
	}, 1000);

	const debouncedShareAllDesktopAudio = useDebouncedCallback(() => {
		if (allDesktopAudio) {
			setSharingNode([-1]);
		} else {
			setSharingNode([]);
		}
	}, 1000);

	const showConnectionError = !connectorConnection || areNodesErrored;
	const isHealthy =
		!isHealthcheckLoading && versionMatches && !showConnectionError;

	function shareNodes(allDesktopAudio) {
		if (!isHealthy || !isRunning || allDesktopAudio) return;
		debouncedSetSharingNodes();
	}

	async function handleStartStop() {
		if (!isRunning) {
			startPipewireScreenAudio();
			if (allDesktopAudio) {
				setSharingNode([-1]);
			} else {
				setSharingNode(Array.from(nodeSelection));
			}
		} else {
			stopPipewireScreenAudio(micId);
		}
	}

	return (
		!isHealthcheckLoading && (
			<>
				<AppBar position="static">
					<Toolbar>
						<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
							Pipewire Screenaudio
						</Typography>
					</Toolbar>
				</AppBar>
				{(showConnectionError ||
					!versionMatches ||
					(isCurrentMicIdInitialized && isRunning)) && (
					<Alert
						severity={isRunning ? "info" : "error"}
						color={isRunning ? "info" : "error"}
					>
						{showConnectionError
							? "The native connector is missing or misconfigured"
							: !versionMatches
								? `Version mismatch! Extension: ${extensionVersion}, Native: ${nativeVersion}`
								: isRunning
									? `Running with ID: ${micId}`
									: console.error("unreachable")}
					</Alert>
				)}
				{/* Content */}
				{(areNodesInitialized || showConnectionError) &&
					(showConnectionError || !nodes.length ? (
						<Paper sx={{ minHeight: 80, borderRadius: 0 }}>
							<div></div>
							<Typography
								variant="h6"
								component="div"
								sx={{
									flexGrow: 1,
									marginLeft: 13,
									paddingTop: 5,
									paddingBottom: 5,
								}}
							>
								{showConnectionError
									? "Could not retrieve node list"
									: "No nodes available for sharing"}
							</Typography>
						</Paper>
					) : (
						<NodesTable
							nodes={nodes}
							nodeSelection={nodeSelection}
							toggleNodes={(serials) => {
								toggleNodes(serials);
								shareNodes(allDesktopAudio);
							}}
							hasError={!isHealthy}
							allDesktopAudio={allDesktopAudio}
						/>
					))}
				<Paper sx={{ borderRadius: "0", padding: 1 }}>
					<Grid container justify="space-between">
						<span
							title={isChromium() ? "Not supported on Chromium browsers" : ""}
						>
							<FormControlLabel
								control={
									<Switch
										onChange={() => {
											const currentAllDesktopAudio = !allDesktopAudio;
											setAllDesktopAudio(currentAllDesktopAudio);

											if (currentAllDesktopAudio) {
												debouncedShareAllDesktopAudio();
											} else {
												shareNodes(currentAllDesktopAudio);
											}
										}}
									/>
								}
								sx={{ marginLeft: 0 }}
								label="All Desktop Audio"
								checked={allDesktopAudio}
								disabled={!isHealthy || isAllDesktopAudioLoading || isChromium() || isIncognito()}
							/>
						</span>
						<Button
							sx={{
								minWidth: 75,
								marginLeft: "auto",
							}}
							variant="contained"
							color={isRunning ? "error" : "success"}
							onClick={handleStartStop}
							disabled={!isHealthy || !isCurrentMicIdInitialized}
						>
							{isRunning ? "Stop" : "Start"}
						</Button>
					</Grid>
				</Paper>
			</>
		)
	);
}


================================================
FILE: extension/react/vite.config.js
================================================
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
	plugins: [react()],
	base: "/react/dist",
	esbuild: {
		jsxFactory: "React.createElement",
		jsxFragment: "React.Fragment",
	},
	css: {
		modules: {
			localsConvention: "camelCaseOnly",
		},
	},
	build: {
		sourcemap: "inline",
		chunkSizeWarningLimit: Infinity,
	},
});


================================================
FILE: extension/scripts/background.js
================================================
// Any event, that is handled in here, should have a comment with the reason it is handled in here

let commandsQueue = [];
let commandsQueueRunning = false;

async function sendNativeMessage(messageName, cmd, args) {
	const response = await chrome.runtime.sendNativeMessage(messageName, {
		cmd,
		args,
	});
	// support previous connector versions
	if (response.success === undefined) {
		return response;
	}
	if (!response.success) {
		throw new Error(
			`unsuccessful message response during call to ${cmd} with arguments ${JSON.stringify(args)}: ${response.errorMessage}`,
		);
	}
	return response.response;
}

async function runQueuedCommands() {
	commandsQueueRunning = true;

	while (commandsQueue.length) {
		try {
			const command = commandsQueue.shift();
			const args = { ...command.args };
			const { inMap, outMap } = command.maps || {};

			if (inMap) {
				for (const [storageKey, argKey] of inMap) {
					const stored = await chrome.storage.local.get(storageKey);
					args[argKey] = stored[storageKey] ?? null;
				}
			}

			console.log(args);
			const result = await sendNativeMessage(
				command.messageName,
				command.cmd,
				args,
				command.maps,
			);
			console.log(result);

			if (outMap) {
				for (const [storageKey, resultKey] of outMap) {
					await chrome.storage.local.set({
						[storageKey]: resultKey ? result[resultKey] : null,
					});
				}
			}

			if (command.event) {
				chrome.runtime.sendMessage(command.event);
			}
		} catch (err) {
			console.error(err);
		}
	}

	commandsQueueRunning = false;
}

function handleMessage(request) {
	// Run multiple commands sequentially
	if (request.message === "enqueue-command") {
		commandsQueue.push({
			...request.command,
			messageName: request.messageName,
		});
		if (!commandsQueueRunning) {
			runQueuedCommands();
		}
	}

	// Called from injector.js - It cannot directly call sendNativeMessage
	if (request.message === "get-session-type") {
		return sendNativeMessage(request.messageName, "GetSessionType");
	}

	if (request.message === "instance-identifier") {
		return sendNativeMessage(request.messageName, "SetInstanceIdentifier", {
			id: request.instanceIdentifier,
		});
	}
}

chrome.runtime.onMessage.addListener(handleMessage);


================================================
FILE: extension/scripts/injector.js
================================================
const MESSAGE_NAME = "com.icedborn.pipewirescreenaudioconnector";

const nullthrows = (v) => {
	if (v == null) throw new Error("null");
	return v;
};

function injectCode(src) {
	const script = document.createElement("script");
	script.src = src;
	script.onload = function () {
		console.log("pipewire-screenaudio script injected");

		chrome.runtime
			.sendMessage({ messageName: MESSAGE_NAME, message: "get-session-type" })
			.then((response) => {
				if (!response) return;
				window.postMessage({
					message: "set-session-type",
					type: response.type,
				});
			});

		this.remove();
	};

	nullthrows(document.head || document.documentElement).appendChild(script);
}

window.addEventListener("message", ({ data }) => {
	if (data.message === "instance-identifier") {
		chrome.runtime.sendMessage({
			messageName: MESSAGE_NAME,
			message: data.message,
			instanceIdentifier: data.instanceIdentifier,
		});
	}
});

injectCode(chrome.runtime.getURL("/scripts/override-gdm.js"));


================================================
FILE: extension/scripts/override-gdm.js
================================================
(() => {
	let sessionType = null;

	const instanceIdentifier = `pipewire-screenaudio-${createRandomString(16)}`;

	const getTitleWithInstanceIdentifier = (title) =>
		`${title} | ${instanceIdentifier}`;

	function createRandomString(
		length,
		chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
	) {
		const array = new Uint8Array(length);
		crypto.getRandomValues(array);
		return Array.from(array, (byte) => chars[byte % chars.length]).join("");
	}

	function overrideGetDisplayMedia() {
		navigator.mediaDevices.chromiumGetDisplayMedia =
			navigator.mediaDevices.getDisplayMedia;

		const getAudioDevice = async (nameOfAudioDevice) => {
			await navigator.mediaDevices.getUserMedia({
				audio: true,
			});

			await new Promise((resolve, reject) => setTimeout(resolve, 1000));
			const devices = await navigator.mediaDevices.enumerateDevices();

			const audioDevice = devices.find(
				({ label }) => label === nameOfAudioDevice,
			);

			return audioDevice;
		};

		const getDisplayMedia = async (constraints = {}) => {
			// Keep the original constraints (video fps/resolution/etc) and only
			// inject `pipewire-screenaudio` audio track when appropriate.
			const originalGetDisplayMedia =
				navigator.mediaDevices.chromiumGetDisplayMedia.bind(
					navigator.mediaDevices,
				);

			// If caller doesn't request audio, or provided an explicit deviceId,
			// forward constraints unchanged.
			if (
				!constraints.audio ||
				(typeof constraints.audio === "object" &&
					constraints.audio !== null &&
					(constraints.audio.deviceId || constraints.audio.deviceId === 0))
			) {
				return await originalGetDisplayMedia(constraints);
			}

			let micId;
			try {
				micId = await getAudioDevice("pipewire-screenaudio").then(
					({ deviceId }) => deviceId,
				);
			} catch {
				return await originalGetDisplayMedia(constraints);
			}

			const capturePipewireScreenaudioMic =
				await navigator.mediaDevices.getUserMedia({
					audio: {
						deviceId: { exact: micId },
						autoGainControl: false,
						echoCancellation: false,
						noiseSuppression: false,
					},
				});

			const [track] = capturePipewireScreenaudioMic.getAudioTracks();

			const displayMedia = await originalGetDisplayMedia(constraints);
			displayMedia.addTrack(track);

			const isChromium = typeof window.chrome !== "undefined";
			let stopWatchTitle;

			if (!isChromium) {
				stopWatchTitle = watchTitle();
				document.title = document.title;

				// Send the node name to exclude for All Desktop Audio
				window.postMessage({
					message: "instance-identifier",
					instanceIdentifier,
				});
			}

			// Watch track and clear instance when ended
			// Workaround solution for firefox, because it does not support MediaStream's inactive event
			const trackWatcher = setInterval(() => {
				if (track.readyState !== "ended") return;

				// TODO: Add instance clearing native logic when implementing multiple instances
				console.log("track ended");

				if (stopWatchTitle) {
					try {
						stopWatchTitle();
					} catch (e) {
						console.error("error while stop watching title.", e);
					}
				}

				clearInterval(trackWatcher);
			}, 50);

			return displayMedia;
		};

		navigator.mediaDevices.getDisplayMedia = getDisplayMedia;
	}

	// Watch the title element for changes and append our identifier if missing
	function watchTitle() {
		const titleEl = document.querySelector("title");
		if (!titleEl) return;

		const titleWatcher = new MutationObserver((mutations) => {
			for (const mut of mutations) {
				if (["childList", "characterData"].includes(mut.type)) {
					if (document.title.includes(instanceIdentifier)) break;
					document.title = getTitleWithInstanceIdentifier(document.title);
					break;
				}
			}
		});

		titleWatcher.observe(titleEl, {
			childList: true,
			characterData: true,
			subtree: true,
		});

		return () => titleWatcher.disconnect();
	}

	overrideGetDisplayMedia();

	const onMessageHooks = {};

	// Store the session type we get (either "x11" or "wayland") into sessionType
	// This message gets sent from the onload listener in injector.js
	const onMessage = (event) => {
		if (event.target !== window) return;
		if (event.data.message === "set-session-type") {
			sessionType = event.data.type;
			window.removeEventListener("message", onMessage);
		}

		Object.values(onMessageHooks).forEach((hook) => hook(event));
	};

	window.addEventListener("message", onMessage);
})();


================================================
FILE: flake.nix
================================================
{
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
  description = "The native part of the Pipewire Screenaudio extension";

  outputs =
    { self, nixpkgs }:
    let
      forAllSystems = nixpkgs.lib.genAttrs systems;
      pkgsFor = nixpkgs.legacyPackages;
      read = builtins.readFile;
      systems = [
        "aarch64-linux"
        "i686-linux"
        "x86_64-linux"
      ];
      write = builtins.toFile;

      mkDate =
        longDate:
        with builtins;
        (concatStringsSep "-" [
          (substring 0 4 longDate)
          (substring 4 2 longDate)
          (substring 6 2 longDate)
        ]);

      manifestJSON = write "manifest.json" (read native/native-messaging-hosts/com.icedborn.pipewirescreenaudioconnector.json);
      connectorPath = "lib/mozilla/native-messaging-hosts/com.icedborn.pipewirescreenaudioconnector.json";
    in
    {
      packages = forAllSystems (
        system:
        let
          pkgs = pkgsFor.${system};
          fs = pkgs.lib.fileset;
        in
        rec {
          default =
            with pkgs;
            rustPlatform.buildRustPackage {
              name = "pipewire-screenaudio";
              version = mkDate (self.lastModifiedDate or "19700101") + "_" + (self.shortRev or "dirty");

              src = ./native/connector-rs;
              nativeBuildInputs = [
                pkg-config
              ];
              buildInputs = [
                pipewire
              ];
              LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath [
                libclang
              ];
              BINDGEN_EXTRA_CLANG_ARGS = ''
                -I${glibc.dev}/include
              '';
              cargoLock.lockFile = ./native/connector-rs/Cargo.lock;

              postInstall = ''
                # Firefox manifest
                install -Dm644 ${manifestJSON} "$out/${connectorPath}"
                substituteInPlace "$out/${connectorPath}" \
                    --replace "CONNECTOR_BINARY_PATH" "$out/bin/connector-rs" \
                    --replace "ALLOWED_FIELD" "allowed_extensions" \
                    --replace "ALLOWED_VALUE" "pipewire-screenaudio@icenjim"
              '';
            };
          extension-react = pkgs.stdenvNoCC.mkDerivation (finalAttrs: {
            pname = "pipewire-screenaudio-extension-react";
            version = "0.4.2";

            src = fs.toSource {
              root = ./.;
              fileset = fs.unions [
                ./yarn.lock
                ./package.json
                ./extension/react
              ];
            };

            yarnOfflineCache = pkgs.fetchYarnDeps {
              yarnLock = finalAttrs.src + "/yarn.lock";
              hash = "sha256-Z/4lmw+AiiQycsppLna+Y2uFKd+5RTAUjILQVqN5mOM=";
            };

            nativeBuildInputs = with pkgs; [
              yarnConfigHook
              yarnBuildHook
              # Needed for executing package.json scripts
              nodejs
            ];
            installPhase = ''
              cp -r extension/react/dist $out/
            '';
          });
          extension =
            pkgs.runCommand "pipewire-screenaudio-extension"
              {
                src = fs.toSource {
                  root = ./extension;
                  fileset = fs.difference ./extension (
                    fs.fileFilter (file: file.name == ".prettierrc.yml") ./extension
                  );
                };
                nativeBuildInputs = with pkgs; [
                  zip
                ];
              }
              ''
                mkdir -p release

                mkdir -p release/react
                ln -s ${extension-react} release/react/dist

                cp -r $src/scripts $src/assets $src/manifest.json release/

                cd release
                zip -r - . > $out
              '';
        }
      );
      devShells = forAllSystems (
        system: with pkgsFor.${system}; {
          default = mkShell {
            buildInputs = [
              cargo
              clippy
              nodejs
              pipewire
              pkg-config
              rust-analyzer
              rustc
              rustfmt
              yarn
            ];
            LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath [
              libclang
            ];
            BINDGEN_EXTRA_CLANG_ARGS = ''
              -I${glibc.dev}/include
            '';
          };
        }
      );
    };
}


================================================
FILE: install.sh
================================================
#!/usr/bin/env bash
set -e

DEFAULT_CHROMIUM_EXT_ID="cbmjbapailadjabjnjnnbfdimkbdicja"
REQUIRED_BINS_JS=("yarn")
REQUIRED_BINS_RUST=("cargo")

projectRoot="$( cd -- "$(dirname "$0")" > /dev/null 2>&1 ; pwd -P )"
jsonTemplate="$projectRoot/native/native-messaging-hosts/com.icedborn.pipewirescreenaudioconnector.json"

function prompt_yn_question() {
	local prompt="$1"
	local default="$2"

	if [[ "$default" == "Y" ]]; then
		promptPostfix="[Y/n]"
		defaultReturn="0"
	else
		promptPostfix="[y/N]"
		defaultReturn="1"
	fi

	while true; do
		read -p "$prompt $promptPostfix: " yn

		[ -z "$yn" ] && return $defaultReturn

		case $yn in
			[Yy]*) return 0 ;;
			[Nn]*) return 1 ;;
			*) echo "Please answer yes (y) or no (n)." ;;
		esac
	done
}

function prompt_browser_type() {
	while true; do
		read -p "Select browser type (1 = Firefox-based, 2 = Chromium-based): " browser_num

		case $browser_num in
			1) BROWSER="firefox"; return ;;
			2) BROWSER="chromium"; return ;;
			*) echo -e "Invalid selection.\n" ;;
		esac
	done
}

function prompt_required_value() {
	local prompt="$1"
	local emptyMessage="$2"

	while true; do
		read -p "$prompt" returnValue

		if [[ -z "$returnValue" ]]; then
			[[ ! -z "$emptyMessage" ]] && echo "$emptyMessage" >/dev/stderr
			continue
		fi

		echo "$returnValue"
		break
	done
}

function prompt_native_messaging_hosts_path() {
	local dir

	while true; do
		dir=$(
			prompt_required_value \
				"Directory path: " \
				"Directory path cannot be empty. Please try again."
		)

		dir=$(eval echo "$dir") # Replace ~/ with absolute path
		if [[ ! -d "$dir" ]]; then
			echo "Directory \"$dir\" does not exist."

			if prompt_yn_question "Do you want to create it?" "N"; then
				mkdir -p "$dir" && echo "Created directory: $dir"
			else
				echo -e "Please provide a valid directory path or create it."
				continue 2
			fi
		fi

		DIR="$dir"
		return
	done
}

function prompt_chromium_extension_id() {
	while true; do
		read -p "Provide the extension ID (default: $DEFAULT_CHROMIUM_EXT_ID). Press enter to use default: " extid
		if [[ -z "$extid" ]]; then
			echo "$DEFAULT_CHROMIUM_EXT_ID"
			return
		else
			echo "$extid"
			return
		fi
	done
}

function check_required_bins() {
	for bin in "${@}"; do
		if command -v "$bin" >/dev/null; then
			continue
		fi

		echo "$bin: command not found" >/dev/stderr
		exit 1
	done
}

if [[ "$DEBUG" != 1 ]] && ! prompt_yn_question "Can you confirm that you are following our instructions in INSTALL.md ?" "N"; then
	echo "Please read the instructions before proceeding." >/dev/stderr
	echo "https://github.com/IceDBorn/pipewire-screenaudio/blob/main/INSTALL.md" >/dev/stderr
	exit 1
fi

# Build React
if prompt_yn_question "Do you want to build the extension?" "N"; then
	check_required_bins "${REQUIRED_BINS_JS[@]}"
	( cd "$projectRoot/extension/react" && yarn install && yarn build || exit 1 ) || exit 1
	echo
else
	echo "Skipping extension build."
fi

# Build Rust
while true; do
	if [[ -f "/usr/lib/pipewire-screenaudio/connector/connector-rs" ]] && prompt_yn_question "Do you want to use the installed native connector binary?" "Y" ; then
		CONNECTOR_PATH="/usr/lib/pipewire-screenaudio/connector/connector-rs"
	elif prompt_yn_question "Do you want to build the native connector?" "Y"; then
		check_required_bins "${REQUIRED_BINS_RUST[@]}"
		( cd "$projectRoot/native/connector-rs" && cargo build || exit 1 ) || exit 1
		echo
		CONNECTOR_PATH="$projectRoot/native/connector-rs/target/debug/connector-rs"
	else
		echo -e "Native connector is required.\n" >/dev/stderr
		continue
	fi

	break
done

# Browser type selection
prompt_browser_type

# Native messaging hosts path selection
echo -e "Provide the browser native messaging hosts directory path:"
if [[ "$BROWSER" == "firefox" ]]; then
	echo "Example paths: ~/.config/mozilla/firefox/native-messaging-hosts, ~/.mozilla/native-messaging-hosts"
	prompt_native_messaging_hosts_path
	ALLOWED_FIELD="allowed_extensions"
	ALLOWED_VALUE="pipewire-screenaudio@icenjim"
elif [[ "$BROWSER" == "chromium" ]]; then
	echo "Example path: ~/.config/google-chrome/NativeMessagingHosts"
	prompt_native_messaging_hosts_path
	extid=$(prompt_chromium_extension_id)
	ALLOWED_FIELD="allowed_origins"
	ALLOWED_VALUE="chrome-extension://$extid/"
fi

# Prepare and install json to native messaging hosts path
output_json="$DIR/com.icedborn.pipewirescreenaudioconnector.json"
tmp_json=$(mktemp)

# Replace values in JSON
cp "$jsonTemplate" "$tmp_json"
sed -i "s|CONNECTOR_BINARY_PATH|$CONNECTOR_PATH|g" "$tmp_json"
sed -i "s|ALLOWED_FIELD|$ALLOWED_FIELD|g" "$tmp_json"
sed -i "s|ALLOWED_VALUE|$ALLOWED_VALUE|g" "$tmp_json"

if cp "$tmp_json" "$output_json"; then
	echo "Installed native messaging hosts manifest json file to $output_json"
else
	echo "Failed to write manifest. Please check permissions and try again."
	exit 1
fi

rm "$tmp_json"


================================================
FILE: native/.gitignore
================================================
build
out


================================================
FILE: native/connector/cli.sh
================================================
#!/usr/bin/env bash

export LC_ALL=C
export PROJECT_ROOT="$( cd -- "$(dirname "$0")" > /dev/null 2>&1 ; cd .. ; pwd -P )"
source $PROJECT_ROOT/connector/util.sh

cmd=$1
args=$2

json="{ \"cmd\": \"$cmd\" }"
if [[ -n "$args" ]]; then
	json=$(echo $json | jq --arg args "$args" '. + { args: ($args | fromjson) }')
fi

echo $cmd $args $json >/dev/stderr

UtilTextToMessage "$json" \
  | (
    cd $PROJECT_ROOT/connector-rs
    if [[ "$DEBUG" -eq 1 ]]; then
      export RUST_BACKTRACE=1
      export RUST_LOG=debug
    fi
    cargo run
  ) \
  | ( head -c 4 >/dev/null ; jq )


================================================
FILE: native/connector/util.sh
================================================
#!/usr/bin/bash

TEMP_PATH_ROOT="$XDG_RUNTIME_DIR/pipewire-screenaudio"
FIFO_PATH="$TEMP_PATH_ROOT/fifos"
LOG_PATH="$TEMP_PATH_ROOT/logs"

mkdir -p $LOG_PATH
MAIN_LOG_PATH="$LOG_PATH/main.log"

CURRENT_PID=$$

set -e

UtilGetFifoPath () {
  local virtmicId="$1"
  mkdir -p $FIFO_PATH
  printf "$FIFO_PATH/$virtmicId"
}

function UtilBinToInt () {
  head -c 4 |                             # Read 4 bytes
    hexdump |                             # Read raw bytes as hex
    head -n 1 |                           # Discard new line
    awk '{print "0x"$3$2}' |              # Format hex number
    xargs -I {} bash -c 'echo $(( {} ))'  # Return int
}

function UtilIntToBin () {
  printf '%08x' $1 |                  # Convert integer to 8 digit hex
    sed 's/\(..\)/\1 /g' |            # Split hex to pairs (bytes)
    awk '{printf $4 $3 $2 $1}' |      # Reverse order of bytes
    sed 's/\(..\)\s*/\\\\x\1/g' |     # Prefix bytes with \\x
    xargs -I {} bash -c "printf '{}'" # Return raw bytes
}

function UtilTextToMessage () {
  local message="$1"
  local messageLength=`echo -n "$message" | wc -c`

  UtilLog "[util.sh] [Sending Message] $message Length: $messageLength"

  UtilIntToBin $messageLength
  echo -n "$message"
}

function UtilGetPayload () {
  payloadLength=`UtilBinToInt`
  UtilLog "[util.sh] [Reading Bytes] $payloadLength"

  payload=`head -c "$payloadLength"`
  UtilLog "[util.sh] [Got Payload] $payload"

  cmd=`echo "$payload" | jq -r .cmd`
  UtilLog "[util.sh] [Got Cmd] $cmd"

  args=`echo "$payload" | jq .args`
  UtilLog "[util.sh] [Got Args] $args"
}

function UtilGetArg () {
  local field="$1"
  UtilLog "[util.sh] [Reading Arg] $field"
  local arg=`echo "$args" | jq -rc ".$field" | head -n 1`
  UtilLog "[util.sh] [Arg Value] `[ "$arg" = "" ] && printf 'null' || printf "%s" "$arg"`"
  printf "%s" "$arg"
}

function UtilLog () {
  echo "$@" >> $MAIN_LOG_PATH
  # notify-send "$@"
}

function UtilGetLogPathForFile () {
  mkdir -p "$LOG_PATH/file"
  echo "$LOG_PATH/file/$1.log"
}

function UtilGetTempFile () {
  mkdir -p "$XDG_RUNTIME_DIR/tmp"
  mktemp -p "$XDG_RUNTIME_DIR/tmp"
}


================================================
FILE: native/connector-rs/.gitignore
================================================
# Generated by Cargo
# will have compiled files and executables
debug/
target/

# These are backup files generated by rustfmt
**/*.rs.bk

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb


================================================
FILE: native/connector-rs/Cargo.toml
================================================
[package]
name = "connector-rs"
version = "0.4.2"
edition = "2021"

[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
pipewire-utils.path = "pipewire-utils"
ctrlc.workspace = true
thiserror.workspace = true
tracing.workspace = true
tracing-appender = "0.2.3"
tracing-subscriber.workspace = true
tracing-panic = { version = "0.1.2", features = ["capture-backtrace"] }

[workspace]
members = ["pipewire-utils"]
resolver = "3"

[workspace.dependencies]
tracing = "0.1.41"
thiserror = "2.0.17"
ctrlc = { version = "3.5.1", features = ["termination"] }
tracing-subscriber = { version = "0.3.20", features = ["env-filter"] }


================================================
FILE: native/connector-rs/pipewire-utils/.gitignore
================================================
/target
/Cargo.lock


================================================
FILE: native/connector-rs/pipewire-utils/Cargo.toml
================================================
[package]
name = "pipewire-utils"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libspa = "0.9.2"
libspa-sys = "0.9.2"
pipewire = "0.9.2"
pipewire-sys = "0.9.2"
tracing.workspace = true
thiserror.workspace = true

[dev-dependencies]
ctrlc.workspace = true
tracing-subscriber.workspace = true


================================================
FILE: native/connector-rs/pipewire-utils/examples/all-desktop-audio.rs
================================================
use pipewire_utils::{self, cancellation_signal::CancellationSignal, ManagedNode, PipewireClient};
use tracing::Level;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::fmt()
        .with_max_level(Level::TRACE)
        .init();

    let client = PipewireClient::new()?;
    let node = ManagedNode::create_managed_node(&client, "test node")?;
    tracing::info!("created node");

    let (controller, signal) = CancellationSignal::pair();
    ctrlc::set_handler(move || {
        controller.cancel();
    })
    .unwrap();

    tracing::info!("started monitoring");
    client.monitor_and_connect_nodes(node.get_node_with_ports().ports, signal, |_| true)?;

    tracing::info!("finishing");

    Ok(())
}


================================================
FILE: native/connector-rs/pipewire-utils/examples/create-node.rs
================================================
use pipewire_utils::PipewireClient;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = PipewireClient::new()?;

    let node = client.await_create_node("pipewire-screenaudio")?;
    dbg!(node);

    Ok(())
}


================================================
FILE: native/connector-rs/pipewire-utils/rustfmt.toml
================================================
tab_spaces=4


================================================
FILE: native/connector-rs/pipewire-utils/src/cancellation_signal.rs
================================================
use std::{
    thread::{self, JoinHandle},
    time::Duration,
};

use pipewire::{
    channel::{channel, AttachedReceiver, Receiver, Sender},
    loop_::Loop,
};

#[derive(Debug)]
pub struct TerminateSignal;

pub struct CancellationSignal {
    receiver: Receiver<TerminateSignal>,
}

pub struct AttachedCancellationSignal<'a> {
    receiver: AttachedReceiver<'a, TerminateSignal>,
}

#[derive(Clone)]
pub struct CancellationController {
    sender: Sender<TerminateSignal>,
}

impl CancellationSignal {
    pub fn pair() -> (CancellationController, CancellationSignal) {
        let (sender, receiver) = channel();
        (
            CancellationController { sender },
            CancellationSignal { receiver },
        )
    }

    pub fn attach(
        self,
        loop_: &Loop,
        callback: impl Fn() + 'static,
    ) -> AttachedCancellationSignal<'_> {
        AttachedCancellationSignal {
            receiver: self.receiver.attach(loop_, move |_| callback()),
        }
    }
}

impl<'a> AttachedCancellationSignal<'a> {
    pub fn deattach(self) -> CancellationSignal {
        CancellationSignal {
            receiver: self.receiver.deattach(),
        }
    }
}

pub struct TimeoutHandle {
    handle: Option<JoinHandle<()>>,
}

impl Drop for TimeoutHandle {
    fn drop(&mut self) {
        let handle = self
            .handle
            .take()
            .expect("handle should always have a value");
        handle.thread().unpark();
        handle.join().unwrap();
    }
}

impl CancellationController {
    pub fn cancel(&self) {
        if self.sender.send(TerminateSignal).is_err() {
            tracing::warn!("error while trying to cancel pipewire loop");
        }
    }

    pub fn timeout(&self, duration: Duration) -> TimeoutHandle {
        let handle = thread::spawn({
            let cloned_self = self.clone();
            move || {
                thread::park_timeout(duration);
                cloned_self.cancel();
            }
        });
        TimeoutHandle {
            handle: Some(handle),
        }
    }
}


================================================
FILE: native/connector-rs/pipewire-utils/src/lib.rs
================================================
pub mod cancellation_signal;
mod monitor;
mod pipewire_client;
mod pipewire_objects;
mod proxies;
mod roundtrip;
mod utils;

pub use pipewire_client::*;
pub use pipewire_objects::{NodeWithPorts, Ports};
pub use utils::ManagedNode;


================================================
FILE: native/connector-rs/pipewire-utils/src/monitor.rs
================================================
use std::{
    cell::{Cell, RefCell},
    collections::{hash_map::Entry, HashMap, HashSet},
    rc::Rc,
};

use pipewire::{
    link::Link,
    proxy::{ProxyListener, ProxyT},
};
use tracing::instrument;

use crate::pipewire_objects::{OwnedPortInfo, PortInfo};

#[derive(Clone)]
pub struct NodeAndPortsRegistry<AddedCallback, RemovedCallback> {
    relevant_nodes: Rc<RefCell<HashSet<u32>>>,
    nodes_to_ports: Rc<RefCell<HashMap<u32, HashSet<u32>>>>,
    ports: Rc<RefCell<HashMap<u32, OwnedPortInfo>>>,
    relevant_port_added_callback: Option<AddedCallback>,
    relevant_port_removed_callback: Option<RemovedCallback>,
}

impl<AddedCallback, RemovedCallback> Default
    for NodeAndPortsRegistry<AddedCallback, RemovedCallback>
{
    fn default() -> Self {
        Self {
            relevant_nodes: Rc::new(RefCell::new(HashSet::new())),
            nodes_to_ports: Rc::new(RefCell::new(HashMap::<u32, HashSet<u32>>::new())),
            ports: Rc::new(RefCell::new(HashMap::<u32, OwnedPortInfo>::new())),
            relevant_port_added_callback: None,
            relevant_port_removed_callback: None,
        }
    }
}

impl<AddedCallback: Fn(&OwnedPortInfo), RemovedCallback: Fn(&OwnedPortInfo)>
    NodeAndPortsRegistry<AddedCallback, RemovedCallback>
{
    pub fn set_relevant_port_added_callback(&mut self, callback: AddedCallback) {
        self.relevant_port_added_callback = Some(callback);
    }

    pub fn set_relevant_port_removed_callback(&mut self, callback: RemovedCallback) {
        self.relevant_port_removed_callback = Some(callback);
    }

    fn invoke_for_all_ports_in_node<F: Fn(&OwnedPortInfo)>(&self, node_id: u32, callback: F) {
        if let Some(port_ids) = self.nodes_to_ports.borrow().get(&node_id) {
            let ports = self.ports.borrow();
            for port_id in port_ids {
                let port_info = ports.get(port_id).expect("there must be info");

                callback(port_info);
            }
        }
    }

    pub fn is_node_relevant(&self, node_id: u32) -> bool {
        self.relevant_nodes.borrow().contains(&node_id)
    }

    #[instrument(skip(self))]
    pub fn add_relevant_node(&self, node_id: u32) {
        self.relevant_nodes.borrow_mut().insert(node_id);

        if let Some(callback) = &self.relevant_port_added_callback {
            self.invoke_for_all_ports_in_node(node_id, callback);
        }
    }

    #[instrument(skip(self))]
    pub fn try_remove_relevant_node(&self, node_id: u32) -> bool {
        let removed = self.relevant_nodes.borrow_mut().remove(&node_id);

        if removed {
            if let Some(callback) = &self.relevant_port_removed_callback {
                self.invoke_for_all_ports_in_node(node_id, callback);
            }
        }

        removed
    }

    #[instrument(skip(self))]
    pub fn add_port(&self, port_info: PortInfo<'_>) {
        match self.nodes_to_ports.borrow_mut().entry(port_info.node_id) {
            Entry::Vacant(entry) => {
                entry.insert(HashSet::from_iter([port_info.id]));
            }
            Entry::Occupied(mut entry) => {
                let node_ports = entry.get_mut();
                node_ports.insert(port_info.id);
            }
        }

        let port_info = OwnedPortInfo::from(port_info);

        if self.relevant_nodes.borrow().contains(&port_info.node_id) {
            tracing::trace!(port_id = port_info.id, "port is from a relevant node");
            if let Some(callback) = &self.relevant_port_added_callback {
                callback(&port_info);
            }
        }

        self.ports.borrow_mut().insert(port_info.id, port_info);
    }

    #[instrument(skip(self))]
    pub fn try_remove_port(&self, port_id: u32) -> Option<OwnedPortInfo> {
        let port_info = self.ports.borrow_mut().remove(&port_id);
        if let Some(port_info) = port_info.as_ref() {
            if self.relevant_nodes.borrow().contains(&port_info.node_id) {
                if let Some(callback) = &self.relevant_port_removed_callback {
                    callback(port_info);
                }
            }
            self.nodes_to_ports
                .borrow_mut()
                .get_mut(&port_info.node_id)
                .unwrap()
                .remove(&port_id);
        }
        port_info
    }
}

pub struct LinkTrackerHandle {
    #[expect(unused)]
    listener: ProxyListener,
    id: Rc<Cell<Option<u32>>>,
}

impl LinkTrackerHandle {
    pub fn new(link: Link) -> Self {
        let id = Rc::new(Cell::new(None));
        let listener = link
            .upcast()
            .add_listener_local()
            .bound({
                let id = id.clone();
                move |link_id| {
                    id.set(Some(link_id));
                }
            })
            .register();
        Self { listener, id }
    }

    pub fn id(&self) -> Option<u32> {
        self.id.get()
    }
}


================================================
FILE: native/connector-rs/pipewire-utils/src/pipewire_client.rs
================================================
use std::{
    cell::{OnceCell, RefCell},
    collections::{HashMap, HashSet},
    rc::Rc,
};

use libspa::utils::dict::DictRef;
use pipewire::{
    context::ContextRc,
    core::CoreRc,
    keys,
    link::Link,
    main_loop::MainLoopRc,
    node::{Node, NodeChangeMask, NodeInfoRef},
    properties::properties,
    proxy::ProxyT,
    registry::{GlobalObject, Listener, RegistryRc},
    types::ObjectType,
};
use thiserror::Error;
use tracing::instrument;

use crate::{
    cancellation_signal::CancellationSignal,
    monitor::{LinkTrackerHandle, NodeAndPortsRegistry},
    pipewire_objects::*,
    proxies::ProxyRefs,
    roundtrip::{Scheduler, StopSettings, StopSettingsBuilder},
};

#[derive(Error, Debug)]
#[error("internal pipewire error {0:?}")]
pub struct PipewireError(#[from] pipewire::Error);

pub type Result<T, E = PipewireError> = std::result::Result<T, E>;

#[derive(Clone)]
pub struct PipewireClient {
    mainloop: MainLoopRc,
    #[allow(unused)]
    context: ContextRc,
    core: CoreRc,
}

pub enum IterationAction {
    Stop,
    ScheduleRoundtrip,
}

#[derive(Clone)]
struct IterationContext {
    registry: RegistryRc,
    scheduler: Scheduler,
}

#[derive(Debug)]
pub struct NodeProperties {
    pub application_name: Option<String>,
    pub media_name: String,
    pub object_serial: i64,

    pub media_class: String,
}

#[derive(Debug)]
pub struct OutputNode {
    pub id: u32,
    pub properties: NodeProperties,
}

#[derive(Error, Debug)]
pub enum OutputNodeCreationError {
    #[error("missing property dictionary")]
    MissingPropertyDict,
    #[error("missing some properties: {properties:?}")]
    MissingProperties { properties: Vec<&'static str> },
}

impl TryFrom<&NodeInfoRef> for OutputNode {
    type Error = OutputNodeCreationError;
    fn try_from(value: &NodeInfoRef) -> Result<Self, Self::Error> {
        let Some(props) = value.props() else {
            return Err(OutputNodeCreationError::MissingPropertyDict);
        };
        let application_name = props.get("application.name");
        let object_serial = props.get("object.serial");
        let media_class = props.get("media.class");
        let media_name = props.get("media.name");
        let (Some(object_serial), Some(media_class), Some(media_name)) =
            (object_serial, media_class, media_name)
        else {
            return Err(OutputNodeCreationError::MissingProperties {
                properties: [
                    (object_serial, "object.serial"),
                    (media_class, "media.class"),
                    (media_name, "media.name"),
                ]
                .into_iter()
                .flat_map(|(prop, name)| prop.is_none().then_some(name))
                .collect(),
            });
        };

        Ok(OutputNode {
            id: value.id(),
            properties: {
                NodeProperties {
                    application_name: application_name.map(|s| s.to_owned()),
                    media_name: media_name.to_owned(),
                    object_serial: object_serial.parse().unwrap(),
                    media_class: media_class.to_owned(),
                }
            },
        })
    }
}
impl IterationContext {
    #[instrument(skip_all)]
    fn stop(&self) {
        tracing::trace!("stopping scheduler");
        self.scheduler.stop();
    }

    #[instrument(skip_all)]
    fn schedule_roundtrip(&self) {
        tracing::trace!("scheduling roundtrip");
        self.scheduler.schedule_roundtrip();
    }
}

struct NodeListenerHandle {
    #[allow(unused)]
    registry_listener: Listener,
    #[allow(unused)]
    proxies: Rc<RefCell<ProxyRefs>>,
}

impl PipewireClient {
    pub fn new() -> Result<Self> {
        let mainloop = MainLoopRc::new(None)?;
        let context = ContextRc::new(&mainloop, None)?;
        let core = context.connect_rc(None)?;

        Ok(Self {
            mainloop,
            context,
            core,
        })
    }

    fn create_scheduler(&self) -> Scheduler {
        //let mainloop = MainLoopRc::new(None).unwrap();
        //let context = ContextRc::new(&mainloop, None).unwrap();
        //let core = context.connect_rc(None).unwrap();

        //Scheduler::new(mainloop, core)
        Scheduler::new(self.mainloop.clone(), self.core.clone())
    }

    fn do_roundtrip(&self) {
        self.create_scheduler().run(
            StopSettingsBuilder::default()
                .stop_on_last_roundtrip()
                .build(),
        );
    }

    fn iterate_globals(
        &self,
        stop_settings: StopSettings,
        global_callback: impl Fn(&IterationContext, &GlobalObject<&DictRef>) + 'static,
    ) {
        let scheduler = self.create_scheduler();

        let registry = self.core.get_registry_rc().unwrap();

        let iteration_context = IterationContext {
            registry: registry.clone(),
            scheduler: scheduler.clone(),
        };
        let reg_listener = registry
            .add_listener_local()
            .global(move |global| global_callback(&iteration_context, global))
            .register();

        scheduler.run(stop_settings);

        drop(reg_listener);
    }

    fn add_node_listener<F, DF>(
        &self,
        registry: RegistryRc,
        node_callback: F,
        node_destroy_callback: DF,
        scheduler: Option<Scheduler>,
    ) -> NodeListenerHandle
    where
        F: Fn(&NodeInfoRef) + Clone + 'static,
        DF: Fn(u32) + 'static,
    {
        let proxies: Rc<RefCell<ProxyRefs>> = Rc::new(RefCell::new(ProxyRefs::new()));

        let listener = registry
            .add_listener_local()
            .global({
                let proxies = proxies.clone();
                let registry = registry.clone();
                move |global| {
                    if !matches!(global.type_, ObjectType::Node) {
                        return;
                    }
                    let Ok(proxy) = registry.bind::<Node, _>(global) else {
                        tracing::trace!("global {} is not assignable to node", global.id);
                        return;
                    };
                    let listener = proxy
                        .add_listener_local()
                        .info({
                            let node_callback = node_callback.clone();
                            move |node| {
                                node_callback(node);
                            }
                        })
                        .register();
                    if let Some(scheduler) = scheduler.as_ref() {
                        scheduler.schedule_roundtrip();
                    }
                    proxies
                        .borrow_mut()
                        .add_proxy(Box::new(proxy), vec![Box::new(listener)]);
                }
            })
            .global_remove({
                let proxies = proxies.clone();
                move |global_id| {
                    if proxies.borrow_mut().remove_proxy(&global_id) {
                        node_destroy_callback(global_id);
                    }
                }
            })
            .register();

        NodeListenerHandle {
            registry_listener: listener,
            proxies,
        }
    }

    fn iterate_nodes<F>(&self, stop_settings: StopSettings, object_callback: F)
    where
        F: Fn(&IterationContext, &NodeInfoRef) + Clone + 'static,
    {
        let scheduler = self.create_scheduler();

        let registry = self.core.get_registry_rc().unwrap();

        let iteration_context = IterationContext {
            registry: registry.clone(),
            scheduler: scheduler.clone(),
        };
        let reg_listener = self.add_node_listener(
            registry,
            move |node| object_callback(&iteration_context, node),
            |_| {},
            Some(scheduler.clone()),
        );
        scheduler.run(stop_settings);

        drop(reg_listener);
    }

    fn extract_port_info<'a>(global: &'a GlobalObject<&'a DictRef>) -> Option<PortInfo<'a>> {
        let props = global.props?;

        if global.type_ != ObjectType::Port {
            return None;
        }

        let id: u32 = global.id;
        let node_id = props.get(*keys::NODE_ID)?.parse().unwrap();
        let direction = props.get(*keys::PORT_DIRECTION)?.parse().unwrap();
        let channel = AudioChannel::from(props.get(*keys::AUDIO_CHANNEL)?);
        Some(PortInfo {
            channel,
            id,
            node_id,
            direction,
        })
    }

    fn is_global_a_port_for_node<'a>(
        global: &'a GlobalObject<&'a DictRef>,
        direction: PortDirection,
        node_id: u32,
    ) -> Option<PortInfo<'a>> {
        let port_info = Self::extract_port_info(global)?;

        (port_info.node_id == node_id && port_info.direction == direction).then_some(port_info)
    }

    fn find_fl_fr_ports(
        &self,
        node_id: u32,
        direction: PortDirection,
        only_existent: bool,
    ) -> MaybePorts {
        let fl_port = Rc::new(OnceCell::new());
        let fr_port = Rc::new(OnceCell::new());

        self.iterate_globals(
            StopSettingsBuilder::default()
                .set_stop_on_last_roundtrip(only_existent)
                .build(),
            {
                let fl_port = fl_port.clone();
                let fr_port = fr_port.clone();
                move |iteration_context, global| {
                    let Some(port) = Self::is_global_a_port_for_node(global, direction, node_id)
                    else {
                        return;
                    };

                    tracing::debug!(port_id = port.id, node_id, "found port for node");
                    // Save port id into channel cell
                    if let Some(channel_cell) = match port.channel {
                        AudioChannel::FrontLeft => Some(&fl_port),
                        AudioChannel::FrontRight => Some(&fr_port),
                        AudioChannel::Other(_) => None,
                    } {
                        channel_cell
                            .set(port.id)
                            .expect("Node has multiple ports for same channel");
                    }

                    // Stop searching if we found all ports
                    let found_all_ports = [&fl_port, &fr_port]
                        .iter()
                        .all(|port_id| port_id.get().is_some());

                    tracing::trace!(found_all_ports);

                    if found_all_ports {
                        iteration_context.stop();
                    }
                }
            },
        );

        let fl_port = Rc::into_inner(fl_port).unwrap().into_inner();
        let fr_port = Rc::into_inner(fr_port).unwrap().into_inner();

        MaybePorts { fl_port, fr_port }
    }

    fn await_find_fl_fr_ports(&self, node_id: u32, direction: PortDirection) -> Ports {
        self.find_fl_fr_ports(node_id, direction, false)
            .both()
            .unwrap()
    }

    pub fn await_create_node(&self, node_name: impl AsRef<str>) -> Result<NodeWithPorts> {
        let node = self.core.create_object::<Node>(
            "adapter",
            &properties! {
                *keys::FACTORY_NAME => "support.null-audio-sink",
                *keys::NODE_NAME => node_name.as_ref(),
                *keys::NODE_DESCRIPTION => node_name.as_ref(),
                *keys::MEDIA_CLASS => "Audio/Source/Virtual",
                "audio.position" => "[FL, FR]",
                *keys::OBJECT_LINGER => "1",
            },
        )?;

        Ok(self.await_node_creation(node))
    }

    pub fn destroy_global(&self, global_id: u32) -> Result<()> {
        let registry = self.core.get_registry()?;
        registry.destroy_global(global_id);
        self.do_roundtrip();
        Ok(())
    }

    fn unlink_ports(&self, ports: HashSet<u32>) {
        tracing::debug!(?ports, "removing links to ports");
        let is_link_to_port = move |global: &GlobalObject<&DictRef>| {
            if global.type_ != ObjectType::Link {
                return false;
            }
            let Some(props) = global.props else {
                return false;
            };
            let Some(output_port) = props.get("link.input.port") else {
                return false;
            };
            let Ok(output_port) = output_port.parse::<u32>() else {
                return false;
            };
            ports.contains(&output_port)
        };

        self.iterate_globals(
            StopSettingsBuilder::default()
                .stop_on_last_roundtrip()
                .build(),
            {
                move |iteration_context, global| {
                    if is_link_to_port(global) {
                        tracing::trace!(link_id = global.id, "removing link");
                        iteration_context.registry.destroy_global(global.id);
                        iteration_context.schedule_roundtrip();
                    }
                }
            },
        );
        tracing::trace!("links removed");
    }

    pub fn unlink_node_ports(&self, ports: Ports) {
        self.unlink_ports(HashSet::from_iter([ports.fl_port, ports.fr_port]));
    }

    fn await_node_creation(&self, node: Node) -> NodeWithPorts {
        let node_id = Rc::new(OnceCell::new());

        tracing::trace!("awaiting to find node");
        let listener = node
            .upcast()
            .add_listener_local()
            .bound({
                let node_id = node_id.clone();
                move |id| {
                    tracing::trace!("node {id} was bound");
                    node_id.set(id).unwrap()
                }
            })
            .register();

        self.do_roundtrip();
        drop(listener);

        let node_id = Rc::into_inner(node_id).unwrap().into_inner().unwrap();

        tracing::trace!("awaiting to find ports");
        let ports = self.await_find_fl_fr_ports(node_id, PortDirection::Input);

        NodeWithPorts { id: node_id, ports }
    }

    fn link_ports(&self, from: u32, to: u32) -> Result<Link, pipewire::Error> {
        self.core.create_object::<Link>(
            "link-factory",
            &properties! {
                *keys::LINK_INPUT_PORT => to.to_string(),
                *keys::LINK_OUTPUT_PORT => from.to_string(),
                *keys::OBJECT_LINGER => "1",
            },
        )
    }

    #[instrument(skip(self))]
    fn try_link_ports(&self, from: u32, to: u32) {
        match self.link_ports(from, to) {
            Err(err) => tracing::warn!("failed to link ports: {err}"),
            Ok(_) => tracing::trace!("linked ports"),
        };
    }

    pub fn link_nodes(&self, from_id: u32, to_ports: Ports) {
        let from_ports = self.find_fl_fr_ports(from_id, PortDirection::Output, true);

        let ports = [from_ports.fl_port, from_ports.fr_port]
            .into_iter()
            .zip([to_ports.fl_port, to_ports.fr_port])
            .zip([AudioChannel::FrontLeft, AudioChannel::FrontRight]);

        for ((from, to), channel) in ports {
            let Some(from) = from else {
                tracing::warn!("missing output port for channel {channel:?} in node {from_id}");
                continue;
            };
            self.try_link_ports(from, to);
        }
        self.do_roundtrip();
    }

    pub fn monitor_and_connect_nodes(
        &self,
        target_ports: Ports,
        cancellation_signal: CancellationSignal,
        media_name_filter: impl Fn(Option<&str>) -> bool + Clone + 'static,
    ) -> Result<()> {
        let scheduler = self.create_scheduler();
        let registry = self.core.get_registry_rc()?;

        let links_by_port = Rc::new(RefCell::new(HashMap::new()));

        let mut node_and_ports_registry = NodeAndPortsRegistry::default();
        node_and_ports_registry.set_relevant_port_added_callback({
            let client = self.clone();
            let links_by_port = links_by_port.clone();
            move |port_info| {
                let Some(channel) = port_info.channel else {
                    tracing::debug!(
                        port = port_info.id,
                        channel = ?port_info.channel,
                        "unmapped channel"
                    );
                    return;
                };
                let target_port = target_ports.get_stereo_channel(&channel);
                match client.link_ports(port_info.id, target_port) {
                    Ok(link) => {
                        if let Some(prev_handle) = links_by_port
                            .borrow_mut()
                            .insert(port_info.id, LinkTrackerHandle::new(link))
                        {
                            tracing::warn!(
                                prev_id = prev_handle.id(),
                                "linked twice without unlinking"
                            );
                        }
                        tracing::debug!(source_port = port_info.id, target_port, "linked ports");
                    }
                    Err(err) => {
                        tracing::warn!(?err, "error while trying to link ports");
                    }
                }
            }
        });
        node_and_ports_registry.set_relevant_port_removed_callback({
            let registry = registry.clone();
            let links_by_port = links_by_port.clone();
            move |port_info| {
                let port_id = port_info.id;
                tracing::debug!(port_id, "port is no longer relevant, unlinking");
                let Some(link_handle) = links_by_port.borrow_mut().remove(&port_id) else {
                    tracing::warn!(
                        port_id,
                        "trying to unlink port, but link is not being tracked"
                    );
                    return;
                };
                let Some(link_id) = link_handle.id() else {
                    tracing::warn!(port_id, "link does not have a defined id");
                    return;
                };
                registry.destroy_global(link_id);
            }
        });

        let node_listener = self.add_node_listener(
            registry.clone(),
            {
                let node_and_ports_registry = node_and_ports_registry.clone();
                move |node| {
                    let node_id: u32 = node.id();

                    if !node.change_mask().contains(NodeChangeMask::PROPS) {
                        return;
                    }

                    let is_node_relevant = node.props().is_some_and(|props| {
                        props.get(*keys::MEDIA_CLASS) == Some("Stream/Output/Audio")
                            && media_name_filter(props.get(*keys::MEDIA_NAME))
                    });

                    tracing::trace!(node_id, is_node_relevant, "node props updated");
                    let was_node_relevant = node_and_ports_registry.is_node_relevant(node_id);
                    if was_node_relevant != is_node_relevant {
                        if is_node_relevant {
                            node_and_ports_registry.add_relevant_node(node_id);
                        } else {
                            node_and_ports_registry.try_remove_relevant_node(node_id);
                        }
                    } else {
                        tracing::trace!(node_id, "node relevancy has not changed");
                    }
                }
            },
            {
                let node_and_ports_registry = node_and_ports_registry.clone();
                move |node_id| {
                    tracing::trace!(node_id, "node removed");
                    node_and_ports_registry.try_remove_relevant_node(node_id);
                }
            },
            None,
        );

        let port_listener = registry
            .add_listener_local()
            .global({
                let node_and_ports_registry = node_and_ports_registry.clone();
                move |global_object| {
                    let Some(port_info) = Self::extract_port_info(global_object) else {
                        return;
                    };

                    if port_info.direction != PortDirection::Output {
                        return;
                    }

                    tracing::trace!(port_id = port_info.id, "port created");
                    node_and_ports_registry.add_port(port_info);
                }
            })
            .global_remove({
                let node_and_ports_registry = node_and_ports_registry.clone();
                move |global_id| {
                    if node_and_ports_registry.try_remove_port(global_id).is_some() {
                        tracing::trace!(port_id = global_id, "port removed");
                    }
                }
            })
            .register();

        scheduler.run(cancellation_signal.into());

        drop(node_listener);
        drop(port_listener);

        Ok(())
    }

    pub fn find_node_by_name(&self, node_name: impl AsRef<str> + 'static) -> Option<u32> {
        let result = Rc::new(OnceCell::new());
        self.iterate_nodes(
            StopSettingsBuilder::default()
                .stop_on_last_roundtrip()
                .build(),
            {
                let result = result.clone();
                let node_name = Rc::new(node_name);
                move |iteration_context, node| {
                    if node
                        .props()
                        .and_then(|props| props.get(*pipewire::keys::NODE_NAME))
                        .is_some_and(|name| (*node_name).as_ref() == name)
                    {
                        result.set(node.id()).unwrap();
                        iteration_context.stop();
                    }
                }
            },
        );
        Rc::try_unwrap(result).unwrap().into_inner()
    }

    pub fn list_output_nodes(&self) -> Vec<OutputNode> {
        let output_nodes = Rc::new(RefCell::new(vec![]));
        tracing::trace!("iterating over nodes");
        self.iterate_nodes(
            StopSettingsBuilder::default()
                .stop_on_last_roundtrip()
                .build(),
            {
                let output_nodes = output_nodes.clone();
                move |_iteration_context, node| match OutputNode::try_from(node) {
                    Ok(node) => {
                        if node.properties.media_class == "Stream/Output/Audio" {
                            tracing::trace!(?node, "adding node");
                            output_nodes.borrow_mut().push(node);
                        } else {
                            tracing::trace!(node_id = node.id, "node is not an output");
                        }
                    }
                    Err(err) => {
                        tracing::trace!(
                            node_id = node.id(),
                            ?err,
                            "node does not contain all required properties",
                        )
                    }
                }
            },
        );
        Rc::into_inner(output_nodes).unwrap().into_inner()
    }

    pub fn get_node_id_from_object_serial(&self, serial: i64) -> Option<u32> {
        let result = Rc::new(OnceCell::new());
        self.iterate_nodes(
            StopSettingsBuilder::default()
                .stop_on_last_roundtrip()
                .build(),
            {
                let result = result.clone();
                move |iteration_context, node| {
                    let Ok(node) = OutputNode::try_from(node) else {
                        return;
                    };
                    if node.properties.object_serial == serial {
                        result.set(node.id).unwrap();
                        iteration_context.stop();
                    }
                }
            },
        );
        Rc::try_unwrap(result).unwrap().into_inner()
    }
}


================================================
FILE: native/connector-rs/pipewire-utils/src/pipewire_objects.rs
================================================
use std::str::FromStr;

use thiserror::Error;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PortDirection {
    Input,
    Output,
}

#[derive(Debug)]
pub struct InvalidPortError;
impl FromStr for PortDirection {
    type Err = InvalidPortError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "in" => Ok(PortDirection::Input),
            "out" => Ok(PortDirection::Output),
            _ => Err(InvalidPortError),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AudioChannel<'a> {
    FrontLeft,
    FrontRight,
    Other(&'a str),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StereoAudioChannel {
    FrontLeft,
    FrontRight,
}

impl<'a> From<&'a str> for AudioChannel<'a> {
    fn from(value: &'a str) -> Self {
        match value {
            "FL" => AudioChannel::FrontLeft,
            "FR" => AudioChannel::FrontRight,
            s => AudioChannel::Other(s),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Ports {
    pub fl_port: u32,
    pub fr_port: u32,
}

impl Ports {
    pub fn get_stereo_channel(&self, channel: &StereoAudioChannel) -> u32 {
        match channel {
            StereoAudioChannel::FrontLeft => self.fl_port,
            StereoAudioChannel::FrontRight => self.fr_port,
        }
    }
    pub fn get_channel<'a>(&self, channel: &AudioChannel<'a>) -> Option<&u32> {
        match channel {
            AudioChannel::FrontLeft => Some(&self.fl_port),
            AudioChannel::FrontRight => Some(&self.fr_port),
            AudioChannel::Other(_) => None,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct NodeWithPorts {
    pub id: u32,
    pub ports: Ports,
}

#[derive(Debug, Clone, Copy)]
pub struct MaybePorts {
    pub fl_port: Option<u32>,
    pub fr_port: Option<u32>,
}

impl MaybePorts {
    pub fn both(self) -> Option<Ports> {
        let MaybePorts { fl_port, fr_port } = self;
        let fl_port = fl_port?;
        let fr_port = fr_port?;
        Some(Ports { fl_port, fr_port })
    }
}

#[derive(Debug, Clone, Copy)]
pub struct PortInfo<'a> {
    pub(crate) channel: AudioChannel<'a>,
    pub(crate) node_id: u32,
    pub(crate) id: u32,
    pub(crate) direction: PortDirection,
}

#[derive(Error, Debug)]
#[error("port channel is not stereo")]
pub struct ChannelIsNotStereoError;
impl<'a> TryFrom<AudioChannel<'a>> for StereoAudioChannel {
    type Error = ChannelIsNotStereoError;
    fn try_from(value: AudioChannel<'a>) -> Result<Self, Self::Error> {
        match value {
            AudioChannel::FrontLeft => Ok(StereoAudioChannel::FrontLeft),
            AudioChannel::FrontRight => Ok(StereoAudioChannel::FrontRight),
            AudioChannel::Other(_) => Err(ChannelIsNotStereoError),
        }
    }
}

pub struct OwnedPortInfo {
    pub(crate) channel: Option<StereoAudioChannel>,
    pub(crate) node_id: u32,
    pub(crate) id: u32,
    #[allow(unused)]
    pub(crate) direction: PortDirection,
}

impl<'a> From<PortInfo<'a>> for OwnedPortInfo {
    fn from(
        PortInfo {
            channel,
            node_id,
            id,
            direction,
        }: PortInfo<'a>,
    ) -> Self {
        OwnedPortInfo {
            id,
            node_id,
            channel: channel.try_into().ok(),
            direction,
        }
    }
}


================================================
FILE: native/connector-rs/pipewire-utils/src/proxies.rs
================================================
use std::collections::HashMap;

use pipewire::proxy::{Listener, ProxyT};

pub struct ProxyRef {
    _proxy: Box<dyn ProxyT>,
    _listeners: Vec<Box<dyn Listener>>,
}

#[derive(Default)]
pub struct ProxyRefs {
    refs: HashMap<u32, ProxyRef>,
}

impl ProxyRefs {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_proxy(&mut self, proxy: Box<dyn ProxyT>, listeners: Vec<Box<dyn Listener>>) {
        let proxy_id = {
            let proxy = proxy.upcast_ref();
            proxy.id()
        };

        self.refs.insert(
            proxy_id,
            ProxyRef {
                _proxy: proxy,
                _listeners: listeners,
            },
        );
    }

    pub fn remove_proxy(&mut self, proxy_id: &u32) -> bool {
        self.refs.remove(proxy_id).is_some()
    }
}


================================================
FILE: native/connector-rs/pipewire-utils/src/roundtrip.rs
================================================
use std::{cell::Cell, fmt::Debug, rc::Rc};

use libspa::utils::result::AsyncSeq;
use pipewire::{
    core::{CoreRc, PW_ID_CORE},
    main_loop::MainLoopRc,
};
use tracing::instrument;

use crate::cancellation_signal::CancellationSignal;

#[derive(Clone)]
pub struct Scheduler {
    sync_seq: Rc<Cell<Option<AsyncSeq>>>,
    mainloop: MainLoopRc,
    core: CoreRc,
    done: Rc<Cell<bool>>,
}

pub struct StopSettings {
    on_last_roundtrip: bool,
    signal_receiver: Option<CancellationSignal>,
}

impl Debug for StopSettings {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "StopSettings {{ on_last_roundtrip: {}, signal_receiver: {} }}",
            self.on_last_roundtrip,
            self.signal_receiver
                .as_ref()
                .map(|_| "Some(...)")
                .unwrap_or("None")
        ))
    }
}

impl From<CancellationSignal> for StopSettings {
    fn from(value: CancellationSignal) -> Self {
        StopSettingsBuilder::default().stop_on_signal(value).build()
    }
}

pub struct StopSettingsBuilder {
    on_last_roundtrip: bool,
    signal_receiver: Option<CancellationSignal>,
}

#[allow(clippy::derivable_impls)]
impl Default for StopSettingsBuilder {
    fn default() -> Self {
        Self {
            on_last_roundtrip: false,
            signal_receiver: None,
        }
    }
}
impl StopSettingsBuilder {
    pub fn stop_on_last_roundtrip(mut self) -> Self {
        self.on_last_roundtrip = true;
        self
    }

    pub fn set_stop_on_last_roundtrip(mut self, value: bool) -> Self {
        self.on_last_roundtrip = value;
        self
    }

    pub fn stop_on_signal(mut self, receiver: CancellationSignal) -> Self {
        self.signal_receiver = Some(receiver);
        self
    }

    pub fn build(self) -> StopSettings {
        StopSettings {
            on_last_roundtrip: self.on_last_roundtrip,
            signal_receiver: self.signal_receiver,
        }
    }
}

impl Scheduler {
    pub fn new(mainloop: MainLoopRc, core: CoreRc) -> Self {
        Self {
            mainloop,
            core,
            sync_seq: Default::default(),
            done: Default::default(),
        }
    }

    #[instrument(skip(self))]
    pub fn schedule_roundtrip(&self) {
        tracing::trace!("sending sync");
        self.sync_seq.replace(Some(self.core.sync(0).unwrap()));
    }

    pub fn stop(&self) {
        self.mainloop.quit();
        self.done.set(true);
    }

    #[instrument(skip(self, stop_settings))]
    pub fn run(self, stop_settings: StopSettings) {
        let mut listener_core = None;
        if stop_settings.on_last_roundtrip {
            self.schedule_roundtrip();
            listener_core = Some(
                self.core
                    .add_listener_local()
                    .done({
                        let done = self.done.clone();
                        let mainloop = self.mainloop.clone();
                        let sync_seq = self.sync_seq.clone();
                        move |id, seq| {
                            tracing::trace!("sync");
                            if id == PW_ID_CORE && Some(seq) == sync_seq.get() {
                                tracing::trace!("core sync");
                                done.set(true);
                                mainloop.quit();
                            }
                        }
                    })
                    .register(),
            );
        }

        let attached_receiver = stop_settings.signal_receiver.map(|stop_signal_receiver| {
            stop_signal_receiver.attach(self.mainloop.loop_(), {
                let done = self.done.clone();
                let mainloop = self.mainloop.clone();
                move || {
                    done.set(true);
                    mainloop.quit()
                }
            })
        });

        tracing::trace!("starting pipewire loop");
        while !self.done.get() {
            self.mainloop.run();
        }
        tracing::trace!("pipewire loop finished");

        if let Some(attached_receiver) = attached_receiver {
            attached_receiver.deattach();
        }

        drop(listener_core);
    }
}


================================================
FILE: native/connector-rs/pipewire-utils/src/utils.rs
================================================
use crate::{pipewire_client::PipewireClient, pipewire_objects::NodeWithPorts, PipewireError};

pub struct ManagedNode {
    pipewire_client: PipewireClient,
    node_with_ports: NodeWithPorts,
}

impl ManagedNode {
    pub fn create_managed_node(
        pipewire_client: &PipewireClient,
        node_name: impl AsRef<str>,
    ) -> Result<Self, PipewireError> {
        let node = pipewire_client.await_create_node(node_name)?;

        Ok(ManagedNode {
            pipewire_client: pipewire_client.clone(),
            node_with_ports: node,
        })
    }

    pub fn get_node_with_ports(&self) -> &NodeWithPorts {
        &self.node_with_ports
    }
}

impl Drop for ManagedNode {
    fn drop(&mut self) {
        let id = self.node_with_ports.id;
        if let Err(err) = self.pipewire_client.destroy_global(id) {
            tracing::error!("error removing managed node {id}, ignoring error: {err}");
        }
    }
}


================================================
FILE: native/connector-rs/rustfmt.toml
================================================
tab_spaces=2


================================================
FILE: native/connector-rs/src/command.rs
================================================
#![allow(non_snake_case)]

use std::env;
use std::env::current_exe;
use std::process::Command;
use std::process::Stdio;
use std::str;

use pipewire_utils::PipewireClient;
use serde_json::{json, Value};

use crate::daemon;
use crate::helpers::io;
use crate::helpers::parse_numeric_argument;
use crate::helpers::pipewire::OutputNode;
use crate::ipc;
use crate::ipc_request;

const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const VIRTMIC_NODE_NAME: &str = "pipewire-screenaudio";

fn GetVersion(_: io::Payload) -> Result<Value, String> {
  Ok(json!({
    "version": VERSION
  }))
}

fn GetSessionType(_: io::Payload) -> Result<Value, String> {
  let session_type = match env::var_os("WAYLAND_DISPLAY") {
    Some(_) => "wayland",
    None => "x11",
  };

  Ok(json!({
    "type": session_type
  }))
}

fn GetNodes(_: io::Payload) -> Result<Value, String> {
  let client = PipewireClient::new().unwrap();
  let nodes: Vec<_> = client
    .list_output_nodes()
    .into_iter()
    .map(OutputNode::from)
    .collect();
  Ok(serde_json::to_value(nodes).unwrap())
}

fn StartPipewireScreenAudio(_: io::Payload) -> Result<Value, String> {
  let mut daemon_process = Command::new(current_exe().unwrap())
    .arg("daemon")
    .stdout(Stdio::piped())
    .stderr(Stdio::null())
    .stdin(Stdio::null())
    .spawn()
    .unwrap();

  let daemon_stdout = daemon_process.stdout.take().unwrap();

  let mic_id = ipc_request::read_start_result(daemon_stdout);
  drop(daemon_process);

  Ok(json!({
    "micId": mic_id?
  }))
}

fn SetSharingNode(payload: io::Payload) -> Result<Value, String> {
  let nodes_arg = payload.arguments.get("nodes");

  let mut isAllDesktop = false;

  let arr = nodes_arg
    .and_then(|nodes_arg| nodes_arg.as_array())
    .ok_or_else(|| "nodes argument must be an array".to_string())?;

  let nodes = {
    let mut node_ids = Vec::new();
    let client = PipewireClient::new().unwrap();

    for node_value in arr {
      if node_value == -1 {
        // If any node is -1, treat as AllDesktop (None)
        node_ids.clear();
        isAllDesktop = true;
        break;
      }

      let node_serial = parse_numeric_argument(node_value.clone());
      tracing::debug!("node serial to connect: {node_serial}");

      let node_id = client
        .get_node_id_from_object_serial(node_serial)
        .ok_or_else(|| format!("failed to obtain node id for node with serial {node_serial}"))?;
      tracing::info!("node id to connect: {node_id}");
      node_ids.push(node_id);
    }

    node_ids
  };

  let pipe = ipc::connect().map_err(|err| err.to_string())?;
  let nodes = if isAllDesktop { None } else { Some(nodes) };
  io::write(daemon::Command::SetSharingNode { nodes }, &pipe).unwrap();
  let res: daemon::Response = io::read(&pipe).unwrap();

  let daemon::Response::SetSharingNodeResult { success } = res else {
    tracing::error!("invalid response for SetSharingNode, {res:?}");
    return Err(format!("invalid response for SetSharingNode, {res:?}"));
  };

  if !success {
    return Err("unable to set sharing node".to_string());
  }

  Ok(json!({}))
}

fn IsPipewireScreenAudioRunning(_payload: io::Payload) -> Result<Value, String> {
  let is_running = ipc_request::is_daemon_running().is_ok_and(|running| running);
  Ok(json!({
    "isRunning": is_running
  }))
}

fn StopPipewireScreenAudio(_payload: io::Payload) -> Result<Value, String> {
  ipc_request::stop_daemon()?;

  Ok(json!({}))
}

fn SetInstanceIdentifier(payload: io::Payload) -> Result<Value, String> {
  let instance_identifier = payload.arguments.get("id").unwrap().as_str().unwrap();
  ipc_request::set_instance_identifier(instance_identifier)?;
  Ok(json!({}))
}

pub fn run(payload: io::Payload) -> Result<Value, String> {
  let cmd = payload.command.as_str();
  match cmd {
    "GetVersion" => GetVersion(payload),
    "GetSessionType" => GetSessionType(payload),
    "GetNodes" => GetNodes(payload),
    "StartPipewireScreenAudio" => StartPipewireScreenAudio(payload),
    "SetSharingNode" => SetSharingNode(payload),
    "IsPipewireScreenAudioRunning" => IsPipewireScreenAudioRunning(payload),
    "StopPipewireScreenAudio" => StopPipewireScreenAudio(payload),
    "SetInstanceIdentifier" => SetInstanceIdentifier(payload),
    _ => Err(format!("Unknown command: {}", payload.command)),
  }
}


================================================
FILE: native/connector-rs/src/daemon.rs
================================================
use serde::{Deserialize, Serialize};
use std::{
  io::stdout,
  num::ParseIntError,
  os::unix::net::UnixStream,
  sync::atomic::{AtomicBool, Ordering},
};
use thiserror::Error;
use tracing::instrument;

use crate::{
  command::VIRTMIC_NODE_NAME,
  helpers::io::{self},
  ipc,
  monitor::MonitorThreadHandle,
};
use pipewire_utils::{ManagedNode, NodeWithPorts, PipewireClient};

#[derive(Error, Debug)]
pub enum ArgParseError {
  #[error("error parsing int")]
  ParseIntError(#[from] ParseIntError),
}

#[derive(Error, Debug)]
pub enum Error {
  #[error("error parsing arguments")]
  ArgParseError(#[from] ArgParseError),
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "cmd")]
pub enum Command {
  SetSharingNode { nodes: Option<Vec<u32>> },
  SetInstanceIdentifier { instance_identifier: String },
  Ping,
  Stop,
}

#[allow(clippy::enum_variant_names)]
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Response {
  StartResult {
    #[serde(rename = "micId")]
    mic_id: u32,
  },
  SetSharingNodeResult {
    success: bool,
  },
  PingResult,
  StopResult,
  SetInstanceIdentifierResult,
}

static KEEP_RUNNING: AtomicBool = AtomicBool::new(true);

enum SharingNodeState {
  Ids(Vec<u32>),
  AllDesktop,
  NotSharing,
}

struct DaemonState {
  running_thread: Option<MonitorThreadHandle>,
  sharing_node_state: SharingNodeState,
  instance_identifier: Option<String>,
}

impl DaemonState {
  fn reshare(&mut self, virtual_node: &NodeWithPorts, pipewire_client: &PipewireClient) -> bool {
    let _ = self.running_thread.take();
    pipewire_client.unlink_node_ports(virtual_node.ports);
    let success = match &self.sharing_node_state {
      SharingNodeState::Ids(node_ids) => {
        for node_id in node_ids {
          pipewire_client.link_nodes(*node_id, virtual_node.ports);
        }
        true
      }
      SharingNodeState::AllDesktop => {
        match MonitorThreadHandle::launch_monitor_thread(
          virtual_node.ports,
          self.instance_identifier.clone(),
        ) {
          Ok(handle) => {
            self.running_thread.replace(handle);
            true
          }
          Err(err) => {
            tracing::error!("error while launching monitor thread: {err}");
            false
          }
        }
      }
      SharingNodeState::NotSharing => true,
    };
    success
  }
}

fn handle_client(
  state: &mut DaemonState,
  pipewire_client: &PipewireClient,
  virtual_node: &NodeWithPorts,
  stream: UnixStream,
) {
  let command = match io::read::<_, Command>(&stream) {
    Ok(command) => command,
    Err(err) => {
      tracing::error!("invalid input from ipc channel: {err:?}");
      return;
    }
  };
  tracing::info!("input: {:?}", command);

  match command {
    Command::SetSharingNode { nodes } => {
      state.sharing_node_state = match nodes {
        Some(node_ids) => SharingNodeState::Ids(node_ids),
        None => SharingNodeState::AllDesktop,
      };
      let success = state.reshare(virtual_node, pipewire_client);
      io::write(Response::SetSharingNodeResult { success }, &stream).unwrap();
    }
    Command::SetInstanceIdentifier {
      instance_identifier,
    } => {
      state.instance_identifier = Some(instance_identifier);
      state.reshare(virtual_node, pipewire_client);
      io::write(Response::SetInstanceIdentifierResult, &stream).unwrap();
    }
    Command::Ping => {
      io::write(Response::PingResult, &stream).unwrap();
    }
    Command::Stop => {
      io::write(Response::StopResult, &stream).unwrap();
      stop_daemon();
    }
  }
}

fn stop_daemon() {
  tracing::info!("shutting down");
  KEEP_RUNNING.store(false, Ordering::Relaxed);
  ipc::fake_connect();
}

#[instrument]
pub fn monitor_and_connect_nodes() -> Result<(), Error> {
  tracing::info!("starting daemon monitor");

  let pipewire_client = PipewireClient::new().unwrap();

  let pipe = ipc::listen().unwrap();

  let managed_virtual_node =
    ManagedNode::create_managed_node(&pipewire_client, VIRTMIC_NODE_NAME).unwrap();
  let virtual_node = *managed_virtual_node.get_node_with_ports();

  ctrlc::set_handler(|| {
    stop_daemon();
  })
  .unwrap();

  let mut state = DaemonState {
    running_thread: None,
    instance_identifier: None,
    sharing_node_state: SharingNodeState::NotSharing,
  };

  io::write(
    Response::StartResult {
      mic_id: virtual_node.id,
    },
    stdout(),
  )
  .unwrap();

  for stream in pipe.incoming() {
    if !KEEP_RUNNING.load(Ordering::Relaxed) {
      tracing::warn!("stopping daemon");
      break;
    }
    let Ok(stream) = stream else {
      tracing::warn!("failed to accept incomming connection");
      continue;
    };
    handle_client(&mut state, &pipewire_client, &virtual_node, stream);
  }

  drop(state);

  Ok(())
}


================================================
FILE: native/connector-rs/src/dirs.rs
================================================
use std::{env, path::PathBuf};

pub fn get_runtime_path() -> PathBuf {
  let mut path: PathBuf = env::var("XDG_RUNTIME_DIR")
    .unwrap_or("/tmp".to_owned())
    .into();

  path.push("pipewire-screenaudio");

  path
}


================================================
FILE: native/connector-rs/src/helpers/io.rs
================================================
use std::fmt::Debug;
use std::io::prelude::{Read, Write};
use std::str;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use thiserror::Error;

#[derive(Debug, Serialize, Deserialize)]
pub struct RawPayload {
  #[serde(rename = "cmd")]
  pub command: String,
  #[serde(rename = "args")]
  pub arguments: Option<Value>,
}

impl From<RawPayload> for Payload {
  fn from(value: RawPayload) -> Self {
    let RawPayload { command, arguments } = value;
    Self {
      command,
      arguments: arguments.unwrap_or_else(|| json!({})),
    }
  }
}

impl From<Payload> for RawPayload {
  fn from(value: Payload) -> Self {
    Self {
      command: value.command,
      arguments: Some(value.arguments),
    }
  }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(from = "RawPayload", into = "RawPayload")]
pub struct Payload {
  pub command: String,
  pub arguments: Value,
}

#[derive(Error, Debug)]
pub enum ReadError {
  #[error("error while reading length header")]
  ReadingLengthHeader(std::io::Error),
  #[error("error while reading payload")]
  ReadingPayload(std::io::Error),
  #[error("error while parsing payload")]
  PayloadUTFError(std::str::Utf8Error),
  #[error("error while parsing payload")]
  ParsingPayload(serde_json::Error),
}

#[derive(Error, Debug)]
pub enum WriteError {
  #[error("error while writing length header")]
  WritingLengthHeader(std::io::Error),
  #[error("error while writing payload")]
  WritingPayload(std::io::Error),
  #[error("error while serializing payload")]
  SerializingPayload(serde_json::Error),
  #[error("error while flushing")]
  Flushing(std::io::Error),
}

pub fn read<R: Read, P: for<'a> Deserialize<'a> + Debug>(mut reader: R) -> Result<P, ReadError> {
  let mut length_buffer = [0u8; 4];

  reader
    .read_exact(&mut length_buffer)
    .map_err(ReadError::ReadingLengthHeader)?;

  let length = u32::from_le_bytes(length_buffer);
  tracing::trace!("Length: {}", length);

  let mut payload_buffer = vec![0u8; length as usize];
  reader
    .read_exact(&mut payload_buffer)
    .map_err(ReadError::ReadingPayload)?;

  let payload_string = str::from_utf8(&payload_buffer).map_err(ReadError::PayloadUTFError)?;

  let payload = serde_json::from_str(payload_string).map_err(ReadError::ParsingPayload)?;
  tracing::debug!("read payload: {:?}", &payload);

  Ok(payload)
}

pub fn write<W: Write, P: Serialize>(payload: P, mut writer: W) -> Result<(), WriteError> {
  let payload = serde_json::to_string(&payload).map_err(WriteError::SerializingPayload)?;
  tracing::debug!("writing payload: {}", payload);

  let payload = payload.as_bytes();
  let length = payload.len();
  let length_buffer = u32::try_from(length).unwrap().to_le_bytes();

  writer
    .write_all(&length_buffer)
    .map_err(WriteError::WritingLengthHeader)?;
  writer
    .write_all(payload)
    .map_err(WriteError::WritingPayload)?;
  writer.flush().map_err(WriteError::Flushing)?;

  Ok(())
}


================================================
FILE: native/connector-rs/src/helpers/pipewire.rs
================================================
use serde::Serialize;

#[derive(Debug, Serialize)]
pub struct NodeProperties {
  #[serde(rename = "application.name")]
  application_name: Option<String>,
  #[serde(rename = "media.name")]
  media_name: String,
  #[serde(rename = "object.serial")]
  object_serial: i64,

  #[serde(skip_serializing)]
  #[allow(unused)]
  media_class: String,
}

#[derive(Debug, Serialize)]
pub struct OutputNode {
  id: u32,
  properties: NodeProperties,
}

impl From<pipewire_utils::NodeProperties> for NodeProperties {
  fn from(
    pipewire_utils::NodeProperties {
      application_name,
      media_name,
      object_serial,
      media_class,
    }: pipewire_utils::NodeProperties,
  ) -> Self {
    Self {
      application_name,
      media_name,
      object_serial,
      media_class,
    }
  }
}

impl From<pipewire_utils::OutputNode> for OutputNode {
  fn from(pipewire_utils::OutputNode { id, properties }: pipewire_utils::OutputNode) -> Self {
    Self {
      id,
      properties: properties.into(),
    }
  }
}


================================================
FILE: native/connector-rs/src/helpers.rs
================================================
use serde_json::Value;

pub mod io;
pub mod pipewire;

pub fn parse_numeric_argument(value: Value) -> i64 {
  if value.is_i64() {
    value.as_number().unwrap().as_i64().unwrap()
  } else {
    value.as_str().unwrap().parse::<i64>().unwrap()
  }
}


================================================
FILE: native/connector-rs/src/ipc.rs
================================================
use std::{
  error::Error,
  fs, io,
  os::unix::net::{UnixListener, UnixStream},
  path::{Path, PathBuf},
  thread,
  time::Duration,
};

use crate::io as ipc_io;
use crate::{daemon, dirs::get_runtime_path};

fn get_ipc_socket_path() -> PathBuf {
  let mut path = get_runtime_path();
  path.push("ipc.sock");
  path
}

fn ensure_stopped(path: &Path) -> Result<(), Box<dyn Error>> {
  if path.exists() {
    let stream = connect_inner(1)?;
    ipc_io::write(daemon::Command::Stop, &stream)?;
  }
  Ok(())
}

pub fn listen() -> io::Result<UnixListener> {
  let path = get_ipc_socket_path();
  let _ = ensure_stopped(&path);
  let _ = fs::remove_file(&path);
  UnixListener::bind(path)
}

pub fn fake_connect() {
  let _ = UnixStream::connect(get_ipc_socket_path());
}

pub fn connect_inner(tries: usize) -> io::Result<UnixStream> {
  let mut retries = tries;
  let path = get_ipc_socket_path();
  let mut last_error = None;
  while retries > 0 {
    tracing::debug!("connecting");
    match UnixStream::connect(path.clone()) {
      Ok(socket) => return Ok(socket),
      Err(err) => last_error = Some(err),
    }
    retries -= 1;
    if retries > 0 {
      thread::sleep(Duration::from_millis(100));
    }
  }
  Err(last_error.unwrap())
}

pub fn connect() -> io::Result<UnixStream> {
  connect_inner(1)
}


================================================
FILE: native/connector-rs/src/ipc_request.rs
================================================
use std::process::ChildStdout;

use crate::{daemon, helpers::io, ipc};

pub fn is_daemon_running() -> Result<bool, String> {
  let pipe = ipc::connect().map_err(|err| err.to_string())?;
  io::write(daemon::Command::Ping, &pipe).map_err(|err| err.to_string())?;
  let res: daemon::Response = io::read(&pipe).map_err(|err| err.to_string())?;

  let daemon::Response::PingResult = res else {
    tracing::error!("invalid response for Ping, {res:?}");
    return Err(format!("invalid response for Ping, {res:?}"));
  };

  Ok(true)
}

pub fn stop_daemon() -> Result<(), String> {
  let pipe = ipc::connect().map_err(|err| err.to_string())?;
  io::write(daemon::Command::Stop, &pipe).map_err(|err| err.to_string())?;
  let res: daemon::Response = io::read(&pipe).map_err(|err| err.to_string())?;

  let daemon::Response::StopResult = res else {
    tracing::error!("invalid response for Stop, {res:?}");
    return Err(format!("invalid response for Stop, {res:?}"));
  };

  Ok(())
}

pub fn set_instance_identifier(instance_identifier: &str) -> Result<(), String> {
  let pipe = ipc::connect().map_err(|err| err.to_string())?;
  io::write(
    daemon::Command::SetInstanceIdentifier {
      instance_identifier: instance_identifier.to_owned(),
    },
    &pipe,
  )
  .map_err(|err| err.to_string())?;
  let res: daemon::Response = io::read(&pipe).map_err(|err| err.to_string())?;

  let daemon::Response::SetInstanceIdentifierResult = res else {
    tracing::error!("invalid response for SetExcludedTitle, {res:?}");
    return Err(format!("invalid response for SetExcludedTitle, {res:?}"));
  };

  Ok(())
}

pub fn read_start_result(daemon_stdout: ChildStdout) -> Result<u32, String> {
  let status: daemon::Response = io::read(daemon_stdout)
    .map_err(|err| format!("error obtaining first response from daemon: {err}"))?;

  let daemon::Response::StartResult { mic_id } = status else {
    return Err(format!(
      "first response from daemon has unexpected format: {status:?}"
    ));
  };
  Ok(mic_id)
}


================================================
FILE: native/connector-rs/src/main.rs
================================================
use std::{
  env,
  error::Error,
  io::{stdin, stdout},
  panic,
  path::PathBuf,
  process,
};

mod command;
mod daemon;
mod dirs;
mod helpers;
mod ipc;
mod ipc_request;
mod monitor;

use helpers::io;
use serde_json::json;
use tracing::{level_filters::LevelFilter, Level};
use tracing_appender::rolling::RollingFileAppender;
use tracing_panic::panic_hook;
use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter, Layer, Registry};

use crate::{daemon::monitor_and_connect_nodes, dirs::get_runtime_path};

fn get_logs_path() -> PathBuf {
  let mut path = get_runtime_path();
  path.push("logs");
  path
}

fn main() -> Result<(), Box<dyn Error>> {
  let mut args = env::args();
  let _ = args.next().expect("binary path should be the first arg");
  let subcommand = args.next();

  let file_appender = RollingFileAppender::builder()
    .filename_prefix(
      match subcommand.as_deref() {
        Some("daemon") => "daemon",
        _ => "connector",
      }
      .to_owned(),
    )
    .build(get_logs_path())
    .unwrap();
  let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
  let subscriber = Registry::default()
    .with(
      fmt::Layer::default()
        .with_writer(non_blocking)
        .with_ansi(false)
        .with_filter(LevelFilter::from_level(Level::DEBUG)),
    )
    .with(
      fmt::Layer::default()
        .with_writer(std::io::stderr)
        .with_filter(
          EnvFilter::builder()
            .with_default_directive(LevelFilter::ERROR.into())
            .from_env_lossy(),
        ),
    );

  tracing::subscriber::set_global_default(subscriber).expect("unable to set global subscriber");
  let span = tracing::info_span!("main", pid = process::id());
  let _span_handle = span.enter();

  panic::set_hook(Box::new(panic_hook));

  match subcommand.as_deref() {
    Some("daemon") => {
      if let Err(err) = monitor_and_connect_nodes() {
        tracing::error!("error: {}", err);
        Err(Box::new(err))?;
      }
    }
    Some(_) | None => {
      let payload = io::read(stdin()).unwrap();
      tracing::info!(payload = format!("{payload:?}"), "running connector");
      match command::run(payload) {
        Ok(result) => {
          let _ = io::write(
            json!({
              "success": true,
              "response": result,
            }),
            stdout(),
          );
        }
        Err(err) => {
          tracing::error!("command error: {}", err);
          let _ = io::write(
            json!({
              "success": false,
              "errorMessage": err,
            }),
            stdout(),
          );
        }
      }
    }
  }

  Ok(())
}


================================================
FILE: native/connector-rs/src/monitor.rs
================================================
use std::{
  io,
  rc::Rc,
  thread::{self, JoinHandle},
};

use pipewire_utils::{
  cancellation_signal::{CancellationController, CancellationSignal},
  PipewireClient, PipewireError, Ports,
};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
  #[error("pipewire error")]
  PipewireError(#[from] PipewireError),
  #[error("thread spawning error")]
  ThreadSpawnError(io::Error),
}

pub type Result<T, E = Error> = std::result::Result<T, E>;

pub struct MonitorThreadHandle {
  join_handle: Option<JoinHandle<Result<(), PipewireError>>>,
  cancellation_controller: CancellationController,
}

impl MonitorThreadHandle {
  pub fn launch_monitor_thread(
    mic_ports: Ports,
    instance_identifier: Option<String>,
  ) -> Result<Self> {
    tracing::debug!("starting monitor thread");
    let (controller, signal) = CancellationSignal::pair();

    let join_handle = thread::Builder::new()
      .name("monitor and connector thread".to_owned())
      .spawn(move || {
        let client = PipewireClient::new()?;
        let instance_identifier = instance_identifier.map(Rc::new);
        client.monitor_and_connect_nodes(mic_ports, signal, move |node_app_name| {
          tracing::trace!(
            node_app_name,
            instance_identifier = instance_identifier.as_ref().map(|ii| ii.as_str()),
            "filtering"
          );
          instance_identifier
            .as_ref()
            .is_none_or(move |excluded_node_name| {
              node_app_name
                .is_none_or(|node_app_name| !node_app_name.ends_with(excluded_node_name.as_ref()))
            })
        })
      })
      .map_err(Error::ThreadSpawnError)?;

    Ok(MonitorThreadHandle {
      join_handle: Some(join_handle),
      cancellation_controller: controller,
    })
  }

  pub fn stop(&mut self) {
    tracing::debug!("stopping monitor thread");
    self.cancellation_controller.cancel();
    if let Some(handle) = self.join_handle.take() {
      if let Err(err) = handle.join().unwrap() {
        tracing::error!("monitor thread returned error: {err}");
      }
    }
  }
}

impl Drop for MonitorThreadHandle {
  fn drop(&mut self) {
    self.stop();
  }
}


================================================
FILE: native/native-messaging-hosts/com.icedborn.pipewirescreenaudioconnector.json
================================================
{
	"name": "com.icedborn.pipewirescreenaudioconnector",
	"description": "Connector to communicate with the browser",
	"path": "CONNECTOR_BINARY_PATH",
	"type": "stdio",
	"ALLOWED_FIELD": ["ALLOWED_VALUE"]
}


================================================
FILE: package.json
================================================
{
	"name": "pipewire-screenaudio",
	"version": "0.4.2",
	"scripts": {
		"build": "vite build extension/react"
	},
	"dependencies": {
		"@emotion/react": "^11.11.1",
		"@emotion/styled": "^11.11.0",
		"@fontsource/roboto": "^5.0.8",
		"@mui/material": "^5.14.4",
		"react": "^18.2.0",
		"react-dom": "^18.2.0",
		"react-router": "^6.17.0",
		"react-router-dom": "^6.17.0",
		"use-debounce": "^9.0.4"
	},
	"devDependencies": {
		"@vitejs/plugin-react": "^4.0.4",
		"eslint": "^8.47.0",
		"eslint-plugin-react": "^7.33.2",
		"nodemon": "^3.0.1",
		"prettier": "^3.0.1",
		"vite": "^4.4.9"
	}
}
Download .txt
gitextract_014v53gh/

├── .editorconfig
├── .eslintrc
├── .github/
│   └── workflows/
│       └── update-changelog.yaml
├── .gitignore
├── .prettierrc.yml
├── CHANGELOG.md
├── INSTALL.md
├── LICENSE
├── README.md
├── extension/
│   ├── manifest.json
│   ├── react/
│   │   ├── .gitignore
│   │   ├── build-watcher.sh
│   │   ├── components/
│   │   │   └── nodes-table.jsx
│   │   ├── index.html
│   │   ├── index.jsx
│   │   ├── lib/
│   │   │   ├── backend.js
│   │   │   ├── hooks.js
│   │   │   ├── local-storage.js
│   │   │   └── match-node.js
│   │   ├── routes/
│   │   │   └── popup.jsx
│   │   └── vite.config.js
│   └── scripts/
│       ├── background.js
│       ├── injector.js
│       └── override-gdm.js
├── flake.nix
├── install.sh
├── native/
│   ├── .gitignore
│   ├── connector/
│   │   ├── cli.sh
│   │   └── util.sh
│   ├── connector-rs/
│   │   ├── .gitignore
│   │   ├── Cargo.toml
│   │   ├── pipewire-utils/
│   │   │   ├── .gitignore
│   │   │   ├── Cargo.toml
│   │   │   ├── examples/
│   │   │   │   ├── all-desktop-audio.rs
│   │   │   │   └── create-node.rs
│   │   │   ├── rustfmt.toml
│   │   │   └── src/
│   │   │       ├── cancellation_signal.rs
│   │   │       ├── lib.rs
│   │   │       ├── monitor.rs
│   │   │       ├── pipewire_client.rs
│   │   │       ├── pipewire_objects.rs
│   │   │       ├── proxies.rs
│   │   │       ├── roundtrip.rs
│   │   │       └── utils.rs
│   │   ├── rustfmt.toml
│   │   └── src/
│   │       ├── command.rs
│   │       ├── daemon.rs
│   │       ├── dirs.rs
│   │       ├── helpers/
│   │       │   ├── io.rs
│   │       │   └── pipewire.rs
│   │       ├── helpers.rs
│   │       ├── ipc.rs
│   │       ├── ipc_request.rs
│   │       ├── main.rs
│   │       └── monitor.rs
│   └── native-messaging-hosts/
│       └── com.icedborn.pipewirescreenaudioconnector.json
└── package.json
Download .txt
SYMBOL INDEX (199 symbols across 29 files)

FILE: extension/react/components/nodes-table.jsx
  function NodesTable (line 13) | function NodesTable({

FILE: extension/react/index.jsx
  function PageWrapper (line 31) | function PageWrapper() {
  function App (line 40) | function App() {

FILE: extension/react/lib/backend.js
  constant MESSAGE_NAME (line 3) | const MESSAGE_NAME = "com.icedborn.pipewirescreenaudioconnector";
  constant EXT_VERSION (line 4) | const EXT_VERSION = chrome.runtime.getManifest().version;
  constant ERROR_VERSION_MISMATCH (line 6) | const ERROR_VERSION_MISMATCH = "Version Mismatch";
  constant EVENT_MIC_ID_UPDATED (line 8) | const EVENT_MIC_ID_UPDATED = "onMicIdUpdated";
  constant EVENT_MIC_ID_REMOVED (line 9) | const EVENT_MIC_ID_REMOVED = "onMicIdRemoved";
  function enqueueCommandToBackground (line 13) | function enqueueCommandToBackground(command) {
  function sendNativeMessage (line 17) | async function sendNativeMessage(command, args) {
  function sendMessage (line 36) | async function sendMessage(message, command) {
  function matchVersion (line 53) | function matchVersion(a, b) {
  function getNewPromise (line 59) | function getNewPromise() {
  function handleMessage (line 69) | function handleMessage(message) {
  function healthCheck (line 89) | async function healthCheck() {
  function getNodes (line 104) | async function getNodes() {
  function isPipewireScreenAudioRunning (line 108) | async function isPipewireScreenAudioRunning(micId) {
  function startPipewireScreenAudio (line 113) | function startPipewireScreenAudio() {
  function stopPipewireScreenAudio (line 122) | function stopPipewireScreenAudio(micId) {
  function setSharingNode (line 132) | function setSharingNode(nodeSerials) {

FILE: extension/react/lib/hooks.js
  function useDidUpdateEffect (line 4) | function useDidUpdateEffect(fn, inputs) {
  function useLocalStorage (line 15) | function useLocalStorage(name) {

FILE: extension/react/lib/local-storage.js
  constant SELECTED_NODES (line 1) | const SELECTED_NODES = "selectedNodes";
  constant MIC_ID (line 2) | const MIC_ID = "micId";
  constant ALL_DESKTOP (line 3) | const ALL_DESKTOP = "allDesktopAudio";
  function readLocalStorage (line 5) | async function readLocalStorage(name) {
  function updateLocalStorage (line 14) | async function updateLocalStorage(name, value) {

FILE: extension/react/lib/match-node.js
  function matchNode (line 1) | function matchNode(a, b) {

FILE: extension/react/routes/popup.jsx
  function mapNode (line 43) | function mapNode(node) {
  function useNodeSelectionState (line 57) | function useNodeSelectionState({ nodes, areNodesLoading }) {
  function useHealthchecks (line 110) | function useHealthchecks() {
  function useNodes (line 148) | function useNodes({ enabled }) {
  function useCurrentMicId (line 189) | function useCurrentMicId({ enabled }) {
  function useAllDesktopAudio (line 240) | function useAllDesktopAudio() {
  function Popup (line 250) | function Popup() {

FILE: extension/scripts/background.js
  function sendNativeMessage (line 6) | async function sendNativeMessage(messageName, cmd, args) {
  function runQueuedCommands (line 23) | async function runQueuedCommands() {
  function handleMessage (line 67) | function handleMessage(request) {

FILE: extension/scripts/injector.js
  constant MESSAGE_NAME (line 1) | const MESSAGE_NAME = "com.icedborn.pipewirescreenaudioconnector";
  function injectCode (line 8) | function injectCode(src) {

FILE: extension/scripts/override-gdm.js
  function createRandomString (line 9) | function createRandomString(
  function overrideGetDisplayMedia (line 18) | function overrideGetDisplayMedia() {
  function watchTitle (line 120) | function watchTitle() {

FILE: native/connector-rs/pipewire-utils/examples/all-desktop-audio.rs
  function main (line 4) | fn main() -> Result<(), Box<dyn std::error::Error>> {

FILE: native/connector-rs/pipewire-utils/examples/create-node.rs
  function main (line 3) | fn main() -> Result<(), Box<dyn std::error::Error>> {

FILE: native/connector-rs/pipewire-utils/src/cancellation_signal.rs
  type TerminateSignal (line 12) | pub struct TerminateSignal;
  type CancellationSignal (line 14) | pub struct CancellationSignal {
    method pair (line 28) | pub fn pair() -> (CancellationController, CancellationSignal) {
    method attach (line 36) | pub fn attach(
  type AttachedCancellationSignal (line 18) | pub struct AttachedCancellationSignal<'a> {
  type CancellationController (line 23) | pub struct CancellationController {
    method cancel (line 71) | pub fn cancel(&self) {
    method timeout (line 77) | pub fn timeout(&self, duration: Duration) -> TimeoutHandle {
  function deattach (line 48) | pub fn deattach(self) -> CancellationSignal {
  type TimeoutHandle (line 55) | pub struct TimeoutHandle {
  method drop (line 60) | fn drop(&mut self) {

FILE: native/connector-rs/pipewire-utils/src/monitor.rs
  type NodeAndPortsRegistry (line 16) | pub struct NodeAndPortsRegistry<AddedCallback, RemovedCallback> {
  method default (line 27) | fn default() -> Self {
  function set_relevant_port_added_callback (line 41) | pub fn set_relevant_port_added_callback(&mut self, callback: AddedCallba...
  function set_relevant_port_removed_callback (line 45) | pub fn set_relevant_port_removed_callback(&mut self, callback: RemovedCa...
  function invoke_for_all_ports_in_node (line 49) | fn invoke_for_all_ports_in_node<F: Fn(&OwnedPortInfo)>(&self, node_id: u...
  function is_node_relevant (line 60) | pub fn is_node_relevant(&self, node_id: u32) -> bool {
  function add_relevant_node (line 65) | pub fn add_relevant_node(&self, node_id: u32) {
  function try_remove_relevant_node (line 74) | pub fn try_remove_relevant_node(&self, node_id: u32) -> bool {
  function add_port (line 87) | pub fn add_port(&self, port_info: PortInfo<'_>) {
  function try_remove_port (line 111) | pub fn try_remove_port(&self, port_id: u32) -> Option<OwnedPortInfo> {
  type LinkTrackerHandle (line 129) | pub struct LinkTrackerHandle {
    method new (line 136) | pub fn new(link: Link) -> Self {
    method id (line 151) | pub fn id(&self) -> Option<u32> {

FILE: native/connector-rs/pipewire-utils/src/pipewire_client.rs
  type PipewireError (line 33) | pub struct PipewireError(#[from] pipewire::Error);
  type Result (line 35) | pub type Result<T, E = PipewireError> = std::result::Result<T, E>;
  type PipewireClient (line 38) | pub struct PipewireClient {
    method new (line 139) | pub fn new() -> Result<Self> {
    method create_scheduler (line 151) | fn create_scheduler(&self) -> Scheduler {
    method do_roundtrip (line 160) | fn do_roundtrip(&self) {
    method iterate_globals (line 168) | fn iterate_globals(
    method add_node_listener (line 191) | fn add_node_listener<F, DF>(
    method iterate_nodes (line 250) | fn iterate_nodes<F>(&self, stop_settings: StopSettings, object_callbac...
    method extract_port_info (line 273) | fn extract_port_info<'a>(global: &'a GlobalObject<&'a DictRef>) -> Opt...
    method is_global_a_port_for_node (line 292) | fn is_global_a_port_for_node<'a>(
    method find_fl_fr_ports (line 302) | fn find_fl_fr_ports(
    method await_find_fl_fr_ports (line 356) | fn await_find_fl_fr_ports(&self, node_id: u32, direction: PortDirectio...
    method await_create_node (line 362) | pub fn await_create_node(&self, node_name: impl AsRef<str>) -> Result<...
    method destroy_global (line 378) | pub fn destroy_global(&self, global_id: u32) -> Result<()> {
    method unlink_ports (line 385) | fn unlink_ports(&self, ports: HashSet<u32>) {
    method unlink_node_ports (line 420) | pub fn unlink_node_ports(&self, ports: Ports) {
    method await_node_creation (line 424) | fn await_node_creation(&self, node: Node) -> NodeWithPorts {
    method link_ports (line 451) | fn link_ports(&self, from: u32, to: u32) -> Result<Link, pipewire::Err...
    method try_link_ports (line 463) | fn try_link_ports(&self, from: u32, to: u32) {
    method link_nodes (line 470) | pub fn link_nodes(&self, from_id: u32, to_ports: Ports) {
    method monitor_and_connect_nodes (line 488) | pub fn monitor_and_connect_nodes(
    method find_node_by_name (line 627) | pub fn find_node_by_name(&self, node_name: impl AsRef<str> + 'static) ...
    method list_output_nodes (line 651) | pub fn list_output_nodes(&self) -> Vec<OutputNode> {
    method get_node_id_from_object_serial (line 682) | pub fn get_node_id_from_object_serial(&self, serial: i64) -> Option<u3...
  type IterationAction (line 45) | pub enum IterationAction {
  type IterationContext (line 51) | struct IterationContext {
    method stop (line 119) | fn stop(&self) {
    method schedule_roundtrip (line 125) | fn schedule_roundtrip(&self) {
  type NodeProperties (line 57) | pub struct NodeProperties {
  type OutputNode (line 66) | pub struct OutputNode {
    type Error (line 80) | type Error = OutputNodeCreationError;
    method try_from (line 81) | fn try_from(value: &NodeInfoRef) -> Result<Self, Self::Error> {
  type OutputNodeCreationError (line 72) | pub enum OutputNodeCreationError {
  type NodeListenerHandle (line 131) | struct NodeListenerHandle {

FILE: native/connector-rs/pipewire-utils/src/pipewire_objects.rs
  type PortDirection (line 6) | pub enum PortDirection {
  type InvalidPortError (line 12) | pub struct InvalidPortError;
  type Err (line 14) | type Err = InvalidPortError;
  method from_str (line 15) | fn from_str(s: &str) -> Result<Self, Self::Err> {
  type AudioChannel (line 25) | pub enum AudioChannel<'a> {
  type StereoAudioChannel (line 32) | pub enum StereoAudioChannel {
    type Error (line 102) | type Error = ChannelIsNotStereoError;
    method try_from (line 103) | fn try_from(value: AudioChannel<'a>) -> Result<Self, Self::Error> {
  function from (line 38) | fn from(value: &'a str) -> Self {
  type Ports (line 48) | pub struct Ports {
    method get_stereo_channel (line 54) | pub fn get_stereo_channel(&self, channel: &StereoAudioChannel) -> u32 {
    method get_channel (line 60) | pub fn get_channel<'a>(&self, channel: &AudioChannel<'a>) -> Option<&u...
  type NodeWithPorts (line 70) | pub struct NodeWithPorts {
  type MaybePorts (line 76) | pub struct MaybePorts {
    method both (line 82) | pub fn both(self) -> Option<Ports> {
  type PortInfo (line 91) | pub struct PortInfo<'a> {
  type ChannelIsNotStereoError (line 100) | pub struct ChannelIsNotStereoError;
  type OwnedPortInfo (line 112) | pub struct OwnedPortInfo {
    method from (line 121) | fn from(

FILE: native/connector-rs/pipewire-utils/src/proxies.rs
  type ProxyRef (line 5) | pub struct ProxyRef {
  type ProxyRefs (line 11) | pub struct ProxyRefs {
    method new (line 16) | pub fn new() -> Self {
    method add_proxy (line 20) | pub fn add_proxy(&mut self, proxy: Box<dyn ProxyT>, listeners: Vec<Box...
    method remove_proxy (line 35) | pub fn remove_proxy(&mut self, proxy_id: &u32) -> bool {

FILE: native/connector-rs/pipewire-utils/src/roundtrip.rs
  type Scheduler (line 13) | pub struct Scheduler {
    method new (line 83) | pub fn new(mainloop: MainLoopRc, core: CoreRc) -> Self {
    method schedule_roundtrip (line 93) | pub fn schedule_roundtrip(&self) {
    method stop (line 98) | pub fn stop(&self) {
    method run (line 104) | pub fn run(self, stop_settings: StopSettings) {
  type StopSettings (line 20) | pub struct StopSettings {
    method from (line 39) | fn from(value: CancellationSignal) -> Self {
  method fmt (line 26) | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  type StopSettingsBuilder (line 44) | pub struct StopSettingsBuilder {
    method stop_on_last_roundtrip (line 59) | pub fn stop_on_last_roundtrip(mut self) -> Self {
    method set_stop_on_last_roundtrip (line 64) | pub fn set_stop_on_last_roundtrip(mut self, value: bool) -> Self {
    method stop_on_signal (line 69) | pub fn stop_on_signal(mut self, receiver: CancellationSignal) -> Self {
    method build (line 74) | pub fn build(self) -> StopSettings {
  method default (line 51) | fn default() -> Self {

FILE: native/connector-rs/pipewire-utils/src/utils.rs
  type ManagedNode (line 3) | pub struct ManagedNode {
    method create_managed_node (line 9) | pub fn create_managed_node(
    method get_node_with_ports (line 21) | pub fn get_node_with_ports(&self) -> &NodeWithPorts {
  method drop (line 27) | fn drop(&mut self) {

FILE: native/connector-rs/src/command.rs
  constant VERSION (line 19) | const VERSION: &str = env!("CARGO_PKG_VERSION");
  constant VIRTMIC_NODE_NAME (line 20) | pub const VIRTMIC_NODE_NAME: &str = "pipewire-screenaudio";
  function GetVersion (line 22) | fn GetVersion(_: io::Payload) -> Result<Value, String> {
  function GetSessionType (line 28) | fn GetSessionType(_: io::Payload) -> Result<Value, String> {
  function GetNodes (line 39) | fn GetNodes(_: io::Payload) -> Result<Value, String> {
  function StartPipewireScreenAudio (line 49) | fn StartPipewireScreenAudio(_: io::Payload) -> Result<Value, String> {
  function SetSharingNode (line 68) | fn SetSharingNode(payload: io::Payload) -> Result<Value, String> {
  function IsPipewireScreenAudioRunning (line 119) | fn IsPipewireScreenAudioRunning(_payload: io::Payload) -> Result<Value, ...
  function StopPipewireScreenAudio (line 126) | fn StopPipewireScreenAudio(_payload: io::Payload) -> Result<Value, Strin...
  function SetInstanceIdentifier (line 132) | fn SetInstanceIdentifier(payload: io::Payload) -> Result<Value, String> {
  function run (line 138) | pub fn run(payload: io::Payload) -> Result<Value, String> {

FILE: native/connector-rs/src/daemon.rs
  type ArgParseError (line 20) | pub enum ArgParseError {
  type Error (line 26) | pub enum Error {
  type Command (line 33) | pub enum Command {
  type Response (line 43) | pub enum Response {
  type SharingNodeState (line 58) | enum SharingNodeState {
  type DaemonState (line 64) | struct DaemonState {
    method reshare (line 71) | fn reshare(&mut self, virtual_node: &NodeWithPorts, pipewire_client: &...
  function handle_client (line 102) | fn handle_client(
  function stop_daemon (line 143) | fn stop_daemon() {
  function monitor_and_connect_nodes (line 150) | pub fn monitor_and_connect_nodes() -> Result<(), Error> {

FILE: native/connector-rs/src/dirs.rs
  function get_runtime_path (line 3) | pub fn get_runtime_path() -> PathBuf {

FILE: native/connector-rs/src/helpers.rs
  function parse_numeric_argument (line 6) | pub fn parse_numeric_argument(value: Value) -> i64 {

FILE: native/connector-rs/src/helpers/io.rs
  type RawPayload (line 11) | pub struct RawPayload {
    method from (line 29) | fn from(value: Payload) -> Self {
  type Payload (line 39) | pub struct Payload {
    method from (line 19) | fn from(value: RawPayload) -> Self {
  type ReadError (line 45) | pub enum ReadError {
  type WriteError (line 57) | pub enum WriteError {
  function read (line 68) | pub fn read<R: Read, P: for<'a> Deserialize<'a> + Debug>(mut reader: R) ...
  function write (line 91) | pub fn write<W: Write, P: Serialize>(payload: P, mut writer: W) -> Resul...

FILE: native/connector-rs/src/helpers/pipewire.rs
  type NodeProperties (line 4) | pub struct NodeProperties {
    method from (line 24) | fn from(
  type OutputNode (line 18) | pub struct OutputNode {
    method from (line 42) | fn from(pipewire_utils::OutputNode { id, properties }: pipewire_utils:...

FILE: native/connector-rs/src/ipc.rs
  function get_ipc_socket_path (line 13) | fn get_ipc_socket_path() -> PathBuf {
  function ensure_stopped (line 19) | fn ensure_stopped(path: &Path) -> Result<(), Box<dyn Error>> {
  function listen (line 27) | pub fn listen() -> io::Result<UnixListener> {
  function fake_connect (line 34) | pub fn fake_connect() {
  function connect_inner (line 38) | pub fn connect_inner(tries: usize) -> io::Result<UnixStream> {
  function connect (line 56) | pub fn connect() -> io::Result<UnixStream> {

FILE: native/connector-rs/src/ipc_request.rs
  function is_daemon_running (line 5) | pub fn is_daemon_running() -> Result<bool, String> {
  function stop_daemon (line 18) | pub fn stop_daemon() -> Result<(), String> {
  function set_instance_identifier (line 31) | pub fn set_instance_identifier(instance_identifier: &str) -> Result<(), ...
  function read_start_result (line 50) | pub fn read_start_result(daemon_stdout: ChildStdout) -> Result<u32, Stri...

FILE: native/connector-rs/src/main.rs
  function get_logs_path (line 27) | fn get_logs_path() -> PathBuf {
  function main (line 33) | fn main() -> Result<(), Box<dyn Error>> {

FILE: native/connector-rs/src/monitor.rs
  type Error (line 14) | pub enum Error {
  type Result (line 21) | pub type Result<T, E = Error> = std::result::Result<T, E>;
  type MonitorThreadHandle (line 23) | pub struct MonitorThreadHandle {
    method launch_monitor_thread (line 29) | pub fn launch_monitor_thread(
    method stop (line 63) | pub fn stop(&mut self) {
  method drop (line 75) | fn drop(&mut self) {
Condensed preview — 57 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (167K chars).
[
  {
    "path": ".editorconfig",
    "chars": 211,
    "preview": "# EditorConfig is awesome: https://EditorConfig.org\n\n# top-most EditorConfig file\nroot = true\n\n[*]\nend_of_line = lf\ninse"
  },
  {
    "path": ".eslintrc",
    "chars": 352,
    "preview": "{\n  \"extends\": [\n    \"eslint:recommended\",\n    \"plugin:react/recommended\"\n  ],\n  \"parserOptions\": {\n    \"ecmaVersion\": 2"
  },
  {
    "path": ".github/workflows/update-changelog.yaml",
    "chars": 1103,
    "preview": "# .github/workflows/update-changelog.yaml\nname: \"Update Changelog\"\n\non:\n  release:\n    types: [released]\n\njobs:\n  update"
  },
  {
    "path": ".gitignore",
    "chars": 362,
    "preview": "# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic"
  },
  {
    "path": ".prettierrc.yml",
    "chars": 14,
    "preview": "useTabs: true\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 5974,
    "preview": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Change"
  },
  {
    "path": "INSTALL.md",
    "chars": 2463,
    "preview": "# Installation Guide\n\n## Dependencies\n\n### Extension UI\n\n- Node.js\n- Yarn\n\n### Native Connector\n\n- Cargo\n\n## Browser Ext"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 3161,
    "preview": "# <img src=\"./extension/assets/icons/icon.svg\" width=\"22\" alt=\"Logo\"> Pipewire Screenaudio\n\nExtension to passthrough Pip"
  },
  {
    "path": "extension/manifest.json",
    "chars": 780,
    "preview": "{\n\t\"manifest_version\": 3,\n\t\"name\": \"Pipewire Screenaudio\",\n\t\"version\": \"0.4.2\",\n\n\t\"description\": \"Passthrough pipewire a"
  },
  {
    "path": "extension/react/.gitignore",
    "chars": 5,
    "preview": "/dist"
  },
  {
    "path": "extension/react/build-watcher.sh",
    "chars": 288,
    "preview": "#!/usr/bin/env bash\n\nscriptRoot=\"$( cd -- \"$(dirname \"$0\")\" > /dev/null 2>&1 ; pwd -P )\"\n\ncd $scriptRoot\n\n# Watch for fi"
  },
  {
    "path": "extension/react/components/nodes-table.jsx",
    "chars": 2289,
    "preview": "import React from \"react\";\n\nimport Table from \"@mui/material/Table\";\nimport TableContainer from \"@mui/material/TableCont"
  },
  {
    "path": "extension/react/index.html",
    "chars": 299,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<meta charset=\"UTF-8\" />\n\t\t<meta name=\"viewport\" content=\"width=device-width,"
  },
  {
    "path": "extension/react/index.jsx",
    "chars": 1050,
    "preview": "import { createRoot } from \"react-dom/client\";\nimport {\n\tcreateBrowserRouter,\n\tuseSearchParams,\n\tRouterProvider,\n} from "
  },
  {
    "path": "extension/react/lib/backend.js",
    "chars": 3732,
    "preview": "import { MIC_ID, readLocalStorage } from \"./local-storage\";\n\nconst MESSAGE_NAME = \"com.icedborn.pipewirescreenaudioconne"
  },
  {
    "path": "extension/react/lib/hooks.js",
    "chars": 728,
    "preview": "import { useEffect, useRef, useState } from \"react\";\nimport { readLocalStorage, updateLocalStorage } from \"./local-stora"
  },
  {
    "path": "extension/react/lib/local-storage.js",
    "chars": 407,
    "preview": "export const SELECTED_NODES = \"selectedNodes\";\nexport const MIC_ID = \"micId\";\nexport const ALL_DESKTOP = \"allDesktopAudi"
  },
  {
    "path": "extension/react/lib/match-node.js",
    "chars": 160,
    "preview": "export default function matchNode(a, b) {\n\treturn (\n\t\ta.serial === b.serial &&\n\t\ta.mediaName === b.mediaName &&\n\t\ta.appl"
  },
  {
    "path": "extension/react/routes/popup.jsx",
    "chars": 10567,
    "preview": "// TODO: Add nodes sorting\nimport React, { useCallback, useEffect, useState } from \"react\";\n\nimport Alert from \"@mui/mat"
  },
  {
    "path": "extension/react/vite.config.js",
    "chars": 383,
    "preview": "import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n\tplugins: "
  },
  {
    "path": "extension/scripts/background.js",
    "chars": 2239,
    "preview": "// Any event, that is handled in here, should have a comment with the reason it is handled in here\n\nlet commandsQueue = "
  },
  {
    "path": "extension/scripts/injector.js",
    "chars": 991,
    "preview": "const MESSAGE_NAME = \"com.icedborn.pipewirescreenaudioconnector\";\n\nconst nullthrows = (v) => {\n\tif (v == null) throw new"
  },
  {
    "path": "extension/scripts/override-gdm.js",
    "chars": 4471,
    "preview": "(() => {\n\tlet sessionType = null;\n\n\tconst instanceIdentifier = `pipewire-screenaudio-${createRandomString(16)}`;\n\n\tconst"
  },
  {
    "path": "flake.nix",
    "chars": 4453,
    "preview": "{\n  inputs.nixpkgs.url = \"github:NixOS/nixpkgs/nixos-unstable\";\n  description = \"The native part of the Pipewire Screena"
  },
  {
    "path": "install.sh",
    "chars": 4859,
    "preview": "#!/usr/bin/env bash\nset -e\n\nDEFAULT_CHROMIUM_EXT_ID=\"cbmjbapailadjabjnjnnbfdimkbdicja\"\nREQUIRED_BINS_JS=(\"yarn\")\nREQUIRE"
  },
  {
    "path": "native/.gitignore",
    "chars": 10,
    "preview": "build\nout\n"
  },
  {
    "path": "native/connector/cli.sh",
    "chars": 573,
    "preview": "#!/usr/bin/env bash\n\nexport LC_ALL=C\nexport PROJECT_ROOT=\"$( cd -- \"$(dirname \"$0\")\" > /dev/null 2>&1 ; cd .. ; pwd -P )"
  },
  {
    "path": "native/connector/util.sh",
    "chars": 2118,
    "preview": "#!/usr/bin/bash\n\nTEMP_PATH_ROOT=\"$XDG_RUNTIME_DIR/pipewire-screenaudio\"\nFIFO_PATH=\"$TEMP_PATH_ROOT/fifos\"\nLOG_PATH=\"$TEM"
  },
  {
    "path": "native/connector-rs/.gitignore",
    "chars": 225,
    "preview": "# Generated by Cargo\n# will have compiled files and executables\ndebug/\ntarget/\n\n# These are backup files generated by ru"
  },
  {
    "path": "native/connector-rs/Cargo.toml",
    "chars": 654,
    "preview": "[package]\nname = \"connector-rs\"\nversion = \"0.4.2\"\nedition = \"2021\"\n\n[dependencies]\nserde_json = \"1.0\"\nserde = { version "
  },
  {
    "path": "native/connector-rs/pipewire-utils/.gitignore",
    "chars": 20,
    "preview": "/target\n/Cargo.lock\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/Cargo.toml",
    "chars": 394,
    "preview": "[package]\nname = \"pipewire-utils\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n# See more keys and their definitions at https://d"
  },
  {
    "path": "native/connector-rs/pipewire-utils/examples/all-desktop-audio.rs",
    "chars": 734,
    "preview": "use pipewire_utils::{self, cancellation_signal::CancellationSignal, ManagedNode, PipewireClient};\nuse tracing::Level;\n\nf"
  },
  {
    "path": "native/connector-rs/pipewire-utils/examples/create-node.rs",
    "chars": 229,
    "preview": "use pipewire_utils::PipewireClient;\n\nfn main() -> Result<(), Box<dyn std::error::Error>> {\n    let client = PipewireClie"
  },
  {
    "path": "native/connector-rs/pipewire-utils/rustfmt.toml",
    "chars": 13,
    "preview": "tab_spaces=4\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/cancellation_signal.rs",
    "chars": 2068,
    "preview": "use std::{\n    thread::{self, JoinHandle},\n    time::Duration,\n};\n\nuse pipewire::{\n    channel::{channel, AttachedReceiv"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/lib.rs",
    "chars": 231,
    "preview": "pub mod cancellation_signal;\nmod monitor;\nmod pipewire_client;\nmod pipewire_objects;\nmod proxies;\nmod roundtrip;\nmod uti"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/monitor.rs",
    "chars": 4898,
    "preview": "use std::{\n    cell::{Cell, RefCell},\n    collections::{hash_map::Entry, HashMap, HashSet},\n    rc::Rc,\n};\n\nuse pipewire"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/pipewire_client.rs",
    "chars": 23978,
    "preview": "use std::{\n    cell::{OnceCell, RefCell},\n    collections::{HashMap, HashSet},\n    rc::Rc,\n};\n\nuse libspa::utils::dict::"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/pipewire_objects.rs",
    "chars": 3320,
    "preview": "use std::str::FromStr;\n\nuse thiserror::Error;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum PortDirection {\n   "
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/proxies.rs",
    "chars": 807,
    "preview": "use std::collections::HashMap;\n\nuse pipewire::proxy::{Listener, ProxyT};\n\npub struct ProxyRef {\n    _proxy: Box<dyn Prox"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/roundtrip.rs",
    "chars": 4233,
    "preview": "use std::{cell::Cell, fmt::Debug, rc::Rc};\n\nuse libspa::utils::result::AsyncSeq;\nuse pipewire::{\n    core::{CoreRc, PW_I"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/utils.rs",
    "chars": 929,
    "preview": "use crate::{pipewire_client::PipewireClient, pipewire_objects::NodeWithPorts, PipewireError};\n\npub struct ManagedNode {\n"
  },
  {
    "path": "native/connector-rs/rustfmt.toml",
    "chars": 13,
    "preview": "tab_spaces=2\n"
  },
  {
    "path": "native/connector-rs/src/command.rs",
    "chars": 4307,
    "preview": "#![allow(non_snake_case)]\n\nuse std::env;\nuse std::env::current_exe;\nuse std::process::Command;\nuse std::process::Stdio;\n"
  },
  {
    "path": "native/connector-rs/src/daemon.rs",
    "chars": 4786,
    "preview": "use serde::{Deserialize, Serialize};\nuse std::{\n  io::stdout,\n  num::ParseIntError,\n  os::unix::net::UnixStream,\n  sync:"
  },
  {
    "path": "native/connector-rs/src/dirs.rs",
    "chars": 220,
    "preview": "use std::{env, path::PathBuf};\n\npub fn get_runtime_path() -> PathBuf {\n  let mut path: PathBuf = env::var(\"XDG_RUNTIME_D"
  },
  {
    "path": "native/connector-rs/src/helpers/io.rs",
    "chars": 2946,
    "preview": "use std::fmt::Debug;\nuse std::io::prelude::{Read, Write};\nuse std::str;\n\nuse serde::{Deserialize, Serialize};\nuse serde_"
  },
  {
    "path": "native/connector-rs/src/helpers/pipewire.rs",
    "chars": 1013,
    "preview": "use serde::Serialize;\n\n#[derive(Debug, Serialize)]\npub struct NodeProperties {\n  #[serde(rename = \"application.name\")]\n "
  },
  {
    "path": "native/connector-rs/src/helpers.rs",
    "chars": 248,
    "preview": "use serde_json::Value;\n\npub mod io;\npub mod pipewire;\n\npub fn parse_numeric_argument(value: Value) -> i64 {\n  if value.i"
  },
  {
    "path": "native/connector-rs/src/ipc.rs",
    "chars": 1307,
    "preview": "use std::{\n  error::Error,\n  fs, io,\n  os::unix::net::{UnixListener, UnixStream},\n  path::{Path, PathBuf},\n  thread,\n  t"
  },
  {
    "path": "native/connector-rs/src/ipc_request.rs",
    "chars": 2010,
    "preview": "use std::process::ChildStdout;\n\nuse crate::{daemon, helpers::io, ipc};\n\npub fn is_daemon_running() -> Result<bool, Strin"
  },
  {
    "path": "native/connector-rs/src/main.rs",
    "chars": 2663,
    "preview": "use std::{\n  env,\n  error::Error,\n  io::{stdin, stdout},\n  panic,\n  path::PathBuf,\n  process,\n};\n\nmod command;\nmod daemo"
  },
  {
    "path": "native/connector-rs/src/monitor.rs",
    "chars": 2173,
    "preview": "use std::{\n  io,\n  rc::Rc,\n  thread::{self, JoinHandle},\n};\n\nuse pipewire_utils::{\n  cancellation_signal::{CancellationC"
  },
  {
    "path": "native/native-messaging-hosts/com.icedborn.pipewirescreenaudioconnector.json",
    "chars": 207,
    "preview": "{\n\t\"name\": \"com.icedborn.pipewirescreenaudioconnector\",\n\t\"description\": \"Connector to communicate with the browser\",\n\t\"p"
  },
  {
    "path": "package.json",
    "chars": 591,
    "preview": "{\n\t\"name\": \"pipewire-screenaudio\",\n\t\"version\": \"0.4.2\",\n\t\"scripts\": {\n\t\t\"build\": \"vite build extension/react\"\n\t},\n\t\"depe"
  }
]

About this extraction

This page contains the full source code of the IceDBorn/pipewire-screenaudio GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 57 files (150.8 KB), approximately 38.2k tokens, and a symbol index with 199 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!