Import kpipewire_5.27.5.orig.tar.xz
authorPatrick Franz <deltaone@debian.org>
Tue, 9 May 2023 21:26:05 +0000 (23:26 +0200)
committerPatrick Franz <deltaone@debian.org>
Tue, 9 May 2023 21:26:05 +0000 (23:26 +0200)
[dgit import orig kpipewire_5.27.5.orig.tar.xz]

82 files changed:
.gitignore [new file with mode: 0644]
.gitlab-ci.yml [new file with mode: 0644]
.kde-ci.yml [new file with mode: 0644]
CMakeLists.txt [new file with mode: 0644]
LICENSES/BSD-3-Clause.txt [new file with mode: 0644]
LICENSES/CC0-1.0.txt [new file with mode: 0644]
LICENSES/LGPL-2.1-only.txt [new file with mode: 0644]
LICENSES/LGPL-3.0-only.txt [new file with mode: 0644]
LICENSES/LicenseRef-KDE-Accepted-LGPL.txt [new file with mode: 0644]
README.md [new file with mode: 0644]
cmake/FindLibdrm.cmake [new file with mode: 0644]
po/ar/kpipewire5.po [new file with mode: 0644]
po/ca/kpipewire5.po [new file with mode: 0644]
po/ca@valencia/kpipewire5.po [new file with mode: 0644]
po/cs/kpipewire5.po [new file with mode: 0644]
po/de/kpipewire5.po [new file with mode: 0644]
po/en_GB/kpipewire5.po [new file with mode: 0644]
po/es/kpipewire5.po [new file with mode: 0644]
po/eu/kpipewire5.po [new file with mode: 0644]
po/fi/kpipewire5.po [new file with mode: 0644]
po/fr/kpipewire5.po [new file with mode: 0644]
po/gl/kpipewire5.po [new file with mode: 0644]
po/it/kpipewire5.po [new file with mode: 0644]
po/ja/kpipewire5.po [new file with mode: 0644]
po/ka/kpipewire5.po [new file with mode: 0644]
po/ko/kpipewire5.po [new file with mode: 0644]
po/nl/kpipewire5.po [new file with mode: 0644]
po/nn/kpipewire5.po [new file with mode: 0644]
po/pa/kpipewire5.po [new file with mode: 0644]
po/pl/kpipewire5.po [new file with mode: 0644]
po/pt/kpipewire5.po [new file with mode: 0644]
po/pt_BR/kpipewire5.po [new file with mode: 0644]
po/ro/kpipewire5.po [new file with mode: 0644]
po/ru/kpipewire5.po [new file with mode: 0644]
po/sk/kpipewire5.po [new file with mode: 0644]
po/sl/kpipewire5.po [new file with mode: 0644]
po/sv/kpipewire5.po [new file with mode: 0644]
po/ta/kpipewire5.po [new file with mode: 0644]
po/tr/kpipewire5.po [new file with mode: 0644]
po/uk/kpipewire5.po [new file with mode: 0644]
po/zh_CN/kpipewire5.po [new file with mode: 0644]
po/zh_TW/kpipewire5.po [new file with mode: 0644]
src/CMakeLists.txt [new file with mode: 0644]
src/KPipeWireConfig.cmake.in [new file with mode: 0644]
src/Messages.sh [new file with mode: 0755]
src/dmabufhandler.cpp [new file with mode: 0644]
src/dmabufhandler.h [new file with mode: 0644]
src/glhelpers.cpp [new file with mode: 0644]
src/glhelpers.h [new file with mode: 0644]
src/kpipewiredeclarativeplugin.cpp [new file with mode: 0644]
src/kpipewiredeclarativeplugin.h [new file with mode: 0644]
src/kpipewirerecorddeclarativeplugin.cpp [new file with mode: 0644]
src/kpipewirerecorddeclarativeplugin.h [new file with mode: 0644]
src/pipewirecore.cpp [new file with mode: 0644]
src/pipewirecore.h [new file with mode: 0644]
src/pipewirerecord.cpp [new file with mode: 0644]
src/pipewirerecord.h [new file with mode: 0644]
src/pipewirerecord_p.h [new file with mode: 0644]
src/pipewiresourceitem.cpp [new file with mode: 0644]
src/pipewiresourceitem.h [new file with mode: 0644]
src/pipewiresourcestream.cpp [new file with mode: 0644]
src/pipewiresourcestream.h [new file with mode: 0644]
src/pwhelpers.cpp [new file with mode: 0644]
src/pwhelpers.h [new file with mode: 0644]
tests/CMakeLists.txt [new file with mode: 0644]
tests/HeadlessTest.cpp [new file with mode: 0644]
tests/PlasmaRecordMe.cpp [new file with mode: 0644]
tests/PlasmaRecordMe.h [new file with mode: 0644]
tests/RecordMe.cpp [new file with mode: 0644]
tests/RecordMe.h [new file with mode: 0644]
tests/main.cpp [new file with mode: 0644]
tests/main.qml [new file with mode: 0644]
tests/org.freedesktop.portal.RemoteDesktop.xml [new file with mode: 0644]
tests/org.freedesktop.portal.ScreenCast.xml [new file with mode: 0644]
tests/org.kde.kpipewireheadlesstest.desktop.cmake [new file with mode: 0644]
tests/org.kde.recordme.desktop.cmake [new file with mode: 0644]
tests/recordme.qrc [new file with mode: 0644]
tests/screencasting.cpp [new file with mode: 0644]
tests/screencasting.h [new file with mode: 0644]
tests/screencastingrequest.cpp [new file with mode: 0644]
tests/screencastingrequest.h [new file with mode: 0644]
tests/xdp-main.cpp [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..d84c817
--- /dev/null
@@ -0,0 +1,28 @@
+# Ignore the following files
+*~
+*.[oa]
+*.diff
+*.kate-swp
+*.kdev4
+.kdev_include_paths
+*.kdevelop.pcs
+*.moc
+*.moc.cpp
+*.orig
+*.user
+.*.swp
+.swp.*
+Doxyfile
+Makefile
+avail
+random_seed
+/build*/
+CMakeLists.txt.user*
+*.unc-backup*
+.cmake/
+/.clang-format
+/compile_commands.json
+.clangd
+.idea
+/cmake-build*
+.cache
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
new file mode 100644 (file)
index 0000000..ef2d7aa
--- /dev/null
@@ -0,0 +1,8 @@
+# SPDX-FileCopyrightText: None
+# SPDX-License-Identifier: CC0-1.0
+
+include:
+  - https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/linux.yml
+  - https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/linux-qt6.yml
+  - https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/freebsd.yml
+  - https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/freebsd-qt6.yml
diff --git a/.kde-ci.yml b/.kde-ci.yml
new file mode 100644 (file)
index 0000000..7840f69
--- /dev/null
@@ -0,0 +1,13 @@
+# SPDX-FileCopyrightText: None
+# SPDX-License-Identifier: CC0-1.0
+
+Dependencies:
+- 'on': ['@all']
+  'require':
+    'frameworks/extra-cmake-modules': '@latest'
+    'frameworks/kcoreaddons': '@latest'
+    'frameworks/ki18n': '@latest'
+    'frameworks/kwayland': '@latest'
+    'libraries/plasma-wayland-protocols': '@latest'
+Options:
+  require-passing-tests-on: [ 'Linux', 'FreeBSD']
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..790eb45
--- /dev/null
@@ -0,0 +1,56 @@
+cmake_minimum_required(VERSION 3.16)
+project(KPipewire)
+set(PROJECT_VERSION "5.27.5")
+set(PROJECT_VERSION_MAJOR 5)
+
+set(KF5_MIN_VERSION "5.102.0")
+find_package(ECM ${KF5_MIN_VERSION} REQUIRED NO_MODULE)
+set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake)
+include(KDEInstallDirs)
+include(KDECompilerSettings NO_POLICY_SCOPE)
+include(KDECMakeSettings)
+include(KDEClangFormat)
+include(KDEGitCommitHooks)
+include(ECMQtDeclareLoggingCategory)
+
+find_package(Qt${QT_MAJOR_VERSION} REQUIRED COMPONENTS DBus Quick WaylandClient)
+find_package(KF5 REQUIRED COMPONENTS Wayland I18n CoreAddons)
+find_package(Wayland REQUIRED COMPONENTS Client)
+
+find_package(PlasmaWaylandProtocols REQUIRED)
+if (QT_MAJOR_VERSION EQUAL "5")
+    find_package(QtWaylandScanner REQUIRED)
+else()
+    find_package(EGL REQUIRED)
+endif()
+
+pkg_check_modules(PipeWire IMPORTED_TARGET libpipewire-0.3 REQUIRED)
+
+# ffmpeg, for recording
+pkg_check_modules(AVCodec IMPORTED_TARGET libavcodec)
+pkg_check_modules(AVUtil IMPORTED_TARGET libavutil)
+pkg_check_modules(AVFormat IMPORTED_TARGET libavformat)
+pkg_check_modules(GBM IMPORTED_TARGET gbm)
+pkg_check_modules(SWScale IMPORTED_TARGET libswscale)
+find_package(epoxy 1.3 REQUIRED)
+find_package(Libdrm 2.4.62)
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+# add clang-format target for all our real source files
+file(GLOB_RECURSE ALL_CLANG_FORMAT_SOURCE_FILES *.cpp *.h)
+kde_clang_format(${ALL_CLANG_FORMAT_SOURCE_FILES})
+kde_configure_git_pre_commit_hook(CHECKS CLANG_FORMAT)
+
+# Prevent EGL headers from including platform headers, in particular Xlib.h.
+add_definitions(-DMESA_EGL_NO_X11_HEADERS)
+add_definitions(-DEGL_NO_X11)
+add_definitions(-DEGL_NO_PLATFORM_SPECIFIC_TYPES)
+
+add_subdirectory(src)
+if (BUILD_TESTING)
+   add_subdirectory(tests)
+endif()
+
+ki18n_install(po)
diff --git a/LICENSES/BSD-3-Clause.txt b/LICENSES/BSD-3-Clause.txt
new file mode 100644 (file)
index 0000000..ea890af
--- /dev/null
@@ -0,0 +1,11 @@
+Copyright (c) <year> <owner>. 
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt
new file mode 100644 (file)
index 0000000..0e259d4
--- /dev/null
@@ -0,0 +1,121 @@
+Creative Commons Legal Code
+
+CC0 1.0 Universal
+
+    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
+    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
+    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
+    INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
+    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
+    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
+    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
+    HEREUNDER.
+
+Statement of Purpose
+
+The laws of most jurisdictions throughout the world automatically confer
+exclusive Copyright and Related Rights (defined below) upon the creator
+and subsequent owner(s) (each and all, an "owner") of an original work of
+authorship and/or a database (each, a "Work").
+
+Certain owners wish to permanently relinquish those rights to a Work for
+the purpose of contributing to a commons of creative, cultural and
+scientific works ("Commons") that the public can reliably and without fear
+of later claims of infringement build upon, modify, incorporate in other
+works, reuse and redistribute as freely as possible in any form whatsoever
+and for any purposes, including without limitation commercial purposes.
+These owners may contribute to the Commons to promote the ideal of a free
+culture and the further production of creative, cultural and scientific
+works, or to gain reputation or greater distribution for their Work in
+part through the use and efforts of others.
+
+For these and/or other purposes and motivations, and without any
+expectation of additional consideration or compensation, the person
+associating CC0 with a Work (the "Affirmer"), to the extent that he or she
+is an owner of Copyright and Related Rights in the Work, voluntarily
+elects to apply CC0 to the Work and publicly distribute the Work under its
+terms, with knowledge of his or her Copyright and Related Rights in the
+Work and the meaning and intended legal effect of CC0 on those rights.
+
+1. Copyright and Related Rights. A Work made available under CC0 may be
+protected by copyright and related or neighboring rights ("Copyright and
+Related Rights"). Copyright and Related Rights include, but are not
+limited to, the following:
+
+  i. the right to reproduce, adapt, distribute, perform, display,
+     communicate, and translate a Work;
+ ii. moral rights retained by the original author(s) and/or performer(s);
+iii. publicity and privacy rights pertaining to a person's image or
+     likeness depicted in a Work;
+ iv. rights protecting against unfair competition in regards to a Work,
+     subject to the limitations in paragraph 4(a), below;
+  v. rights protecting the extraction, dissemination, use and reuse of data
+     in a Work;
+ vi. database rights (such as those arising under Directive 96/9/EC of the
+     European Parliament and of the Council of 11 March 1996 on the legal
+     protection of databases, and under any national implementation
+     thereof, including any amended or successor version of such
+     directive); and
+vii. other similar, equivalent or corresponding rights throughout the
+     world based on applicable law or treaty, and any national
+     implementations thereof.
+
+2. Waiver. To the greatest extent permitted by, but not in contravention
+of, applicable law, Affirmer hereby overtly, fully, permanently,
+irrevocably and unconditionally waives, abandons, and surrenders all of
+Affirmer's Copyright and Related Rights and associated claims and causes
+of action, whether now known or unknown (including existing as well as
+future claims and causes of action), in the Work (i) in all territories
+worldwide, (ii) for the maximum duration provided by applicable law or
+treaty (including future time extensions), (iii) in any current or future
+medium and for any number of copies, and (iv) for any purpose whatsoever,
+including without limitation commercial, advertising or promotional
+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
+member of the public at large and to the detriment of Affirmer's heirs and
+successors, fully intending that such Waiver shall not be subject to
+revocation, rescission, cancellation, termination, or any other legal or
+equitable action to disrupt the quiet enjoyment of the Work by the public
+as contemplated by Affirmer's express Statement of Purpose.
+
+3. Public License Fallback. Should any part of the Waiver for any reason
+be judged legally invalid or ineffective under applicable law, then the
+Waiver shall be preserved to the maximum extent permitted taking into
+account Affirmer's express Statement of Purpose. In addition, to the
+extent the Waiver is so judged Affirmer hereby grants to each affected
+person a royalty-free, non transferable, non sublicensable, non exclusive,
+irrevocable and unconditional license to exercise Affirmer's Copyright and
+Related Rights in the Work (i) in all territories worldwide, (ii) for the
+maximum duration provided by applicable law or treaty (including future
+time extensions), (iii) in any current or future medium and for any number
+of copies, and (iv) for any purpose whatsoever, including without
+limitation commercial, advertising or promotional purposes (the
+"License"). The License shall be deemed effective as of the date CC0 was
+applied by Affirmer to the Work. Should any part of the License for any
+reason be judged legally invalid or ineffective under applicable law, such
+partial invalidity or ineffectiveness shall not invalidate the remainder
+of the License, and in such case Affirmer hereby affirms that he or she
+will not (i) exercise any of his or her remaining Copyright and Related
+Rights in the Work or (ii) assert any associated claims and causes of
+action with respect to the Work, in either case contrary to Affirmer's
+express Statement of Purpose.
+
+4. Limitations and Disclaimers.
+
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
+    surrendered, licensed or otherwise affected by this document.
+ b. Affirmer offers the Work as-is and makes no representations or
+    warranties of any kind concerning the Work, express, implied,
+    statutory or otherwise, including without limitation warranties of
+    title, merchantability, fitness for a particular purpose, non
+    infringement, or the absence of latent or other defects, accuracy, or
+    the present or absence of errors, whether or not discoverable, all to
+    the greatest extent permissible under applicable law.
+ c. Affirmer disclaims responsibility for clearing rights of other persons
+    that may apply to the Work or any use thereof, including without
+    limitation any person's Copyright and Related Rights in the Work.
+    Further, Affirmer disclaims responsibility for obtaining any necessary
+    consents, permissions or other rights required for any use of the
+    Work.
+ d. Affirmer understands and acknowledges that Creative Commons is not a
+    party to this document and has no duty or obligation with respect to
+    this CC0 or use of the Work.
diff --git a/LICENSES/LGPL-2.1-only.txt b/LICENSES/LGPL-2.1-only.txt
new file mode 100644 (file)
index 0000000..c9aa530
--- /dev/null
@@ -0,0 +1,175 @@
+GNU LESSER GENERAL PUBLIC LICENSE
+
+Version 2.1, February 1999
+
+Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.]
+
+Preamble
+
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.
+
+This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.
+
+When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.
+
+To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.
+
+For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.
+
+We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.
+
+To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.
+
+Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.
+
+Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.
+
+When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.
+
+We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.
+
+For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.
+
+In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.
+
+Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.
+
+The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.
+
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you".
+
+A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.
+
+The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)
+
+"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.
+
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.
+
+1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library.
+
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
+
+2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
+
+     a) The modified work must itself be a software library.
+
+     b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
+
+     c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
+
+     d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.
+
+(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
+
+3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.
+
+Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy.
+
+This option is useful when you wish to copy part of the code of the Library into a program that is not a library.
+
+4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange.
+
+If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.
+
+5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.
+
+However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.
+
+When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.
+
+If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)
+
+Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.
+
+6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.
+
+You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:
+
+     a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
+
+     b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
+
+     c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
+
+     d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
+
+     e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
+
+For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
+
+It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.
+
+7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:
+
+     a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
+
+     b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
+
+8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
+
+9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.
+
+10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.
+
+11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
+
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
+
+12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
+
+13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.
+
+14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
+
+NO WARRANTY
+
+15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+END OF TERMS AND CONDITIONS
+
+How to Apply These Terms to Your New Libraries
+
+If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License).
+
+To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
+
+     one line to give the library's name and an idea of what it does.
+     Copyright (C) year  name of author
+
+     This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
+
+     This library 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 Lesser General Public License for more details.
+
+     You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names:
+
+Yoyodyne, Inc., hereby disclaims all copyright interest in
+the library `Frob' (a library for tweaking knobs) written
+by James Random Hacker.
+
+signature of Ty Coon, 1 April 1990
+Ty Coon, President of Vice
+That's all there is to it!
diff --git a/LICENSES/LGPL-3.0-only.txt b/LICENSES/LGPL-3.0-only.txt
new file mode 100644 (file)
index 0000000..513d1c0
--- /dev/null
@@ -0,0 +1,304 @@
+GNU LESSER GENERAL PUBLIC LICENSE
+Version 3, 29 June 2007
+
+Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+
+This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
+
+0. Additional Definitions.
+
+As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License.
+
+"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
+
+An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
+
+A "Combined Work" is a work produced by combining or linking an Application with the Library.  The particular version of the Library with which the Combined Work was made is also called the "Linked Version".
+
+The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
+
+The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
+
+1. Exception to Section 3 of the GNU GPL.
+You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
+
+2. Conveying Modified Versions.
+If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
+
+     a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
+
+     b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
+
+3. Object Code Incorporating Material from Library Header Files.
+The object code form of an Application may incorporate material from a header file that is part of the Library.  You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
+
+     a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
+
+     b) Accompany the object code with a copy of the GNU GPL and this license document.
+
+4. Combined Works.
+You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
+
+     a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
+
+     b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
+
+     c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
+
+     d) Do one of the following:
+
+           0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
+
+          1) Use a suitable shared library mechanism for linking with the Library.  A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
+
+     e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
+
+5. Combined Libraries.
+You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
+
+     a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
+
+     b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
+
+6. Revised Versions of the GNU Lesser General Public License.
+The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
+
+If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
+
+GNU GENERAL PUBLIC LICENSE
+Version 3, 29 June 2007
+
+Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+
+Preamble
+
+The GNU General Public License is a free, copyleft license for software and other kinds of works.
+
+The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
+
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
+
+Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
+
+Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and modification follow.
+
+TERMS AND CONDITIONS
+
+0. Definitions.
+
+“This License” refers to version 3 of the GNU General Public License.
+
+“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
+
+“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
+
+To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
+
+A “covered work” means either the unmodified Program or a work based on the Program.
+
+To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
+
+To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
+
+An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
+
+1. Source Code.
+The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
+
+A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
+
+The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
+
+The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
+
+The Corresponding Source for a work in source code form is that same work.
+
+2. Basic Permissions.
+All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
+
+Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
+
+3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
+
+When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
+
+4. Conveying Verbatim Copies.
+You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
+
+You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
+
+5. Conveying Modified Source Versions.
+You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
+
+     a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
+
+     b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
+
+     c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
+
+     d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
+
+A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
+
+6. Conveying Non-Source Forms.
+You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
+
+     a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
+
+     b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
+
+     c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
+
+     d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
+
+     e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
+
+A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
+
+“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
+
+If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
+
+The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
+
+Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
+
+7. Additional Terms.
+“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
+
+     a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
+
+     b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
+
+     c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
+
+     d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
+
+     e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
+
+     f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
+
+All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
+
+8. Termination.
+You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
+
+However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
+
+Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
+
+9. Acceptance Not Required for Having Copies.
+You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
+
+10. Automatic Licensing of Downstream Recipients.
+Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
+
+An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
+
+11. Patents.
+A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
+
+A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
+
+In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
+
+A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
+
+12. No Surrender of Others' Freedom.
+If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
+
+13. Use with the GNU Affero General Public License.
+Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
+
+14. Revised Versions of this License.
+The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
+
+If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
+
+Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
+
+15. Disclaimer of Warranty.
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+16. Limitation of Liability.
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+17. Interpretation of Sections 15 and 16.
+If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+
+How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
+
+To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
+
+     <one line to give the program's name and a brief idea of what it does.>
+     Copyright (C) <year>  <name of author>
+
+     This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
+
+     This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+
+     You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
+
+     <program>  Copyright (C) <year>  <name of author>
+     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+     This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
+
+You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
+
+The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/LICENSES/LicenseRef-KDE-Accepted-LGPL.txt b/LICENSES/LicenseRef-KDE-Accepted-LGPL.txt
new file mode 100644 (file)
index 0000000..232b3c5
--- /dev/null
@@ -0,0 +1,12 @@
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 3 of the license or (at your option) any later version
+that is accepted by the membership of KDE e.V. (or its successor
+approved by the membership of KDE e.V.), which shall act as a
+proxy as defined in Section 6 of version 3 of the license.
+
+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.
diff --git a/README.md b/README.md
new file mode 100644 (file)
index 0000000..3a83df7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,21 @@
+# KPipeWire
+
+Offers a set of convenient classes to use PipeWire (https://pipewire.org/) in Qt projects.
+
+It is developed in C++ and it's main use target is QML components.
+
+As it's what's been useful, this framework focuses on graphical PipeWire features. If it was necessary, these could be included.
+
+## Features
+
+At the moment we offer two main components:
+* KPipeWire: offers the main components to connect to and render PipeWire into your app.
+* KPipeWireRecord: using FFmpeg, helps to record a PipeWire video stream into a file.
+
+## Usage
+
+You can refer to the `tests/` subdirectory for two examples of rendering Plasma video streams. One through the internal Plasma Wayland protocol and the other using the standard XDG Desktop Portals screencast API.
+
+## Licence
+
+This project is licenced under LGPL v2.1+, you can find all the information under `LICENSES/`.
diff --git a/cmake/FindLibdrm.cmake b/cmake/FindLibdrm.cmake
new file mode 100644 (file)
index 0000000..cf6e061
--- /dev/null
@@ -0,0 +1,105 @@
+#.rst:
+# FindLibdrm
+# -------
+#
+# Try to find libdrm on a Unix system.
+#
+# This will define the following variables:
+#
+# ``Libdrm_FOUND``
+#     True if (the requested version of) libdrm is available
+# ``Libdrm_VERSION``
+#     The version of libdrm
+# ``Libdrm_LIBRARIES``
+#     This can be passed to target_link_libraries() instead of the ``Libdrm::Libdrm``
+#     target
+# ``Libdrm_INCLUDE_DIRS``
+#     This should be passed to target_include_directories() if the target is not
+#     used for linking
+# ``Libdrm_DEFINITIONS``
+#     This should be passed to target_compile_options() if the target is not
+#     used for linking
+#
+# If ``Libdrm_FOUND`` is TRUE, it will also define the following imported target:
+#
+# ``Libdrm::Libdrm``
+#     The libdrm library
+#
+# In general we recommend using the imported target, as it is easier to use.
+# Bear in mind, however, that if the target is in the link interface of an
+# exported library, it must be made available by the package config file.
+
+#=============================================================================
+# SPDX-FileCopyrightText: 2014 Alex Merry <alex.merry@kde.org>
+# SPDX-FileCopyrightText: 2014 Martin Gräßlin <mgraesslin@kde.org>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+#=============================================================================
+
+if(CMAKE_VERSION VERSION_LESS 2.8.12)
+    message(FATAL_ERROR "CMake 2.8.12 is required by FindLibdrm.cmake")
+endif()
+if(CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 2.8.12)
+    message(AUTHOR_WARNING "Your project should require at least CMake 2.8.12 to use FindLibdrm.cmake")
+endif()
+
+if(NOT WIN32)
+    # Use pkg-config to get the directories and then use these values
+    # in the FIND_PATH() and FIND_LIBRARY() calls
+    find_package(PkgConfig)
+    pkg_check_modules(PKG_Libdrm QUIET libdrm)
+
+    set(Libdrm_DEFINITIONS ${PKG_Libdrm_CFLAGS_OTHER})
+    set(Libdrm_VERSION ${PKG_Libdrm_VERSION})
+
+    find_path(Libdrm_INCLUDE_DIR
+        NAMES
+            xf86drm.h
+        HINTS
+            ${PKG_Libdrm_INCLUDE_DIRS}
+    )
+    find_library(Libdrm_LIBRARY
+        NAMES
+            drm
+        HINTS
+            ${PKG_Libdrm_LIBRARY_DIRS}
+    )
+
+    include(FindPackageHandleStandardArgs)
+    find_package_handle_standard_args(Libdrm
+        FOUND_VAR
+            Libdrm_FOUND
+        REQUIRED_VARS
+            Libdrm_LIBRARY
+            Libdrm_INCLUDE_DIR
+        VERSION_VAR
+            Libdrm_VERSION
+    )
+
+    if(Libdrm_FOUND AND NOT TARGET Libdrm::Libdrm)
+        add_library(Libdrm::Libdrm UNKNOWN IMPORTED)
+        set_target_properties(Libdrm::Libdrm PROPERTIES
+            IMPORTED_LOCATION "${Libdrm_LIBRARY}"
+            INTERFACE_COMPILE_OPTIONS "${Libdrm_DEFINITIONS}"
+            INTERFACE_INCLUDE_DIRECTORIES "${Libdrm_INCLUDE_DIR}"
+            INTERFACE_INCLUDE_DIRECTORIES "${Libdrm_INCLUDE_DIR}/libdrm"
+        )
+    endif()
+
+    mark_as_advanced(Libdrm_LIBRARY Libdrm_INCLUDE_DIR)
+
+    # compatibility variables
+    set(Libdrm_LIBRARIES ${Libdrm_LIBRARY})
+    set(Libdrm_INCLUDE_DIRS ${Libdrm_INCLUDE_DIR} "${Libdrm_INCLUDE_DIR}/libdrm")
+    set(Libdrm_VERSION_STRING ${Libdrm_VERSION})
+
+else()
+    message(STATUS "FindLibdrm.cmake cannot find libdrm on Windows systems.")
+    set(Libdrm_FOUND FALSE)
+endif()
+
+include(FeatureSummary)
+set_package_properties(Libdrm PROPERTIES
+    URL "https://wiki.freedesktop.org/dri/"
+    DESCRIPTION "Userspace interface to kernel DRM services"
+)
diff --git a/po/ar/kpipewire5.po b/po/ar/kpipewire5.po
new file mode 100644 (file)
index 0000000..3f03165
--- /dev/null
@@ -0,0 +1,34 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Zayed Al-Saidi <zayed.alsaidi@gmail.com>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-09-13 19:09+0400\n"
+"Last-Translator: Zayed Al-Saidi <zayed.alsaidi@gmail.com>\n"
+"Language-Team: ar\n"
+"Language: ar\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 "
+"&& n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5;\n"
+"X-Generator: Lokalize 21.12.3\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "فشل في إنشاء سياق PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "فشل الاتصال بPipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "فشل في بدء الحلقة الرئيسة لـPipeWire"
diff --git a/po/ca/kpipewire5.po b/po/ca/kpipewire5.po
new file mode 100644 (file)
index 0000000..16fd30b
--- /dev/null
@@ -0,0 +1,35 @@
+# Translation of kpipewire5.po to Catalan
+# Copyright (C) 2022 This_file_is_part_of_KDE
+# This file is distributed under the license LGPL version 2.1 or
+# version 3 or later versions approved by the membership of KDE e.V.
+#
+# Josep M. Ferrer <txemaq@gmail.com>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-05-31 13:21+0200\n"
+"Last-Translator: Josep M. Ferrer <txemaq@gmail.com>\n"
+"Language-Team: Catalan <kde-i18n-ca@kde.org>\n"
+"Language: ca\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 20.12.0\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Ha fallat en crear el context del PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Ha fallat en connectar amb el PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Ha fallat en iniciar el bucle principal del PipeWire"
diff --git a/po/ca@valencia/kpipewire5.po b/po/ca@valencia/kpipewire5.po
new file mode 100644 (file)
index 0000000..1a54b25
--- /dev/null
@@ -0,0 +1,35 @@
+# Translation of kpipewire5.po to Catalan (Valencian)
+# Copyright (C) 2022 This_file_is_part_of_KDE
+# This file is distributed under the license LGPL version 2.1 or
+# version 3 or later versions approved by the membership of KDE e.V.
+#
+# Josep M. Ferrer <txemaq@gmail.com>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-05-31 13:21+0200\n"
+"Last-Translator: Josep M. Ferrer <txemaq@gmail.com>\n"
+"Language-Team: Catalan <kde-i18n-ca@kde.org>\n"
+"Language: ca@valencia\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 20.12.0\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "No s'ha pogut crear el context de PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "No s'ha pogut connectar amb PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "No s'ha pogut iniciar el bucle principal de PipeWire"
diff --git a/po/cs/kpipewire5.po b/po/cs/kpipewire5.po
new file mode 100644 (file)
index 0000000..55cdf40
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# Vit Pelcak <vit@pelcak.org>, 2022.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-27 16:26+0200\n"
+"Last-Translator: Vit Pelcak <vpelcak@suse.cz>\n"
+"Language-Team: Czech <kde-i18n-doc@kde.org>\n"
+"Language: cs\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n"
+"X-Generator: Lokalize 22.04.2\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Chyba při vytváření kontextu PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Chyba při připojení k PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Chyba při spouštění hlavní smyčky PipeWire"
diff --git a/po/de/kpipewire5.po b/po/de/kpipewire5.po
new file mode 100644 (file)
index 0000000..1accaf0
--- /dev/null
@@ -0,0 +1,35 @@
+# German translations for kpipewire package.
+# Copyright (C) 2022 This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# Frederik Schwarzer <schwarzer@kde.org>, 2022.
+#
+# Automatically generated, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-08 01:35+0200\n"
+"Last-Translator: Frederik Schwarzer <schwarzer@kde.org>\n"
+"Language-Team: German <kde-i18n-de@kde.org>\n"
+"Language: de\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"X-Generator: Lokalize 21.12.2\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr ""
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Fehler beim Verbinden mit PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr ""
diff --git a/po/en_GB/kpipewire5.po b/po/en_GB/kpipewire5.po
new file mode 100644 (file)
index 0000000..cea33d1
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Steve Allewell <steve.allewell@gmail.com>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-07-22 15:33+0100\n"
+"Last-Translator: Steve Allewell <steve.allewell@gmail.com>\n"
+"Language-Team: British English <kde-l10n-en_gb@kde.org>\n"
+"Language: en_GB\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 22.04.3\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Failed to create PipeWire context"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Failed to connect to PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Failed to start main PipeWire loop"
diff --git a/po/es/kpipewire5.po b/po/es/kpipewire5.po
new file mode 100644 (file)
index 0000000..68c5e0b
--- /dev/null
@@ -0,0 +1,35 @@
+# Spanish translations for kpipewire5.po package.
+# Copyright (C) 2022 This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Automatically generated, 2022.
+# Eloy Cuadra <ecuadra@eloihr.net>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire5\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-01 03:45+0200\n"
+"Last-Translator: Eloy Cuadra <ecuadra@eloihr.net>\n"
+"Language-Team: Spanish <kde-l10n-es@kde.org>\n"
+"Language: es\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 22.04.1\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Ha fallado la creación de un contexto de PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Ha fallado la conexión a PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Ha fallado el inicio del bucle principal de PipeWire"
diff --git a/po/eu/kpipewire5.po b/po/eu/kpipewire5.po
new file mode 100644 (file)
index 0000000..10a2cc5
--- /dev/null
@@ -0,0 +1,36 @@
+# Translation for kpipewire5.po to Euskara/Basque (eu).
+# Copyright (C) 2022, This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# KDE euskaratzeko proiektuko arduraduna <xalba@ni.eus>.
+#
+# Translators:
+# Iñigo Salvador Azurmendi <xalba@ni.eus>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-07-28 12:48+0200\n"
+"Last-Translator: Iñigo Salvador Azurmendi <xalba@ni.eus>\n"
+"Language-Team: Basque <kde-i18n-eu@kde.org>\n"
+"Language: eu\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"X-Generator: Lokalize 22.04.3\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "«PipeWire» testuingurua sortzea huts egin du"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "«PipeWire»ra konektatzea huts egin du"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "«PipeWire» begizta nagusia abiatzea huts egin du"
diff --git a/po/fi/kpipewire5.po b/po/fi/kpipewire5.po
new file mode 100644 (file)
index 0000000..f43feb2
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# Tommi Nieminen <translator@legisign.org>, 2022.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-11 18:54+0300\n"
+"Last-Translator: Tommi Nieminen <translator@legisign.org>\n"
+"Language-Team: Finnish <kde-i18n-doc@kde.org>\n"
+"Language: fi\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"X-Generator: Lokalize 21.12.3\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "PipeWire-kontekstin luominen epäonnistui"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "PipeWireen yhdistäminen epäonnistui"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "PipeWire-pääsilmukan käynnistäminen epäonnistui"
diff --git a/po/fr/kpipewire5.po b/po/fr/kpipewire5.po
new file mode 100644 (file)
index 0000000..bb2185e
--- /dev/null
@@ -0,0 +1,30 @@
+# Xavier Besnard <xavier.besnard@neuf.fr>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-05 11:29+0200\n"
+"Last-Translator: Xavier Besnard <xavier.besnard@neuf.fr>\n"
+"Language-Team: French <kde-francophone@kde.org>\n"
+"Language: fr\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n > 1);\n"
+"X-Generator: Lokalize 22.04.1\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Impossible de créer un contexte pour PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Impossible de se connecter à PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Impossible de démarrer une boucle pour PipeWire"
diff --git a/po/gl/kpipewire5.po b/po/gl/kpipewire5.po
new file mode 100644 (file)
index 0000000..8408342
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# Adrián Chaves (Gallaecio) <adrian@chaves.io>, 2023.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2023-04-24 07:46+0200\n"
+"Last-Translator: Adrián Chaves (Gallaecio) <adrian@chaves.io>\n"
+"Language-Team: Galician <proxecto@trasno.gal>\n"
+"Language: gl\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 22.12.3\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Non se puido crear o contexto de PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Non se puido conectar a PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Non se puido iniciar o bucle principal de PipeWire"
diff --git a/po/it/kpipewire5.po b/po/it/kpipewire5.po
new file mode 100644 (file)
index 0000000..a630fef
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# Vincenzo Reale <smart2128vr@gmail.com>, 2022.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-05-31 14:02+0200\n"
+"Last-Translator: Vincenzo Reale <smart2128vr@gmail.com>\n"
+"Language-Team: Italian <kde-i18n-it@kde.org>\n"
+"Language: it\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"X-Generator: Lokalize 22.04.1\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Creazione del contesto PipeWire non riuscita"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Connessione a PipeWire non riuscita"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Avvio del ciclo principale di PipeWire non riuscito"
diff --git a/po/ja/kpipewire5.po b/po/ja/kpipewire5.po
new file mode 100644 (file)
index 0000000..5d1ccdd
--- /dev/null
@@ -0,0 +1,30 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-04 21:24-0700\n"
+"Last-Translator: Japanese KDE translation team <kde-jp@kde.org>\n"
+"Language-Team: Japanese <kde-jp@kde.org>\n"
+"Language: ja\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Accelerator-Marker: &\n"
+"X-Text-Markup: kde4\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr ""
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr ""
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr ""
diff --git a/po/ka/kpipewire5.po b/po/ka/kpipewire5.po
new file mode 100644 (file)
index 0000000..8e61918
--- /dev/null
@@ -0,0 +1,34 @@
+# SOME DESCRIPTIVE TITLE.
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-09-14 07:49+0200\n"
+"Last-Translator: Temuri Doghonadze <temuri.doghonadze@gmail.com>\n"
+"Language-Team: Georgian <kde-i18n-doc@kde.org>\n"
+"Language: ka\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"X-Generator: Poedit 3.1.1\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "PipeWire-ის კონტექსტის შექმნის შეცდოა"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "PipeWire-სთან მიერთების შეცდომა"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "PipeWire-ის მთავარი მარყუჟის დაწყების შეცდომა"
diff --git a/po/ko/kpipewire5.po b/po/ko/kpipewire5.po
new file mode 100644 (file)
index 0000000..9557466
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# Shinjo Park <kde@peremen.name>, 2022.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-07-13 15:41+0200\n"
+"Last-Translator: Shinjo Park <kde@peremen.name>\n"
+"Language-Team: Korean <kde-kr@kde.org>\n"
+"Language: ko\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=1; plural=0;\n"
+"X-Generator: Lokalize 21.12.3\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "PipeWire 콘텍스트를 만들 수 없음"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "PipeWire 콘텍스트에 연결할 수 없음"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "주 PipeWire 루프를 시작할 수 없음"
diff --git a/po/nl/kpipewire5.po b/po/nl/kpipewire5.po
new file mode 100644 (file)
index 0000000..8c7b63e
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Freek de Kruijf <freekdekruijf@kde.nl>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-05-31 16:34+0200\n"
+"Last-Translator: Freek de Kruijf <freekdekruijf@kde.nl>\n"
+"Language-Team: \n"
+"Language: nl\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 22.04.1\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Aanmaken van PipeWire-context is mislukt"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Verbinden met PipeWire is mislukt"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Starten van hoofd PipeWire-loop is mislukt"
diff --git a/po/nn/kpipewire5.po b/po/nn/kpipewire5.po
new file mode 100644 (file)
index 0000000..e54dda9
--- /dev/null
@@ -0,0 +1,35 @@
+# Translation of kpipewire5 to Norwegian Nynorsk
+#
+# Karl Ove Hufthammer <karl@huftis.org>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-19 13:56+0200\n"
+"Last-Translator: Karl Ove Hufthammer <karl@huftis.org>\n"
+"Language-Team: Norwegian Nynorsk <l10n-no@lister.huftis.org>\n"
+"Language: nn\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 22.04.2\n"
+"X-Environment: kde\n"
+"X-Accelerator-Marker: &\n"
+"X-Text-Markup: kde4\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Klarte ikkje oppretta PipeWire-kontekst"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Klarte ikkje kopla til PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Klarte ikkje starta hovudlykkje for PipeWire"
diff --git a/po/pa/kpipewire5.po b/po/pa/kpipewire5.po
new file mode 100644 (file)
index 0000000..2ecff6d
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# A S Alam <aalam@satluj.org>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-11 08:49-0700\n"
+"Last-Translator: A S Alam <aalam@satluj.org>\n"
+"Language-Team: Punjabi <punjabi-users@lists.sf.net>\n"
+"Language: pa\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 21.12.2\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "ਪਾਈਪਵਾਇਰ ਭਾਗ ਬਣਾਉਣ ਲਈ ਅਸਫ਼ਲ"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "ਪਾਈਪਵਾਇਰ ਨਾਲ ਕਨੈਕਟ ਕਰਨ ਲਈ ਅਸਫ਼ਲ"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "ਮੁੱਖ ਪਾਈਪਵਾਇਰ ਲੂਪ ਸ਼ੁਰੂ ਕਰਨ ਲਈ ਅਸਫ਼ਲ"
diff --git a/po/pl/kpipewire5.po b/po/pl/kpipewire5.po
new file mode 100644 (file)
index 0000000..9cfc384
--- /dev/null
@@ -0,0 +1,34 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Łukasz Wojniłowicz <lukasz.wojnilowicz@gmail.com>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-05 11:21+0200\n"
+"Last-Translator: Łukasz Wojniłowicz <lukasz.wojnilowicz@gmail.com>\n"
+"Language-Team: Polish <kde-i18n-doc@kde.org>\n"
+"Language: pl\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 "
+"|| n%100>=20) ? 1 : 2);\n"
+"X-Generator: Lokalize 22.03.70\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Nie udało się utworzyć kontekstu PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Nie udało się połączyć z PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Nie udało się uruchomić głównej pętli PipeWire"
diff --git a/po/pt/kpipewire5.po b/po/pt/kpipewire5.po
new file mode 100644 (file)
index 0000000..4e113e8
--- /dev/null
@@ -0,0 +1,29 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-03 18:06+0100\n"
+"Last-Translator: José Nuno Coelho Pires <zepires@gmail.com>\n"
+"Language-Team: Portuguese <kde-i18n-pt@kde.org>\n"
+"Language: pt\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"X-POFile-SpellExtra: PipeWire\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Não foi possível criar um contexto do PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Não foi possível contactar o PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Não foi possível iniciar o ciclo principal do PipeWire"
diff --git a/po/pt_BR/kpipewire5.po b/po/pt_BR/kpipewire5.po
new file mode 100644 (file)
index 0000000..79c4d8e
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Luiz Fernando Ranghetti <elchevive@opensuse.org>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-07-12 16:19-0300\n"
+"Last-Translator: Luiz Fernando Ranghetti <elchevive@opensuse.org>\n"
+"Language-Team: Portuguese <kde-i18n-pt_BR@kde.org>\n"
+"Language: pt_BR\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n > 1);\n"
+"X-Generator: Lokalize 21.12.3\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Falha ao criar o contexto PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Falha ao conectar ao PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Falha ao iniciar o loop principal do PipeWire"
diff --git a/po/ro/kpipewire5.po b/po/ro/kpipewire5.po
new file mode 100644 (file)
index 0000000..a11eb3e
--- /dev/null
@@ -0,0 +1,34 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# Sergiu Bivol <sergiu@cip.md>, 2022.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-01 15:37+0100\n"
+"Last-Translator: Sergiu Bivol <sergiu@cip.md>\n"
+"Language-Team: Romanian <kde-i18n-ro@kde.org>\n"
+"Language: ro\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < "
+"20)) ? 1 : 2;\n"
+"X-Generator: Lokalize 21.12.3\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Crearea contextului PipeWire a eșuat"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Conectarea la PipeWire a eșuat"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Pornirea buclei principale PipeWire a eșuat"
diff --git a/po/ru/kpipewire5.po b/po/ru/kpipewire5.po
new file mode 100644 (file)
index 0000000..76d5394
--- /dev/null
@@ -0,0 +1,34 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Olesya Gerasimenko <translation-team@basealt.ru>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-10-31 15:53+0300\n"
+"Last-Translator: Olesya Gerasimenko <translation-team@basealt.ru>\n"
+"Language-Team: Basealt Translation Team\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=4; plural=n==1 ? 3 : n%10==1 && n%100!=11 ? 0 : n"
+"%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Lokalize 22.04.3\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Не удалось создать контекст PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Не удалось подключиться к PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Не удалось запустить основной цикл PipeWire"
diff --git a/po/sk/kpipewire5.po b/po/sk/kpipewire5.po
new file mode 100644 (file)
index 0000000..6d2fe63
--- /dev/null
@@ -0,0 +1,31 @@
+# translation of kpipewire5.po to Slovak
+# Roman Paholík <wizzardsk@gmail.com>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire5\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-01 20:03+0200\n"
+"Last-Translator: Roman Paholik <wizzardsk@gmail.com>\n"
+"Language-Team: Slovak <kde-sk@linux.sk>\n"
+"Language: sk\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"X-Generator: Lokalize 22.04.1\n"
+"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Zlyhalo vytvorenie kontextu PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Zlyhalo pripojenie na PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Zlyhalo spustenie hlavnej slučky PipeWire"
diff --git a/po/sl/kpipewire5.po b/po/sl/kpipewire5.po
new file mode 100644 (file)
index 0000000..24413b8
--- /dev/null
@@ -0,0 +1,34 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Matjaž Jeran <matjaz.jeran@amis.net>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-01 07:51+0200\n"
+"Last-Translator: Matjaž Jeran <matjaz.jeran@amis.net>\n"
+"Language-Team: Slovenian <lugos-slo@lugos.si>\n"
+"Language: sl\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=4; plural=(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n"
+"%100==4 ? 3 : 0);\n"
+"X-Generator: Lokalize 21.12.2\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Kreiranje konteksta PipeWire ni uspelo"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Priklop na PipeWire ni uspel"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Zagon glavne zanke PipeWire ni uspel"
diff --git a/po/sv/kpipewire5.po b/po/sv/kpipewire5.po
new file mode 100644 (file)
index 0000000..470c98d
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Stefan Asserhäll <stefan.asserhall@bredband.net>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-05-31 16:57+0200\n"
+"Last-Translator: Stefan Asserhäll <stefan.asserhall@bredband.net>\n"
+"Language-Team: Swedish <kde-i18n-doc@kde.org>\n"
+"Language: sv\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 20.08.1\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Misslyckades skapa PipeWire-sammanhang"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Misslyckades ansluta till PipeWire-sammanhang"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Misslyckades starta PipeWire-huvudsnurra"
diff --git a/po/ta/kpipewire5.po b/po/ta/kpipewire5.po
new file mode 100644 (file)
index 0000000..9462f83
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Kishore G <kishore96@gmail.com>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-07-05 21:45+0530\n"
+"Last-Translator: Kishore G <kishore96@gmail.com>\n"
+"Language-Team: Tamil <kde-i18n-doc@kde.org>\n"
+"Language: ta\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Lokalize 22.04.2\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr ""
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "PipeWire-க்கு இணைப்பை உண்டாக்க முடியவில்லை"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr ""
diff --git a/po/tr/kpipewire5.po b/po/tr/kpipewire5.po
new file mode 100644 (file)
index 0000000..db77fe6
--- /dev/null
@@ -0,0 +1,33 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Emir SARI <emir_sari@icloud.com>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-06-19 09:59+0300\n"
+"Last-Translator: Emir SARI <emir_sari@icloud.com>\n"
+"Language-Team: Turkish <kde-l10n-tr@kde.org>\n"
+"Language: tr\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n > 1);\n"
+"X-Generator: Lokalize 22.04.2\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "PipeWire bağlamı oluşturulamadı"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "PipeWire'a bağlanamadı"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Ana PipeWire döngüsü başlatılamadı"
diff --git a/po/uk/kpipewire5.po b/po/uk/kpipewire5.po
new file mode 100644 (file)
index 0000000..468b855
--- /dev/null
@@ -0,0 +1,34 @@
+# Copyright (C) YEAR This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+#
+# Yuri Chornoivan <yurchor@ukr.net>, 2022.
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-05-31 08:48+0300\n"
+"Last-Translator: Yuri Chornoivan <yurchor@ukr.net>\n"
+"Language-Team: Ukrainian <kde-i18n-uk@kde.org>\n"
+"Language: uk\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=4; plural=n==1 ? 3 : n%10==1 && n%100!=11 ? 0 : n"
+"%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Lokalize 20.12.0\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "Не вдалося створити контекст PipeWire"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "Не вдалося встановити з'єднання із PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "Не вдалося запустити основний цикл PipeWire"
diff --git a/po/zh_CN/kpipewire5.po b/po/zh_CN/kpipewire5.po
new file mode 100644 (file)
index 0000000..ae27c36
--- /dev/null
@@ -0,0 +1,33 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: kdeorg\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2023-04-29 08:36\n"
+"Last-Translator: \n"
+"Language-Team: Chinese Simplified\n"
+"Language: zh_CN\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=1; plural=0;\n"
+"X-Crowdin-Project: kdeorg\n"
+"X-Crowdin-Project-ID: 269464\n"
+"X-Crowdin-Language: zh-CN\n"
+"X-Crowdin-File: /kf5-stable/messages/kpipewire/kpipewire5.pot\n"
+"X-Crowdin-File-ID: 40856\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr "创建 PipeWire 环境失败"
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr "无法连接到 PipeWire"
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr "无法启动 PipeWire 主循环"
diff --git a/po/zh_TW/kpipewire5.po b/po/zh_TW/kpipewire5.po
new file mode 100644 (file)
index 0000000..8c12c09
--- /dev/null
@@ -0,0 +1,34 @@
+# Chinese translations for kpipewire package
+# kpipewire 套件的正體中文翻譯.
+# Copyright (C) 2022 This file is copyright:
+# This file is distributed under the same license as the kpipewire package.
+# Automatically generated, 2022.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: kpipewire\n"
+"Report-Msgid-Bugs-To: https://bugs.kde.org\n"
+"POT-Creation-Date: 2022-05-31 00:52+0000\n"
+"PO-Revision-Date: 2022-05-31 00:52+0000\n"
+"Last-Translator: Automatically generated\n"
+"Language-Team: none\n"
+"Language: zh_TW\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=1; plural=0;\n"
+
+#: pipewirecore.cpp:86
+#, kde-format
+msgid "Failed to create PipeWire context"
+msgstr ""
+
+#: pipewirecore.cpp:96
+#, kde-format
+msgid "Failed to connect to PipeWire"
+msgstr ""
+
+#: pipewirecore.cpp:103
+#, kde-format
+msgid "Failed to start main PipeWire loop"
+msgstr ""
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..d54b8b8
--- /dev/null
@@ -0,0 +1,176 @@
+include(ECMGenerateExportHeader)
+include(ECMQmlModule)
+include(ECMGenerateHeaders)
+include(ECMSetupVersion)
+
+add_definitions(-DTRANSLATION_DOMAIN=\"kpipewire5\")
+
+add_library(KPipeWire)
+
+ecm_qt_declare_logging_category(kpipewire_SRCS
+                            HEADER logging.h
+                            IDENTIFIER PIPEWIRE_LOGGING
+                            CATEGORY_NAME kpipewire_logging
+                            DESCRIPTION "PipeWire components for KDE"
+                            EXPORT KPipeWire)
+ecm_qt_declare_logging_category(kpipewiredmabuf_SRCS
+                            HEADER logging_dmabuf.h
+                            IDENTIFIER PIPEWIREDMABUF_LOGGING
+                            CATEGORY_NAME kpipewire_dmabuf_logging
+                            DESCRIPTION "PipeWire and DMABuf components for KDE"
+                            EXPORT KPipeWireDmaBuf)
+ecm_qt_declare_logging_category(kpipewirerecord_SRCS
+                            HEADER logging_record.h
+                            IDENTIFIER PIPEWIRERECORD_LOGGING
+                            CATEGORY_NAME kpipewire_record_logging
+                            DESCRIPTION "PipeWire and FFmpeg components for KDE"
+                            EXPORT KPipeWireRecord)
+ecm_qt_install_logging_categories(
+    EXPORT KPipeWire
+    FILE kpipewire.categories
+    DESTINATION "${KDE_INSTALL_LOGGINGCATEGORIESDIR}"
+)
+
+ecm_qt_install_logging_categories(
+    EXPORT KPipeWireRecord
+    FILE kpipewirerecord.categories
+    DESTINATION "${KDE_INSTALL_LOGGINGCATEGORIESDIR}"
+)
+
+target_sources(KPipeWire PRIVATE
+    pipewirecore.cpp
+    pipewiresourceitem.cpp
+    pipewiresourcestream.cpp
+    glhelpers.cpp
+    pwhelpers.cpp
+    ${kpipewire_SRCS}
+)
+
+target_link_libraries(KPipeWire PRIVATE Qt::Quick Qt::GuiPrivate KF5::I18n
+    KF5::CoreAddons PkgConfig::PipeWire epoxy::epoxy PkgConfig::GBM)
+
+target_compile_definitions(KPipeWire INTERFACE -DKPW_WITH_SOURCESIZE=1)
+
+if (QT_MAJOR_VERSION EQUAL "5")
+    target_link_libraries(KPipeWire PRIVATE Qt5::Gui_EGL)
+    if (${Qt5Gui_OPENGL_IMPLEMENTATION} STREQUAL "GLESv2")
+        target_link_libraries(KPipeWire PRIVATE Qt5::Gui_GLESv2)
+    else()
+        target_link_libraries(KPipeWire PRIVATE Qt5::Gui_GL)
+    endif()
+else()
+    target_link_libraries(KPipeWire PRIVATE EGL::EGL)
+endif()
+
+target_include_directories(KPipeWire PRIVATE ${CMAKE_CURRENT_BINARY_DIR}
+                                     PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>" ${PipeWire_INCLUDE_DIRS}
+                                     INTERFACE "$<INSTALL_INTERFACE:${KDE_INSTALL_INCLUDEDIR}/KPipeWire>")
+set_target_properties(KPipeWire PROPERTIES
+                             VERSION ${PROJECT_VERSION}
+                             SOVERSION ${PROJECT_VERSION_MAJOR}
+                      )
+
+ecm_generate_export_header(KPipeWire
+    BASE_NAME KPipeWire
+    VERSION ${PROJECT_VERSION}
+)
+
+ecm_generate_headers(KPipeWire_HEADERS
+  HEADER_NAMES
+  PipeWireSourceStream
+  PipeWireSourceItem
+  REQUIRED_HEADERS KPipeWire_HEADERS
+)
+
+install(FILES
+  ${KPipeWire_HEADERS}
+  ${CMAKE_CURRENT_BINARY_DIR}/kpipewire_export.h
+  DESTINATION ${KDE_INSTALL_INCLUDEDIR}/KPipeWire COMPONENT Devel
+)
+
+add_library(KPipeWireDmaBuf dmabufhandler.cpp ${kpipewiredmabuf_SRCS})
+target_link_libraries(KPipeWireDmaBuf PUBLIC KPipeWire
+    PRIVATE Qt::Core Qt::Gui PkgConfig::GBM
+    epoxy::epoxy Libdrm::Libdrm Qt::GuiPrivate
+)
+
+set_target_properties(KPipeWireDmaBuf PROPERTIES
+                             VERSION ${PROJECT_VERSION}
+                             SOVERSION ${PROJECT_VERSION_MAJOR}
+                      )
+
+ecm_generate_export_header(KPipeWireDmaBuf
+    BASE_NAME KPipeWireDmaBuf
+    VERSION ${PROJECT_VERSION}
+)
+
+ecm_generate_headers(KPipeWireDmaBuf_HEADERS
+  HEADER_NAMES
+    DmaBufHandler
+  REQUIRED_HEADERS KPipeWireDmaBuf_HEADERS
+)
+
+install(FILES
+  ${KPipeWireDmaBuf_HEADERS}
+  ${CMAKE_CURRENT_BINARY_DIR}/kpipewiredmabuf_export.h
+  DESTINATION ${KDE_INSTALL_INCLUDEDIR}/KPipeWire COMPONENT Devel
+)
+
+add_library(KPipeWireRecord pipewirerecord.cpp ${kpipewirerecord_SRCS})
+target_link_libraries(KPipeWireRecord PUBLIC KPipeWire
+    PRIVATE Qt::Core Qt::Gui KF5::CoreAddons KPipeWireDmaBuf
+    PkgConfig::AVCodec PkgConfig::AVUtil PkgConfig::AVFormat PkgConfig::GBM PkgConfig::SWScale
+    epoxy::epoxy Libdrm::Libdrm Qt::GuiPrivate
+)
+
+target_compile_definitions(KPipeWireRecord INTERFACE -DKPW_WITH_SUGGESTED=1)
+
+ecm_generate_headers(KPipeWireRecord_HEADERS
+  HEADER_NAMES
+  PipeWireRecord
+  REQUIRED_HEADERS KPipeWireRecord_HEADERS
+)
+set_target_properties(KPipeWireRecord PROPERTIES
+                             VERSION ${PROJECT_VERSION}
+                             SOVERSION ${PROJECT_VERSION_MAJOR}
+                      )
+
+install(FILES
+  ${KPipeWireRecord_HEADERS}
+  DESTINATION ${KDE_INSTALL_INCLUDEDIR}/KPipeWire COMPONENT Devel
+)
+
+install(TARGETS KPipeWire KPipeWireRecord KPipeWireDmaBuf EXPORT KPipeWireTargets ${KDE_INSTALL_TARGETS_DEFAULT_ARGS})
+
+
+ecm_setup_version(PROJECT VARIABLE_PREFIX KPIPEWIRE
+                        VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/kpipewire_version.h"
+                        PACKAGE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/KPipeWireConfigVersion.cmake"
+                        SOVERSION 5)
+
+set(CMAKECONFIG_INSTALL_DIR "${KDE_INSTALL_CMAKEPACKAGEDIR}/KPipeWire")
+install(EXPORT KPipeWireTargets DESTINATION "${CMAKECONFIG_INSTALL_DIR}" FILE KPipeWireTargets.cmake NAMESPACE K::)
+
+configure_package_config_file("${CMAKE_CURRENT_SOURCE_DIR}/KPipeWireConfig.cmake.in"
+                              "${CMAKE_CURRENT_BINARY_DIR}/KPipeWireConfig.cmake"
+                              INSTALL_DESTINATION  ${CMAKECONFIG_INSTALL_DIR}
+                              )
+install(FILES  "${CMAKE_CURRENT_BINARY_DIR}/KPipeWireConfig.cmake"
+               "${CMAKE_CURRENT_BINARY_DIR}/KPipeWireConfigVersion.cmake"
+        DESTINATION "${CMAKECONFIG_INSTALL_DIR}"
+        COMPONENT Devel )
+
+
+#################
+# Declarative
+
+ecm_add_qml_module(KPipeWireDeclarative URI "org.kde.pipewire" VERSION 1.0)
+target_sources(KPipeWireDeclarative PRIVATE kpipewiredeclarativeplugin.cpp)
+target_link_libraries(KPipeWireDeclarative PRIVATE KPipeWire Qt::Quick)
+ecm_finalize_qml_module(KPipeWireDeclarative DESTINATION ${KDE_INSTALL_QMLDIR})
+
+ecm_add_qml_module(KPipeWireRecordDeclarative URI "org.kde.pipewire.record" VERSION 1.0)
+target_sources(KPipeWireRecordDeclarative PRIVATE kpipewirerecorddeclarativeplugin.cpp)
+target_link_libraries(KPipeWireRecordDeclarative PRIVATE KPipeWire KPipeWireRecord Qt::Quick)
+ecm_finalize_qml_module(KPipeWireRecordDeclarative DESTINATION ${KDE_INSTALL_QMLDIR})
+
diff --git a/src/KPipeWireConfig.cmake.in b/src/KPipeWireConfig.cmake.in
new file mode 100644 (file)
index 0000000..2298b93
--- /dev/null
@@ -0,0 +1,9 @@
+@PACKAGE_INIT@
+
+include(CMakeFindDependencyMacro)
+find_dependency(Qt@QT_MAJOR_VERSION@Core @REQUIRED_QT_VERSION@)
+find_dependency(Qt@QT_MAJOR_VERSION@Gui @REQUIRED_QT_VERSION@)
+
+
+include("${CMAKE_CURRENT_LIST_DIR}/KPipeWireTargets.cmake")
+@PACKAGE_INCLUDE_QCHTARGETS@
diff --git a/src/Messages.sh b/src/Messages.sh
new file mode 100755 (executable)
index 0000000..ab58f8f
--- /dev/null
@@ -0,0 +1,6 @@
+#!/bin/sh
+
+# Extract strings from all source files.
+# If your framework depends on KI18n, use $XGETTEXT. If it uses Qt translation
+# system, use $EXTRACT_TR_STRINGS.
+$XGETTEXT `find . -name \*.cpp -o -name \*.h` -o $podir/kpipewire5.pot
diff --git a/src/dmabufhandler.cpp b/src/dmabufhandler.cpp
new file mode 100644 (file)
index 0000000..55a96b8
--- /dev/null
@@ -0,0 +1,222 @@
+// SPDX-FileCopyrightText: 2022 Aleix Pol i Gonzalez <aleixpol@kde.org>
+// SPDX-License-Identifier: Apache-2.0
+
+#include "dmabufhandler.h"
+#include "glhelpers.h"
+#include <QGuiApplication>
+#include <fcntl.h>
+#include <gbm.h>
+#include <logging_dmabuf.h>
+#include <qpa/qplatformnativeinterface.h>
+#include <unistd.h>
+#include <xf86drm.h>
+
+static QByteArray fetchRenderNode()
+{
+    int max_devices = drmGetDevices2(0, nullptr, 0);
+    if (max_devices <= 0) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "drmGetDevices2() has not found any devices (errno=" << -max_devices << ")";
+        return "/dev/dri/renderD128";
+    }
+
+    std::vector<drmDevicePtr> devices(max_devices);
+    int ret = drmGetDevices2(0, devices.data(), max_devices);
+    if (ret < 0) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "drmGetDevices2() returned an error " << ret;
+        return "/dev/dri/renderD128";
+    }
+
+    QByteArray render_node;
+
+    for (const drmDevicePtr &device : devices) {
+        if (device->available_nodes & (1 << DRM_NODE_RENDER)) {
+            render_node = device->nodes[DRM_NODE_RENDER];
+            break;
+        }
+    }
+
+    drmFreeDevices(devices.data(), ret);
+    return render_node;
+}
+
+DmaBufHandler::DmaBufHandler()
+{
+}
+
+DmaBufHandler::~DmaBufHandler()
+{
+    if (m_drmFd) {
+        close(m_drmFd);
+    }
+}
+
+void DmaBufHandler::setupEgl()
+{
+    if (m_eglInitialized) {
+        return;
+    }
+
+    m_egl.display = static_cast<EGLDisplay>(QGuiApplication::platformNativeInterface()->nativeResourceForIntegration("egldisplay"));
+
+    // Use eglGetPlatformDisplayEXT() to get the display pointer
+    // if the implementation supports it.
+    if (!epoxy_has_egl_extension(m_egl.display, "EGL_EXT_platform_base") || !epoxy_has_egl_extension(m_egl.display, "EGL_MESA_platform_gbm")) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "One of required EGL extensions is missing";
+        return;
+    }
+
+    if (m_egl.display == EGL_NO_DISPLAY) {
+        m_egl.display = eglGetPlatformDisplay(EGL_PLATFORM_WAYLAND_KHR, (void *)EGL_DEFAULT_DISPLAY, nullptr);
+    }
+    if (m_egl.display == EGL_NO_DISPLAY) {
+        const QByteArray renderNode = fetchRenderNode();
+        m_drmFd = open(renderNode.constData(), O_RDWR);
+
+        if (m_drmFd < 0) {
+            qCWarning(PIPEWIREDMABUF_LOGGING) << "Failed to open drm render node" << renderNode << "with error: " << strerror(errno);
+            return;
+        }
+
+        m_gbmDevice = gbm_create_device(m_drmFd);
+
+        if (!m_gbmDevice) {
+            qCWarning(PIPEWIREDMABUF_LOGGING) << "Cannot create GBM device: " << strerror(errno);
+            return;
+        }
+        m_egl.display = eglGetPlatformDisplayEXT(EGL_PLATFORM_GBM_MESA, m_gbmDevice, nullptr);
+    }
+
+    if (m_egl.display == EGL_NO_DISPLAY) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "Error during obtaining EGL display: " << GLHelpers::formatGLError(eglGetError());
+        return;
+    }
+
+    EGLint major, minor;
+    if (eglInitialize(m_egl.display, &major, &minor) == EGL_FALSE) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "Error during eglInitialize: " << GLHelpers::formatGLError(eglGetError());
+        return;
+    }
+
+    if (eglBindAPI(EGL_OPENGL_API) == EGL_FALSE) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "bind OpenGL API failed";
+        return;
+    }
+
+    EGLConfig configs;
+    auto createConfig = [&] {
+        static const EGLint configAttribs[] = {
+            EGL_SURFACE_TYPE,
+            EGL_WINDOW_BIT,
+            EGL_RED_SIZE,
+            8,
+            EGL_GREEN_SIZE,
+            8,
+            EGL_BLUE_SIZE,
+            8,
+            EGL_RENDERABLE_TYPE,
+            EGL_OPENGL_BIT,
+            EGL_CONFIG_CAVEAT,
+            EGL_NONE,
+            EGL_NONE,
+        };
+
+        EGLint count = 333;
+        if (eglChooseConfig(m_egl.display, configAttribs, &configs, 1, &count) == EGL_FALSE) {
+            qCWarning(PIPEWIREDMABUF_LOGGING) << "choose config failed";
+            return false;
+        }
+        // if (count != 1) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "eglChooseConfig returned this many configs:" << count;
+        //     return false;
+        // }
+        return true;
+    };
+
+    bool b = createConfig();
+    static const EGLint configAttribs[] = {EGL_CONTEXT_OPENGL_DEBUG, EGL_TRUE, EGL_NONE};
+    Q_ASSERT(configs);
+    m_egl.context = eglCreateContext(m_egl.display, b ? configs : EGL_NO_CONFIG_KHR, EGL_NO_CONTEXT, configAttribs);
+
+    Q_ASSERT(b);
+    Q_ASSERT(m_egl.context);
+    if (m_egl.context == EGL_NO_CONTEXT) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "Couldn't create EGL context: " << GLHelpers::formatEGLError(eglGetError());
+        return;
+    }
+
+    qCDebug(PIPEWIREDMABUF_LOGGING) << "Egl initialization succeeded";
+    qCDebug(PIPEWIREDMABUF_LOGGING) << QStringLiteral("EGL version: %1.%2").arg(major).arg(minor);
+
+    m_eglInitialized = true;
+}
+
+GLenum closestGLType(const QImage &image)
+{
+    switch (image.format()) {
+    case QImage::Format_RGB888:
+        return GL_RGB;
+    case QImage::Format_BGR888:
+        return GL_BGR;
+    case QImage::Format_RGB32:
+    case QImage::Format_RGBX8888:
+    case QImage::Format_RGBA8888:
+    case QImage::Format_RGBA8888_Premultiplied:
+        return GL_RGBA;
+    default:
+        qDebug() << "unknown format" << image.format();
+        return GL_RGBA;
+    }
+}
+
+bool DmaBufHandler::downloadFrame(QImage &qimage, const PipeWireFrame &frame)
+{
+    Q_ASSERT(frame.dmabuf);
+    const QSize streamSize = {frame.dmabuf->width, frame.dmabuf->height};
+    Q_ASSERT(qimage.size() == streamSize);
+    setupEgl();
+    if (!m_eglInitialized) {
+        return false;
+    }
+
+    if (!eglMakeCurrent(m_egl.display, EGL_NO_SURFACE, EGL_NO_SURFACE, m_egl.context)) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "Failed to make context current" << GLHelpers::formatEGLError(eglGetError());
+        return false;
+    }
+    EGLImageKHR image =
+        GLHelpers::createImage(m_egl.display, *frame.dmabuf, PipeWireSourceStream::spaVideoFormatToDrmFormat(frame.format), qimage.size(), m_gbmDevice);
+
+    if (image == EGL_NO_IMAGE_KHR) {
+        qCWarning(PIPEWIREDMABUF_LOGGING) << "Failed to record frame: Error creating EGLImageKHR - " << GLHelpers::formatEGLError(eglGetError());
+        return false;
+    }
+
+    GLHelpers::initDebugOutput();
+    // create GL 2D texture for framebuffer
+    GLuint texture;
+    GLuint fbo;
+    glGenTextures(1, &texture);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+    glBindTexture(GL_TEXTURE_2D, texture);
+
+    glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
+    glGenFramebuffers(1, &fbo);
+    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
+    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
+                           texture, 0);
+    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
+        glDeleteFramebuffers(1, &fbo);
+        glDeleteTextures(1, &texture);
+        eglDestroyImageKHR(m_egl.display, image);
+        return false;
+    }
+
+    glReadPixels(0, 0, frame.dmabuf->width, frame.dmabuf->height, closestGLType(qimage), GL_UNSIGNED_BYTE, qimage.bits());
+
+    glDeleteFramebuffers(1, &fbo);
+    glDeleteTextures(1, &texture);
+    eglDestroyImageKHR(m_egl.display, image);
+    return true;
+}
diff --git a/src/dmabufhandler.h b/src/dmabufhandler.h
new file mode 100644 (file)
index 0000000..50186b2
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol i Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#ifndef DMABUFHANDLER_H
+#define DMABUFHANDLER_H
+
+#include "kpipewiredmabuf_export.h"
+#include "pipewiresourcestream.h"
+#include <QImage>
+#include <epoxy/egl.h>
+
+class KPIPEWIREDMABUF_EXPORT DmaBufHandler
+{
+public:
+    DmaBufHandler();
+    ~DmaBufHandler();
+
+    bool downloadFrame(QImage &image, const PipeWireFrame &frame);
+
+private:
+    void setupEgl();
+    bool m_eglInitialized = false;
+    qint32 m_drmFd = 0; // for GBM buffer mmap
+    gbm_device *m_gbmDevice = nullptr; // for passed GBM buffer retrieval
+
+    struct EGLStruct {
+        EGLDisplay display = EGL_NO_DISPLAY;
+        EGLContext context = EGL_NO_CONTEXT;
+    };
+    EGLStruct m_egl;
+};
+
+#endif // DMABUFHANDLER_H
diff --git a/src/glhelpers.cpp b/src/glhelpers.cpp
new file mode 100644 (file)
index 0000000..63385a1
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "glhelpers.h"
+#include <QList>
+#include <QVersionNumber>
+#include <epoxy/gl.h>
+#include <libdrm/drm_fourcc.h>
+#include <logging.h>
+#include <mutex>
+
+#include <gbm.h>
+
+namespace GLHelpers
+{
+
+void initDebugOutputOnce()
+{
+    auto callback = [](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const GLvoid *userParam) {
+        Q_UNUSED(source)
+        Q_UNUSED(severity)
+        Q_UNUSED(userParam)
+        while (length && std::isspace(message[length - 1])) {
+            --length;
+        }
+
+        switch (type) {
+        case GL_DEBUG_TYPE_ERROR:
+        case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
+            qCWarning(PIPEWIRE_LOGGING, "%#x: %.*s", id, length, message);
+            break;
+
+        case GL_DEBUG_TYPE_OTHER:
+        case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
+        case GL_DEBUG_TYPE_PORTABILITY:
+        case GL_DEBUG_TYPE_PERFORMANCE:
+        default:
+            qCDebug(PIPEWIRE_LOGGING, "%#x: %.*s", id, length, message);
+            break;
+        }
+    };
+    glDebugMessageCallback(callback, nullptr);
+    glEnable(GL_DEBUG_OUTPUT);
+}
+
+static std::once_flag initDebugOnce;
+void initDebugOutput()
+{
+    if (!PIPEWIRE_LOGGING().isDebugEnabled()) {
+        return;
+    }
+
+    if (!eglGetCurrentDisplay()) {
+        // Epoxy gets very confused and it will crash
+        return;
+    }
+
+    std::call_once(initDebugOnce, initDebugOutputOnce);
+}
+
+#define ENUM_STRING(x) case x: return #x;
+
+QByteArray formatGLError(GLenum err)
+{
+    switch (err) {
+    ENUM_STRING(GL_NO_ERROR)
+    ENUM_STRING(GL_INVALID_ENUM)
+    ENUM_STRING(GL_INVALID_VALUE)
+    ENUM_STRING(GL_INVALID_OPERATION)
+    ENUM_STRING(GL_STACK_OVERFLOW)
+    ENUM_STRING(GL_STACK_UNDERFLOW)
+    ENUM_STRING(GL_OUT_OF_MEMORY)
+    default:
+        return QByteArray("0x") + QByteArray::number(err, 16);
+    }
+}
+
+QByteArray formatEGLError(GLenum err)
+{
+    switch (err) {
+        ENUM_STRING(EGL_SUCCESS)
+        ENUM_STRING(EGL_BAD_DISPLAY)
+        ENUM_STRING(EGL_BAD_CONTEXT)
+        ENUM_STRING(EGL_BAD_PARAMETER)
+        ENUM_STRING(EGL_BAD_MATCH)
+        ENUM_STRING(EGL_BAD_ACCESS)
+        ENUM_STRING(EGL_BAD_ALLOC)
+        ENUM_STRING(EGL_BAD_CONFIG)
+    default:
+        return QByteArray("0x") + QByteArray::number(err, 16);
+    }
+}
+
+EGLImage createImage(EGLDisplay display, const DmaBufAttributes &dmabufAttribs, uint32_t format, const QSize &size, gbm_device *gbmDevice)
+{
+    Q_ASSERT(!size.isEmpty());
+    gbm_bo *imported = nullptr;
+    if (gbmDevice) {
+        gbm_import_fd_data importInfo = {static_cast<int>(dmabufAttribs.planes[0].fd),
+                                         static_cast<uint32_t>(size.width()),
+                                         static_cast<uint32_t>(size.height()),
+                                         static_cast<uint32_t>(dmabufAttribs.planes[0].stride),
+                                         GBM_BO_FORMAT_ARGB8888};
+        imported = gbm_bo_import(gbmDevice, GBM_BO_IMPORT_FD, &importInfo, GBM_BO_USE_SCANOUT);
+        if (!imported) {
+            qCWarning(PIPEWIRE_LOGGING) << "Failed to process buffer: Cannot import passed GBM fd - " << strerror(errno);
+            return EGL_NO_IMAGE_KHR;
+        }
+    }
+
+    const bool hasModifiers = dmabufAttribs.modifier != DRM_FORMAT_MOD_INVALID;
+
+    QVector<EGLint> attribs;
+    attribs << EGL_WIDTH << size.width() << EGL_HEIGHT << size.height() << EGL_LINUX_DRM_FOURCC_EXT << EGLint(format)
+
+            << EGL_DMA_BUF_PLANE0_FD_EXT << dmabufAttribs.planes[0].fd << EGL_DMA_BUF_PLANE0_OFFSET_EXT << EGLint(dmabufAttribs.planes[0].offset)
+            << EGL_DMA_BUF_PLANE0_PITCH_EXT << EGLint(dmabufAttribs.planes[0].stride);
+
+    if (hasModifiers) {
+        attribs << EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT << EGLint(dmabufAttribs.modifier & 0xffffffff) << EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT
+                << EGLint(dmabufAttribs.modifier >> 32);
+    }
+
+    if (dmabufAttribs.planes.count() > 1) {
+        attribs << EGL_DMA_BUF_PLANE1_FD_EXT << dmabufAttribs.planes[1].fd << EGL_DMA_BUF_PLANE1_OFFSET_EXT << EGLint(dmabufAttribs.planes[1].offset)
+                << EGL_DMA_BUF_PLANE1_PITCH_EXT << EGLint(dmabufAttribs.planes[1].stride);
+
+        if (hasModifiers) {
+            attribs << EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT << EGLint(dmabufAttribs.modifier & 0xffffffff) << EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT
+                    << EGLint(dmabufAttribs.modifier >> 32);
+        }
+    }
+
+    if (dmabufAttribs.planes.count() > 2) {
+        attribs << EGL_DMA_BUF_PLANE2_FD_EXT << dmabufAttribs.planes[2].fd << EGL_DMA_BUF_PLANE2_OFFSET_EXT << EGLint(dmabufAttribs.planes[2].offset)
+                << EGL_DMA_BUF_PLANE2_PITCH_EXT << EGLint(dmabufAttribs.planes[2].stride);
+
+        if (hasModifiers) {
+            attribs << EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT << EGLint(dmabufAttribs.modifier & 0xffffffff) << EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT
+                    << EGLint(dmabufAttribs.modifier >> 32);
+        }
+    }
+
+    if (dmabufAttribs.planes.count() > 3) {
+        attribs << EGL_DMA_BUF_PLANE3_FD_EXT << dmabufAttribs.planes[3].fd << EGL_DMA_BUF_PLANE3_OFFSET_EXT << EGLint(dmabufAttribs.planes[3].offset)
+                << EGL_DMA_BUF_PLANE3_PITCH_EXT << EGLint(dmabufAttribs.planes[3].stride);
+
+        if (hasModifiers) {
+            attribs << EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT << EGLint(dmabufAttribs.modifier & 0xffffffff) << EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT
+                    << EGLint(dmabufAttribs.modifier >> 32);
+        }
+    }
+
+    attribs << EGL_NONE;
+
+    static auto eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC)eglGetProcAddress("eglCreateImageKHR");
+
+    /* MESA says:
+     * "If <target> is EGL_LINUX_DMA_BUF_EXT, <dpy> must be a valid display,
+     *  <ctx> must be EGL_NO_CONTEXT..."
+     */
+    EGLImage ret = eglCreateImageKHR(display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, imported, attribs.data());
+    if (ret == EGL_NO_IMAGE_KHR) {
+        qCWarning(PIPEWIRE_LOGGING) << "invalid image" << GLHelpers::formatEGLError(eglGetError());
+    }
+    if (imported) {
+        gbm_bo_destroy(imported);
+    }
+    return ret;
+}
+}
diff --git a/src/glhelpers.h b/src/glhelpers.h
new file mode 100644 (file)
index 0000000..5cc07fa
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include "pipewiresourcestream.h"
+#include <QByteArray>
+#include <epoxy/egl.h>
+#include <kpipewire_export.h>
+
+typedef unsigned int GLenum;
+
+namespace GLHelpers
+{
+
+KPIPEWIRE_EXPORT void initDebugOutput();
+KPIPEWIRE_EXPORT QByteArray formatGLError(GLenum err);
+KPIPEWIRE_EXPORT QByteArray formatEGLError(GLenum err);
+
+KPIPEWIRE_EXPORT EGLImage createImage(EGLDisplay display, const DmaBufAttributes &attribs, uint32_t format, const QSize &size, gbm_device *device);
+}
diff --git a/src/kpipewiredeclarativeplugin.cpp b/src/kpipewiredeclarativeplugin.cpp
new file mode 100644 (file)
index 0000000..0def62f
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "kpipewiredeclarativeplugin.h"
+
+#include "pipewiresourceitem.h"
+#include "pipewirerecord.h"
+
+void KPipewireDeclarativePlugin::registerTypes(const char *uri)
+{
+    qmlRegisterType<PipeWireSourceItem>(uri, 0, 1, "PipeWireSourceItem");
+}
diff --git a/src/kpipewiredeclarativeplugin.h b/src/kpipewiredeclarativeplugin.h
new file mode 100644 (file)
index 0000000..7771dcd
--- /dev/null
@@ -0,0 +1,17 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QQmlExtensionPlugin>
+
+class KPipewireDeclarativePlugin : public QQmlExtensionPlugin
+{
+    Q_OBJECT
+    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")
+public:
+    void registerTypes(const char *uri) override;
+};
diff --git a/src/kpipewirerecorddeclarativeplugin.cpp b/src/kpipewirerecorddeclarativeplugin.cpp
new file mode 100644 (file)
index 0000000..a84c5e1
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "kpipewirerecorddeclarativeplugin.h"
+
+#include "pipewirerecord.h"
+#include <qqml.h>
+
+void KPipewireRecordDeclarativePlugin::registerTypes(const char *uri)
+{
+    qmlRegisterType<PipeWireRecord>(uri, 0, 1, "PipeWireRecord");
+}
diff --git a/src/kpipewirerecorddeclarativeplugin.h b/src/kpipewirerecorddeclarativeplugin.h
new file mode 100644 (file)
index 0000000..882ff2c
--- /dev/null
@@ -0,0 +1,17 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QQmlExtensionPlugin>
+
+class KPipewireRecordDeclarativePlugin : public QQmlExtensionPlugin
+{
+    Q_OBJECT
+    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")
+public:
+    void registerTypes(const char *uri) override;
+};
diff --git a/src/pipewirecore.cpp b/src/pipewirecore.cpp
new file mode 100644 (file)
index 0000000..ed175c8
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+    SPDX-FileCopyrightText: 2020 Aleix Pol Gonzalez <aleixpol@kde.org>
+    SPDX-FileContributor: Jan Grulich <jgrulich@redhat.com>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "pipewirecore.h"
+#include "logging.h"
+#include <KLocalizedString>
+#include <QSocketNotifier>
+#include <QThread>
+#include <QThreadStorage>
+#include <spa/utils/result.h>
+#include <mutex>
+
+pw_core_events PipeWireCore::s_pwCoreEvents = {
+    .version = PW_VERSION_CORE_EVENTS,
+    .info = &PipeWireCore::onCoreInfo,
+    .done = nullptr,
+    .ping = nullptr,
+    .error = &PipeWireCore::onCoreError,
+    .remove_id = nullptr,
+    .bound_id = nullptr,
+    .add_mem = nullptr,
+    .remove_mem = nullptr,
+};
+
+PipeWireCore::PipeWireCore()
+{
+    static std::once_flag pwInitOnce;
+    std::call_once(pwInitOnce, [] { pw_init(nullptr, nullptr); });
+}
+
+void PipeWireCore::onCoreError(void *data, uint32_t id, int seq, int res, const char *message)
+{
+    Q_UNUSED(seq)
+
+    qCWarning(PIPEWIRE_LOGGING) << "PipeWire remote error: " << res << message;
+    if (id == PW_ID_CORE) {
+        PipeWireCore *pw = static_cast<PipeWireCore *>(data);
+        Q_EMIT pw->pipewireFailed(QString::fromUtf8(message));
+    }
+}
+
+void PipeWireCore::onCoreInfo(void *data, const struct pw_core_info *info)
+{
+    PipeWireCore *pw = static_cast<PipeWireCore *>(data);
+    pw->m_serverVersion = QVersionNumber::fromString(QString::fromUtf8(info->version));
+}
+
+PipeWireCore::~PipeWireCore()
+{
+    if (m_pwMainLoop) {
+        pw_loop_leave(m_pwMainLoop);
+    }
+
+    if (m_pwCore) {
+        pw_core_disconnect(m_pwCore);
+    }
+
+    if (m_pwContext) {
+        pw_context_destroy(m_pwContext);
+    }
+
+    if (m_pwMainLoop) {
+        pw_loop_destroy(m_pwMainLoop);
+    }
+}
+
+bool PipeWireCore::init(int fd)
+{
+    m_pwMainLoop = pw_loop_new(nullptr);
+    pw_loop_enter(m_pwMainLoop);
+
+    QSocketNotifier *notifier = new QSocketNotifier(pw_loop_get_fd(m_pwMainLoop), QSocketNotifier::Read, this);
+    connect(notifier, &QSocketNotifier::activated, this, [this] {
+        int result = pw_loop_iterate(m_pwMainLoop, 0);
+        if (result < 0)
+            qCWarning(PIPEWIRE_LOGGING) << "pipewire_loop_iterate failed: " << spa_strerror(result);
+    });
+
+    m_pwContext = pw_context_new(m_pwMainLoop, nullptr, 0);
+    if (!m_pwContext) {
+        qCWarning(PIPEWIRE_LOGGING) << "Failed to create PipeWire context";
+        m_error = i18n("Failed to create PipeWire context");
+        return false;
+    }
+
+    if (fd > 0) {
+        m_pwCore = pw_context_connect_fd(m_pwContext, fd, nullptr, 0);
+    } else {
+        m_pwCore = pw_context_connect(m_pwContext, nullptr, 0);
+    }
+    if (!m_pwCore) {
+        m_error = i18n("Failed to connect to PipeWire");
+        qCWarning(PIPEWIRE_LOGGING) << "error:" << m_error << fd;
+        return false;
+    }
+
+    if (pw_loop_iterate(m_pwMainLoop, 0) < 0) {
+        qCWarning(PIPEWIRE_LOGGING) << "Failed to start main PipeWire loop";
+        m_error = i18n("Failed to start main PipeWire loop");
+        return false;
+    }
+
+    pw_core_add_listener(m_pwCore, &m_coreListener, &s_pwCoreEvents, this);
+    return true;
+}
+
+QSharedPointer<PipeWireCore> PipeWireCore::fetch(int fd)
+{
+    static QThreadStorage<QHash<int, QWeakPointer<PipeWireCore>>> global;
+    QSharedPointer<PipeWireCore> ret = global.localData().value(fd).toStrongRef();
+    if (!ret) {
+        ret.reset(new PipeWireCore);
+        if (ret->init(fd)) {
+            global.localData().insert(fd, ret);
+        }
+    }
+    return ret;
+}
+
+QString PipeWireCore::error() const
+{
+    return m_error;
+}
diff --git a/src/pipewirecore.h b/src/pipewirecore.h
new file mode 100644 (file)
index 0000000..db94ecf
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+    SPDX-FileCopyrightText: 2020 Aleix Pol Gonzalez <aleixpol@kde.org>
+    SPDX-FileContributor: Jan Grulich <jgrulich@redhat.com>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QObject>
+#include <QVersionNumber>
+#include <pipewire/pipewire.h>
+
+class PipeWireCore : public QObject
+{
+    Q_OBJECT
+public:
+    PipeWireCore();
+
+    static void onCoreError(void *data, uint32_t id, int seq, int res, const char *message);
+    static void onCoreInfo(void *data, const struct pw_core_info *info);
+
+    ~PipeWireCore();
+
+    bool init(int fd);
+    QString error() const;
+    QVersionNumber serverVersion() const
+    {
+        return m_serverVersion;
+    }
+
+    pw_loop *loop() const
+    {
+        return m_pwMainLoop;
+    }
+
+    pw_core *operator*() const { return m_pwCore; };
+    static QSharedPointer<PipeWireCore> fetch(int fd);
+
+private:
+    pw_core *m_pwCore = nullptr;
+    pw_context *m_pwContext = nullptr;
+    pw_loop *m_pwMainLoop = nullptr;
+    spa_hook m_coreListener;
+    QString m_error;
+    QVersionNumber m_serverVersion;
+
+    static pw_core_events s_pwCoreEvents;
+
+Q_SIGNALS:
+    void pipewireFailed(const QString &message);
+};
diff --git a/src/pipewirerecord.cpp b/src/pipewirerecord.cpp
new file mode 100644 (file)
index 0000000..ac8132e
--- /dev/null
@@ -0,0 +1,614 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "pipewirerecord.h"
+#include "glhelpers.h"
+#include "pipewirerecord_p.h"
+#include "pipewiresourcestream.h"
+#include <epoxy/egl.h>
+#include <epoxy/gl.h>
+#include <logging_record.h>
+
+#include <QDateTime>
+#include <QGuiApplication>
+#include <QImage>
+#include <QMutex>
+#include <QPainter>
+#include <QThreadPool>
+#include <QTimer>
+#include <qpa/qplatformnativeinterface.h>
+
+#include <KShell>
+
+#include <unistd.h>
+
+extern "C" {
+#include <libavcodec/avcodec.h>
+#include <libavformat/avformat.h>
+#include <libavutil/imgutils.h>
+#include <libavutil/opt.h>
+#include <libavutil/timestamp.h>
+#include <libswscale/swscale.h>
+}
+
+#ifdef av_err2str
+#undef av_err2str
+#include <string>
+char str[AV_ERROR_MAX_STRING_SIZE];
+av_always_inline char *av_err2str(int errnum)
+{
+    return av_make_error_string(str, AV_ERROR_MAX_STRING_SIZE, errnum);
+}
+#endif // av_err2str
+
+#ifdef av_ts2str
+#undef av_ts2str
+char buf[AV_TS_MAX_STRING_SIZE];
+#define av_ts2str(ts) av_ts_make_string(buf, ts)
+#endif // av_ts2str
+
+#ifdef av_ts2timestr
+#undef av_ts2timestr
+char timebuf[AV_TS_MAX_STRING_SIZE];
+#define av_ts2timestr(ts, tb) av_ts_make_time_string(timebuf, ts, tb)
+#endif // av_ts2timestr
+
+class CustomAVFrame
+{
+public:
+    CustomAVFrame()
+        : m_avFrame(av_frame_alloc())
+    {
+    }
+
+    ~CustomAVFrame()
+    {
+        av_freep(m_avFrame->data);
+        av_frame_free(&m_avFrame);
+    }
+
+    int alloc(int width, int height, AVPixelFormat pix_fmt)
+    {
+        m_avFrame->format = pix_fmt;
+        m_avFrame->width = width;
+        m_avFrame->height = height;
+        return av_image_alloc(m_avFrame->data, m_avFrame->linesize, width, height, pix_fmt, 32);
+    }
+
+    AVFrame *m_avFrame;
+};
+
+static AVPixelFormat convertQImageFormatToAVPixelFormat(QImage::Format format)
+{
+    // Listing those handed by SpaToQImageFormat
+    switch (format) {
+    case QImage::Format_BGR888:
+        return AV_PIX_FMT_BGR24;
+    case QImage::Format_RGBX8888:
+    case QImage::Format_RGBA8888_Premultiplied:
+        return AV_PIX_FMT_RGBA;
+    case QImage::Format_RGB32:
+        return AV_PIX_FMT_RGB32;
+    default:
+        qDebug() << "Unexpected pixel format" << format;
+        return AV_PIX_FMT_RGB32;
+    }
+}
+
+Q_DECLARE_METATYPE(std::optional<int>);
+Q_DECLARE_METATYPE(std::optional<std::chrono::nanoseconds>);
+
+PipeWireRecord::PipeWireRecord(QObject *parent)
+    : QObject(parent)
+    , d(new PipeWireRecordPrivate)
+{
+    d->m_encoder = "libvpx";
+    av_log_set_level(AV_LOG_DEBUG);
+    qRegisterMetaType<std::optional<int>>();
+    qRegisterMetaType<std::optional<std::chrono::nanoseconds>>();
+}
+
+PipeWireRecord::~PipeWireRecord()
+{
+    setActive(false);
+    if (d->m_fd) {
+        close(*d->m_fd);
+    }
+
+    if (d->m_recordThread) {
+        d->m_recordThread->wait();
+    }
+}
+
+PipeWireRecord::State PipeWireRecord::state() const
+{
+    if (d->m_active)
+        return Recording;
+    else if (d->m_recordThread || !d->m_produceThreadFinished)
+        return Rendering;
+
+    return Idle;
+}
+
+void PipeWireRecord::setNodeId(uint nodeId)
+{
+    if (nodeId == d->m_nodeId)
+        return;
+
+    d->m_nodeId = nodeId;
+    refresh();
+    Q_EMIT nodeIdChanged(nodeId);
+}
+
+void PipeWireRecord::setFd(uint fd)
+{
+    if (fd == d->m_fd)
+        return;
+
+    if (d->m_fd) {
+        close(*d->m_fd);
+    }
+    d->m_fd = fd;
+    refresh();
+    Q_EMIT fdChanged(fd);
+}
+
+void PipeWireRecord::setActive(bool active)
+{
+    if (d->m_active == active)
+        return;
+
+    d->m_active = active;
+    refresh();
+    Q_EMIT activeChanged(active);
+}
+
+void PipeWireRecord::setOutput(const QString &_output)
+{
+    const QString output = KShell::tildeExpand(_output);
+
+    if (d->m_output == output)
+        return;
+
+    d->m_output = output;
+    refresh();
+    Q_EMIT outputChanged(output);
+}
+
+PipeWireRecordProduce::PipeWireRecordProduce(const QByteArray &encoder, uint nodeId, uint fd, const QString &output)
+    : QObject()
+    , m_output(output)
+    , m_nodeId(nodeId)
+    , m_encoder(encoder)
+{
+    m_stream.reset(new PipeWireSourceStream(nullptr));
+    bool created = m_stream->createStream(m_nodeId, fd);
+    if (!created || !m_stream->error().isEmpty()) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "failed to set up stream for" << m_nodeId << m_stream->error();
+        m_error = m_stream->error();
+        m_stream.reset(nullptr);
+        return;
+    }
+    connect(m_stream.get(), &PipeWireSourceStream::streamParametersChanged, this, &PipeWireRecordProduce::setupStream);
+    connect(m_stream.get(), &PipeWireSourceStream::stateChanged, this, &PipeWireRecordProduce::stateChanged);
+}
+
+PipeWireRecordProduce::~PipeWireRecordProduce()
+{
+}
+
+void PipeWireRecordProduceThread::run()
+{
+    PipeWireRecordProduce produce(m_encoder, m_nodeId, m_fd, m_output);
+    if (!produce.m_stream) {
+        Q_EMIT errorFound(produce.error());
+        return;
+    }
+    m_producer = &produce;
+    qCDebug(PIPEWIRERECORD_LOGGING) << "executing";
+    const int ret = exec();
+    qCDebug(PIPEWIRERECORD_LOGGING) << "finishing" << ret;
+    m_producer = nullptr;
+}
+
+void PipeWireRecordProduceThread::deactivate()
+{
+    if (m_producer) {
+        m_producer->m_deactivated = true;
+        m_producer->m_stream->setActive(false);
+    }
+}
+
+void PipeWireRecordProduce::stateChanged(pw_stream_state state)
+{
+    if (state != PW_STREAM_STATE_PAUSED || !m_deactivated) {
+        return;
+    }
+    if (!m_stream) {
+        qCDebug(PIPEWIRERECORD_LOGGING) << "finished without a stream";
+        return;
+    }
+
+    disconnect(m_stream.data(), &PipeWireSourceStream::frameReceived, this, &PipeWireRecordProduce::processFrame);
+    if (m_writeThread) {
+        m_writeThread->quit();
+        bool done = m_writeThread->wait();
+        Q_ASSERT(done);
+    }
+
+    qCDebug(PIPEWIRERECORD_LOGGING) << "finished";
+    if (m_avCodecContext) {
+        avio_closep(&m_avFormatContext->pb);
+        avcodec_close(m_avCodecContext);
+        av_free(m_avCodecContext);
+        avformat_free_context(m_avFormatContext);
+    }
+    QThread::currentThread()->quit();
+}
+
+QString PipeWireRecord::extension()
+{
+    return QStringLiteral("webm");
+}
+
+QString PipeWireRecord::currentExtension() const
+{
+    static QHash<QByteArray, QString> s_extensions = {
+        {"libx264", QStringLiteral("mp4")},
+        {"libvpx", QStringLiteral("webm")},
+    };
+    return s_extensions.value(d->m_encoder, QStringLiteral("mkv"));
+}
+
+void PipeWireRecordProduce::setupStream()
+{
+    qCDebug(PIPEWIRERECORD_LOGGING) << "Setting up stream";
+    disconnect(m_stream.get(), &PipeWireSourceStream::streamParametersChanged, this, &PipeWireRecordProduce::setupStream);
+    avformat_alloc_output_context2(&m_avFormatContext, nullptr, nullptr, m_output.toUtf8().constData());
+    if (!m_avFormatContext) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "Could not deduce output format from file: using WebM." << m_output;
+        avformat_alloc_output_context2(&m_avFormatContext, nullptr, "webm", m_output.toUtf8().constData());
+    }
+    if (!m_avFormatContext) {
+        qCDebug(PIPEWIRERECORD_LOGGING) << "could not set stream up";
+        return;
+    }
+
+    m_codec = avcodec_find_encoder_by_name(m_encoder.constData());
+    if (!m_codec) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "Codec not found";
+        return;
+    }
+
+    m_avCodecContext = avcodec_alloc_context3(m_codec);
+    if (!m_avCodecContext) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "Could not allocate video codec context";
+        return;
+    }
+
+    const QSize size = m_stream->size();
+    const Fraction framerate = m_stream->framerate();
+
+    // Have the bitrate depend on the size of the input stream. What looks acceptable on a small
+    // stream on a big one will look bad.
+    m_avCodecContext->bit_rate = size.width() * size.height() * 2;
+
+    Q_ASSERT(!size.isEmpty());
+    m_avCodecContext->width = size.width();
+    m_avCodecContext->height = size.height();
+    m_avCodecContext->max_b_frames = 1;
+    m_avCodecContext->gop_size = 100;
+    if (m_codec->pix_fmts && m_codec->pix_fmts[0] > 0) {
+        m_avCodecContext->pix_fmt = m_codec->pix_fmts[0];
+    } else {
+        m_avCodecContext->pix_fmt = AV_PIX_FMT_YUV420P;
+    }
+    m_avCodecContext->time_base = AVRational{1, 1000};
+
+    AVDictionary *options = nullptr;
+    av_dict_set_int(&options, "threads", qMin(16, QThread::idealThreadCount()), 0);
+    av_dict_set(&options, "preset", "veryfast", 0);
+    av_dict_set(&options, "tune-content", "screen", 0);
+    av_dict_set(&options, "deadline", "realtime", 0);
+    // In theory a lower number should be faster, but the opposite seems to be true
+    av_dict_set(&options, "quality", "40", 0);
+    av_dict_set(&options, "cpu-used", "6", 0);
+    // Disable motion estimation, not great while dragging windows but speeds up encoding by an order of magnitude
+    av_dict_set(&options, "flags", "+mv4", 0);
+    // Disable in-loop filtering
+    av_dict_set(&options, "-flags", "+loop", 0);
+
+    int ret = avcodec_open2(m_avCodecContext, m_codec, &options);
+    if (ret < 0) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "Could not open codec" << av_err2str(ret);
+        return;
+    }
+
+    ret = avio_open(&m_avFormatContext->pb, QFile::encodeName(m_output).constData(), AVIO_FLAG_WRITE);
+    if (ret < 0) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "Could not open" << m_output << av_err2str(ret);
+        return;
+    }
+
+    auto avStream = avformat_new_stream(m_avFormatContext, nullptr);
+    avStream->start_time = 0;
+    avStream->r_frame_rate.num = framerate.numerator;
+    avStream->r_frame_rate.den = framerate.denominator;
+    avStream->avg_frame_rate.num = framerate.numerator;
+    avStream->avg_frame_rate.den = framerate.denominator;
+
+    ret = avcodec_parameters_from_context(avStream->codecpar, m_avCodecContext);
+    if (ret < 0) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "Error occurred when passing the codec:" << av_err2str(ret);
+        return;
+    }
+
+    ret = avformat_write_header(m_avFormatContext, nullptr);
+    if (ret < 0) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "Error occurred when writing header:" << av_err2str(ret);
+        return;
+    }
+
+    connect(m_stream.data(), &PipeWireSourceStream::frameReceived, this, &PipeWireRecordProduce::processFrame);
+    m_writeThread = new PipeWireRecordWriteThread(this, m_avFormatContext, m_avCodecContext);
+    m_writeThread->start();
+}
+
+void PipeWireRecordProduce::processFrame(const PipeWireFrame &frame)
+{
+    bool cursorChanged = false;
+    if (frame.cursor) {
+        cursorChanged = m_cursor.position != frame.cursor->position;
+        m_cursor.position = frame.cursor->position;
+        m_cursor.hotspot = frame.cursor->hotspot;
+        if (!frame.cursor->texture.isNull()) {
+            m_cursor.dirty = true;
+            m_cursor.texture = frame.cursor->texture;
+        }
+    }
+
+    if (frame.dmabuf) {
+        if (m_frameWithoutMetadataCursor.size() != m_stream->size()) {
+            m_frameWithoutMetadataCursor = QImage(m_stream->size(), QImage::Format_RGBA8888_Premultiplied);
+        }
+
+        if (!m_dmabufHandler.downloadFrame(m_frameWithoutMetadataCursor, frame)) {
+            m_stream->renegotiateModifierFailed(frame.format, frame.dmabuf->modifier);
+            return;
+        }
+        render(frame);
+    } else if (frame.image) {
+        updateTextureImage(*frame.image, frame);
+    } else if (cursorChanged && !m_frameWithoutMetadataCursor.isNull()) {
+        render(frame);
+    }
+}
+
+void PipeWireRecord::refresh()
+{
+    if (!d->m_output.isEmpty() && d->m_active && d->m_nodeId > 0) {
+        d->m_recordThread.reset(new PipeWireRecordProduceThread(d->m_encoder, d->m_nodeId, d->m_fd.value_or(0), d->m_output));
+        connect(d->m_recordThread.get(), &PipeWireRecordProduceThread::errorFound, this, &PipeWireRecord::errorFound);
+        connect(d->m_recordThread.get(), &PipeWireRecordProduceThread::finished, this, [this] {
+            setActive(false);
+        });
+        d->m_recordThread->start();
+    } else if (d->m_recordThread) {
+        d->m_recordThread->deactivate();
+
+        connect(d->m_recordThread.get(), &PipeWireRecordProduceThread::finished, this, [this] {
+            qCDebug(PIPEWIRERECORD_LOGGING) << "produce thread finished" << d->m_output;
+            d->m_recordThread.reset();
+            d->m_produceThreadFinished = true;
+            Q_EMIT stateChanged();
+        });
+        d->m_produceThreadFinished = false;
+    }
+    Q_EMIT stateChanged();
+}
+
+void PipeWireRecordProduce::updateTextureImage(const QImage &image, const PipeWireFrame &frame)
+{
+    m_frameWithoutMetadataCursor = image;
+    render(frame);
+}
+
+void PipeWireRecordProduce::render(const PipeWireFrame &frame)
+{
+    Q_ASSERT(!m_frameWithoutMetadataCursor.isNull());
+
+    QImage image(m_frameWithoutMetadataCursor);
+    if (!image.isNull() && m_cursor.position && !m_cursor.texture.isNull()) {
+        image = m_frameWithoutMetadataCursor.copy();
+        QPainter p(&image);
+        p.drawImage(*m_cursor.position, m_cursor.texture);
+    }
+
+    Q_EMIT producedFrame(image, frame.sequential, frame.presentationTimestamp);
+}
+
+static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
+{
+    AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
+
+    qCDebug(PIPEWIRERECORD_LOGGING,
+            "pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s "
+            "stream_index:%d",
+            av_ts2str(pkt->pts),
+            av_ts2timestr(pkt->pts, time_base),
+            av_ts2str(pkt->dts),
+            av_ts2timestr(pkt->dts, time_base),
+            av_ts2str(pkt->duration),
+            av_ts2timestr(pkt->duration, time_base),
+            pkt->stream_index);
+}
+
+void PipeWireRecord::setEncoder(const QByteArray &encoder)
+{
+    if (d->m_encoder == encoder) {
+        return;
+    }
+    d->m_encoder = encoder;
+    Q_EMIT encoderChanged();
+}
+
+QByteArray PipeWireRecord::encoder() const
+{
+    return d->m_encoder;
+}
+
+QList<QByteArray> PipeWireRecord::suggestedEncoders() const
+{
+    QList<QByteArray> ret = {"libvpx", "libx264"};
+    std::remove_if(ret.begin(), ret.end(), [](const QByteArray &encoder) {
+        return !avcodec_find_encoder_by_name(encoder.constData());
+    });
+    return ret;
+}
+
+QString PipeWireRecord::output() const
+{
+    return d->m_output;
+}
+
+bool PipeWireRecord::isActive() const
+{
+    return d->m_active;
+}
+
+uint PipeWireRecord::nodeId() const
+{
+    return d->m_nodeId;
+}
+
+uint PipeWireRecord::fd() const
+{
+    return d->m_fd.value_or(0);
+}
+
+PipeWireRecordWrite::PipeWireRecordWrite(PipeWireRecordProduce *produce, AVFormatContext *avFormatContext, AVCodecContext *avCodecContext)
+    : QObject()
+    , m_packet(av_packet_alloc())
+    , m_avFormatContext(avFormatContext)
+    , m_avCodecContext(avCodecContext)
+{
+    connect(produce, &PipeWireRecordProduce::producedFrame, this, &PipeWireRecordWrite::addFrame);
+}
+
+PipeWireRecordWrite::~PipeWireRecordWrite()
+{
+    int ret = av_write_trailer(m_avFormatContext);
+    if (ret < 0) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "failed to write trailer" << av_err2str(ret);
+    }
+    av_packet_free(&m_packet);
+}
+
+PipeWireRecordWriteThread::PipeWireRecordWriteThread(PipeWireRecordProduce *produce, AVFormatContext *avFormatContext, AVCodecContext *avCodecContext)
+    : QThread(produce)
+    , m_produce(produce)
+    , m_avFormatContext(avFormatContext)
+    , m_avCodecContext(avCodecContext)
+{
+}
+
+void PipeWireRecordWrite::addFrame(const QImage &image, std::optional<int> sequential, std::optional<std::chrono::nanoseconds> presentationTimestamp)
+{
+    if (!sws_context || m_lastReceivedSize != image.size()) {
+        sws_context = sws_getCachedContext(sws_context,
+                                           image.width(),
+                                           image.height(),
+                                           convertQImageFormatToAVPixelFormat(image.format()),
+                                           m_avCodecContext->width,
+                                           m_avCodecContext->height,
+                                           m_avCodecContext->pix_fmt,
+                                           0,
+                                           nullptr,
+                                           nullptr,
+                                           nullptr);
+    }
+
+    CustomAVFrame avFrame;
+    int ret = avFrame.alloc(m_avCodecContext->width, m_avCodecContext->height, m_avCodecContext->pix_fmt);
+    if (ret < 0) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "Could not allocate raw picture buffer" << av_err2str(ret);
+        return;
+    }
+    const std::uint8_t *buffers[] = {image.constBits(), nullptr};
+    const int strides[] = {static_cast<int>(image.bytesPerLine()), 0, 0, 0};
+    sws_scale(sws_context, buffers, strides, 0, m_avCodecContext->height, avFrame.m_avFrame->data, avFrame.m_avFrame->linesize);
+
+    if (presentationTimestamp.has_value()) {
+        const auto current = std::chrono::duration_cast<std::chrono::milliseconds>(*presentationTimestamp).count();
+        if ((*m_avFormatContext->streams)->start_time == 0) {
+            (*m_avFormatContext->streams)->start_time = current;
+        }
+
+        Q_ASSERT((*m_avFormatContext->streams)->start_time <= current);
+        avFrame.m_avFrame->pts = current - (*m_avFormatContext->streams)->start_time;
+    } else {
+        avFrame.m_avFrame->pts = AV_NOPTS_VALUE;
+    }
+
+    // Let's add a key frame every 100 frames and also the first frame
+    if (sequential && (*sequential == 0 || (*sequential - m_lastKeyFrame) > 100)) {
+        avFrame.m_avFrame->key_frame = 1;
+        m_lastKeyFrame = *sequential;
+    }
+
+    if (m_lastPts > 0 && avFrame.m_avFrame->pts <= m_lastPts) {
+        // Make sure we don't have two frames at the same presentation time
+        avFrame.m_avFrame->pts = m_lastPts + 1;
+    }
+    m_lastPts = avFrame.m_avFrame->pts;
+
+    ret = avcodec_send_frame(m_avCodecContext, avFrame.m_avFrame);
+    if (ret < 0) {
+        qCWarning(PIPEWIRERECORD_LOGGING) << "Error sending a frame for encoding:" << av_err2str(ret);
+        return;
+    }
+    for (;;) {
+        ret = avcodec_receive_packet(m_avCodecContext, m_packet);
+        if (ret < 0) {
+            if (ret != AVERROR_EOF && ret != AVERROR(EAGAIN)) {
+                qCWarning(PIPEWIRERECORD_LOGGING) << "Error encoding a frame: " << av_err2str(ret) << ret;
+            }
+            break;
+        }
+
+        m_packet->stream_index = (*m_avFormatContext->streams)->index;
+        av_packet_rescale_ts(m_packet, m_avCodecContext->time_base, (*m_avFormatContext->streams)->time_base);
+        log_packet(m_avFormatContext, m_packet);
+        ret = av_interleaved_write_frame(m_avFormatContext, m_packet);
+        if (ret < 0) {
+            qCWarning(PIPEWIRERECORD_LOGGING) << "Error while writing output packet:" << av_err2str(ret);
+        }
+        av_packet_unref(m_packet);
+    }
+}
+
+void PipeWireRecordWriteThread::run()
+{
+    PipeWireRecordWrite writer(m_produce, m_avFormatContext, m_avCodecContext);
+    QThread::exec();
+    AVPacket *pkt = av_packet_alloc();
+    avcodec_send_frame(m_avCodecContext, nullptr);
+
+    for (;;) {
+        if (avcodec_receive_packet(m_avCodecContext, pkt) < 0)
+            break;
+
+        pkt->stream_index = (*m_avFormatContext->streams)->index;
+        av_packet_rescale_ts(pkt, m_avCodecContext->time_base, (*m_avFormatContext->streams)->time_base);
+        log_packet(m_avFormatContext, pkt);
+        int ret = av_interleaved_write_frame(m_avFormatContext, pkt);
+        if (ret < 0) {
+            qCWarning(PIPEWIRERECORD_LOGGING) << "Error while writing output packet:" << av_err2str(ret);
+        }
+        av_packet_unref(pkt);
+    }
+    av_packet_free(&pkt);
+}
diff --git a/src/pipewirerecord.h b/src/pipewirerecord.h
new file mode 100644 (file)
index 0000000..8f4e0e9
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QObject>
+
+#include <kpipewire_export.h>
+
+struct PipeWireRecordPrivate;
+
+class KPIPEWIRE_EXPORT PipeWireRecord : public QObject
+{
+    Q_OBJECT
+    /// Specify the pipewire node id that we want to record
+    Q_PROPERTY(uint nodeId READ nodeId WRITE setNodeId NOTIFY nodeIdChanged)
+    /**
+     * Specifies the file descriptor we are connected to, if none 0 will be returned
+     *
+     * Transfers the ownership of the fd, will close it when it's done with it.
+     */
+    Q_PROPERTY(uint fd READ fd WRITE setFd NOTIFY fdChanged)
+    Q_PROPERTY(bool active READ isActive WRITE setActive NOTIFY activeChanged)
+    Q_PROPERTY(QString output READ output WRITE setOutput NOTIFY outputChanged)
+    Q_PROPERTY(State state READ state NOTIFY stateChanged)
+    Q_PROPERTY(QString extension READ extension NOTIFY encoderChanged)
+    Q_PROPERTY(QByteArray encoder READ encoder WRITE setEncoder NOTIFY encoderChanged)
+public:
+    PipeWireRecord(QObject *parent = nullptr);
+    ~PipeWireRecord() override;
+
+    enum State {
+        Idle, //< ready to get started
+        Recording, //< actively recording
+        Rendering, //< recording is over but the video file is still being written
+    };
+    Q_ENUM(State)
+
+    void setNodeId(uint nodeId);
+    uint nodeId() const;
+
+    void setFd(uint fd);
+    uint fd() const;
+
+    bool isActive() const;
+    void setActive(bool active);
+    State state() const;
+
+    QString output() const;
+    void setOutput(const QString &output);
+
+    /**
+     * Set the FFmpeg @p encoder that will be used to create the video
+     *
+     * They can be inspected using:
+     * ffmpeg -encoders | grep "^ V"
+     */
+    void setEncoder(const QByteArray &encoder);
+    QByteArray encoder() const;
+
+    /// Returns the encoders that are tested to work, sorted by preference
+    QList<QByteArray> suggestedEncoders() const;
+
+    QString currentExtension() const;
+    Q_DECL_DEPRECATED static QString extension();
+
+Q_SIGNALS:
+    void activeChanged(bool active);
+    void nodeIdChanged(uint nodeId);
+    void fdChanged(uint fd);
+    void outputChanged(const QString &output);
+    void errorFound(const QString &error);
+    void stateChanged();
+    void encoderChanged();
+
+private:
+    void refresh();
+    QScopedPointer<PipeWireRecordPrivate> d;
+};
diff --git a/src/pipewirerecord_p.h b/src/pipewirerecord_p.h
new file mode 100644 (file)
index 0000000..b554949
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QFile>
+#include <QImage>
+#include <QPoint>
+#include <QRunnable>
+#include <QThread>
+#include <QWaitCondition>
+
+#include <functional>
+#include <optional>
+
+#include <epoxy/egl.h>
+#include <pipewire/pipewire.h>
+#include <spa/param/format-utils.h>
+#include <spa/param/props.h>
+#include <spa/param/video/format-utils.h>
+
+#include "dmabufhandler.h"
+#include "pipewiresourcestream.h"
+
+struct AVCodec;
+struct AVCodecContext;
+struct AVFrame;
+struct AVFormatContext;
+struct AVPacket;
+class CustomAVFrame;
+class PipeWireRecordProduce;
+struct gbm_device;
+
+class PipeWireRecordWrite : public QObject
+{
+public:
+    PipeWireRecordWrite(PipeWireRecordProduce *produce, AVFormatContext *avFormatContext, AVCodecContext *avCodecContext);
+    ~PipeWireRecordWrite();
+
+    void addFrame(const QImage &image, std::optional<int> sequential, std::optional<std::chrono::nanoseconds> presentationTimestamp);
+
+private:
+    QAtomicInt m_active = true;
+    AVPacket *m_packet;
+    AVFormatContext *const m_avFormatContext;
+    AVCodecContext *const m_avCodecContext;
+    struct SwsContext *sws_context = nullptr;
+    int64_t m_lastPts = -1;
+    uint m_lastKeyFrame = 0;
+    QSize m_lastReceivedSize;
+};
+
+class PipeWireRecordWriteThread : public QThread
+{
+public:
+    PipeWireRecordWriteThread(PipeWireRecordProduce *produce, AVFormatContext *avFormatContext, AVCodecContext *avCodecContext);
+
+    void run() override;
+    void drain();
+
+private:
+    PipeWireRecordProduce *const m_produce;
+    AVFormatContext *const m_avFormatContext;
+    AVCodecContext *const m_avCodecContext;
+};
+
+class PipeWireRecordProduce : public QObject
+{
+    Q_OBJECT
+public:
+    PipeWireRecordProduce(const QByteArray &encoder, uint nodeId, uint fd, const QString &output);
+    ~PipeWireRecordProduce() override;
+
+    QString error() const
+    {
+        return m_error;
+    }
+
+Q_SIGNALS:
+    void producedFrame(const QImage &image, std::optional<int> sequential, std::optional<std::chrono::nanoseconds> presentationTimestamp);
+
+private:
+    friend class PipeWireRecordProduceThread;
+    void setupStream();
+    void processFrame(const PipeWireFrame &frame);
+    void updateTextureImage(const QImage &image, const PipeWireFrame &frame);
+    void render(const PipeWireFrame &frame);
+    void stateChanged(pw_stream_state state);
+
+    AVCodecContext *m_avCodecContext = nullptr;
+    const AVCodec *m_codec = nullptr;
+    AVFormatContext *m_avFormatContext = nullptr;
+    const QString m_output;
+    const uint m_nodeId;
+    QScopedPointer<PipeWireSourceStream> m_stream;
+    QString m_error;
+
+    PipeWireRecordWriteThread *m_writeThread = nullptr;
+    const QByteArray m_encoder;
+
+    struct {
+        QImage texture;
+        std::optional<QPoint> position;
+        QPoint hotspot;
+        bool dirty = false;
+    } m_cursor;
+    QImage m_frameWithoutMetadataCursor;
+    DmaBufHandler m_dmabufHandler;
+    QAtomicInt m_deactivated = false;
+};
+
+class PipeWireRecordProduceThread : public QThread
+{
+    Q_OBJECT
+public:
+    PipeWireRecordProduceThread(const QByteArray &encoder, uint nodeId, uint fd, const QString &output)
+        : m_nodeId(nodeId)
+        , m_fd(fd)
+        , m_output(output)
+        , m_encoder(encoder)
+    {
+    }
+    void run() override;
+    void deactivate();
+
+Q_SIGNALS:
+    void errorFound(const QString &error);
+
+private:
+    const uint m_nodeId;
+    const uint m_fd;
+    const QString m_output;
+    PipeWireRecordProduce *m_producer = nullptr;
+    const QByteArray m_encoder;
+};
+
+struct PipeWireRecordPrivate {
+    uint m_nodeId = 0;
+    std::optional<uint> m_fd;
+    bool m_active = false;
+    QString m_output;
+    std::unique_ptr<PipeWireRecordProduceThread> m_recordThread;
+    bool m_produceThreadFinished = true;
+    QByteArray m_encoder;
+};
diff --git a/src/pipewiresourceitem.cpp b/src/pipewiresourceitem.cpp
new file mode 100644 (file)
index 0000000..9ef9bb9
--- /dev/null
@@ -0,0 +1,461 @@
+/*
+    Render a PipeWire stream into a QtQuick scene as a standard Item
+    SPDX-FileCopyrightText: 2020 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "pipewiresourceitem.h"
+#include "glhelpers.h"
+#include "logging.h"
+#include "pipewiresourcestream.h"
+
+#include <QGuiApplication>
+#include <QOpenGLContext>
+#include <QOpenGLTexture>
+#include <QPainter>
+#include <QQuickWindow>
+#include <QRunnable>
+#include <QSGImageNode>
+#include <QSocketNotifier>
+#include <QThread>
+#include <qpa/qplatformnativeinterface.h>
+
+#include <EGL/eglext.h>
+#include <fcntl.h>
+#include <libdrm/drm_fourcc.h>
+#include <unistd.h>
+
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
+#include <QtPlatformHeaders/QEGLNativeContext>
+#endif
+
+static void pwInit()
+{
+    pw_init(nullptr, nullptr);
+}
+Q_COREAPP_STARTUP_FUNCTION(pwInit);
+
+class PipeWireSourceItemPrivate
+{
+public:
+    uint m_nodeId = 0;
+    std::optional<uint> m_fd;
+    std::function<QSGTexture *()> m_createNextTexture;
+    QScopedPointer<PipeWireSourceStream> m_stream;
+    QScopedPointer<QOpenGLTexture> m_texture;
+
+    EGLImage m_image = nullptr;
+    bool m_needsRecreateTexture = false;
+
+    struct {
+        QImage texture;
+        std::optional<QPoint> position;
+        QPoint hotspot;
+        bool dirty = false;
+    } m_cursor;
+    std::optional<QRegion> m_damage;
+};
+
+class DiscardEglPixmapRunnable : public QRunnable
+{
+public:
+    DiscardEglPixmapRunnable(EGLImageKHR image, QOpenGLTexture *texture)
+        : m_image(image)
+        , m_texture(texture)
+    {
+    }
+
+    void run() override
+    {
+        if (m_image != EGL_NO_IMAGE_KHR) {
+            eglDestroyImageKHR(eglGetCurrentDisplay(), m_image);
+        }
+
+        delete m_texture;
+    }
+
+private:
+    const EGLImageKHR m_image;
+    QOpenGLTexture *m_texture;
+};
+
+PipeWireSourceItem::PipeWireSourceItem(QQuickItem *parent)
+    : QQuickItem(parent)
+    , d(new PipeWireSourceItemPrivate)
+{
+    setFlag(ItemHasContents, true);
+
+    connect(this, &QQuickItem::visibleChanged, this, [this]() {
+        setEnabled(isVisible());
+        if (d->m_stream)
+            d->m_stream->setActive(isVisible());
+    });
+}
+
+PipeWireSourceItem::~PipeWireSourceItem()
+{
+    if (d->m_fd) {
+        close(*d->m_fd);
+    }
+}
+
+void PipeWireSourceItem::itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &data)
+{
+    switch (change) {
+    case ItemVisibleHasChanged:
+        setEnabled(isVisible());
+        if (d->m_stream)
+            d->m_stream->setActive(isVisible() && data.boolValue && isComponentComplete());
+        break;
+    case ItemSceneChange:
+        d->m_needsRecreateTexture = true;
+        releaseResources();
+        break;
+    default:
+        break;
+    }
+}
+
+void PipeWireSourceItem::releaseResources()
+{
+    if (window()) {
+        window()->scheduleRenderJob(new DiscardEglPixmapRunnable(d->m_image, d->m_texture.take()), QQuickWindow::NoStage);
+        d->m_image = EGL_NO_IMAGE_KHR;
+    }
+}
+
+void PipeWireSourceItem::setFd(uint fd)
+{
+    if (fd == d->m_fd)
+        return;
+
+    if (d->m_fd) {
+        close(*d->m_fd);
+    }
+    d->m_fd = fd;
+    refresh();
+    Q_EMIT fdChanged(fd);
+}
+
+void PipeWireSourceItem::resetFd()
+{
+    if (!d->m_fd.has_value()) {
+        return;
+    }
+
+    setEnabled(false);
+    close(*d->m_fd);
+    d->m_fd.reset();
+    d->m_stream.reset(nullptr);
+    d->m_createNextTexture = [] {
+        return nullptr;
+    };
+    Q_EMIT streamSizeChanged();
+}
+
+void PipeWireSourceItem::refresh()
+{
+    setEnabled(false);
+
+    if (!isComponentComplete()) {
+        return;
+    }
+
+    if (d->m_nodeId == 0) {
+        d->m_stream.reset(nullptr);
+        Q_EMIT streamSizeChanged();
+
+        d->m_createNextTexture = [] {
+            return nullptr;
+        };
+    } else {
+        d->m_stream.reset(new PipeWireSourceStream(this));
+        Q_EMIT streamSizeChanged();
+        connect(d->m_stream.get(), &PipeWireSourceStream::streamParametersChanged, this, &PipeWireSourceItem::streamSizeChanged);
+
+        d->m_stream->createStream(d->m_nodeId, d->m_fd.value_or(0));
+        if (!d->m_stream->error().isEmpty()) {
+            d->m_stream.reset(nullptr);
+            d->m_nodeId = 0;
+            return;
+        }
+        d->m_stream->setActive(isVisible() && isComponentComplete());
+
+        connect(d->m_stream.data(), &PipeWireSourceStream::frameReceived, this, &PipeWireSourceItem::processFrame);
+        connect(d->m_stream.data(), &PipeWireSourceStream::stateChanged, this, &PipeWireSourceItem::stateChanged);
+    }
+    Q_EMIT stateChanged();
+}
+
+void PipeWireSourceItem::setNodeId(uint nodeId)
+{
+    if (nodeId == d->m_nodeId)
+        return;
+
+    d->m_nodeId = nodeId;
+    refresh();
+    Q_EMIT nodeIdChanged(nodeId);
+}
+
+class PipeWireRenderNode : public QSGNode
+{
+public:
+    QSGImageNode *screenNode(QQuickWindow *window)
+    {
+        if (!m_screenNode) {
+            m_screenNode = window->createImageNode();
+            appendChildNode(m_screenNode);
+        }
+        return m_screenNode;
+    }
+    QSGImageNode *cursorNode(QQuickWindow *window)
+    {
+        if (!m_cursorNode) {
+            m_cursorNode = window->createImageNode();
+            appendChildNode(m_cursorNode);
+        }
+        return m_cursorNode;
+    }
+
+    QSGImageNode *damageNode(QQuickWindow *window)
+    {
+        if (!m_damageNode) {
+            m_damageNode = window->createImageNode();
+            appendChildNode(m_damageNode);
+        }
+        return m_damageNode;
+    }
+
+    void discardCursor()
+    {
+        if (m_cursorNode) {
+            removeChildNode(m_cursorNode);
+            delete m_cursorNode;
+            m_cursorNode = nullptr;
+        }
+    }
+
+    void discardDamage()
+    {
+        if (m_damageNode) {
+            removeChildNode(m_damageNode);
+            delete m_damageNode;
+            m_damageNode = nullptr;
+        }
+    }
+
+private:
+    QSGImageNode *m_screenNode = nullptr;
+    QSGImageNode *m_cursorNode = nullptr;
+    QSGImageNode *m_damageNode = nullptr;
+};
+
+QSGNode *PipeWireSourceItem::updatePaintNode(QSGNode *node, QQuickItem::UpdatePaintNodeData *)
+{
+    if (Q_UNLIKELY(!d->m_createNextTexture)) {
+        return node;
+    }
+
+    auto texture = d->m_createNextTexture();
+    if (!texture) {
+        delete node;
+        return nullptr;
+    }
+
+    QSGImageNode *screenNode;
+    auto pwNode = dynamic_cast<PipeWireRenderNode *>(node);
+    if (!pwNode) {
+        delete node;
+        pwNode = new PipeWireRenderNode;
+        screenNode = window()->createImageNode();
+        screenNode->setOwnsTexture(true);
+        pwNode->appendChildNode(screenNode);
+    } else {
+        screenNode = static_cast<QSGImageNode *>(pwNode->childAtIndex(0));
+    }
+    screenNode->setTexture(texture);
+
+    const auto br = boundingRect().toRect();
+    QRect rect({0, 0}, texture->textureSize().scaled(br.size(), Qt::KeepAspectRatio));
+    rect.moveCenter(br.center());
+    screenNode->setRect(rect);
+
+    if (!d->m_cursor.position.has_value() || d->m_cursor.texture.isNull()) {
+        pwNode->discardCursor();
+    } else {
+        QSGImageNode *cursorNode = pwNode->cursorNode(window());
+        if (d->m_cursor.dirty || !cursorNode->texture()) {
+            cursorNode->setTexture(window()->createTextureFromImage(d->m_cursor.texture));
+            d->m_cursor.dirty = false;
+        }
+        const qreal scale = qreal(rect.width()) / texture->textureSize().width();
+        cursorNode->setRect(QRectF{rect.topLeft() + (d->m_cursor.position.value() * scale), d->m_cursor.texture.size() * scale});
+        Q_ASSERT(cursorNode->texture());
+    }
+
+    if (!d->m_damage || d->m_damage->isEmpty()) {
+        pwNode->discardDamage();
+    } else {
+        auto *damageNode = pwNode->damageNode(window());
+        QImage damageImage(texture->textureSize(), QImage::Format_RGBA64_Premultiplied);
+        damageImage.fill(Qt::transparent);
+        QPainter p(&damageImage);
+        p.setBrush(Qt::red);
+        for (auto rect : *d->m_damage) {
+            p.drawRect(rect);
+        }
+        damageNode->setTexture(window()->createTextureFromImage(damageImage));
+        damageNode->setRect(rect);
+        Q_ASSERT(damageNode->texture());
+    }
+    return pwNode;
+}
+
+QString PipeWireSourceItem::error() const
+{
+    return d->m_stream->error();
+}
+
+void PipeWireSourceItem::processFrame(const PipeWireFrame &frame)
+{
+    d->m_damage = frame.damage;
+
+    if (frame.cursor) {
+        d->m_cursor.position = frame.cursor->position;
+        d->m_cursor.hotspot = frame.cursor->hotspot;
+        if (!frame.cursor->texture.isNull()) {
+            d->m_cursor.dirty = true;
+            d->m_cursor.texture = frame.cursor->texture;
+        }
+    } else {
+        d->m_cursor.position = std::nullopt;
+        d->m_cursor.hotspot = {};
+    }
+
+    if (frame.dmabuf) {
+        updateTextureDmaBuf(*frame.dmabuf, frame.format);
+    } else if (frame.image) {
+        updateTextureImage(*frame.image);
+    }
+
+    if (window() && window()->isVisible()) {
+        update();
+    }
+}
+
+void PipeWireSourceItem::updateTextureDmaBuf(const DmaBufAttributes &attribs, spa_video_format format)
+{
+    if (!window()) {
+        qCWarning(PIPEWIRE_LOGGING) << "Window not available" << this;
+        return;
+    }
+
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
+    const auto openglContext = window()->openglContext();
+#else
+    const auto openglContext = static_cast<QOpenGLContext *>(window()->rendererInterface()->getResource(window(), QSGRendererInterface::OpenGLContextResource));
+#endif
+    if (!openglContext || !d->m_stream) {
+        qCWarning(PIPEWIRE_LOGGING) << "need a window and a context" << window();
+        return;
+    }
+
+    d->m_createNextTexture = [this, format, attribs]() -> QSGTexture * {
+        const EGLDisplay display = static_cast<EGLDisplay>(QGuiApplication::platformNativeInterface()->nativeResourceForIntegration("egldisplay"));
+        if (d->m_image) {
+            eglDestroyImageKHR(display, d->m_image);
+        }
+        const auto size = d->m_stream->size();
+        d->m_image = GLHelpers::createImage(display, attribs, PipeWireSourceStream::spaVideoFormatToDrmFormat(format), size, nullptr);
+        if (d->m_image == EGL_NO_IMAGE_KHR) {
+            d->m_stream->renegotiateModifierFailed(format, attribs.modifier);
+            return nullptr;
+        }
+        if (!d->m_texture) {
+            d->m_texture.reset(new QOpenGLTexture(QOpenGLTexture::Target2D));
+            bool created = d->m_texture->create();
+            Q_ASSERT(created);
+        }
+
+        GLHelpers::initDebugOutput();
+        d->m_texture->bind();
+
+        glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)d->m_image);
+
+        d->m_texture->setWrapMode(QOpenGLTexture::ClampToEdge);
+        d->m_texture->setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
+        d->m_texture->release();
+        d->m_texture->setSize(size.width(), size.height());
+
+        int textureId = d->m_texture->textureId();
+        QQuickWindow::CreateTextureOption textureOption =
+            format == SPA_VIDEO_FORMAT_ARGB || format == SPA_VIDEO_FORMAT_BGRA ? QQuickWindow::TextureHasAlphaChannel : QQuickWindow::TextureIsOpaque;
+        setEnabled(true);
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
+        return window()->createTextureFromNativeObject(QQuickWindow::NativeObjectTexture, &textureId, 0 /*a vulkan thing?*/, size, textureOption);
+#else
+        return QNativeInterface::QSGOpenGLTexture::fromNative(textureId, window(), size, textureOption);
+#endif
+    };
+}
+
+void PipeWireSourceItem::updateTextureImage(const QImage &image)
+{
+    if (!window()) {
+        qCWarning(PIPEWIRE_LOGGING) << "pass";
+        return;
+    }
+
+    d->m_createNextTexture = [this, image] {
+        setEnabled(true);
+        return window()->createTextureFromImage(image, QQuickWindow::TextureIsOpaque);
+    };
+}
+
+void PipeWireSourceItem::componentComplete()
+{
+    QQuickItem::componentComplete();
+    if (d->m_nodeId != 0) {
+        refresh();
+    }
+}
+
+PipeWireSourceItem::StreamState PipeWireSourceItem::state() const
+{
+    if (!d->m_stream) {
+        return StreamState::Unconnected;
+    }
+    switch (d->m_stream->state()) {
+    case PW_STREAM_STATE_ERROR:
+        return StreamState::Error;
+    case PW_STREAM_STATE_UNCONNECTED:
+        return StreamState::Unconnected;
+    case PW_STREAM_STATE_CONNECTING:
+        return StreamState::Connecting;
+    case PW_STREAM_STATE_PAUSED:
+        return StreamState::Paused;
+    case PW_STREAM_STATE_STREAMING:
+        return StreamState::Streaming;
+    default:
+        return StreamState::Error;
+    }
+}
+
+uint PipeWireSourceItem::fd() const
+{
+    return d->m_fd.value_or(0);
+}
+
+uint PipeWireSourceItem::nodeId() const
+{
+    return d->m_nodeId;
+}
+
+QSize PipeWireSourceItem::streamSize() const
+{
+    if (!d->m_stream) {
+        return QSize();
+    }
+    return d->m_stream->size();
+}
diff --git a/src/pipewiresourceitem.h b/src/pipewiresourceitem.h
new file mode 100644 (file)
index 0000000..c35f5d8
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+    Render a PipeWire stream into a QtQuick scene as a standard Item
+    SPDX-FileCopyrightText: 2020 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QImage>
+#include <QQuickItem>
+#include <functional>
+#include <optional>
+
+#include <pipewire/pipewire.h>
+#include <spa/param/format-utils.h>
+#include <spa/param/props.h>
+#include <spa/param/video/format-utils.h>
+
+#include <kpipewire_export.h>
+
+struct DmaBufAttributes;
+class PipeWireSourceStream;
+struct PipeWireFrame;
+class QSGTexture;
+class QOpenGLTexture;
+typedef void *EGLImage;
+
+class PipeWireSourceItemPrivate;
+
+class KPIPEWIRE_EXPORT PipeWireSourceItem : public QQuickItem
+{
+    Q_OBJECT
+
+    /// Returns where the streams current state
+    Q_PROPERTY(StreamState state READ state NOTIFY stateChanged)
+
+    /// Specify the pipewire node id that we want to play
+    Q_PROPERTY(uint nodeId READ nodeId WRITE setNodeId NOTIFY nodeIdChanged)
+
+    /**
+     * Specifies the file descriptor we are connected to, if none 0 will be returned
+     *
+     * Transfers the ownership of the fd, will close it when it's done with it.
+     */
+    Q_PROPERTY(uint fd READ fd WRITE setFd NOTIFY fdChanged RESET resetFd)
+
+    /**
+     * Returns the size of the source being rendered
+     * @note: This won't be updated until the first frame is recieved
+     */
+    Q_PROPERTY(QSize streamSize READ streamSize NOTIFY streamSizeChanged)
+public:
+    enum class StreamState { Error, Unconnected, Connecting, Paused, Streaming };
+    Q_ENUM(StreamState);
+
+    PipeWireSourceItem(QQuickItem *parent = nullptr);
+    ~PipeWireSourceItem() override;
+
+    QSGNode *updatePaintNode(QSGNode *node, UpdatePaintNodeData *data) override;
+    Q_SCRIPTABLE QString error() const;
+
+    void setNodeId(uint nodeId);
+    uint nodeId() const;
+
+    void setFd(uint fd);
+    void resetFd();
+    uint fd() const;
+
+    QSize streamSize() const;
+
+    void componentComplete() override;
+    void releaseResources() override;
+
+    StreamState state() const;
+
+Q_SIGNALS:
+    void nodeIdChanged(uint nodeId);
+    void fdChanged(uint fd);
+    void stateChanged();
+    void streamSizeChanged();
+
+private:
+    void itemChange(ItemChange change, const ItemChangeData &data) override;
+    void processFrame(const PipeWireFrame &frame);
+    void updateTextureDmaBuf(const DmaBufAttributes &attribs, spa_video_format format);
+    void updateTextureImage(const QImage &image);
+    void refresh();
+
+    QScopedPointer<PipeWireSourceItemPrivate> d;
+};
diff --git a/src/pipewiresourcestream.cpp b/src/pipewiresourcestream.cpp
new file mode 100644 (file)
index 0000000..c759e88
--- /dev/null
@@ -0,0 +1,565 @@
+/*
+    SPDX-FileCopyrightText: 2018-2020 Red Hat Inc
+    SPDX-FileCopyrightText: 2020-2021 Aleix Pol Gonzalez <aleixpol@kde.org>
+    SPDX-FileContributor: Jan Grulich <jgrulich@redhat.com>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "pipewiresourcestream.h"
+#include "glhelpers.h"
+#include "logging.h"
+#include "pipewirecore.h"
+#include "pwhelpers.h"
+
+#include <libdrm/drm_fourcc.h>
+#include <spa/utils/result.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+#include <QGuiApplication>
+#include <QOpenGLTexture>
+#include <QSocketNotifier>
+#include <QThread>
+#include <QVersionNumber>
+#include <qpa/qplatformnativeinterface.h>
+
+#include <KLocalizedString>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
+#include <QtPlatformHeaders/QEGLNativeContext>
+#endif
+#undef Status
+
+#if !PW_CHECK_VERSION(0, 3, 29)
+#define SPA_POD_PROP_FLAG_MANDATORY (1u << 3)
+#endif
+#if !PW_CHECK_VERSION(0, 3, 33)
+#define SPA_POD_PROP_FLAG_DONT_FIXATE (1u << 4)
+#endif
+
+#define CURSOR_BPP 4
+#define CURSOR_META_SIZE(w, h) (sizeof(struct spa_meta_cursor) + sizeof(struct spa_meta_bitmap) + w * h * CURSOR_BPP)
+
+pw_stream_events pwStreamEvents = {};
+
+struct PipeWireSourceStreamPrivate
+{
+    QSharedPointer<PipeWireCore> pwCore;
+    pw_stream *pwStream = nullptr;
+    spa_hook streamListener;
+
+    uint32_t pwNodeId = 0;
+    std::optional<std::chrono::nanoseconds> m_currentPresentationTimestamp;
+
+    QAtomicInt m_stopped = false;
+    pw_stream_state m_state = PW_STREAM_STATE_UNCONNECTED;
+
+    spa_video_info_raw videoFormat;
+    QString m_error;
+    bool m_allowDmaBuf = true;
+
+    QHash<spa_video_format, QVector<uint64_t>> m_availableModifiers;
+    spa_source *m_renegotiateEvent = nullptr;
+
+    bool m_withDamage = false;
+};
+
+static const QVersionNumber pwClientVersion = QVersionNumber::fromString(QString::fromUtf8(pw_get_library_version()));
+static const QVersionNumber kDmaBufMinVersion = {0, 3, 24};
+static const QVersionNumber kDmaBufModifierMinVersion = {0, 3, 33};
+static const QVersionNumber kDropSingleModifierMinVersion = {0, 3, 40};
+
+uint32_t PipeWireSourceStream::spaVideoFormatToDrmFormat(spa_video_format spa_format)
+{
+    switch (spa_format) {
+    case SPA_VIDEO_FORMAT_RGBA:
+        return DRM_FORMAT_ABGR8888;
+    case SPA_VIDEO_FORMAT_RGBx:
+        return DRM_FORMAT_XBGR8888;
+    case SPA_VIDEO_FORMAT_BGRA:
+        return DRM_FORMAT_ARGB8888;
+    case SPA_VIDEO_FORMAT_BGRx:
+        return DRM_FORMAT_XRGB8888;
+    case SPA_VIDEO_FORMAT_BGR:
+        return DRM_FORMAT_BGR888;
+    case SPA_VIDEO_FORMAT_RGB:
+        return DRM_FORMAT_RGB888;
+    default:
+        qCWarning(PIPEWIRE_LOGGING) << "unknown QImage format" << spa_format;
+        return DRM_FORMAT_INVALID;
+    }
+}
+
+static QHash<spa_video_format, QVector<uint64_t>> queryDmaBufModifiers(EGLDisplay display, const QVector<spa_video_format> &formats)
+{
+    QHash<spa_video_format, QVector<uint64_t>> ret;
+    ret.reserve(formats.size());
+    const bool hasEglImageDmaBufImportExt = epoxy_has_egl_extension(display, "EGL_EXT_image_dma_buf_import");
+    static auto eglQueryDmaBufModifiersEXT = (PFNEGLQUERYDMABUFMODIFIERSEXTPROC)eglGetProcAddress("eglQueryDmaBufModifiersEXT");
+    static auto eglQueryDmaBufFormatsEXT = (PFNEGLQUERYDMABUFFORMATSEXTPROC)eglGetProcAddress("eglQueryDmaBufFormatsEXT");
+
+    EGLint count = 0;
+    EGLBoolean successFormats = eglQueryDmaBufFormatsEXT(display, 0, nullptr, &count);
+
+    QVector<uint32_t> drmFormats(count);
+    successFormats &= eglQueryDmaBufFormatsEXT(display, count, reinterpret_cast<EGLint *>(drmFormats.data()), &count);
+    if (!successFormats)
+        qCWarning(PIPEWIRE_LOGGING) << "Failed to query DMA-BUF formats.";
+
+    const QVector<uint64_t> mods = hasEglImageDmaBufImportExt ? QVector<uint64_t>{DRM_FORMAT_MOD_INVALID} : QVector<uint64_t>{};
+    if (!eglQueryDmaBufFormatsEXT || !eglQueryDmaBufModifiersEXT || !hasEglImageDmaBufImportExt || !successFormats) {
+        for (spa_video_format format : formats) {
+            ret[format] = mods;
+        }
+        return ret;
+    }
+
+    for (spa_video_format format : formats) {
+        uint32_t drm_format = PipeWireSourceStream::spaVideoFormatToDrmFormat(format);
+        if (drm_format == DRM_FORMAT_INVALID) {
+            qCDebug(PIPEWIRE_LOGGING) << "Failed to find matching DRM format." << format;
+            break;
+        }
+
+        if (std::find(drmFormats.begin(), drmFormats.end(), drm_format) == drmFormats.end()) {
+            qCDebug(PIPEWIRE_LOGGING) << "Format " << drm_format << " not supported for modifiers.";
+            ret[format] = mods;
+            break;
+        }
+
+        successFormats = eglQueryDmaBufModifiersEXT(display, drm_format, 0, nullptr, nullptr, &count);
+        if (!successFormats) {
+            qCWarning(PIPEWIRE_LOGGING) << "Failed to query DMA-BUF modifier count.";
+            ret[format] = mods;
+            break;
+        }
+
+        QVector<uint64_t> modifiers(count);
+        if (count > 0) {
+            if (!eglQueryDmaBufModifiersEXT(display, drm_format, count, modifiers.data(), nullptr, &count)) {
+                qCWarning(PIPEWIRE_LOGGING) << "Failed to query DMA-BUF modifiers.";
+            }
+        }
+
+        // Support modifier-less buffers
+        modifiers.push_back(DRM_FORMAT_MOD_INVALID);
+        ret[format] = modifiers;
+    }
+    return ret;
+}
+
+void PipeWireSourceStream::onStreamStateChanged(void *data, pw_stream_state old, pw_stream_state state, const char *error_message)
+{
+    PipeWireSourceStream *pw = static_cast<PipeWireSourceStream *>(data);
+    qCDebug(PIPEWIRE_LOGGING) << "state changed" << pw_stream_state_as_string(old) << "->" << pw_stream_state_as_string(state) << error_message;
+    pw->d->m_state = state;
+    Q_EMIT pw->stateChanged(state, old);
+
+    switch (state) {
+    case PW_STREAM_STATE_ERROR:
+        qCWarning(PIPEWIRE_LOGGING) << "Stream error: " << error_message;
+        break;
+    case PW_STREAM_STATE_PAUSED:
+        Q_EMIT pw->streamReady();
+        break;
+    case PW_STREAM_STATE_STREAMING:
+        Q_EMIT pw->startStreaming();
+        break;
+    case PW_STREAM_STATE_CONNECTING:
+        break;
+    case PW_STREAM_STATE_UNCONNECTED:
+        if (!pw->d->m_stopped) {
+            Q_EMIT pw->stopStreaming();
+        }
+        break;
+    }
+}
+
+void PipeWireSourceStream::onRenegotiate(void *data, uint64_t)
+{
+    PipeWireSourceStream *pw = static_cast<PipeWireSourceStream *>(data);
+    uint8_t buffer[4096];
+    spa_pod_builder podBuilder = SPA_POD_BUILDER_INIT(buffer, sizeof(buffer));
+    auto params = pw->createFormatsParams(podBuilder);
+    pw_stream_update_params(pw->d->pwStream, params.data(), params.size());
+}
+
+void PipeWireSourceStream::renegotiateModifierFailed(spa_video_format format, quint64 modifier)
+{
+    if (d->pwCore->serverVersion() >= kDropSingleModifierMinVersion) {
+        const int removed = d->m_availableModifiers[format].removeAll(modifier);
+        if (removed == 0) {
+            d->m_allowDmaBuf = false;
+        }
+    } else {
+        d->m_allowDmaBuf = false;
+    }
+    qCDebug(PIPEWIRE_LOGGING) << "renegotiating, modifier didn't work" << format << modifier << "now only offering" << d->m_availableModifiers[format].count();
+    pw_loop_signal_event(d->pwCore->loop(), d->m_renegotiateEvent);
+}
+
+static spa_pod *buildFormat(spa_pod_builder *builder, spa_video_format format, const QVector<uint64_t> &modifiers, bool withDontFixate)
+{
+    spa_pod_frame f[2];
+    const spa_rectangle pw_min_screen_bounds{1, 1};
+    const spa_rectangle pw_max_screen_bounds{UINT32_MAX, UINT32_MAX};
+
+    spa_pod_builder_push_object(builder, &f[0], SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat);
+    spa_pod_builder_add(builder, SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video), 0);
+    spa_pod_builder_add(builder, SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw), 0);
+    spa_pod_builder_add(builder, SPA_FORMAT_VIDEO_format, SPA_POD_Id(format), 0);
+    spa_pod_builder_add(builder, SPA_FORMAT_VIDEO_size, SPA_POD_CHOICE_RANGE_Rectangle(&pw_min_screen_bounds, &pw_min_screen_bounds, &pw_max_screen_bounds), 0);
+
+    if (modifiers.size() == 1 && modifiers[0] == DRM_FORMAT_MOD_INVALID) {
+        // we only support implicit modifiers, use shortpath to skip fixation phase
+        spa_pod_builder_prop(builder, SPA_FORMAT_VIDEO_modifier, SPA_POD_PROP_FLAG_MANDATORY);
+        spa_pod_builder_long(builder, modifiers[0]);
+    } else if (modifiers.size()) {
+        // SPA_POD_PROP_FLAG_DONT_FIXATE can be used with PipeWire >= 0.3.33
+        if (withDontFixate) {
+            spa_pod_builder_prop(builder, SPA_FORMAT_VIDEO_modifier, SPA_POD_PROP_FLAG_MANDATORY | SPA_POD_PROP_FLAG_DONT_FIXATE);
+        } else {
+            spa_pod_builder_prop(builder, SPA_FORMAT_VIDEO_modifier, SPA_POD_PROP_FLAG_MANDATORY);
+        }
+        spa_pod_builder_push_choice(builder, &f[1], SPA_CHOICE_Enum, 0);
+        // mofifiers from the array
+        for (auto it = modifiers.begin(); it != modifiers.end(); it++) {
+            spa_pod_builder_long(builder, *it);
+            if (it == modifiers.begin()) {
+                spa_pod_builder_long(builder, *it);
+            }
+        }
+        spa_pod_builder_pop(builder, &f[1]);
+    }
+
+    return static_cast<spa_pod *>(spa_pod_builder_pop(builder, &f[0]));
+}
+
+static const int videoDamageRegionCount = 16;
+
+void PipeWireSourceStream::onStreamParamChanged(void *data, uint32_t id, const struct spa_pod *format)
+{
+    if (!format || id != SPA_PARAM_Format) {
+        return;
+    }
+
+    PipeWireSourceStream *pw = static_cast<PipeWireSourceStream *>(data);
+    spa_format_video_raw_parse(format, &pw->d->videoFormat);
+
+    uint8_t paramsBuffer[1024];
+    spa_pod_builder pod_builder = SPA_POD_BUILDER_INIT(paramsBuffer, sizeof(paramsBuffer));
+
+    // When SPA_FORMAT_VIDEO_modifier is present we can use DMA-BUFs as
+    // the server announces support for it.
+    // See https://github.com/PipeWire/pipewire/blob/master/doc/dma-buf.dox
+
+    const auto bufferTypes = pw->d->m_allowDmaBuf && spa_pod_find_prop(format, nullptr, SPA_FORMAT_VIDEO_modifier)
+        ? (1 << SPA_DATA_DmaBuf) | (1 << SPA_DATA_MemFd) | (1 << SPA_DATA_MemPtr)
+        : (1 << SPA_DATA_MemFd) | (1 << SPA_DATA_MemPtr);
+
+    QVarLengthArray<const spa_pod *> params = {
+        (spa_pod *)spa_pod_builder_add_object(&pod_builder,
+                                              SPA_TYPE_OBJECT_ParamBuffers,
+                                              SPA_PARAM_Buffers,
+                                              SPA_PARAM_BUFFERS_buffers,
+                                              SPA_POD_CHOICE_RANGE_Int(16, 2, 16),
+                                              SPA_PARAM_BUFFERS_align,
+                                              SPA_POD_Int(16),
+                                              SPA_PARAM_BUFFERS_dataType,
+                                              SPA_POD_CHOICE_FLAGS_Int(bufferTypes)),
+        (spa_pod *)spa_pod_builder_add_object(&pod_builder,
+                                              SPA_TYPE_OBJECT_ParamMeta,
+                                              SPA_PARAM_Meta,
+                                              SPA_PARAM_META_type,
+                                              SPA_POD_Id(SPA_META_Header),
+                                              SPA_PARAM_META_size,
+                                              SPA_POD_Int(sizeof(struct spa_meta_header))),
+        (spa_pod *)spa_pod_builder_add_object(&pod_builder,
+                                              SPA_TYPE_OBJECT_ParamMeta,
+                                              SPA_PARAM_Meta,
+                                              SPA_PARAM_META_type,
+                                              SPA_POD_Id(SPA_META_Cursor),
+                                              SPA_PARAM_META_size,
+                                              SPA_POD_CHOICE_RANGE_Int(CURSOR_META_SIZE(64, 64), CURSOR_META_SIZE(1, 1), CURSOR_META_SIZE(1024, 1024))),
+    };
+
+    if (pw->d->m_withDamage) {
+        params.append((spa_pod *)spa_pod_builder_add_object(&pod_builder,
+                                                            SPA_TYPE_OBJECT_ParamMeta,
+                                                            SPA_PARAM_Meta,
+                                                            SPA_PARAM_META_type,
+                                                            SPA_POD_Id(SPA_META_VideoDamage),
+                                                            SPA_PARAM_META_size,
+                                                            SPA_POD_CHOICE_RANGE_Int(sizeof(struct spa_meta_region) * videoDamageRegionCount,
+                                                                                     sizeof(struct spa_meta_region) * 1,
+                                                                                     sizeof(struct spa_meta_region) * videoDamageRegionCount)));
+    }
+
+    pw_stream_update_params(pw->d->pwStream, params.data(), params.count());
+    Q_EMIT pw->streamParametersChanged();
+}
+
+static void onProcess(void *data)
+{
+    PipeWireSourceStream *stream = static_cast<PipeWireSourceStream *>(data);
+    stream->process();
+}
+
+QSize PipeWireSourceStream::size() const
+{
+    return QSize(d->videoFormat.size.width, d->videoFormat.size.height);
+}
+
+pw_stream_state PipeWireSourceStream::state() const
+{
+    return d->m_state;
+}
+
+std::optional< std::chrono::nanoseconds > PipeWireSourceStream::currentPresentationTimestamp() const
+{
+    return d->m_currentPresentationTimestamp;
+}
+
+QString PipeWireSourceStream::error() const
+{
+    return d->m_error;
+}
+
+PipeWireSourceStream::PipeWireSourceStream(QObject *parent)
+    : QObject(parent)
+    , d(new PipeWireSourceStreamPrivate)
+{
+    qRegisterMetaType<QVector<DmaBufPlane>>();
+
+    pwStreamEvents.version = PW_VERSION_STREAM_EVENTS;
+    pwStreamEvents.process = &onProcess;
+    pwStreamEvents.state_changed = &PipeWireSourceStream::onStreamStateChanged;
+    pwStreamEvents.param_changed = &PipeWireSourceStream::onStreamParamChanged;
+}
+
+PipeWireSourceStream::~PipeWireSourceStream()
+{
+    d->m_stopped = true;
+    if (d->m_renegotiateEvent) {
+        pw_loop_destroy_source(d->pwCore->loop(), d->m_renegotiateEvent);
+    }
+    if (d->pwStream) {
+        pw_stream_destroy(d->pwStream);
+    }
+}
+
+Fraction PipeWireSourceStream::framerate() const
+{
+    if (d->pwStream) {
+        return {d->videoFormat.max_framerate.num, d->videoFormat.max_framerate.denom};
+    }
+
+    return {0, 1};
+}
+
+uint PipeWireSourceStream::nodeId()
+{
+    return d->pwNodeId;
+}
+
+QVector<const spa_pod *> PipeWireSourceStream::createFormatsParams(spa_pod_builder podBuilder)
+{
+    const auto pwServerVersion = d->pwCore->serverVersion();
+    const QVector<spa_video_format> formats =
+        {SPA_VIDEO_FORMAT_RGBx, SPA_VIDEO_FORMAT_RGBA, SPA_VIDEO_FORMAT_BGRx, SPA_VIDEO_FORMAT_BGRA, SPA_VIDEO_FORMAT_RGB, SPA_VIDEO_FORMAT_BGR};
+    QVector<const spa_pod *> params;
+    params.reserve(formats.size() * 2);
+    const EGLDisplay display = static_cast<EGLDisplay>(QGuiApplication::platformNativeInterface()->nativeResourceForIntegration("egldisplay"));
+
+    d->m_allowDmaBuf = pwServerVersion.isNull() || (pwClientVersion >= kDmaBufMinVersion && pwServerVersion >= kDmaBufMinVersion);
+    const bool withDontFixate = pwServerVersion.isNull() || (pwClientVersion >= kDmaBufModifierMinVersion && pwServerVersion >= kDmaBufModifierMinVersion);
+
+    if (d->m_availableModifiers.isEmpty()) {
+        d->m_availableModifiers = queryDmaBufModifiers(display, formats);
+    }
+
+    for (auto it = d->m_availableModifiers.constBegin(), itEnd = d->m_availableModifiers.constEnd(); it != itEnd; ++it) {
+        if (d->m_allowDmaBuf && !it->isEmpty()) {
+            params += buildFormat(&podBuilder, it.key(), it.value(), withDontFixate);
+        }
+
+        params += buildFormat(&podBuilder, it.key(), {}, withDontFixate);
+    }
+    return params;
+}
+
+bool PipeWireSourceStream::createStream(uint nodeid, int fd)
+{
+    d->m_availableModifiers.clear();
+    d->pwCore = PipeWireCore::fetch(fd);
+    if (!d->pwCore->error().isEmpty()) {
+        qCDebug(PIPEWIRE_LOGGING) << "received error while creating the stream" << d->pwCore->error();
+        d->m_error = d->pwCore->error();
+        return false;
+    }
+
+    connect(d->pwCore.data(), &PipeWireCore::pipewireFailed, this, &PipeWireSourceStream::coreFailed);
+
+    if (objectName().isEmpty()) {
+        setObjectName(QStringLiteral("plasma-screencast-%1").arg(nodeid));
+    }
+
+    const auto pwServerVersion = d->pwCore->serverVersion();
+    d->pwStream = pw_stream_new(**d->pwCore, objectName().toUtf8().constData(), nullptr);
+    d->pwNodeId = nodeid;
+    pw_stream_add_listener(d->pwStream, &d->streamListener, &pwStreamEvents, this);
+
+    d->m_renegotiateEvent = pw_loop_add_event(d->pwCore->loop(), onRenegotiate, this);
+
+    uint8_t buffer[4096];
+    spa_pod_builder podBuilder = SPA_POD_BUILDER_INIT(buffer, sizeof(buffer));
+    auto params = createFormatsParams(podBuilder);
+    pw_stream_flags s = (pw_stream_flags)(PW_STREAM_FLAG_DONT_RECONNECT | PW_STREAM_FLAG_AUTOCONNECT);
+    if (pw_stream_connect(d->pwStream, PW_DIRECTION_INPUT, d->pwNodeId, s, params.data(), params.size()) != 0) {
+        qCWarning(PIPEWIRE_LOGGING) << "Could not connect to stream";
+        pw_stream_destroy(d->pwStream);
+        d->pwStream = nullptr;
+        return false;
+    }
+    qCDebug(PIPEWIRE_LOGGING) << "created successfully" << nodeid;
+    return true;
+}
+
+void PipeWireSourceStream::handleFrame(struct pw_buffer *buffer)
+{
+    spa_buffer *spaBuffer = buffer->buffer;
+
+    PipeWireFrame frame;
+    frame.format = d->videoFormat.format;
+
+    struct spa_meta_header *h = (struct spa_meta_header *)spa_buffer_find_meta_data(spaBuffer, SPA_META_Header, sizeof(*h));
+    if (h) {
+        d->m_currentPresentationTimestamp = std::chrono::nanoseconds(h->pts);
+        frame.presentationTimestamp = std::chrono::nanoseconds(h->pts);
+        frame.sequential = h->seq;
+    } else {
+        using namespace std::chrono;
+        auto now = system_clock::now();
+        d->m_currentPresentationTimestamp = time_point_cast<nanoseconds>(now).time_since_epoch();
+    }
+
+    if (spa_meta *vd = spa_buffer_find_meta(spaBuffer, SPA_META_VideoDamage)) {
+        frame.damage = QRegion();
+        spa_meta_region *mr;
+        spa_meta_for_each(mr, vd)
+        {
+            *frame.damage += QRect(mr->region.position.x, mr->region.position.y, mr->region.size.width, mr->region.size.height);
+        }
+    }
+
+    { // process cursor
+        struct spa_meta_cursor *cursor = static_cast<struct spa_meta_cursor *>(spa_buffer_find_meta_data(spaBuffer, SPA_META_Cursor, sizeof(*cursor)));
+        if (cursor && spa_meta_cursor_is_valid(cursor)) {
+            struct spa_meta_bitmap *bitmap = nullptr;
+
+            if (cursor->bitmap_offset)
+                bitmap = SPA_MEMBER(cursor, cursor->bitmap_offset, struct spa_meta_bitmap);
+
+            QImage cursorTexture;
+            if (bitmap && bitmap->size.width > 0 && bitmap->size.height > 0) {
+                const uint8_t *bitmap_data = SPA_MEMBER(bitmap, bitmap->offset, uint8_t);
+                cursorTexture =
+                    PWHelpers::SpaBufferToQImage(bitmap_data, bitmap->size.width, bitmap->size.height, bitmap->stride, spa_video_format(bitmap->format));
+            }
+            frame.cursor = {{cursor->position.x, cursor->position.y}, {cursor->hotspot.x, cursor->hotspot.y}, cursorTexture};
+        } else {
+            frame.cursor = {{}, {}, {}};
+        }
+    }
+
+    if (spaBuffer->datas->chunk->size == 0 || spaBuffer->datas->chunk->flags == SPA_CHUNK_FLAG_CORRUPTED) {
+        // do not get a frame
+    } else if (spaBuffer->datas->type == SPA_DATA_MemFd) {
+        if (spaBuffer->datas->chunk->size == 0)
+            return;
+
+        uint8_t *map =
+            static_cast<uint8_t *>(mmap(nullptr, spaBuffer->datas->maxsize + spaBuffer->datas->mapoffset, PROT_READ, MAP_PRIVATE, spaBuffer->datas->fd, 0));
+
+        if (map == MAP_FAILED) {
+            qCWarning(PIPEWIRE_LOGGING) << "Failed to mmap the memory: " << strerror(errno);
+            return;
+        }
+        QImage img =
+            PWHelpers::SpaBufferToQImage(map, d->videoFormat.size.width, d->videoFormat.size.height, spaBuffer->datas->chunk->stride, d->videoFormat.format);
+        frame.image = img.copy();
+
+        munmap(map, spaBuffer->datas->maxsize + spaBuffer->datas->mapoffset);
+    } else if (spaBuffer->datas->type == SPA_DATA_DmaBuf) {
+        DmaBufAttributes attribs;
+        attribs.planes.reserve(spaBuffer->n_datas);
+        attribs.format = spaVideoFormatToDrmFormat(d->videoFormat.format);
+        attribs.modifier = d->videoFormat.modifier;
+        attribs.width = d->videoFormat.size.width;
+        attribs.height = d->videoFormat.size.height;
+
+        for (uint i = 0; i < spaBuffer->n_datas; ++i) {
+            const auto &data = spaBuffer->datas[i];
+
+            DmaBufPlane plane;
+            plane.fd = data.fd;
+            plane.stride = data.chunk->stride;
+            plane.offset = data.chunk->offset;
+            attribs.planes += plane;
+        }
+        Q_ASSERT(!attribs.planes.isEmpty());
+        frame.dmabuf = attribs;
+    } else if (spaBuffer->datas->type == SPA_DATA_MemPtr) {
+        frame.image = PWHelpers::SpaBufferToQImage(static_cast<uint8_t *>(spaBuffer->datas->data),
+                                                   d->videoFormat.size.width,
+                                                   d->videoFormat.size.height,
+                                                   spaBuffer->datas->chunk->stride,
+                                                   d->videoFormat.format);
+    } else {
+        if (spaBuffer->datas->type == SPA_ID_INVALID)
+            qWarning() << "invalid buffer type";
+        else
+            qWarning() << "unsupported buffer type" << spaBuffer->datas->type;
+        QImage errorImage(200, 200, QImage::Format_ARGB32_Premultiplied);
+        errorImage.fill(Qt::red);
+        frame.image = errorImage;
+    }
+
+    Q_EMIT frameReceived(frame);
+}
+
+void PipeWireSourceStream::coreFailed(const QString &errorMessage)
+{
+    qCDebug(PIPEWIRE_LOGGING) << "received error message" << errorMessage;
+    d->m_error = errorMessage;
+    Q_EMIT stopStreaming();
+}
+
+void PipeWireSourceStream::process()
+{
+    pw_buffer *buf = pw_stream_dequeue_buffer(d->pwStream);
+    if (!buf) {
+        qCDebug(PIPEWIRE_LOGGING) << "out of buffers";
+        return;
+    }
+
+    handleFrame(buf);
+
+    pw_stream_queue_buffer(d->pwStream, buf);
+}
+
+void PipeWireSourceStream::setActive(bool active)
+{
+    Q_ASSERT(d->pwStream);
+    pw_stream_set_active(d->pwStream, active);
+}
+
+void PipeWireSourceStream::setDamageEnabled(bool withDamage)
+{
+    d->m_withDamage = withDamage;
+}
diff --git a/src/pipewiresourcestream.h b/src/pipewiresourcestream.h
new file mode 100644 (file)
index 0000000..ea334b1
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+    SPDX-FileCopyrightText: 2018-2020 Red Hat Inc
+    SPDX-FileCopyrightText: 2020-2021 Aleix Pol Gonzalez <aleixpol@kde.org>
+    SPDX-FileContributor: Jan Grulich <jgrulich@redhat.com>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QHash>
+#include <QImage>
+#include <QObject>
+#include <QPoint>
+#include <QSharedPointer>
+#include <QSize>
+#include <optional>
+
+#include <pipewire/pipewire.h>
+#include <spa/param/format-utils.h>
+#include <spa/param/props.h>
+#include <spa/param/video/format-utils.h>
+
+#include <kpipewire_export.h>
+
+#undef Status
+
+class PipeWireCore;
+struct gbm_device;
+
+typedef void *EGLDisplay;
+
+struct DmaBufPlane {
+    int fd; ///< The dmabuf file descriptor
+    uint32_t offset; ///< The offset from the start of buffer
+    uint32_t stride; ///< The distance from the start of a row to the next row in bytes
+};
+
+struct DmaBufAttributes {
+    int width = 0;
+    int height = 0;
+    uint32_t format = 0;
+    uint64_t modifier = 0; ///< The layout modifier
+
+    QVector<DmaBufPlane> planes;
+};
+
+struct PipeWireCursor {
+    QPoint position;
+    QPoint hotspot;
+    QImage texture;
+};
+
+struct KPIPEWIRE_EXPORT PipeWireFrame {
+    spa_video_format format;
+    std::optional<int> sequential;
+    std::optional<std::chrono::nanoseconds> presentationTimestamp;
+    std::optional<DmaBufAttributes> dmabuf;
+    std::optional<QImage> image;
+    std::optional<QRegion> damage;
+    std::optional<PipeWireCursor> cursor;
+};
+
+struct Fraction {
+    const quint32 numerator;
+    const quint32 denominator;
+};
+
+KPIPEWIRE_EXPORT QImage::Format SpaToQImageFormat(quint32 /*spa_video_format*/ format);
+
+struct PipeWireSourceStreamPrivate;
+
+class KPIPEWIRE_EXPORT PipeWireSourceStream : public QObject
+{
+    Q_OBJECT
+public:
+    explicit PipeWireSourceStream(QObject *parent = nullptr);
+    ~PipeWireSourceStream();
+
+    Fraction framerate() const;
+    uint nodeId();
+    QString error() const;
+
+    QSize size() const;
+    pw_stream_state state() const;
+    bool createStream(uint nodeid, int fd);
+    void setActive(bool active);
+    void setDamageEnabled(bool withDamage);
+
+    void handleFrame(struct pw_buffer *buffer);
+    void process();
+    void renegotiateModifierFailed(spa_video_format format, quint64 modifier);
+
+    std::optional<std::chrono::nanoseconds> currentPresentationTimestamp() const;
+
+    static uint32_t spaVideoFormatToDrmFormat(spa_video_format spa_format);
+
+Q_SIGNALS:
+    void streamReady();
+    void startStreaming();
+    void stopStreaming();
+    void streamParametersChanged();
+    void frameReceived(const PipeWireFrame &frame);
+    void stateChanged(pw_stream_state state, pw_stream_state oldState);
+
+private:
+    static void onStreamParamChanged(void *data, uint32_t id, const struct spa_pod *format);
+    static void onStreamStateChanged(void *data, pw_stream_state old, pw_stream_state state, const char *error_message);
+    static void onRenegotiate(void *data, uint64_t);
+    QVector<const spa_pod *> createFormatsParams(spa_pod_builder podBuilder);
+
+    void coreFailed(const QString &errorMessage);
+    QScopedPointer<PipeWireSourceStreamPrivate> d;
+};
+
+Q_DECLARE_METATYPE(QVector<DmaBufPlane>);
diff --git a/src/pwhelpers.cpp b/src/pwhelpers.cpp
new file mode 100644 (file)
index 0000000..1bceb5b
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+    SPDX-FileCopyrightText: 2023 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "pwhelpers.h"
+#include "logging.h"
+
+QImage::Format SpaToQImageFormat(quint32 format)
+{
+    switch (format) {
+    case SPA_VIDEO_FORMAT_BGRx:
+    case SPA_VIDEO_FORMAT_BGRA:
+        return QImage::Format_RGBA8888_Premultiplied; // TODO: Add BGR to QImage
+    case SPA_VIDEO_FORMAT_BGR:
+        return QImage::Format_BGR888;
+    case SPA_VIDEO_FORMAT_RGBx:
+        return QImage::Format_RGBX8888;
+    case SPA_VIDEO_FORMAT_RGB:
+        return QImage::Format_RGB888;
+    case SPA_VIDEO_FORMAT_RGBA:
+        return QImage::Format_RGBA8888_Premultiplied;
+    default:
+        qCWarning(PIPEWIRE_LOGGING) << "unknown spa format" << format;
+        return QImage::Format_RGB32;
+    }
+}
+
+QImage PWHelpers::SpaBufferToQImage(const uchar *data, int width, int height, qsizetype bytesPerLine, spa_video_format format)
+{
+    switch (format) {
+    case SPA_VIDEO_FORMAT_BGRx:
+    case SPA_VIDEO_FORMAT_BGRA: {
+        // This is needed because QImage does not support BGRA
+        // This is obviously a much slower path, it makes sense to avoid it as much as possible
+        return QImage(data, width, height, bytesPerLine, SpaToQImageFormat(format)).rgbSwapped();
+    }
+    case SPA_VIDEO_FORMAT_BGR:
+    case SPA_VIDEO_FORMAT_RGBx:
+    case SPA_VIDEO_FORMAT_RGB:
+    case SPA_VIDEO_FORMAT_RGBA:
+    default:
+        return QImage(data, width, height, bytesPerLine, SpaToQImageFormat(format));
+    }
+}
diff --git a/src/pwhelpers.h b/src/pwhelpers.h
new file mode 100644 (file)
index 0000000..592f712
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+    SPDX-FileCopyrightText: 2023 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include "pipewiresourcestream.h"
+#include <QByteArray>
+#include <epoxy/egl.h>
+#include <kpipewire_export.h>
+
+typedef unsigned int GLenum;
+
+namespace PWHelpers
+{
+
+KPIPEWIRE_EXPORT QImage SpaBufferToQImage(const uchar *data, int width, int height, qsizetype bytesPerLine, spa_video_format format);
+
+}
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
new file mode 100644 (file)
index 0000000..8d86243
--- /dev/null
@@ -0,0 +1,53 @@
+add_library(PipeWireScreencastingTest STATIC screencasting.cpp screencastingrequest.cpp)
+
+qt_add_dbus_interface(
+   SRCS
+   org.freedesktop.portal.ScreenCast.xml
+   xdp_dbus_screencast_interface
+)
+
+qt_add_dbus_interface(
+   SRCS
+   org.freedesktop.portal.RemoteDesktop.xml
+   xdp_dbus_remotedesktop_interface
+)
+
+if (QT_MAJOR_VERSION EQUAL "5")
+    ecm_add_qtwayland_client_protocol(PipeWireScreencastingTest
+        PROTOCOL ${PLASMA_WAYLAND_PROTOCOLS_DIR}/zkde-screencast-unstable-v1.xml
+        BASENAME zkde-screencast-unstable-v1
+    )
+else()
+    qt6_generate_wayland_protocol_client_sources(PipeWireScreencastingTest FILES
+        ${PLASMA_WAYLAND_PROTOCOLS_DIR}/zkde-screencast-unstable-v1.xml)
+endif()
+
+target_link_libraries(PipeWireScreencastingTest PUBLIC KF5::WaylandClient Wayland::Client Qt::DBus Qt::GuiPrivate KPipeWire Qt::WaylandClient)
+
+add_executable(recordme main.cpp recordme.qrc PlasmaRecordMe.cpp)
+target_link_libraries(recordme PipeWireScreencastingTest Qt::Quick)
+
+add_executable(kpipewireheadlesstest HeadlessTest.cpp ${SRCS})
+target_link_libraries(kpipewireheadlesstest PipeWireScreencastingTest KPipeWireDmaBuf)
+
+#########
+
+qt_add_dbus_interface(
+   XDP_SRCS
+   org.freedesktop.portal.ScreenCast.xml
+   xdp_dbus_screencast_interface
+)
+
+add_executable(xdp-recordme xdp-main.cpp recordme.qrc ${XDP_SRCS} RecordMe.cpp)
+target_link_libraries(xdp-recordme Qt::DBus Qt::Quick KPipeWire Qt::GuiPrivate Wayland::Client KF5::WaylandClient Qt::WaylandClient )
+
+option(INSTALL_TESTS "The recordme test needs installing, disabled by default for convenience" OFF)
+if(INSTALL_TESTS)
+   configure_file(org.kde.recordme.desktop.cmake ${CMAKE_CURRENT_BINARY_DIR}/org.kde.recordme.desktop @ONLY)
+   configure_file(org.kde.kpipewireheadlesstest.desktop.cmake ${CMAKE_CURRENT_BINARY_DIR}/org.kde.kpipewireheadlesstest.desktop @ONLY)
+
+   install(TARGETS recordme kpipewireheadlesstest DESTINATION ${KDE_INSTALL_TARGETS_DEFAULT_ARGS})
+   install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/org.kde.recordme.desktop DESTINATION ${KDE_INSTALL_APPDIR})
+   install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/org.kde.kpipewireheadlesstest.desktop DESTINATION ${KDE_INSTALL_APPDIR})
+   install(TARGETS xdp-recordme DESTINATION ${KDE_INSTALL_TARGETS_DEFAULT_ARGS})
+endif()
diff --git a/tests/HeadlessTest.cpp b/tests/HeadlessTest.cpp
new file mode 100644 (file)
index 0000000..6ec2c6e
--- /dev/null
@@ -0,0 +1,467 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include <QCommandLineParser>
+#include <QDebug>
+#include <QGuiApplication>
+#include <QScreen>
+
+#include "screencasting.h"
+#include "xdp_dbus_remotedesktop_interface.h"
+#include "xdp_dbus_screencast_interface.h"
+#include <DmaBufHandler>
+#include <PipeWireSourceStream>
+#include <QDBusArgument>
+#include <unistd.h>
+
+static QString createHandleToken()
+{
+    return QStringLiteral("kpipewireheadlesstest%1").arg(QRandomGenerator::global()->generate());
+}
+
+void checkPlasmaScreens()
+{
+    auto screencasting = new Screencasting(qGuiApp);
+    for (auto screen : qGuiApp->screens()) {
+        auto stream = screencasting->createOutputStream(screen->name(), Screencasting::Embedded);
+        QObject::connect(stream, &ScreencastingStream::created, qGuiApp, [stream] {
+            auto pwStream = new PipeWireSourceStream(qGuiApp);
+            if (!pwStream->createStream(stream->nodeId(), 0)) {
+                qWarning() << "failed!" << pwStream->error();
+                exit(1);
+            }
+
+            auto handler = std::make_shared<DmaBufHandler>();
+            QObject::connect(pwStream, &PipeWireSourceStream::frameReceived, qGuiApp, [handler, pwStream](const PipeWireFrame &frame) {
+                QImage qimage(pwStream->size(), QImage::Format_RGBA8888);
+                if (!handler->downloadFrame(qimage, frame)) {
+                    qDebug() << "failed to download frame";
+                    pwStream->renegotiateModifierFailed(frame.format, frame.dmabuf->modifier);
+                } else {
+                    qDebug() << ".";
+                }
+            });
+        });
+    }
+}
+
+void checkPlasmaWorkspace()
+{
+    auto screencasting = new Screencasting(qGuiApp);
+    QRegion region;
+    for (auto screen : qGuiApp->screens()) {
+        region |= screen->geometry();
+    }
+    auto stream = screencasting->createRegionStream(region.boundingRect(), 1, Screencasting::Embedded);
+    QObject::connect(stream, &ScreencastingStream::created, qGuiApp, [stream] {
+        auto pwStream = new PipeWireSourceStream(qGuiApp);
+        if (!pwStream->createStream(stream->nodeId(), 0)) {
+            qWarning() << "failed!" << pwStream->error();
+            exit(1);
+        }
+
+        auto handler = std::make_shared<DmaBufHandler>();
+        QObject::connect(pwStream, &PipeWireSourceStream::frameReceived, qGuiApp, [handler, pwStream](const PipeWireFrame &frame) {
+            QImage qimage(pwStream->size(), QImage::Format_RGBA8888);
+            if (!handler->downloadFrame(qimage, frame)) {
+                qDebug() << "failed to download frame";
+                pwStream->renegotiateModifierFailed(frame.format, frame.dmabuf->modifier);
+            } else {
+                qDebug() << ".";
+            }
+        });
+    });
+}
+
+using Stream = struct {
+    uint nodeId;
+    QVariantMap map;
+};
+using Streams = QList<Stream>;
+
+Q_DECLARE_METATYPE(Stream);
+Q_DECLARE_METATYPE(Streams);
+
+const QDBusArgument &operator>>(const QDBusArgument &arg, Stream &stream)
+{
+    arg.beginStructure();
+    arg >> stream.nodeId;
+
+    arg.beginMap();
+    while (!arg.atEnd()) {
+        QString key;
+        QVariant map;
+        arg.beginMapEntry();
+        arg >> key >> map;
+        arg.endMapEntry();
+        stream.map.insert(key, map);
+    }
+    arg.endMap();
+    arg.endStructure();
+
+    return arg;
+}
+
+class XdpScreenCast : public QObject
+{
+    Q_OBJECT
+public:
+    XdpScreenCast(QObject *parent)
+        : QObject(parent)
+    {
+        initDbus();
+    }
+
+    void initDbus()
+    {
+        dbusXdpScreenCastService.reset(new OrgFreedesktopPortalScreenCastInterface(QStringLiteral("org.freedesktop.portal.Desktop"),
+                                                                                   QStringLiteral("/org/freedesktop/portal/desktop"),
+                                                                                   QDBusConnection::sessionBus()));
+
+        qInfo() << "Initializing D-Bus connectivity with XDG Desktop Portal" << dbusXdpScreenCastService->version();
+        Q_ASSERT(dbusXdpScreenCastService->isValid());
+
+        // create session
+        auto sessionParameters =
+            QVariantMap{{QStringLiteral("session_handle_token"), createHandleToken()}, {QStringLiteral("handle_token"), createHandleToken()}};
+        auto sessionReply = dbusXdpScreenCastService->CreateSession(sessionParameters);
+        sessionReply.waitForFinished();
+        if (!sessionReply.isValid()) {
+            qWarning() << "Couldn't initialize XDP-KDE screencast session" << sessionReply.error();
+            exit(1);
+            return;
+        }
+
+        qInfo() << "DBus session created: " << sessionReply.value().path()
+                << QDBusConnection::sessionBus().connect(QString(),
+                                                         sessionReply.value().path(),
+                                                         QStringLiteral("org.freedesktop.portal.Request"),
+                                                         QStringLiteral("Response"),
+                                                         this,
+                                                         SLOT(handleSessionCreated(uint, QVariantMap)));
+    }
+
+public Q_SLOTS:
+    void handleSessionCreated(quint32 code, const QVariantMap &results)
+    {
+        if (code != 0) {
+            qWarning() << "Failed to create session: " << code;
+            exit(1);
+            return;
+        }
+
+        sessionPath = QDBusObjectPath(results.value(QStringLiteral("session_handle")).toString());
+
+        // select sources for the session
+        const QVariantMap sourcesParameters = {{QLatin1String("handle_token"), createHandleToken()},
+                                               {QLatin1String("types"), dbusXdpScreenCastService->availableSourceTypes()},
+                                               {QLatin1String("multiple"), false},
+                                               {QLatin1String("cursor_mode"), uint(2 /*Embedded*/)}};
+        auto selectorReply = dbusXdpScreenCastService->SelectSources(sessionPath, sourcesParameters);
+        selectorReply.waitForFinished();
+        if (!selectorReply.isValid()) {
+            qWarning() << "Couldn't select devices for the remote-desktop session";
+            exit(1);
+            return;
+        }
+        QDBusConnection::sessionBus().connect(QString(),
+                                              selectorReply.value().path(),
+                                              QStringLiteral("org.freedesktop.portal.Request"),
+                                              QStringLiteral("Response"),
+                                              this,
+                                              SLOT(handleSourcesSelected(uint, QVariantMap)));
+    }
+
+    void handleSourcesSelected(quint32 code, const QVariantMap &)
+    {
+        if (code != 0) {
+            qWarning() << "Failed to select sources: " << code;
+            exit(1);
+            return;
+        }
+
+        // start session
+        auto startParameters = QVariantMap{{QStringLiteral("handle_token"), createHandleToken()}};
+        auto startReply = dbusXdpScreenCastService->Start(sessionPath, QString(), startParameters);
+        startReply.waitForFinished();
+        QDBusConnection::sessionBus().connect(QString(),
+                                              startReply.value().path(),
+                                              QStringLiteral("org.freedesktop.portal.Request"),
+                                              QStringLiteral("Response"),
+                                              this,
+                                              SLOT(handleRemoteDesktopStarted(uint, QVariantMap)));
+    }
+
+    void handleRemoteDesktopStarted(quint32 code, const QVariantMap &results)
+    {
+        if (code != 0) {
+            qWarning() << "Failed to start screencast: " << code;
+            exit(1);
+            return;
+        }
+
+        // there should be only one stream
+        const Streams streams = qdbus_cast<Streams>(results.value(QStringLiteral("streams")));
+        if (streams.isEmpty()) {
+            // maybe we should check deeper with qdbus_cast but this suffices for now
+            qWarning() << "Failed to get screencast streams";
+            exit(1);
+            return;
+        }
+
+        const QVariantMap startParameters = {
+            { QLatin1String("handle_token"), createHandleToken() }
+        };
+
+        auto streamReply = dbusXdpScreenCastService->OpenPipeWireRemote(sessionPath, startParameters);
+        streamReply.waitForFinished();
+        if (!streamReply.isValid()) {
+            qWarning() << "Couldn't open pipewire remote for the screen-casting session";
+            exit(1);
+            return;
+        }
+
+        auto pipewireFd = streamReply.value();
+        if (!pipewireFd.isValid()) {
+            qWarning() << "Couldn't get pipewire connection file descriptor";
+            exit(1);
+            return;
+        }
+
+        const int fd = pipewireFd.takeFileDescriptor();
+        if (!stream.createStream(streams.first().nodeId, fd)) {
+            qWarning() << "Couldn't create the pipewire stream";
+            exit(1);
+            return;
+        }
+
+        QObject::connect(&stream, &PipeWireSourceStream::frameReceived, this, [](const PipeWireFrame &frame) {
+            qDebug() << "." << frame.format;
+        });
+
+        QObject::connect(&stream, &PipeWireSourceStream::stopStreaming, this, [fd] {
+            close(fd);
+        });
+    }
+
+private:
+    QScopedPointer<OrgFreedesktopPortalScreenCastInterface> dbusXdpScreenCastService;
+    QDBusObjectPath sessionPath;
+    PipeWireSourceStream stream;
+};
+
+class XdpRemoteDesktop : public QObject
+{
+    Q_OBJECT
+public:
+    XdpRemoteDesktop(QObject *parent)
+        : QObject(parent)
+    {
+        initDbus();
+    }
+
+    void initDbus()
+    {
+        dbusXdpScreenCastService.reset(new OrgFreedesktopPortalScreenCastInterface(QStringLiteral("org.freedesktop.portal.Desktop"),
+                                                                                   QStringLiteral("/org/freedesktop/portal/desktop"),
+                                                                                   QDBusConnection::sessionBus()));
+        dbusXdpRemoteDesktopService.reset(new OrgFreedesktopPortalRemoteDesktopInterface(QStringLiteral("org.freedesktop.portal.Desktop"),
+                                                                                         QStringLiteral("/org/freedesktop/portal/desktop"),
+                                                                                         QDBusConnection::sessionBus()));
+
+        qInfo() << "Initializing D-Bus connectivity with XDG Desktop Portal" << dbusXdpScreenCastService->version();
+        Q_ASSERT(dbusXdpScreenCastService->isValid());
+        Q_ASSERT(dbusXdpRemoteDesktopService->isValid());
+
+        // create session
+        auto sessionParameters =
+            QVariantMap{{QStringLiteral("session_handle_token"), createHandleToken()}, {QStringLiteral("handle_token"), createHandleToken()}};
+        auto sessionReply = dbusXdpRemoteDesktopService->CreateSession(sessionParameters);
+        sessionReply.waitForFinished();
+        if (!sessionReply.isValid()) {
+            qWarning() << "Couldn't initialize XDP-KDE screencast session" << sessionReply.error();
+            exit(1);
+            return;
+        }
+
+        qInfo() << "DBus session created: " << sessionReply.value().path()
+                << QDBusConnection::sessionBus().connect(QString(),
+                                                         sessionReply.value().path(),
+                                                         QStringLiteral("org.freedesktop.portal.Request"),
+                                                         QStringLiteral("Response"),
+                                                         this,
+                                                         SLOT(handleSessionCreated(uint, QVariantMap)));
+    }
+
+public Q_SLOTS:
+    void handleSessionCreated(quint32 code, const QVariantMap &results)
+    {
+        if (code != 0) {
+            qWarning() << "Failed to create session: " << code;
+            exit(1);
+            return;
+        }
+
+        sessionPath = QDBusObjectPath(results.value(QStringLiteral("session_handle")).toString());
+
+        // select sources for the session
+        auto selectionOptions = QVariantMap{// We have to specify it's an uint, otherwise xdg-desktop-portal will not forward it to backend implementation
+                                            {QStringLiteral("types"), QVariant::fromValue<uint>(7)}, // request all (KeyBoard, Pointer, TouchScreen)
+                                            {QStringLiteral("handle_token"), createHandleToken()}};
+        auto selectorReply = dbusXdpRemoteDesktopService->SelectDevices(sessionPath, selectionOptions);
+        selectorReply.waitForFinished();
+        if (!selectorReply.isValid()) {
+            qWarning() << "Couldn't select devices for the remote-desktop session";
+            exit(1);
+            return;
+        }
+        QDBusConnection::sessionBus().connect(QString(),
+                                              selectorReply.value().path(),
+                                              QStringLiteral("org.freedesktop.portal.Request"),
+                                              QStringLiteral("Response"),
+                                              this,
+                                              SLOT(handleDevicesSelected(uint, QVariantMap)));
+    }
+
+    void handleDevicesSelected(quint32 code, const QVariantMap &results)
+    {
+        Q_UNUSED(results)
+        if (code != 0) {
+            qWarning() << "Failed to select devices: " << code;
+            exit(1);
+            return;
+        }
+
+        // select sources for the session
+        auto selectionOptions = QVariantMap{{QStringLiteral("types"), QVariant::fromValue<uint>(7)},
+                                            {QStringLiteral("multiple"), false},
+                                            {QStringLiteral("handle_token"), createHandleToken()}};
+        auto selectorReply = dbusXdpScreenCastService->SelectSources(sessionPath, selectionOptions);
+        selectorReply.waitForFinished();
+        if (!selectorReply.isValid()) {
+            qWarning() << "Couldn't select sources for the screen-casting session";
+            exit(1);
+            return;
+        }
+        QDBusConnection::sessionBus().connect(QString(),
+                                              selectorReply.value().path(),
+                                              QStringLiteral("org.freedesktop.portal.Request"),
+                                              QStringLiteral("Response"),
+                                              this,
+                                              SLOT(handleSourcesSelected(uint, QVariantMap)));
+    }
+
+    void handleSourcesSelected(quint32 code, const QVariantMap &)
+    {
+        if (code != 0) {
+            qWarning() << "Failed to select sources: " << code;
+            exit(1);
+            return;
+        }
+
+        // start session
+        auto startParameters = QVariantMap{{QStringLiteral("handle_token"), createHandleToken()}};
+        auto startReply = dbusXdpRemoteDesktopService->Start(sessionPath, QString(), startParameters);
+        startReply.waitForFinished();
+        QDBusConnection::sessionBus().connect(QString(),
+                                              startReply.value().path(),
+                                              QStringLiteral("org.freedesktop.portal.Request"),
+                                              QStringLiteral("Response"),
+                                              this,
+                                              SLOT(handleRemoteDesktopStarted(uint, QVariantMap)));
+    }
+
+    void handleRemoteDesktopStarted(quint32 code, const QVariantMap &results)
+    {
+        if (code != 0) {
+            qWarning() << "Failed to start screencast: " << code;
+            exit(1);
+            return;
+        }
+
+        if (results.value(QStringLiteral("devices")).toUInt() == 0) {
+            qWarning() << "No devices were granted" << results;
+            exit(1);
+            return;
+        }
+
+        // there should be only one stream
+        const Streams streams = qdbus_cast<Streams>(results.value(QStringLiteral("streams")));
+        if (streams.isEmpty()) {
+            // maybe we should check deeper with qdbus_cast but this suffices for now
+            qWarning() << "Failed to get screencast streams";
+            exit(1);
+            return;
+        }
+
+        auto streamReply = dbusXdpScreenCastService->OpenPipeWireRemote(sessionPath, QVariantMap());
+        streamReply.waitForFinished();
+        if (!streamReply.isValid()) {
+            qWarning() << "Couldn't open pipewire remote for the screen-casting session";
+            exit(1);
+            return;
+        }
+
+        auto pipewireFd = streamReply.value();
+        if (!pipewireFd.isValid()) {
+            qWarning() << "Couldn't get pipewire connection file descriptor";
+            exit(1);
+            return;
+        }
+
+        const uint fd = pipewireFd.takeFileDescriptor();
+        if (!stream.createStream(streams.first().nodeId, fd)) {
+            qWarning() << "Couldn't create the pipewire stream";
+            exit(1);
+            return;
+        }
+
+        QObject::connect(&stream, &PipeWireSourceStream::frameReceived, this, [](const PipeWireFrame &frame) {
+            qDebug() << "." << frame.format;
+        });
+
+        QObject::connect(&stream, &PipeWireSourceStream::stopStreaming, this, [fd] {
+            close(fd);
+        });
+    }
+
+private:
+    QScopedPointer<OrgFreedesktopPortalScreenCastInterface> dbusXdpScreenCastService;
+    QScopedPointer<OrgFreedesktopPortalRemoteDesktopInterface> dbusXdpRemoteDesktopService;
+    QDBusObjectPath sessionPath;
+    PipeWireSourceStream stream;
+};
+
+int main(int argc, char **argv)
+{
+    QGuiApplication app(argc, argv);
+
+    {
+        QCommandLineParser parser;
+        QCommandLineOption useXdpRD(QStringLiteral("xdp-remotedesktop"), QStringLiteral("Uses the XDG Desktop Portal RemoteDesktop interface"));
+        parser.addOption(useXdpRD);
+        QCommandLineOption useXdpSC(QStringLiteral("xdp-screencast"), QStringLiteral("Uses the XDG Desktop Portal ScreenCast interface"));
+        parser.addOption(useXdpSC);
+        QCommandLineOption useWorkspace(QStringLiteral("workspace"), QStringLiteral("Uses the Plasma screencasting workspace feed"));
+        parser.addOption(useWorkspace);
+        parser.addHelpOption();
+        parser.process(app);
+
+        if (parser.isSet(useXdpRD)) {
+            new XdpRemoteDesktop(&app);
+        } else if (parser.isSet(useXdpSC)) {
+            new XdpScreenCast(&app);
+        } else if (parser.isSet(useWorkspace)) {
+            checkPlasmaWorkspace();
+        } else {
+            checkPlasmaScreens();
+        }
+    }
+
+    return app.exec();
+}
+
+#include "HeadlessTest.moc"
diff --git a/tests/PlasmaRecordMe.cpp b/tests/PlasmaRecordMe.cpp
new file mode 100644 (file)
index 0000000..2c1b2ab
--- /dev/null
@@ -0,0 +1,180 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "PlasmaRecordMe.h"
+#include <QCoreApplication>
+#include <QDir>
+#include <QGuiApplication>
+#include <QLoggingCategory>
+#include <QProcess>
+#include <QQmlApplicationEngine>
+#include <QQmlContext>
+#include <QQuickItem>
+#include <QQuickView>
+#include <QRegularExpression>
+#include <QScreen>
+#include <QThread>
+#include <QTimer>
+
+#include <KWayland/Client/event_queue.h>
+#include <KWayland/Client/connection_thread.h>
+#include <KWayland/Client/output.h>
+#include <KWayland/Client/xdgoutput.h>
+#include <KWayland/Client/registry.h>
+#include <KWayland/Client/plasmawindowmanagement.h>
+
+using namespace KWayland::Client;
+
+PlasmaRecordMe::PlasmaRecordMe(Screencasting::CursorMode cursorMode, const QString &source, QObject *parent)
+    : QObject(parent)
+    , m_cursorMode(cursorMode)
+    , m_durationTimer(new QTimer(this))
+    , m_sourceName(source)
+    , m_engine(new QQmlApplicationEngine(this))
+{
+    m_engine->setInitialProperties({
+        { QStringLiteral("app"), QVariant::fromValue<QObject *>(this) },
+    });
+    m_engine->load(QUrl(QStringLiteral("qrc:/main.qml")));
+
+    auto connection = ConnectionThread::fromApplication(this);
+    if (!connection) {
+        qWarning() << "Failed getting Wayland connection from QPA";
+        QCoreApplication::exit(1);
+        return;
+    }
+
+    m_durationTimer->setSingleShot(true);
+    auto registry = new Registry(qApp);
+    connect(registry, &KWayland::Client::Registry::plasmaWindowManagementAnnounced, this, [this, registry] (quint32 name, quint32 version) {
+        m_management = registry->createPlasmaWindowManagement(name, version, this);
+        auto addWindow = [this] (KWayland::Client::PlasmaWindow *window) {
+            const QRegularExpression rx(m_sourceName);
+            const auto match = rx.match(window->appId());
+            if (match.hasMatch()) {
+                auto f = [this, window] {
+                    start(m_screencasting->createWindowStream(window, m_cursorMode));
+                };
+                qDebug() << "window" << window << window->uuid() << m_sourceName << m_screencasting;
+                if (m_screencasting)
+                    f();
+                else
+                    m_delayed << f;
+            }
+        };
+        for (auto w : m_management->windows())
+            addWindow(w);
+        connect(m_management, &KWayland::Client::PlasmaWindowManagement::windowCreated, this, addWindow);
+    });
+
+    connect(registry, &KWayland::Client::Registry::outputAnnounced, this, [this, registry] (quint32 name, quint32 version) {
+            auto output = new KWayland::Client::Output(this);
+            output->setup(registry->bindOutput(name, version));
+
+            connect(output, &Output::changed, this, [this, output] {
+                const QRegularExpression rx(m_sourceName);
+                const auto match = rx.match(output->model());
+                if (match.hasMatch()) {
+                    auto f = [this, output] {
+                        start(m_screencasting->createOutputStream(output, m_cursorMode));
+                    };
+                    connect(this, &PlasmaRecordMe::cursorModeChanged, output, f);
+                    if (m_screencasting)
+                        f();
+                    else
+                        m_delayed << f;
+                }
+            });
+    });
+
+    if (m_sourceName.isEmpty() || m_sourceName == QLatin1String("region")) {
+        connect(this, &PlasmaRecordMe::workspaceChanged, this, [this] {
+            delete m_workspaceStream;
+            m_workspaceStream = m_screencasting->createRegionStream(m_workspace, 1, m_cursorMode);
+            start(m_workspaceStream);
+        });
+    }
+
+    registry->create(connection);
+    registry->setup();
+
+    m_screencasting = new Screencasting(this);
+
+    bool ok = false;
+    auto node = m_sourceName.toInt(&ok);
+    if (ok) {
+        const auto roots = m_engine->rootObjects();
+        for (auto root : roots) {
+            auto mo = root->metaObject();
+            mo->invokeMethod(root,
+                             "addStream",
+                             Q_ARG(QVariant, QVariant::fromValue<int>(node)),
+                             Q_ARG(QVariant, QStringLiteral("raw node %1").arg(node)),
+                             Q_ARG(QVariant, 0));
+        }
+    }
+
+    for (auto screen : qGuiApp->screens()) {
+        m_workspace |= screen->geometry();
+    }
+    Q_EMIT workspaceChanged();
+}
+
+PlasmaRecordMe::~PlasmaRecordMe()
+{
+}
+
+void PlasmaRecordMe::start(ScreencastingStream *stream)
+{
+    qDebug() << "start" << stream;
+    connect(stream, &ScreencastingStream::failed, this, [this] (const QString &error) {
+        qWarning() << "stream failed" << error;const auto roots = m_engine->rootObjects();
+        for (auto root : roots) {
+            auto mo = root->metaObject();
+            mo->invokeMethod(root, "showPassiveNotification", Qt::QueuedConnection, Q_ARG(QVariant, QVariant(error))
+                                                                                  , Q_ARG(QVariant, {})
+                                                                                  , Q_ARG(QVariant, {})
+                                                                                  , Q_ARG(QVariant, {})
+            );
+        }
+    });
+    connect(stream, &ScreencastingStream::closed, this, [this, stream] {
+        auto nodeId = stream->property("nodeid").toInt();
+        qDebug() << "bye bye" << stream << nodeId;
+
+        const auto roots = m_engine->rootObjects();
+        for (auto root : roots) {
+            auto mo = root->metaObject();
+            mo->invokeMethod(root, "removeStream", Qt::QueuedConnection, Q_ARG(QVariant, QVariant::fromValue<quint32>(nodeId)));
+        }
+    });
+    connect(stream, &ScreencastingStream::created, this, [this, stream] (quint32 nodeId)
+        {
+            stream->setProperty("nodeid", nodeId);
+            qDebug() << "starting..." << nodeId;
+            const auto roots = m_engine->rootObjects();
+            for (auto root : roots) {
+                auto mo = root->metaObject();
+                mo->invokeMethod(root,
+                                 "addStream",
+                                 Q_ARG(QVariant, QVariant::fromValue<quint32>(nodeId)),
+                                 Q_ARG(QVariant, stream->objectName()),
+                                 Q_ARG(QVariant, 0));
+            }
+        }
+    );
+    connect(this, &PlasmaRecordMe::cursorModeChanged, stream, &ScreencastingStream::closed);
+}
+
+void PlasmaRecordMe::setDuration(int duration)
+{
+    m_durationTimer->setInterval(duration);
+}
+
+void PlasmaRecordMe::createVirtualMonitor()
+{
+    m_screencasting->createVirtualMonitorStream(QStringLiteral("recordme"), {1920, 1080}, 1, m_cursorMode);
+}
diff --git a/tests/PlasmaRecordMe.h b/tests/PlasmaRecordMe.h
new file mode 100644 (file)
index 0000000..e933a6f
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QDBusObjectPath>
+#include <QObject>
+#include <QRect>
+#include <screencasting.h>
+
+class QQmlApplicationEngine;
+class QTimer;
+class Screencasting;
+
+namespace KWayland {
+    namespace Client {
+        class Registry;
+        class PlasmaWindowManagement;
+        class Output;
+        class XdgOutputManager;
+    }
+}
+class ScreencastingStream;
+class OrgFreedesktopPortalScreenCastInterface;
+
+class PlasmaRecordMe : public QObject
+{
+    Q_OBJECT
+public:
+    PlasmaRecordMe(Screencasting::CursorMode cursorMode, const QString &source, QObject *parent = nullptr);
+    ~PlasmaRecordMe() override;
+
+    void setDuration(int duration);
+
+    Q_SCRIPTABLE void createVirtualMonitor();
+
+Q_SIGNALS:
+    void cursorModeChanged(Screencasting::CursorMode cursorMode);
+    void workspaceChanged();
+
+private:
+    void start(ScreencastingStream* stream);
+
+    const Screencasting::CursorMode m_cursorMode;
+    QTimer* const m_durationTimer;
+    const QString m_sourceName;
+    QVector<std::function<void()>> m_delayed;
+    KWayland::Client::PlasmaWindowManagement* m_management = nullptr;
+    Screencasting* m_screencasting = nullptr;
+    QQmlApplicationEngine* m_engine;
+    ScreencastingStream *m_workspaceStream = nullptr;
+    QRect m_workspace;
+};
diff --git a/tests/RecordMe.cpp b/tests/RecordMe.cpp
new file mode 100644 (file)
index 0000000..e00ef83
--- /dev/null
@@ -0,0 +1,201 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "RecordMe.h"
+#include <QLoggingCategory>
+#include <QQmlApplicationEngine>
+#include <QQmlContext>
+#include <QTimer>
+
+#include "xdp_dbus_screencast_interface.h"
+
+Q_DECLARE_METATYPE(Stream)
+
+QDebug operator<<(QDebug debug, const Stream& plug)
+{
+    QDebugStateSaver saver(debug);
+    debug.nospace() << "Stream(id: " << plug.id << ", opts: " << plug.opts << ')';
+    return debug;
+}
+
+
+const QDBusArgument &operator<<(const QDBusArgument &argument, const Stream &/*stream*/)
+{
+    argument.beginStructure();
+//     argument << stream.id << stream.opts;
+    argument.endStructure();
+    return argument;
+}
+
+const QDBusArgument &operator>>(const QDBusArgument &argument, Stream &stream)
+{
+    argument.beginStructure();
+    argument >> stream.id >> stream.opts;
+    argument.endStructure();
+    return argument;
+}
+
+const QDBusArgument &operator>>(const QDBusArgument &argument, QVector<Stream> &stream)
+{
+    argument.beginArray();
+    while ( !argument.atEnd() ) {
+        Stream element;
+        argument >> element;
+        stream.append( element );
+    }
+    argument.endArray();
+    return argument;
+}
+
+RecordMe::RecordMe(QObject* parent)
+    : QObject(parent)
+    , iface(new OrgFreedesktopPortalScreenCastInterface(
+        QLatin1String("org.freedesktop.portal.Desktop"), QLatin1String("/org/freedesktop/portal/desktop"), QDBusConnection::sessionBus(), this))
+    , m_durationTimer(new QTimer(this))
+    , m_handleToken(QStringLiteral("RecordMe%1").arg(QRandomGenerator::global()->generate()))
+    , m_engine(new QQmlApplicationEngine(this))
+{
+    m_engine->rootContext()->setContextProperty(QStringLiteral("app"), this);
+    m_engine->load(QUrl(QStringLiteral("qrc:/main.qml")));
+
+    // create session
+    const auto sessionParameters = QVariantMap {
+        { QLatin1String("session_handle_token"), m_handleToken },
+        { QLatin1String("handle_token"), m_handleToken }
+    };
+    auto sessionReply = iface->CreateSession(sessionParameters);
+    sessionReply.waitForFinished();
+    if (!sessionReply.isValid()) {
+        qWarning("Couldn't initialize the remote control session");
+        exit(1);
+        return;
+    }
+
+    const bool ret = QDBusConnection::sessionBus().connect(QString(),
+                                                           sessionReply.value().path(),
+                                                           QLatin1String("org.freedesktop.portal.Request"),
+                                                           QLatin1String("Response"),
+                                                           this,
+                                                           SLOT(response(uint, QVariantMap)));
+    if (!ret) {
+        qWarning() << "failed to create session";
+        exit(2);
+        return;
+    }
+
+    qDBusRegisterMetaType<Stream>();
+    qDBusRegisterMetaType<QVector<Stream>>();
+
+    m_durationTimer->setSingleShot(true);
+}
+
+RecordMe::~RecordMe() = default;
+
+void RecordMe::init(const QDBusObjectPath& path)
+{
+    m_path = path;
+    {
+        uint32_t cursor_mode;
+        if (iface->availableCursorModes() & Metadata) {
+            cursor_mode = Metadata;
+        } else {
+            cursor_mode = Hidden;
+        }
+        const QVariantMap sourcesParameters = {{QLatin1String("handle_token"), m_handleToken},
+                                               {QLatin1String("types"), iface->availableSourceTypes()},
+                                               {QLatin1String("multiple"), false}, // for now?
+                                               {QLatin1String("cursor_mode"), uint(cursor_mode)}};
+
+        auto reply = iface->SelectSources(m_path, sourcesParameters);
+        reply.waitForFinished();
+
+        if (reply.isError()) {
+            qWarning() << "Could not select sources" << reply.error();
+            exit(1);
+            return;
+        }
+        qDebug() << "select sources done" << reply.value().path();
+    }
+}
+
+void RecordMe::response(uint code, const QVariantMap& results)
+{
+    if (code > 0) {
+        qWarning() << "error!!!" << code << results;
+        exit(666);
+        return;
+    }
+
+    const auto streamsIt = results.constFind(QStringLiteral("streams"));
+    if (streamsIt != results.constEnd()) {
+        QVector<Stream> streams;
+        streamsIt->value<QDBusArgument>() >> streams;
+
+        handleStreams(streams);
+        return;
+    }
+
+    const auto handleIt = results.constFind(QStringLiteral("session_handle"));
+    if (handleIt != results.constEnd()) {
+        init(QDBusObjectPath(handleIt->toString()));
+        return;
+    }
+
+    qDebug() << "params" << results << code;
+    if (results.isEmpty()) {
+        start();
+        return;
+    }
+}
+
+void RecordMe::start()
+{
+    const QVariantMap startParameters = {
+        { QLatin1String("handle_token"), m_handleToken }
+    };
+
+    auto reply = iface->Start(m_path, QStringLiteral("org.freedesktop.RecordMe"), startParameters);
+    reply.waitForFinished();
+
+    if (reply.isError()) {
+        qWarning() << "Could not start stream" << reply.error();
+        exit(1);
+        return;
+    }
+    qDebug() << "started!" << reply.value().path();
+}
+
+void RecordMe::handleStreams(const QVector<Stream> &streams)
+{
+    const QVariantMap startParameters = {
+        { QLatin1String("handle_token"), m_handleToken }
+    };
+
+    auto reply = iface->OpenPipeWireRemote(m_path, startParameters);
+    reply.waitForFinished();
+
+    if (reply.isError()) {
+        qWarning() << "Could not start stream" << reply.error();
+        exit(1);
+        return;
+    }
+
+    const int fd = reply.value().takeFileDescriptor();
+
+    const auto roots = m_engine->rootObjects();
+    for (const auto &stream : streams) {
+        for (auto root : roots) {
+            auto mo = root->metaObject();
+            qDebug() << "feeding..." << stream.id << fd;
+            mo->invokeMethod(root, "addStream", Q_ARG(QVariant, QVariant::fromValue<quint32>(stream.id)), Q_ARG(QVariant, m_handleToken), Q_ARG(QVariant, fd));
+        }
+    }
+}
+
+void RecordMe::setDuration(int duration)
+{
+    m_durationTimer->setInterval(duration);
+}
diff --git a/tests/RecordMe.h b/tests/RecordMe.h
new file mode 100644 (file)
index 0000000..0d4b2ce
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QObject>
+#include <QDBusObjectPath>
+
+class QTimer;
+class QQmlApplicationEngine;
+
+struct Stream {
+    uint id;
+    QVariantMap opts;
+};
+
+class OrgFreedesktopPortalScreenCastInterface;
+
+class RecordMe : public QObject
+{
+    Q_OBJECT
+public:
+    RecordMe(QObject* parent = nullptr);
+    ~RecordMe() override;
+
+    enum CursorModes {
+        Hidden = 1,
+        Embedded = 2,
+        Metadata = 4
+    };
+    Q_ENUM(CursorModes);
+
+    enum SourceTypes {
+        Monitor = 1,
+        Window = 2
+    };
+    Q_ENUM(SourceTypes);
+
+    void setDuration(int duration);
+
+public Q_SLOTS:
+    void response(uint code, const QVariantMap& results);
+
+private:
+    void init(const QDBusObjectPath &path);
+    void handleStreams(const QVector<Stream> &streams);
+    void start();
+
+    OrgFreedesktopPortalScreenCastInterface *iface;
+    QDBusObjectPath m_path;
+    QTimer* const m_durationTimer;
+    const QString m_handleToken;
+    QQmlApplicationEngine* m_engine;
+};
diff --git a/tests/main.cpp b/tests/main.cpp
new file mode 100644 (file)
index 0000000..0fe4bfe
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "PlasmaRecordMe.h"
+#include <QCommandLineParser>
+#include <QGuiApplication>
+
+int main(int argc, char **argv)
+{
+    QGuiApplication app(argc, argv);
+
+    {
+        QCommandLineParser parser;
+        QCommandLineOption duration(QStringLiteral("duration"), QStringLiteral("seconds length of the video"), QStringLiteral("duration"));
+        QCommandLineOption kwaylandSource(QStringLiteral("source"),
+                                          QStringLiteral("use KWayland::Screencasting to record instead of xdg-desktop-portals"),
+                                          QStringLiteral("source"),
+                                          {});
+
+        const QMap<QString, Screencasting::CursorMode> cursorOptions = {
+            {QStringLiteral("hidden"), Screencasting::CursorMode::Hidden},
+            {QStringLiteral("embedded"), Screencasting::CursorMode::Embedded},
+            {QStringLiteral("metadata"), Screencasting::CursorMode::Metadata},
+        };
+
+        QCommandLineOption cursor(QStringLiteral("cursor"),
+                                  QStringList(cursorOptions.keys()).join(QStringLiteral(", ")),
+                                  QStringLiteral("mode"),
+                                  QStringLiteral("metadata"));
+        parser.addOption(duration);
+        parser.addOption(kwaylandSource);
+        parser.addOption(cursor);
+        parser.addHelpOption();
+        parser.process(app);
+
+        PlasmaRecordMe *me = new PlasmaRecordMe(cursorOptions[parser.value(cursor).toLower()], parser.value(kwaylandSource), &app);
+        if (parser.isSet(duration)) {
+            me->setDuration(parser.value(duration).toInt() * 1000);
+        }
+    }
+
+    return app.exec();
+}
diff --git a/tests/main.qml b/tests/main.qml
new file mode 100644 (file)
index 0000000..9f21f7c
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+import QtQuick 2.1
+import QtQuick.Layouts 1.1
+import QtQuick.Controls 2.1
+import org.kde.kirigami 2.15 as Kirigami
+
+import org.kde.pipewire 0.1 as PipeWire
+import org.kde.pipewire.record 0.1 as PWRec
+
+Kirigami.ApplicationWindow
+{
+    id: root
+    width: 500
+    height: 500
+    visible: true
+    property QtObject app
+
+    function addStream(nodeid, displayText, fd) {
+        if (fd == null)
+            fd = 0;
+        rep.model.append({nodeId: nodeid, uuid: "", display: displayText, fd: fd})
+    }
+    function removeStream(nodeid) {
+        for(var i=0; i<rep.model.count; ++i) {
+            if (rep.model.get(i).nodeId === nodeid) {
+               rep.model.remove(i)
+                break;
+            }
+        }
+    }
+
+    signal record(int nodeId, bool capture)
+
+    ColumnLayout {
+        id: pipes
+        anchors.fill: parent
+
+        Button {
+            text: "Add Virtual Monitor"
+            onClicked: app.createVirtualMonitor()
+        }
+
+        Repeater {
+            id: rep
+            model: ListModel {}
+
+            delegate: Item {
+                Layout.fillWidth: true
+                Layout.fillHeight: true
+                PipeWire.PipeWireSourceItem {
+                    id: sourceItem
+                    nodeId: model.nodeId
+                    fd: model.fd
+                    visible: record.state !== PWRec.PipeWireRecord.Recording
+                    anchors.fill: parent
+
+                }
+                Button {
+                    id: butt
+                    icon.name: "media-record"
+                    text: model.display + " " + model.nodeId
+                    enabled: checked === (record.state !== PWRec.PipeWireRecord.Idle)
+                    checkable: true
+
+                    PWRec.PipeWireRecord {
+                        id: record
+                        nodeId: model.nodeId
+                        fd: model.fd
+                        output: "~/clementine.mp4"
+                        active: butt.checked
+                    }
+                }
+            }
+        }
+    }
+}
diff --git a/tests/org.freedesktop.portal.RemoteDesktop.xml b/tests/org.freedesktop.portal.RemoteDesktop.xml
new file mode 100644 (file)
index 0000000..055e64d
--- /dev/null
@@ -0,0 +1,415 @@
+<?xml version="1.0"?>
+<!--
+ Copyright (C) 2017-2018 Red Hat, Inc.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+-->
+
+<node name="/" xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">
+  <!--
+      org.freedesktop.portal.RemoteDesktop:
+      @short_description: Remote desktop portal
+
+      The Remote desktop portal allows to create remote desktop sessions.
+
+      This documentation describes version 1 of this interface.
+  -->
+  <interface name="org.freedesktop.portal.RemoteDesktop">
+    <!--
+        CreateSession:
+        @options: Vardict with optional further information
+        @handle: Object path for the #org.freedesktop.portal.Request object representing this call
+
+        Create a remote desktop session.
+
+        A remote desktop session is used to allow remote controlling a desktop
+        session.
+
+        A remote desktop session may only be started and stopped with this interface,
+        but you can use the #org.freedesktop.portal.Session object created with this
+        method together with certain methods on the #org.freedesktop.portal.ScreenCast
+        interface. Specifically, you can call
+        org.freedesktop.portal.ScreenCast.SelectSources() to also get screen content,
+        and org.freedesktop.portal.ScreenCast.OpenPipewireRemote() to acquire a file
+        descriptor for a PipeWire remote. See #org.freedesktop.portal.ScreenCast for
+        more information on how to use those methods.
+
+        Supported keys in the @options vardict include:
+        <variablelist>
+          <varlistentry>
+            <term>handle_token s</term>
+            <listitem><para>
+              A string that will be used as the last element of the @handle. Must be a valid
+              object path element. See the #org.freedesktop.portal.Request documentation for
+              more information about the @handle.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>session_handle_token s</term>
+            <listitem><para>
+              A string that will be used as the last element of the session handle. Must be a valid
+              object path element. See the #org.freedesktop.portal.Session documentation for
+              more information about the session handle.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+
+        The following results get returned via the #org.freedesktop.portal.Request::Response signal:
+        <variablelist>
+          <varlistentry>
+            <term>session_handle o</term>
+            <listitem><para>
+              The session handle. An object path for the
+              #org.freedesktop.portal.Session object representing the created
+              session.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+    -->
+    <method name="CreateSession">
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QVariantMap" />
+      <arg type="o" name="handle" direction="out"/>
+    </method>
+    <!--
+        SelectDevices:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @handle: Object path for the #org.freedesktop.portal.Request object representing this call
+
+        Select input devices to remote control.
+
+        Supported keys in the @options vardict include:
+        <variablelist>
+          <varlistentry>
+            <term>handle_token s</term>
+            <listitem><para>
+              A string that will be used as the last element of the @handle. Must be a valid
+              object path element. See the #org.freedesktop.portal.Request documentation for
+              more information about the @handle.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>types u</term>
+            <listitem><para>
+              Bitmask of what device types to request remote controlling of.
+              Default is all.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+
+        For available source types, see the AvailableDeviceTypes property.
+    -->
+    <method name="SelectDevices">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="o" name="handle" direction="out"/>
+    </method>
+    <!--
+        Start:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @parent_window: Identifier for the application window, see <link linkend="parent_window">Common Conventions</link>
+        @options: Vardict with optional further information
+        @handle: Object path for the #org.freedesktop.portal.Request object representing this call
+
+        Start the remote desktop session. This will typically result in the portal
+        presenting a dialog letting the user select what to share, including
+        devices and optionally screen content if screen cast sources was
+        selected.
+
+        Supported keys in the @options vardict include:
+        <variablelist>
+          <varlistentry>
+            <term>handle_token s</term>
+            <listitem><para>
+              A string that will be used as the last element of the @handle. Must be a valid
+              object path element. See the #org.freedesktop.portal.Request documentation for
+              more information about the @handle.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+
+        The following results get returned via the
+        #org.freedesktop.portal.Request::Response signal:
+        <variablelist>
+          <varlistentry>
+            <term>devices u</term>
+            <listitem><para>
+              A bitmask of the devices selected by the user.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+
+        If a screen cast source was selected, the results of the
+        #org.freedesktop.portal.ScreenCast.Start response signal may be
+        included.
+    -->
+    <method name="Start">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="s" name="parent_window" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In2" value="QVariantMap" />
+      <arg type="o" name="handle" direction="out"/>
+    </method>
+    <!--
+        NotifyPointerMotion:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @dx: Relative movement on the x axis
+        @dy: Relative movement on the y axis
+
+        Notify about a new relative pointer motion event. The (dx, dy) vector
+        represents the new pointer position in the streams logical coordinate
+        space.
+    -->
+    <method name="NotifyPointerMotion">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="d" name="dx" direction="in"/>
+      <arg type="d" name="dy" direction="in"/>
+    </method>
+    <!--
+        NotifyPointerMotionAbsolute:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @stream: The PipeWire stream node the coordinate is relative to
+        @x: Pointer motion x coordinate
+        @y: Pointer motion y coordinate
+
+        Notify about a new absolute pointer motion event. The (x, y) position
+        represents the new pointer position in the streams logical coordinate
+        space (see the logical_size stream property in
+        #org.freedesktop.portal.ScreenCast).
+    -->
+    <method name="NotifyPointerMotionAbsolute">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="u" name="stream" direction="in"/>
+      <arg type="d" name="x" direction="in"/>
+      <arg type="d" name="y" direction="in"/>
+    </method>
+    <!--
+        NotifyPointerButton:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @button: The pointer button was pressed or released
+        @state: The new state of the button
+
+        The pointer button is encoded according to Linux Evdev button codes.
+
+        May only be called if POINTER access was provided after starting the
+        session.
+
+        Available button states:
+        <simplelist>
+          <member>0: Released</member>
+          <member>1: Pressed</member>
+        </simplelist>
+    -->
+    <method name="NotifyPointerButton">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="i" name="button" direction="in"/>
+      <arg type="u" name="state" direction="in"/>
+    </method>
+    <!--
+        NotifyPointerAxis:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @dx: Relative axis movement on the x axis
+        @dy: Relative axis movement on the y axis
+
+        The axis movement from a 'smooth scroll' device, such as a touchpad.
+        When applicable, the size of the motion delta should be equivalent to
+        the motion vector of a pointer motion done using the same advice.
+
+        May only be called if POINTER access was provided after starting the
+        session.
+
+        Supported keys in the @options vardict include:
+        <variablelist>
+          <varlistentry>
+            <term>finish b</term>
+            <listitem><para>
+              If set to true, this is the last axis event in a series, for
+              example as a result of the fingers being lifted from a touchpad
+              after a two-finger scroll.  Default is false.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+    -->
+    <method name="NotifyPointerAxis">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="d" name="dx" direction="in"/>
+      <arg type="d" name="dy" direction="in"/>
+    </method>
+    <!--
+        NotifyPointerAxisDiscrete:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @axis: The axis that was scrolled
+        @steps: The number of steps scrolled
+
+        May only be called if POINTER access was provided after starting the
+        session.
+
+        Available axes:
+        <simplelist>
+          <member>0: Vertical scroll</member>
+          <member>1: Horizontal scroll</member>
+        </simplelist>
+    -->
+    <method name="NotifyPointerAxisDiscrete">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="u" name="axis" direction="in"/>
+      <arg type="i" name="steps" direction="in"/>
+    </method>
+    <!--
+        NotifyKeyboardKeycode:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @keycode: Keyboard code that was pressed or released
+        @state: New state of keyboard keycode
+
+        May only be called if KEYBOARD access was provided after starting the
+        session.
+
+        Available keyboard keycode states:
+        <simplelist>
+          <member>0: Released</member>
+          <member>1: Pressed</member>
+        </simplelist>
+    -->
+    <method name="NotifyKeyboardKeycode">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="i" name="keycode" direction="in"/>
+      <arg type="u" name="state" direction="in"/>
+    </method>
+    <!--
+        NotifyKeyboardKeysym:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @keysym: Keyboard symbol that was pressed or released
+        @state: New state of keyboard keysym
+
+        May only be called if KEYBOARD access was provided after starting the
+        session.
+
+        Available keyboard keysym states:
+        <simplelist>
+          <member>0: Released</member>
+          <member>1: Pressed</member>
+        </simplelist>
+    -->
+    <method name="NotifyKeyboardKeysym">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="i" name="keysym" direction="in"/>
+      <arg type="u" name="state" direction="in"/>
+    </method>
+    <!--
+        NotifyTouchDown:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @stream: The PipeWire stream node the coordinate is relative to
+        @slot: Touch slot where touch point appeared
+        @x: Touch down x coordinate
+        @y: Touch down y coordinate
+
+        May only be called if TOUCHSCREEN access was provided after starting the
+        session.
+
+        Notify about a new touch down event. The (x, y) position
+        represents the new touch point position in the streams logical
+        coordinate space (see the logical_size stream property in
+        #org.freedesktop.portal.ScreenCast).
+    -->
+    <method name="NotifyTouchDown">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="u" name="stream" direction="in"/>
+      <arg type="u" name="slot" direction="in"/>
+      <arg type="d" name="x" direction="in"/>
+      <arg type="d" name="y" direction="in"/>
+    </method>
+    <!--
+        NotifyTouchMotion:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @stream: The PipeWire stream node the coordinate is relative to
+        @slot: Touch slot where touch point appeared
+        @x: Touch motion x coordinate
+        @y: Touch motion y coordinate
+
+        May only be called if TOUCHSCREEN access was provided after starting the
+        session.
+
+        Notify about a new touch motion event. The (x, y) position
+        represents where the touch point position in the streams logical
+        coordinate space moved (see the logical_size stream property in
+        #org.freedesktop.portal.ScreenCast).
+    -->
+    <method name="NotifyTouchMotion">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="u" name="stream" direction="in"/>
+      <arg type="u" name="slot" direction="in"/>
+      <arg type="d" name="x" direction="in"/>
+      <arg type="d" name="y" direction="in"/>
+    </method>
+    <!--
+        NotifyTouchUp:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @slot: Touch slot where touch point appeared
+
+        May only be called if TOUCHSCREEN access was provided after starting the
+        session.
+
+        Notify about a new touch up event.
+    -->
+    <method name="NotifyTouchUp">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="u" name="slot" direction="in"/>
+    </method>
+    <!--
+        AvailableDeviceTypes:
+
+        A bitmask of available source types. Currently defined types are:
+
+        <simplelist>
+          <member>1: KEYBOARD</member>
+          <member>2: POINTER</member>
+          <member>4: TOUCHSCREEN</member>
+        </simplelist>
+    -->
+    <property name="AvailableDeviceTypes" type="u" access="read"/>
+    <property name="version" type="u" access="read"/>
+  </interface>
+</node>
diff --git a/tests/org.freedesktop.portal.ScreenCast.xml b/tests/org.freedesktop.portal.ScreenCast.xml
new file mode 100644 (file)
index 0000000..6b7054f
--- /dev/null
@@ -0,0 +1,323 @@
+<?xml version="1.0"?>
+<!--
+ Copyright (C) 2017-2018 Red Hat, Inc.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+-->
+
+<node name="/" xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">
+  <!--
+      org.freedesktop.portal.ScreenCast:
+      @short_description: Screen cast portal
+
+      The Screen cast portal allows to create screen cast sessions.
+
+      This documentation describes version 4 of this interface.
+  -->
+  <interface name="org.freedesktop.portal.ScreenCast">
+    <!--
+        CreateSession:
+        @options: Vardict with optional further information
+        @handle: Object path for the #org.freedesktop.portal.Request object representing this call
+
+        Create a screen cast session. A successfully created session can at
+        any time be closed using org.freedesktop.portal.Session.Close(), or may
+        at any time be closed by the portal implementation, which will be
+        signalled via #org.freedesktop.portal.Session::Closed.
+
+        Supported keys in the @options vardict include:
+        <variablelist>
+          <varlistentry>
+            <term>handle_token s</term>
+            <listitem><para>
+              A string that will be used as the last element of the @handle. Must be a valid
+              object path element. See the #org.freedesktop.portal.Request documentation for
+              more information about the @handle.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>session_handle_token s</term>
+            <listitem><para>
+              A string that will be used as the last element of the session handle. Must be a valid
+              object path element. See the #org.freedesktop.portal.Session documentation for
+              more information about the session handle.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+
+        The following results get returned via the #org.freedesktop.portal.Request::Response signal:
+        <variablelist>
+          <varlistentry>
+            <term>session_handle o</term>
+            <listitem><para>
+              The session handle. An object path for the
+              #org.freedesktop.portal.Session object representing the created
+              session.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+    -->
+    <method name="CreateSession">
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QVariantMap" />
+      <arg type="o" name="handle" direction="out"/>
+    </method>
+    <!--
+        SelectSources:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @handle: Object path for the #org.freedesktop.portal.Request object representing this call
+
+        Configure what the screen cast session should record. This method must
+        be called before starting the session.
+
+        Passing invalid input to this method will cause the session to be
+        closed. An application may only attempt to select sources once per
+        session.
+
+        Supported keys in the @options vardict include:
+        <variablelist>
+          <varlistentry>
+            <term>handle_token s</term>
+            <listitem><para>
+              A string that will be used as the last element of the @handle. Must be a valid
+              object path element. See the #org.freedesktop.portal.Request documentation for
+              more information about the @handle.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>types u</term>
+            <listitem><para>
+              Bitmask of what types of content to record. Default is MONITOR.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>multiple b</term>
+            <listitem><para>
+              Whether to allow selecting multiple sources. Default is no.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>cursor_mode u</term>
+            <listitem><para>
+              Determines how the cursor will be drawn in the screen cast stream. It must be
+              one of the cursor modes advertised in
+              #org.freedesktop.portal.ScreenCast.AvailableCursorModes. Setting a cursor mode
+              not advertised will cause the screen cast session to be closed. The default
+              cursor mode is 'Hidden'.
+
+              This option was added in version 2 of this interface.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>restore_token s</term>
+            <listitem><para>
+              The token to restore a previous session.
+
+              If the stored session cannot be restored, this value is ignored
+              and the user will be prompted normally. This may happen when, for
+              example, the session contains a monitor or a window that is not
+              available anymore, or when the stored permissions are withdrawn.
+
+              The restore token is invalidated after using it once. To restore
+              the same session again, use the new restore token sent in response
+              to starting this session.
+
+              This option was added in version 4 of this interface.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>persist_mode u</term>
+            <listitem><para>
+              How this session should persist. Default is 0. Accepted values are:
+
+              <simplelist>
+                <member>0: Do not persist (default)</member>
+                <member>1: Permissions persist as long as the application is running</member>
+                <member>2: Permissions persist until explicitly revoked</member>
+              </simplelist>
+
+              Remote desktop screen cast sessions cannot persist. The only allowed
+              persist_mode for remote desktop sessions is 0.
+
+              If the permission for the session to persist is granted, a restore token will
+              be returned via the #org.freedesktop.portal.Request::Response signal of the
+              #org.freedesktop.portal.ScreenCast.Start method.
+
+              This option was added in version 4 of this interface.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+
+        For available source types, see the AvailableSourceTypes property.
+    -->
+    <method name="SelectSources">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+      <arg type="o" name="handle" direction="out"/>
+    </method>
+    <!--
+        Start:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @parent_window: Identifier for the application window, see <link linkend="parent_window">Common Conventions</link>
+        @options: Vardict with optional further information
+        @handle: Object path for the #org.freedesktop.portal.Request object representing this call
+
+        Start the screen cast session. This will typically result the portal
+        presenting a dialog letting the user do the selection set up by
+        org.freedesktop.portal.ScreenCast.SelectSources(). An application can
+        only attempt start a session once.
+
+        A screen cast session may only be started after having selected sources
+        using org.freedesktop.portal.ScreenCast.SelectSources().
+
+        Supported keys in the @options vardict include:
+        <variablelist>
+          <varlistentry>
+            <term>handle_token s</term>
+            <listitem><para>
+              A string that will be used as the last element of the @handle. Must be a valid
+              object path element. See the #org.freedesktop.portal.Request documentation for
+              more information about the @handle.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+
+        The following results get returned via the
+        #org.freedesktop.portal.Request::Response signal:
+        <variablelist>
+          <varlistentry>
+            <term>streams a(ua{sv})</term>
+            <listitem><para>
+              An array of PipeWire streams. Each stream consists of a PipeWire
+              node ID (the first element in the tuple, and a Vardict of
+              properties.
+
+              The array will contain a single stream if 'multiple' (see
+              org.freedesktop.portal.ScreenCast.SelectSources())
+              was set to 'false', or at least one stream if
+              'multiple' was set to 'true' as part of the
+              org.freedesktop.portal.ScreenCast.SelectSources() method.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>restore_token s</term>
+            <listitem><para>
+              The restore token. This token is a single use token that can later
+              be used to restore a session. See
+              org.freedesktop.portal.ScreenCast.SelectSources() for details.
+
+              This response option was added in version 4 of this interface.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+
+        Stream properties include:
+        <variablelist>
+          <varlistentry>
+            <term>id s</term>
+            <listitem><para>
+              Opaque identifier. Will be unique for this stream and local to this
+              session. Will persist with future sessions, if they are restored
+              using a restore token. This property was added in version 4 of this
+              interface. Optional.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>position (ii)</term>
+            <listitem><para>
+              A tuple consisting of the position (x, y) in the compositor
+              coordinate space. Note that the position may not be equivalent to a
+              position in a pixel coordinate space. Only available for monitor
+              streams. Optional.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>size (ii)</term>
+            <listitem><para>
+              A tuple consisting of (width, height). The size represents the size
+              of the stream as it is displayed in the compositor coordinate
+              space. Note that this size may not be equivalent to a size in a
+              pixel coordinate space. The size may differ from the size of the
+              stream. Optional.
+            </para></listitem>
+          </varlistentry>
+          <varlistentry>
+            <term>source_type u</term>
+            <listitem><para>
+              The type of the content which is being screen casted.
+              For available source types, see the AvailableSourceTypes property.
+              This property was added in version 3 of this interface.
+            </para></listitem>
+          </varlistentry>
+        </variablelist>
+    -->
+    <method name="Start">
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="s" name="parent_window" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In2" value="QVariantMap" />
+      <arg type="o" name="handle" direction="out"/>
+    </method>
+    <!--
+        OpenPipeWireRemote:
+        @session_handle: Object path for the #org.freedesktop.portal.Session object
+        @options: Vardict with optional further information
+        @fd: File descriptor of an open PipeWire remote.
+
+        Open a file descriptor to the PipeWire remote where the screen cast
+        streams are available. The file descriptor should be used to create a
+        <classname>pw_core</classname> object, by using
+        <function>pw_context_connect_fd</function>. Only the screen cast stream
+        nodes will be available from this PipeWire node.
+    -->
+    <method name="OpenPipeWireRemote">
+      <annotation name="org.gtk.GDBus.C.Name" value="open_pipewire_remote"/>
+      <annotation name="org.gtk.GDBus.C.UnixFD" value="true"/>
+      <arg type="o" name="session_handle" direction="in"/>
+      <arg type="a{sv}" name="options" direction="in"/>
+      <arg type="h" name="fd" direction="out"/>
+      <annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap" />
+    </method>
+    <!--
+        AvailableSourceTypes:
+
+        A bitmask of available source types. Currently defined types are:
+
+        <simplelist>
+          <member>1: MONITOR</member>
+          <member>2: WINDOW</member>
+          <member>4: VIRTUAL</member>
+        </simplelist>
+    -->
+    <property name="AvailableSourceTypes" type="u" access="read"/>
+    <!--
+        AvailableCursorModes:
+
+        A bitmask of available cursor modes.
+
+        Available cursor mode values:
+        <simplelist>
+          <member>1: Hidden. The cursor is not part of the screen cast stream.</member>
+          <member>2: Embedded: The cursor is embedded as part of the stream buffers.</member>
+          <member>4: Metadata: The cursor is not part of the screen cast stream, but sent as PipeWire stream metadata.</member>
+        </simplelist>
+
+        This property was added in version 2 of this interface.
+    -->
+    <property name="AvailableCursorModes" type="u" access="read"/>
+    <property name="version" type="u" access="read"/>
+  </interface>
+</node>
diff --git a/tests/org.kde.kpipewireheadlesstest.desktop.cmake b/tests/org.kde.kpipewireheadlesstest.desktop.cmake
new file mode 100644 (file)
index 0000000..1725a37
--- /dev/null
@@ -0,0 +1,7 @@
+[Desktop Entry]
+Name=PlasmaHeadlessTest
+Exec=@CMAKE_INSTALL_PREFIX@/bin/kpipewireheadlesstest
+Icon=camera-video
+Type=Application
+X-KDE-Wayland-Interfaces=zkde_screencast_unstable_v1
+
diff --git a/tests/org.kde.recordme.desktop.cmake b/tests/org.kde.recordme.desktop.cmake
new file mode 100644 (file)
index 0000000..7d6624e
--- /dev/null
@@ -0,0 +1,7 @@
+[Desktop Entry]
+Name=RecordMe
+Exec=@CMAKE_INSTALL_PREFIX@/bin/recordme
+Icon=camera-video
+Type=Application
+X-KDE-Wayland-Interfaces=org_kde_plasma_window_management,zkde_screencast_unstable_v1
+
diff --git a/tests/recordme.qrc b/tests/recordme.qrc
new file mode 100644 (file)
index 0000000..7e7c8e3
--- /dev/null
@@ -0,0 +1,10 @@
+<!--
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+-->
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+    <file>main.qml</file>
+</qresource>
+</RCC>
diff --git a/tests/screencasting.cpp b/tests/screencasting.cpp
new file mode 100644 (file)
index 0000000..bb32896
--- /dev/null
@@ -0,0 +1,167 @@
+/*
+    SPDX-FileCopyrightText: 2020 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "screencasting.h"
+#include "logging.h"
+#include "qwayland-zkde-screencast-unstable-v1.h"
+#include <KWayland/Client/output.h>
+#include <KWayland/Client/plasmawindowmanagement.h>
+#include <KWayland/Client/registry.h>
+#include <QGuiApplication>
+#include <QRect>
+#include <QtWaylandClient/QWaylandClientExtensionTemplate>
+#include <qpa/qplatformnativeinterface.h>
+#include <qscreen.h>
+#include <qtwaylandclientversion.h>
+
+using namespace KWayland::Client;
+
+class ScreencastingStreamPrivate : public QtWayland::zkde_screencast_stream_unstable_v1
+{
+public:
+    ScreencastingStreamPrivate(ScreencastingStream *q)
+        : q(q)
+    {
+    }
+    ~ScreencastingStreamPrivate()
+    {
+        if (isInitialized()) {
+            close();
+        }
+        q->deleteLater();
+    }
+
+    void zkde_screencast_stream_unstable_v1_created(uint32_t node) override
+    {
+        m_nodeId = node;
+        Q_EMIT q->created(node);
+    }
+
+    void zkde_screencast_stream_unstable_v1_closed() override
+    {
+        Q_EMIT q->closed();
+    }
+
+    void zkde_screencast_stream_unstable_v1_failed(const QString &error) override
+    {
+        Q_EMIT q->failed(error);
+    }
+
+    std::optional<uint> m_nodeId;
+    QPointer<ScreencastingStream> q;
+};
+
+ScreencastingStream::ScreencastingStream(QObject *parent)
+    : QObject(parent)
+    , d(new ScreencastingStreamPrivate(this))
+{
+}
+
+ScreencastingStream::~ScreencastingStream() = default;
+
+quint32 ScreencastingStream::nodeId() const
+{
+    Q_ASSERT(d->m_nodeId.has_value());
+    return *d->m_nodeId;
+}
+
+class ScreencastingPrivate : public QWaylandClientExtensionTemplate<ScreencastingPrivate>, public QtWayland::zkde_screencast_unstable_v1
+{
+public:
+    ScreencastingPrivate(Screencasting *q)
+        : QWaylandClientExtensionTemplate<ScreencastingPrivate>(ZKDE_SCREENCAST_UNSTABLE_V1_STREAM_REGION_SINCE_VERSION)
+        , q(q)
+    {
+#if QTWAYLANDCLIENT_VERSION >= QT_VERSION_CHECK(6, 2, 0)
+        initialize();
+#else
+        // QWaylandClientExtensionTemplate invokes this with a QueuedConnection but we want it called immediately
+        QMetaObject::invokeMethod(this, "addRegistryListener", Qt::DirectConnection);
+#endif
+
+        if (!isInitialized()) {
+            qWarning() << "Remember requesting the interface on your desktop file: X-KDE-Wayland-Interfaces=zkde_screencast_unstable_v1";
+        }
+        Q_ASSERT(isInitialized());
+    }
+
+    ~ScreencastingPrivate()
+    {
+        destroy();
+    }
+
+    Screencasting *const q;
+};
+
+Screencasting::Screencasting(QObject *parent)
+    : QObject(parent)
+    , d(new ScreencastingPrivate(this))
+{
+}
+
+Screencasting::~Screencasting() = default;
+
+ScreencastingStream *Screencasting::createOutputStream(const QString &outputName, Screencasting::CursorMode mode)
+{
+    wl_output *output = nullptr;
+    for (auto screen : qGuiApp->screens()) {
+        if (screen->name() == outputName) {
+            output = (wl_output *)QGuiApplication::platformNativeInterface()->nativeResourceForScreen("output", screen);
+        }
+    }
+
+    if (!output) {
+        return nullptr;
+    }
+
+    auto stream = new ScreencastingStream(this);
+    stream->setObjectName(outputName);
+    stream->d->init(d->stream_output(output, mode));
+    return stream;
+}
+
+ScreencastingStream *Screencasting::createOutputStream(Output *output, CursorMode mode)
+{
+    auto stream = new ScreencastingStream(this);
+    stream->setObjectName(output->model());
+    stream->d->init(d->stream_output(*output, mode));
+    return stream;
+}
+
+ScreencastingStream *Screencasting::createRegionStream(const QRect &geometry, qreal scaling, CursorMode mode)
+{
+    Q_ASSERT(d->QWaylandClientExtension::version() >= ZKDE_SCREENCAST_UNSTABLE_V1_STREAM_REGION_SINCE_VERSION);
+    auto stream = new ScreencastingStream(this);
+    stream->setObjectName(QStringLiteral("region-%1,%2 (%3x%4)").arg(geometry.x()).arg(geometry.y()).arg(geometry.width()).arg(geometry.height()));
+    stream->d->init(d->stream_region(geometry.x(), geometry.y(), geometry.width(), geometry.height(), wl_fixed_from_double(scaling), mode));
+    return stream;
+}
+
+ScreencastingStream *Screencasting::createWindowStream(PlasmaWindow *window, CursorMode mode)
+{
+    auto stream = createWindowStream(QString::fromUtf8(window->uuid()), mode);
+    stream->setObjectName(window->appId());
+    return stream;
+}
+
+ScreencastingStream *Screencasting::createWindowStream(const QString &uuid, CursorMode mode)
+{
+    auto stream = new ScreencastingStream(this);
+    stream->d->init(d->stream_window(uuid, mode));
+    return stream;
+}
+
+ScreencastingStream *Screencasting::createVirtualMonitorStream(const QString &name, const QSize &size, qreal scale, CursorMode mode)
+{
+    auto stream = new ScreencastingStream(this);
+    stream->d->init(d->stream_virtual_output(name, size.width(), size.height(), wl_fixed_from_double(scale), mode));
+    return stream;
+}
+
+void Screencasting::destroy()
+{
+    d.reset(nullptr);
+}
diff --git a/tests/screencasting.h b/tests/screencasting.h
new file mode 100644 (file)
index 0000000..f6ca84f
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+    SPDX-FileCopyrightText: 2020 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include <QObject>
+#include <QSharedPointer>
+#include <QVector>
+#include <optional>
+
+#include <kpipewire_export.h>
+
+struct zkde_screencast_unstable_v1;
+
+namespace KWayland
+{
+namespace Client
+{
+class PlasmaWindow;
+class Registry;
+class Output;
+}
+}
+
+class ScreencastingPrivate;
+class ScreencastingSourcePrivate;
+class ScreencastingStreamPrivate;
+class KPIPEWIRE_EXPORT ScreencastingStream : public QObject
+{
+    Q_OBJECT
+public:
+    ScreencastingStream(QObject *parent);
+    ~ScreencastingStream() override;
+
+    quint32 nodeId() const;
+
+Q_SIGNALS:
+    void created(quint32 nodeid);
+    void failed(const QString &error);
+    void closed();
+
+private:
+    friend class Screencasting;
+    QScopedPointer<ScreencastingStreamPrivate> d;
+};
+
+class KPIPEWIRE_EXPORT Screencasting : public QObject
+{
+    Q_OBJECT
+public:
+    explicit Screencasting(QObject *parent = nullptr);
+    ~Screencasting() override;
+
+    enum CursorMode {
+        Hidden = 1,
+        Embedded = 2,
+        Metadata = 4,
+    };
+    Q_ENUM(CursorMode);
+
+    ScreencastingStream *createOutputStream(const QString &outputName, CursorMode mode);
+    ScreencastingStream *createOutputStream(KWayland::Client::Output *output, CursorMode mode);
+    ScreencastingStream *createRegionStream(const QRect &region, qreal scaling, CursorMode mode);
+    ScreencastingStream *createWindowStream(KWayland::Client::PlasmaWindow *window, CursorMode mode);
+    ScreencastingStream *createWindowStream(const QString &uuid, CursorMode mode);
+    ScreencastingStream *createVirtualMonitorStream(const QString &name, const QSize &size, qreal scale, CursorMode mode);
+
+    void destroy();
+
+Q_SIGNALS:
+    void initialized();
+    void removed();
+    void sourcesChanged();
+
+private:
+    QScopedPointer<ScreencastingPrivate> d;
+};
diff --git a/tests/screencastingrequest.cpp b/tests/screencastingrequest.cpp
new file mode 100644 (file)
index 0000000..ad8ed96
--- /dev/null
@@ -0,0 +1,105 @@
+/*
+    SPDX-FileCopyrightText: 2020 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "screencastingrequest.h"
+#include "logging.h"
+
+#include <KWayland/Client/connection_thread.h>
+#include <KWayland/Client/registry.h>
+#include <QCoreApplication>
+#include <QDebug>
+#include <QPointer>
+#include <functional>
+
+struct ScreencastingRequestPrivate {
+    QPointer<ScreencastingStream> m_stream;
+    QString m_uuid;
+    QString m_outputName;
+    quint32 m_nodeId = 0;
+};
+
+ScreencastingRequest::ScreencastingRequest(QObject *parent)
+    : QObject(parent)
+    , d(new ScreencastingRequestPrivate)
+{
+}
+
+ScreencastingRequest::~ScreencastingRequest() = default;
+
+quint32 ScreencastingRequest::nodeId() const
+{
+    return d->m_nodeId;
+}
+
+void ScreencastingRequest::setUuid(const QString &uuid)
+{
+    if (d->m_uuid == uuid) {
+        return;
+    }
+
+    d->m_stream->deleteLater();
+    setNodeid(0);
+
+    d->m_uuid = uuid;
+    Q_EMIT uuidChanged(uuid);
+
+    if (!d->m_uuid.isEmpty()) {
+        auto screencasting = new Screencasting(this);
+        auto stream = screencasting->createWindowStream(d->m_uuid, Screencasting::CursorMode::Hidden);
+        adopt(stream);
+    }
+}
+
+void ScreencastingRequest::setOutputName(const QString &outputName)
+{
+    if (d->m_outputName == outputName) {
+        return;
+    }
+
+    setNodeid(0);
+    d->m_outputName = outputName;
+    Q_EMIT outputNameChanged(outputName);
+
+    if (!d->m_outputName.isEmpty()) {
+        auto screencasting = new Screencasting(this);
+        auto stream = screencasting->createOutputStream(d->m_outputName, Screencasting::CursorMode::Hidden);
+        adopt(stream);
+        stream->setObjectName(d->m_outputName);
+    }
+}
+
+void ScreencastingRequest::adopt(ScreencastingStream *stream)
+{
+    connect(stream, &ScreencastingStream::created, this, &ScreencastingRequest::setNodeid);
+    connect(stream, &ScreencastingStream::failed, this, [](const QString &error) {
+        qWarning() << "error creating screencast" << error;
+    });
+    connect(stream, &ScreencastingStream::closed, this, [this, stream] {
+        if (stream->nodeId() == d->m_nodeId) {
+            setNodeid(0);
+        }
+    });
+}
+
+void ScreencastingRequest::setNodeid(uint nodeId)
+{
+    if (nodeId == d->m_nodeId) {
+        return;
+    }
+
+    d->m_nodeId = nodeId;
+    Q_EMIT nodeIdChanged(nodeId);
+}
+
+QString ScreencastingRequest::uuid() const
+{
+    return d->m_uuid;
+}
+
+QString ScreencastingRequest::outputName() const
+{
+    return d->m_outputName;
+}
diff --git a/tests/screencastingrequest.h b/tests/screencastingrequest.h
new file mode 100644 (file)
index 0000000..8d6c23c
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+    SPDX-FileCopyrightText: 2020 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#pragma once
+
+#include "screencasting.h"
+#include <QObject>
+
+#include <kpipewire_export.h>
+
+class ScreencastingStream;
+struct ScreencastingRequestPrivate;
+
+/**
+ * Allows us to request a stream for a window identified by its universally
+ * unique identifier.
+ *
+ * We will get a PipeWire node id that can be fed to any pipewire player, be it
+ * the PipeWireSourceItem, GStreamer's pipewiresink or any other.
+ */
+class KPIPEWIRE_EXPORT ScreencastingRequest : public QObject
+{
+    Q_OBJECT
+    /**
+     * The unique identifier of the window we want to cast.
+     *
+     * @see PlasmaWindow::uuid
+     * @see PlasmaWindow::stackingOrderUuids
+     * @see PlasmaWindowModel::Uuid
+     * @see TasksModel::WinIdList
+     */
+    Q_PROPERTY(QString uuid READ uuid WRITE setUuid NOTIFY uuidChanged)
+
+    /**
+     * The output name as define in Screen.name
+     */
+    Q_PROPERTY(QString outputName READ outputName WRITE setOutputName NOTIFY outputNameChanged)
+
+    /** The offered nodeId to give to a source */
+    Q_PROPERTY(quint32 nodeId READ nodeId NOTIFY nodeIdChanged)
+public:
+    ScreencastingRequest(QObject *parent = nullptr);
+    ~ScreencastingRequest();
+
+    void setUuid(const QString &uuid);
+    QString uuid() const;
+    void setOutputName(const QString &outputName);
+    QString outputName() const;
+    quint32 nodeId() const;
+
+Q_SIGNALS:
+    void nodeIdChanged(quint32 nodeId);
+    void uuidChanged(const QString &uuid);
+    void outputNameChanged(const QString &outputNames);
+
+private:
+    void adopt(ScreencastingStream *stream);
+    void setNodeid(uint nodeId);
+
+    QScopedPointer<ScreencastingRequestPrivate> d;
+};
diff --git a/tests/xdp-main.cpp b/tests/xdp-main.cpp
new file mode 100644 (file)
index 0000000..14e0eee
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+    SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
+
+    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
+*/
+
+#include "RecordMe.h"
+#include <QCommandLineParser>
+#include <QGuiApplication>
+
+int main(int argc, char **argv)
+{
+    QGuiApplication app(argc, argv);
+
+    {
+        QCommandLineParser parser;
+        QCommandLineOption duration(QStringLiteral("duration"), QStringLiteral("seconds length of the video"), QStringLiteral("duration"));
+        parser.addOption(duration);
+        parser.process(app);
+
+        RecordMe *me = new RecordMe(&app);
+        if (parser.isSet(duration)) {
+            me->setDuration(parser.value(duration).toInt() * 1000);
+        }
+    }
+
+    return app.exec();
+}