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. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . ================================================ FILE: README.md ================================================ # 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": [""], "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": [""], "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 ( toggleNodes(null)} checked={allChecked} /> Media Application {nodes.map((node) => ( toggleNodes([node.serial])} disabled={allDesktopAudio || hasError} checked={nodeSelection.has(node.serial)} />
{node.mediaName}
{node.applicationName}
))}
); } ================================================ FILE: extension/react/index.html ================================================ Document
================================================ 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: , }, ]); function PageWrapper() { const [search] = useSearchParams(); console.log(search); if (!search.has("page")) { return ; } } function App() { return ( ); } const rootEl = document.getElementById("root"); const root = createRoot(rootEl); root.render(); ================================================ 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 && ( <> Pipewire Screenaudio {(showConnectionError || !versionMatches || (isCurrentMicIdInitialized && isRunning)) && ( {showConnectionError ? "The native connector is missing or misconfigured" : !versionMatches ? `Version mismatch! Extension: ${extensionVersion}, Native: ${nativeVersion}` : isRunning ? `Running with ID: ${micId}` : console.error("unreachable")} )} {/* Content */} {(areNodesInitialized || showConnectionError) && (showConnectionError || !nodes.length ? (
{showConnectionError ? "Could not retrieve node list" : "No nodes available for sharing"}
) : ( { toggleNodes(serials); shareNodes(allDesktopAudio); }} hasError={!isHealthy} allDesktopAudio={allDesktopAudio} /> ))} { 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()} /> ) ); } ================================================ 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> { 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> { 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, } pub struct AttachedCancellationSignal<'a> { receiver: AttachedReceiver<'a, TerminateSignal>, } #[derive(Clone)] pub struct CancellationController { sender: Sender, } 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>, } 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 { relevant_nodes: Rc>>, nodes_to_ports: Rc>>>, ports: Rc>>, relevant_port_added_callback: Option, relevant_port_removed_callback: Option, } impl Default for NodeAndPortsRegistry { fn default() -> Self { Self { relevant_nodes: Rc::new(RefCell::new(HashSet::new())), nodes_to_ports: Rc::new(RefCell::new(HashMap::>::new())), ports: Rc::new(RefCell::new(HashMap::::new())), relevant_port_added_callback: None, relevant_port_removed_callback: None, } } } impl NodeAndPortsRegistry { 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(&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 { 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>>, } 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 { 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 = std::result::Result; #[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, 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 { 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>, } impl PipewireClient { pub fn new() -> Result { 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( &self, registry: RegistryRc, node_callback: F, node_destroy_callback: DF, scheduler: Option, ) -> NodeListenerHandle where F: Fn(&NodeInfoRef) + Clone + 'static, DF: Fn(u32) + 'static, { let proxies: Rc> = 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::(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(&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> { 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> { 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) -> Result { let node = self.core.create_object::( "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) { 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::() 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 { self.core.create_object::( "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 + 'static) -> Option { 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 { 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 { 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 { 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, pub fr_port: Option, } impl MaybePorts { pub fn both(self) -> Option { 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> for StereoAudioChannel { type Error = ChannelIsNotStereoError; fn try_from(value: AudioChannel<'a>) -> Result { match value { AudioChannel::FrontLeft => Ok(StereoAudioChannel::FrontLeft), AudioChannel::FrontRight => Ok(StereoAudioChannel::FrontRight), AudioChannel::Other(_) => Err(ChannelIsNotStereoError), } } } pub struct OwnedPortInfo { pub(crate) channel: Option, pub(crate) node_id: u32, pub(crate) id: u32, #[allow(unused)] pub(crate) direction: PortDirection, } impl<'a> From> 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, _listeners: Vec>, } #[derive(Default)] pub struct ProxyRefs { refs: HashMap, } impl ProxyRefs { pub fn new() -> Self { Self::default() } pub fn add_proxy(&mut self, proxy: Box, listeners: Vec>) { 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>>, mainloop: MainLoopRc, core: CoreRc, done: Rc>, } pub struct StopSettings { on_last_roundtrip: bool, signal_receiver: Option, } 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 for StopSettings { fn from(value: CancellationSignal) -> Self { StopSettingsBuilder::default().stop_on_signal(value).build() } } pub struct StopSettingsBuilder { on_last_roundtrip: bool, signal_receiver: Option, } #[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, ) -> Result { 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 { Ok(json!({ "version": VERSION })) } fn GetSessionType(_: io::Payload) -> Result { let session_type = match env::var_os("WAYLAND_DISPLAY") { Some(_) => "wayland", None => "x11", }; Ok(json!({ "type": session_type })) } fn GetNodes(_: io::Payload) -> Result { 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 { 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 { 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 { let is_running = ipc_request::is_daemon_running().is_ok_and(|running| running); Ok(json!({ "isRunning": is_running })) } fn StopPipewireScreenAudio(_payload: io::Payload) -> Result { ipc_request::stop_daemon()?; Ok(json!({})) } fn SetInstanceIdentifier(payload: io::Payload) -> Result { 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 { 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> }, 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), AllDesktop, NotSharing, } struct DaemonState { running_thread: Option, sharing_node_state: SharingNodeState, instance_identifier: Option, } 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, } impl From for Payload { fn from(value: RawPayload) -> Self { let RawPayload { command, arguments } = value; Self { command, arguments: arguments.unwrap_or_else(|| json!({})), } } } impl From 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 Deserialize<'a> + Debug>(mut reader: R) -> Result { 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(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, #[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 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 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::().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> { if path.exists() { let stream = connect_inner(1)?; ipc_io::write(daemon::Command::Stop, &stream)?; } Ok(()) } pub fn listen() -> io::Result { 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 { 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 { 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 { 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 { 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> { 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 = std::result::Result; pub struct MonitorThreadHandle { join_handle: Option>>, cancellation_controller: CancellationController, } impl MonitorThreadHandle { pub fn launch_monitor_thread( mic_ports: Ports, instance_identifier: Option, ) -> Result { 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" } }