mirror of
https://github.com/nestriness/warp.git
synced 2025-12-11 09:25:39 +02:00
init
This commit is contained in:
510
LICENSE
510
LICENSE
@@ -1,201 +1,373 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1. Definitions.
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
2.1. Grants
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
2.2. Effective Date
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
0
Cargo.lock → gstreamer/Cargo.lock
generated
0
Cargo.lock → gstreamer/Cargo.lock
generated
@@ -12,6 +12,22 @@ rust-version = "1.70"
|
||||
url = "2"
|
||||
gst = { package = "gstreamer", git = "https://gitlab.freedesktop.org/gstreamer/gstreamer-rs" }
|
||||
gst-base = { package = "gstreamer-base", git = "https://gitlab.freedesktop.org/gstreamer/gstreamer-rs" }
|
||||
gst-video.workspace = true
|
||||
wayland-display-core = { path = "../wayland-display-core" }
|
||||
moq-transport = { path = "../moq-transport" }
|
||||
tracing.workspace = true
|
||||
once_cell.workspace = true
|
||||
tracing-subscriber = "0.3.16"
|
||||
|
||||
# QUIC
|
||||
quinn = "0.10"
|
||||
webtransport-quinn = "0.6.1"
|
||||
url = "2"
|
||||
|
||||
# Crypto
|
||||
rustls = { version = "0.21", features = ["dangerous_configuration"] }
|
||||
rustls-native-certs = "0.6"
|
||||
rustls-pemfile = "1"
|
||||
|
||||
[lib]
|
||||
name = "gstwarp"
|
||||
51
gstreamer/src/README.md
Normal file
51
gstreamer/src/README.md
Normal file
@@ -0,0 +1,51 @@
|
||||
To be used as follows:
|
||||
|
||||
```rust
|
||||
use gst::prelude::*;
|
||||
|
||||
fn main() {
|
||||
// Initialize GStreamer
|
||||
gst::init().unwrap();
|
||||
|
||||
// Create the elements
|
||||
let source = gst::ElementFactory::make("videotestsrc", Some("source")).unwrap();
|
||||
let encoder = gst::ElementFactory::make("x264enc", Some("encoder")).unwrap();
|
||||
let muxer = gst::ElementFactory::make("fmp4mux", Some("muxer")).unwrap();
|
||||
let sink = gst::ElementFactory::make("warpsink", Some("sink")).unwrap();
|
||||
|
||||
// Create an empty pipeline
|
||||
let pipeline = gst::Pipeline::new(Some("pipeline"));
|
||||
|
||||
// Build the pipeline
|
||||
pipeline.add_many(&[&source, &encoder, &muxer, &sink]).unwrap();
|
||||
gst::Element::link_many(&[&source, &encoder, &muxer, &sink]).unwrap();
|
||||
|
||||
// Start playing
|
||||
pipeline.set_state(gst::State::Playing).unwrap();
|
||||
|
||||
// Wait until error or EOS
|
||||
let bus = pipeline.bus().unwrap();
|
||||
for msg in bus.iter_timed(gst::CLOCK_TIME_NONE) {
|
||||
use gst::MessageView;
|
||||
|
||||
match msg.view() {
|
||||
MessageView::Error(err) => {
|
||||
eprintln!(
|
||||
"Error from {:?}: {} ({:?})",
|
||||
err.src().map(|s| s.path_string()),
|
||||
err.error(),
|
||||
err.debug()
|
||||
);
|
||||
break;
|
||||
}
|
||||
MessageView::Eos(..) => break,
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up
|
||||
pipeline.set_state(gst::State::Null).unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
373
gstreamer/src/fmp4mux/LICENSE.md
Normal file
373
gstreamer/src/fmp4mux/LICENSE.md
Normal file
@@ -0,0 +1,373 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
1
gstreamer/src/fmp4mux/README.md
Normal file
1
gstreamer/src/fmp4mux/README.md
Normal file
@@ -0,0 +1 @@
|
||||
https://github.com/sdroege/gst-plugin-rs/tree/main/mux/fmp4
|
||||
2258
gstreamer/src/fmp4mux/boxes.rs
Normal file
2258
gstreamer/src/fmp4mux/boxes.rs
Normal file
File diff suppressed because it is too large
Load Diff
3869
gstreamer/src/fmp4mux/imp.rs
Normal file
3869
gstreamer/src/fmp4mux/imp.rs
Normal file
File diff suppressed because it is too large
Load Diff
208
gstreamer/src/fmp4mux/mod.rs
Normal file
208
gstreamer/src/fmp4mux/mod.rs
Normal file
@@ -0,0 +1,208 @@
|
||||
// Copyright (C) 2021 Sebastian Dröge <sebastian@centricular.com>
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the Mozilla Public License, v2.0.
|
||||
// If a copy of the MPL was not distributed with this file, You can obtain one at
|
||||
// <https://mozilla.org/MPL/2.0/>.
|
||||
//
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
use gst::glib;
|
||||
use gst::prelude::*;
|
||||
|
||||
mod boxes;
|
||||
mod imp;
|
||||
|
||||
glib::wrapper! {
|
||||
pub(crate) struct FMP4MuxPad(ObjectSubclass<imp::FMP4MuxPad>) @extends gst_base::AggregatorPad, gst::Pad, gst::Object;
|
||||
}
|
||||
|
||||
glib::wrapper! {
|
||||
pub(crate) struct FMP4Mux(ObjectSubclass<imp::FMP4Mux>) @extends gst_base::Aggregator, gst::Element, gst::Object;
|
||||
}
|
||||
|
||||
glib::wrapper! {
|
||||
pub(crate) struct ISOFMP4Mux(ObjectSubclass<imp::ISOFMP4Mux>) @extends FMP4Mux, gst_base::Aggregator, gst::Element, gst::Object;
|
||||
}
|
||||
|
||||
glib::wrapper! {
|
||||
pub(crate) struct CMAFMux(ObjectSubclass<imp::CMAFMux>) @extends FMP4Mux, gst_base::Aggregator, gst::Element, gst::Object;
|
||||
}
|
||||
|
||||
glib::wrapper! {
|
||||
pub(crate) struct DASHMP4Mux(ObjectSubclass<imp::DASHMP4Mux>) @extends FMP4Mux, gst_base::Aggregator, gst::Element, gst::Object;
|
||||
}
|
||||
|
||||
glib::wrapper! {
|
||||
pub(crate) struct ONVIFFMP4Mux(ObjectSubclass<imp::ONVIFFMP4Mux>) @extends FMP4Mux, gst_base::Aggregator, gst::Element, gst::Object;
|
||||
}
|
||||
|
||||
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
|
||||
#[cfg(feature = "doc")]
|
||||
{
|
||||
FMP4Mux::static_type().mark_as_plugin_api(gst::PluginAPIFlags::empty());
|
||||
FMP4MuxPad::static_type().mark_as_plugin_api(gst::PluginAPIFlags::empty());
|
||||
HeaderUpdateMode::static_type().mark_as_plugin_api(gst::PluginAPIFlags::empty());
|
||||
}
|
||||
gst::Element::register(
|
||||
Some(plugin),
|
||||
"isofmp4mux",
|
||||
gst::Rank::PRIMARY,
|
||||
ISOFMP4Mux::static_type(),
|
||||
)?;
|
||||
gst::Element::register(
|
||||
Some(plugin),
|
||||
"cmafmux",
|
||||
gst::Rank::PRIMARY,
|
||||
CMAFMux::static_type(),
|
||||
)?;
|
||||
gst::Element::register(
|
||||
Some(plugin),
|
||||
"dashmp4mux",
|
||||
gst::Rank::PRIMARY,
|
||||
DASHMP4Mux::static_type(),
|
||||
)?;
|
||||
gst::Element::register(
|
||||
Some(plugin),
|
||||
"onviffmp4mux",
|
||||
gst::Rank::PRIMARY,
|
||||
ONVIFFMP4Mux::static_type(),
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HeaderConfiguration {
|
||||
variant: Variant,
|
||||
update: bool,
|
||||
|
||||
/// Pre-defined movie timescale if not 0.
|
||||
movie_timescale: u32,
|
||||
|
||||
/// First caps must be the video/reference stream. Must be in the order the tracks are going to
|
||||
/// be used later for the fragments too.
|
||||
streams: Vec<HeaderStream>,
|
||||
|
||||
write_mehd: bool,
|
||||
duration: Option<gst::ClockTime>,
|
||||
|
||||
/// Start UTC time in ONVIF mode.
|
||||
/// Since Jan 1 1601 in 100ns units.
|
||||
start_utc_time: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HeaderStream {
|
||||
/// Caps of this stream
|
||||
caps: gst::Caps,
|
||||
|
||||
/// Set if this is an intra-only stream
|
||||
delta_frames: DeltaFrames,
|
||||
|
||||
/// Pre-defined trak timescale if not 0.
|
||||
trak_timescale: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct FragmentHeaderConfiguration<'a> {
|
||||
variant: Variant,
|
||||
|
||||
/// Sequence number for this fragment.
|
||||
sequence_number: u32,
|
||||
|
||||
/// If this is a full fragment or only a chunk.
|
||||
chunk: bool,
|
||||
|
||||
streams: &'a [FragmentHeaderStream],
|
||||
buffers: &'a [Buffer],
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct FragmentHeaderStream {
|
||||
/// Caps of this stream
|
||||
caps: gst::Caps,
|
||||
|
||||
/// Set if this is an intra-only stream
|
||||
delta_frames: DeltaFrames,
|
||||
|
||||
/// Pre-defined trak timescale if not 0.
|
||||
trak_timescale: u32,
|
||||
|
||||
/// Start time of this fragment
|
||||
///
|
||||
/// `None` if this stream has no buffers in this fragment.
|
||||
start_time: Option<gst::ClockTime>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(crate) enum DeltaFrames {
|
||||
/// Only single completely decodable frames
|
||||
IntraOnly,
|
||||
/// Frames may depend on past frames
|
||||
PredictiveOnly,
|
||||
/// Frames may depend on past or future frames
|
||||
Bidirectional,
|
||||
}
|
||||
|
||||
impl DeltaFrames {
|
||||
/// Whether dts is required to order buffers differently from presentation order
|
||||
pub(crate) fn requires_dts(&self) -> bool {
|
||||
matches!(self, Self::Bidirectional)
|
||||
}
|
||||
/// Whether this coding structure does not allow delta flags on buffers
|
||||
pub(crate) fn intra_only(&self) -> bool {
|
||||
matches!(self, Self::IntraOnly)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Buffer {
|
||||
/// Track index
|
||||
idx: usize,
|
||||
|
||||
/// Actual buffer
|
||||
buffer: gst::Buffer,
|
||||
|
||||
/// Timestamp
|
||||
timestamp: gst::ClockTime,
|
||||
|
||||
/// Sample duration
|
||||
duration: gst::ClockTime,
|
||||
|
||||
/// Composition time offset
|
||||
composition_time_offset: Option<i64>,
|
||||
}
|
||||
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Variant {
|
||||
ISO,
|
||||
CMAF,
|
||||
DASH,
|
||||
ONVIF,
|
||||
}
|
||||
|
||||
impl Variant {
|
||||
pub(crate) fn is_single_stream(self) -> bool {
|
||||
match self {
|
||||
Variant::ISO | Variant::ONVIF => false,
|
||||
Variant::CMAF | Variant::DASH => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct FragmentOffset {
|
||||
time: gst::ClockTime,
|
||||
offset: u64,
|
||||
}
|
||||
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, glib::Enum)]
|
||||
#[repr(i32)]
|
||||
#[enum_type(name = "GstFMP4MuxHeaderUpdateMode")]
|
||||
pub(crate) enum HeaderUpdateMode {
|
||||
None,
|
||||
Rewrite,
|
||||
Update,
|
||||
}
|
||||
39
gstreamer/src/lib.rs
Normal file
39
gstreamer/src/lib.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
// Copyright (C) 2021 Sebastian Dröge <sebastian@centricular.com>
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the Mozilla Public License, v2.0.
|
||||
// If a copy of the MPL was not distributed with this file, You can obtain one at
|
||||
// <https://mozilla.org/MPL/2.0/>.
|
||||
//
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#![allow(clippy::non_send_fields_in_send_ty, unused_doc_comments)]
|
||||
|
||||
/**
|
||||
* plugin-fmp4:
|
||||
*
|
||||
* Since: plugins-rs-0.8.0
|
||||
*/
|
||||
use gst::glib;
|
||||
|
||||
mod fmp4mux;
|
||||
mod warpsink;
|
||||
mod waylandsrc;
|
||||
|
||||
fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
|
||||
waylandsrc::register(plugin)?;
|
||||
fmp4mux::register(plugin)?;
|
||||
warpsink::register(plugin)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
gst::plugin_define!(
|
||||
warp,
|
||||
env!("CARGO_PKG_DESCRIPTION"),
|
||||
plugin_init,
|
||||
concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
|
||||
// FIXME: MPL-2.0 is only allowed since 1.18.3 (as unknown) and 1.20 (as known)
|
||||
"MPL",
|
||||
env!("CARGO_PKG_NAME"),
|
||||
env!("CARGO_PKG_NAME"),
|
||||
env!("CARGO_PKG_REPOSITORY"),
|
||||
env!("BUILD_REL_DATE")
|
||||
);
|
||||
@@ -34,7 +34,7 @@ impl ElementImpl for MoqSink {
|
||||
"MoQ Sink",
|
||||
"Sink/Network",
|
||||
"Send data over QUIC using the MoQ protocol",
|
||||
"Wanjohi Ryan <elviswanjohi47@gmail.com>",
|
||||
"Wanjohi Ryan<wanjohi.ryan@example.com>",
|
||||
)
|
||||
});
|
||||
Some(&*ELEMENT_METADATA)
|
||||
@@ -94,58 +94,14 @@ impl BaseSinkImpl for MoqSink {
|
||||
|
||||
fn render(&self, element: &Self::Type, buffer: &gst::Buffer) -> Result<gst::FlowSuccess, gst::FlowError> {
|
||||
// Send buffer data over QUIC using moq_transport.
|
||||
// Extract data from the buffer
|
||||
let data = buffer.map_readable().map_err(|_| gst::FlowError::Error)?;
|
||||
// from the provided `imp.rs` code. For simplicity, we'll just print the buffer size.
|
||||
|
||||
let size = buffer.size();
|
||||
println!("Received buffer of size {}", size);
|
||||
|
||||
// Assuming that the upstream element is producing MP4 atoms, we need to distinguish
|
||||
// between 'moof' and 'mdat' atoms. We will also assume that each buffer contains a
|
||||
// complete atom for simplicity. In a real-world scenario, you might need to handle
|
||||
// partial atoms and reassemble them here.
|
||||
//
|
||||
// The first 4 bytes of the buffer contain the size of the atom, and the next 4 bytes
|
||||
// contain the atom type. For 'moof' and 'mdat', we would send them as separate messages
|
||||
// or bundle them together, depending on the protocol requirements.
|
||||
// You would then send the buffer data over QUIC using moq_transport.
|
||||
// This part is omitted and should be implemented based on your transport protocol.
|
||||
|
||||
// Check if the buffer is large enough to contain the size and type of the atom.
|
||||
if data.len() < 8 {
|
||||
gst::element_error!(
|
||||
element,
|
||||
gst::CoreError::Failed,
|
||||
("Buffer is too small to contain an MP4 atom")
|
||||
);
|
||||
return Err(gst::FlowError::Error);
|
||||
}
|
||||
|
||||
// Read atom size and type
|
||||
let size = u32::from_be_bytes(data[0..4].try_into().unwrap()) as usize;
|
||||
let atom_type = &data[4..8];
|
||||
|
||||
// Ensure the buffer contains the complete atom
|
||||
if size > data.len() {
|
||||
gst::element_error!(
|
||||
element,
|
||||
gst::CoreError::Failed,
|
||||
("Buffer does not contain the complete MP4 atom")
|
||||
);
|
||||
return Err(gst::FlowError::Error);
|
||||
}
|
||||
|
||||
// Handle 'moof' and 'mdat' atoms
|
||||
match atom_type {
|
||||
b"moof" => {
|
||||
// Handle 'moof' atom
|
||||
// Send the 'moof' atom over the moq_transport protocol
|
||||
// self.moq_transport.send_moof(data.as_slice());
|
||||
},
|
||||
b"mdat" => {
|
||||
// Handle 'mdat' atom
|
||||
// Send the 'mdat' atom over the moq_transport protocol
|
||||
// self.moq_transport.send_mdat(data.as_slice());
|
||||
},
|
||||
_ => {
|
||||
// Handle other atoms or ignore them
|
||||
}
|
||||
}
|
||||
Ok(gst::FlowSuccess::Ok)
|
||||
}
|
||||
}
|
||||
282
gstreamer/src/wayland/imp.rs
Normal file
282
gstreamer/src/wayland/imp.rs
Normal file
@@ -0,0 +1,282 @@
|
||||
use std::sync::Mutex;
|
||||
|
||||
use gst::message::Application;
|
||||
use gst_video::{VideoCapsBuilder, VideoFormat};
|
||||
|
||||
use gst::subclass::prelude::*;
|
||||
use gst::{glib, Event, Fraction};
|
||||
use gst::{
|
||||
glib::{once_cell::sync::Lazy, ValueArray},
|
||||
LibraryError,
|
||||
};
|
||||
use gst::{prelude::*, Structure};
|
||||
|
||||
use gst_base::subclass::base_src::CreateSuccess;
|
||||
use gst_base::subclass::prelude::*;
|
||||
use gst_base::traits::BaseSrcExt;
|
||||
|
||||
use waylanddisplaycore::WaylandDisplay;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::Registry;
|
||||
|
||||
use crate::utils::{GstLayer, CAT};
|
||||
|
||||
pub struct WaylandDisplaySrc {
|
||||
state: Mutex<Option<State>>,
|
||||
settings: Mutex<Settings>,
|
||||
}
|
||||
|
||||
impl Default for WaylandDisplaySrc {
|
||||
fn default() -> Self {
|
||||
WaylandDisplaySrc {
|
||||
state: Mutex::new(None),
|
||||
settings: Mutex::new(Settings::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Settings {
|
||||
render_node: Option<String>,
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
display: WaylandDisplay,
|
||||
}
|
||||
|
||||
#[glib::object_subclass]
|
||||
impl ObjectSubclass for WaylandDisplaySrc {
|
||||
const NAME: &'static str = "GstWaylandDisplaySrc";
|
||||
type Type = super::WaylandDisplaySrc;
|
||||
type ParentType = gst_base::PushSrc;
|
||||
type Interfaces = ();
|
||||
}
|
||||
|
||||
impl ObjectImpl for WaylandDisplaySrc {
|
||||
fn properties() -> &'static [glib::ParamSpec] {
|
||||
static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
|
||||
vec![glib::ParamSpecString::builder("render-node")
|
||||
.nick("DRM Render Node")
|
||||
.blurb("DRM Render Node to use (e.g. /dev/dri/renderD128")
|
||||
.construct()
|
||||
.build()]
|
||||
});
|
||||
|
||||
PROPERTIES.as_ref()
|
||||
}
|
||||
|
||||
fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
|
||||
match pspec.name() {
|
||||
"render-node" => {
|
||||
let mut settings = self.settings.lock().unwrap();
|
||||
settings.render_node = value
|
||||
.get::<Option<String>>()
|
||||
.expect("Type checked upstream");
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
|
||||
match pspec.name() {
|
||||
"render-node" => {
|
||||
let settings = self.settings.lock().unwrap();
|
||||
settings
|
||||
.render_node
|
||||
.clone()
|
||||
.unwrap_or_else(|| String::from("/dev/dri/renderD128"))
|
||||
.to_value()
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn constructed(&self) {
|
||||
self.parent_constructed();
|
||||
|
||||
let obj = self.obj();
|
||||
obj.set_element_flags(gst::ElementFlags::SOURCE);
|
||||
obj.set_live(true);
|
||||
obj.set_format(gst::Format::Time);
|
||||
obj.set_automatic_eos(false);
|
||||
obj.set_do_timestamp(true);
|
||||
}
|
||||
}
|
||||
|
||||
impl GstObjectImpl for WaylandDisplaySrc {}
|
||||
|
||||
impl ElementImpl for WaylandDisplaySrc {
|
||||
fn metadata() -> Option<&'static gst::subclass::ElementMetadata> {
|
||||
static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| {
|
||||
gst::subclass::ElementMetadata::new(
|
||||
"Wayland display source",
|
||||
"Source/Video",
|
||||
"GStreamer video src running a wayland compositor",
|
||||
"Victoria Brekenfeld <wayland@drakulix.de>",
|
||||
)
|
||||
});
|
||||
|
||||
Some(&*ELEMENT_METADATA)
|
||||
}
|
||||
|
||||
fn pad_templates() -> &'static [gst::PadTemplate] {
|
||||
static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| {
|
||||
let caps = gst_video::VideoCapsBuilder::new()
|
||||
.format(VideoFormat::Rgbx)
|
||||
.height_range(..i32::MAX)
|
||||
.width_range(..i32::MAX)
|
||||
.framerate_range(Fraction::new(1, 1)..Fraction::new(i32::MAX, 1))
|
||||
.build();
|
||||
let src_pad_template = gst::PadTemplate::new(
|
||||
"src",
|
||||
gst::PadDirection::Src,
|
||||
gst::PadPresence::Always,
|
||||
&caps,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
vec![src_pad_template]
|
||||
});
|
||||
|
||||
PAD_TEMPLATES.as_ref()
|
||||
}
|
||||
|
||||
fn change_state(
|
||||
&self,
|
||||
transition: gst::StateChange,
|
||||
) -> Result<gst::StateChangeSuccess, gst::StateChangeError> {
|
||||
let res = self.parent_change_state(transition);
|
||||
match res {
|
||||
Ok(gst::StateChangeSuccess::Success) => {
|
||||
if transition.next() == gst::State::Paused {
|
||||
// this is a live source
|
||||
Ok(gst::StateChangeSuccess::NoPreroll)
|
||||
} else {
|
||||
Ok(gst::StateChangeSuccess::Success)
|
||||
}
|
||||
}
|
||||
x => x,
|
||||
}
|
||||
}
|
||||
|
||||
fn query(&self, query: &mut gst::QueryRef) -> bool {
|
||||
ElementImplExt::parent_query(self, query)
|
||||
}
|
||||
}
|
||||
|
||||
impl BaseSrcImpl for WaylandDisplaySrc {
|
||||
fn query(&self, query: &mut gst::QueryRef) -> bool {
|
||||
BaseSrcImplExt::parent_query(self, query)
|
||||
}
|
||||
|
||||
fn caps(&self, filter: Option<&gst::Caps>) -> Option<gst::Caps> {
|
||||
let mut caps = VideoCapsBuilder::new()
|
||||
.format(VideoFormat::Rgbx)
|
||||
.height_range(..i32::MAX)
|
||||
.width_range(..i32::MAX)
|
||||
.framerate_range(Fraction::new(1, 1)..Fraction::new(i32::MAX, 1))
|
||||
.build();
|
||||
|
||||
if let Some(filter) = filter {
|
||||
caps = caps.intersect(filter);
|
||||
}
|
||||
|
||||
Some(caps)
|
||||
}
|
||||
|
||||
fn negotiate(&self) -> Result<(), gst::LoggableError> {
|
||||
self.parent_negotiate()
|
||||
}
|
||||
|
||||
fn event(&self, event: &Event) -> bool {
|
||||
if event.type_() == gst::EventType::CustomUpstream {
|
||||
let structure = event.structure().expect("Unable to get message structure");
|
||||
if structure.has_name("VirtualDevicesReady") {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
let display = &mut state.as_mut().unwrap().display;
|
||||
|
||||
let paths = structure
|
||||
.get::<ValueArray>("paths")
|
||||
.expect("Should contain paths");
|
||||
for value in paths.into_iter() {
|
||||
let path = value.get::<String>().expect("Paths are strings");
|
||||
display.add_input_device(path);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
self.parent_event(event)
|
||||
}
|
||||
|
||||
fn set_caps(&self, caps: &gst::Caps) -> Result<(), gst::LoggableError> {
|
||||
let video_info = gst_video::VideoInfo::from_caps(caps).expect("failed to get video info");
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.display
|
||||
.set_video_info(video_info);
|
||||
|
||||
self.parent_set_caps(caps)
|
||||
}
|
||||
|
||||
fn start(&self) -> Result<(), gst::ErrorMessage> {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if state.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let settings = self.settings.lock().unwrap();
|
||||
let elem = self.obj().upcast_ref::<gst::Element>().to_owned();
|
||||
let subscriber = Registry::default().with(GstLayer);
|
||||
|
||||
let Ok(mut display) = tracing::subscriber::with_default(subscriber, || WaylandDisplay::new(settings.render_node.clone())) else {
|
||||
return Err(gst::error_msg!(LibraryError::Failed, ("Failed to open drm node {}, if you want to utilize software rendering set `render-node=software`.", settings.render_node.as_deref().unwrap_or("/dev/dri/renderD128"))));
|
||||
};
|
||||
|
||||
let mut structure = Structure::builder("wayland.src");
|
||||
for (key, var) in display.env_vars().flat_map(|var| var.split_once("=")) {
|
||||
structure = structure.field(key, var);
|
||||
}
|
||||
let structure = structure.build();
|
||||
if let Err(err) = elem.post_message(Application::builder(structure).src(&elem).build()) {
|
||||
gst::warning!(CAT, "Failed to post environment to gstreamer bus: {}", err);
|
||||
}
|
||||
|
||||
*state = Some(State { display });
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stop(&self) -> Result<(), gst::ErrorMessage> {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if let Some(state) = state.take() {
|
||||
let subscriber = Registry::default().with(GstLayer);
|
||||
tracing::subscriber::with_default(subscriber, || std::mem::drop(state.display));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_seekable(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl PushSrcImpl for WaylandDisplaySrc {
|
||||
fn create(
|
||||
&self,
|
||||
_buffer: Option<&mut gst::BufferRef>,
|
||||
) -> Result<CreateSuccess, gst::FlowError> {
|
||||
let mut state_guard = self.state.lock().unwrap();
|
||||
let Some(state) = state_guard.as_mut() else {
|
||||
return Err(gst::FlowError::Eos);
|
||||
};
|
||||
|
||||
let subscriber = Registry::default().with(GstLayer);
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
state.display.frame().map(CreateSuccess::NewBuffer)
|
||||
})
|
||||
}
|
||||
}
|
||||
17
gstreamer/src/wayland/mod.rs
Normal file
17
gstreamer/src/wayland/mod.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use gst::glib;
|
||||
use gst::prelude::*;
|
||||
|
||||
mod imp;
|
||||
|
||||
glib::wrapper! {
|
||||
pub struct WaylandDisplaySrc(ObjectSubclass<imp::WaylandDisplaySrc>) @extends gst_base::PushSrc, gst_base::BaseSrc, gst::Element, gst::Object;
|
||||
}
|
||||
|
||||
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
|
||||
gst::Element::register(
|
||||
Some(plugin),
|
||||
"waylanddisplaysrc",
|
||||
gst::Rank::Marginal,
|
||||
WaylandDisplaySrc::static_type(),
|
||||
)
|
||||
}
|
||||
1315
moq-transport/Cargo.lock
generated
Normal file
1315
moq-transport/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
52
moq-transport/Cargo.toml
Normal file
52
moq-transport/Cargo.toml
Normal file
@@ -0,0 +1,52 @@
|
||||
[package]
|
||||
name = "moq-transport"
|
||||
description = "Media over QUIC"
|
||||
authors = ["Luke Curley"]
|
||||
repository = "https://github.com/kixelated/moq-rs"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
|
||||
keywords = ["quic", "http3", "webtransport", "media", "live"]
|
||||
categories = ["multimedia", "network-programming", "web-programming"]
|
||||
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bytes = "1"
|
||||
thiserror = "1"
|
||||
tokio = { version = "1", features = ["macros", "io-util", "sync"] }
|
||||
log = "0.4"
|
||||
indexmap = "2"
|
||||
|
||||
quinn = "0.10"
|
||||
webtransport-quinn = "0.6.1"
|
||||
#webtransport-quinn = { path = "../../webtransport-rs/webtransport-quinn" }
|
||||
|
||||
async-trait = "0.1"
|
||||
paste = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
# QUIC
|
||||
url = "2"
|
||||
|
||||
# Crypto
|
||||
rustls = { version = "0.21", features = ["dangerous_configuration"] }
|
||||
rustls-native-certs = "0.6"
|
||||
rustls-pemfile = "1"
|
||||
|
||||
# Async stuff
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
||||
# CLI, logging, error handling
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
log = { version = "0.4", features = ["std"] }
|
||||
env_logger = "0.9"
|
||||
mp4 = "0.13"
|
||||
anyhow = { version = "1", features = ["backtrace"] }
|
||||
serde_json = "1"
|
||||
rfc6381-codec = "0.1"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = "0.3"
|
||||
202
moq-transport/LICENSE-APACHE
Normal file
202
moq-transport/LICENSE-APACHE
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
21
moq-transport/LICENSE-MIT
Normal file
21
moq-transport/LICENSE-MIT
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Luke Curley
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
10
moq-transport/README.md
Normal file
10
moq-transport/README.md
Normal file
@@ -0,0 +1,10 @@
|
||||
[](https://docs.rs/moq-transport/)
|
||||
[](https://crates.io/crates/moq-transport)
|
||||
[](LICENSE-MIT)
|
||||
|
||||
# moq-transport
|
||||
|
||||
A Rust implementation of the proposed IETF standard.
|
||||
|
||||
[Specification](https://datatracker.ietf.org/doc/draft-ietf-moq-transport/)
|
||||
[Github](https://github.com/moq-wg/moq-transport)
|
||||
262
moq-transport/src/cache/broadcast.rs
vendored
Normal file
262
moq-transport/src/cache/broadcast.rs
vendored
Normal file
@@ -0,0 +1,262 @@
|
||||
//! A broadcast is a collection of tracks, split into two handles: [Publisher] and [Subscriber].
|
||||
//!
|
||||
//! The [Publisher] can create tracks, either manually or on request.
|
||||
//! It receives all requests by a [Subscriber] for a tracks that don't exist.
|
||||
//! The simplest implementation is to close every unknown track with [CacheError::NotFound].
|
||||
//!
|
||||
//! A [Subscriber] can request tracks by name.
|
||||
//! If the track already exists, it will be returned.
|
||||
//! If the track doesn't exist, it will be sent to [Unknown] to be handled.
|
||||
//! A [Subscriber] can be cloned to create multiple subscriptions.
|
||||
//!
|
||||
//! The broadcast is automatically closed with [CacheError::Closed] when [Publisher] is dropped, or all [Subscriber]s are dropped.
|
||||
use std::{
|
||||
collections::{hash_map, HashMap, VecDeque},
|
||||
fmt,
|
||||
ops::Deref,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use super::{track, CacheError, Watch};
|
||||
|
||||
/// Create a new broadcast.
|
||||
pub fn new(id: &str) -> (Publisher, Subscriber) {
|
||||
let state = Watch::new(State::default());
|
||||
let info = Arc::new(Info { id: id.to_string() });
|
||||
|
||||
let publisher = Publisher::new(state.clone(), info.clone());
|
||||
let subscriber = Subscriber::new(state, info);
|
||||
|
||||
(publisher, subscriber)
|
||||
}
|
||||
|
||||
/// Static information about a broadcast.
|
||||
#[derive(Debug)]
|
||||
pub struct Info {
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
/// Dynamic information about the broadcast.
|
||||
#[derive(Debug)]
|
||||
struct State {
|
||||
tracks: HashMap<String, track::Subscriber>,
|
||||
requested: VecDeque<track::Publisher>,
|
||||
closed: Result<(), CacheError>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn get(&self, name: &str) -> Result<Option<track::Subscriber>, CacheError> {
|
||||
// Don't check closed, so we can return from cache.
|
||||
Ok(self.tracks.get(name).cloned())
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, track: track::Subscriber) -> Result<(), CacheError> {
|
||||
self.closed.clone()?;
|
||||
|
||||
match self.tracks.entry(track.name.clone()) {
|
||||
hash_map::Entry::Occupied(_) => return Err(CacheError::Duplicate),
|
||||
hash_map::Entry::Vacant(v) => v.insert(track),
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn request(&mut self, name: &str) -> Result<track::Subscriber, CacheError> {
|
||||
self.closed.clone()?;
|
||||
|
||||
// Create a new track.
|
||||
let (publisher, subscriber) = track::new(name);
|
||||
|
||||
// Insert the track into our Map so we deduplicate future requests.
|
||||
self.tracks.insert(name.to_string(), subscriber.clone());
|
||||
|
||||
// Send the track to the Publisher to handle.
|
||||
self.requested.push_back(publisher);
|
||||
|
||||
Ok(subscriber)
|
||||
}
|
||||
|
||||
pub fn has_next(&self) -> Result<bool, CacheError> {
|
||||
// Check if there's any elements in the queue before checking closed.
|
||||
if !self.requested.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
self.closed.clone()?;
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub fn next(&mut self) -> track::Publisher {
|
||||
// We panic instead of erroring to avoid a nasty wakeup loop if you don't call has_next first.
|
||||
self.requested.pop_front().expect("no entry in queue")
|
||||
}
|
||||
|
||||
pub fn close(&mut self, err: CacheError) -> Result<(), CacheError> {
|
||||
self.closed.clone()?;
|
||||
self.closed = Err(err);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tracks: HashMap::new(),
|
||||
closed: Ok(()),
|
||||
requested: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish new tracks for a broadcast by name.
|
||||
// TODO remove Clone
|
||||
#[derive(Clone)]
|
||||
pub struct Publisher {
|
||||
state: Watch<State>,
|
||||
info: Arc<Info>,
|
||||
_dropped: Arc<Dropped>,
|
||||
}
|
||||
|
||||
impl Publisher {
|
||||
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
|
||||
let _dropped = Arc::new(Dropped::new(state.clone()));
|
||||
Self { state, info, _dropped }
|
||||
}
|
||||
|
||||
/// Create a new track with the given name, inserting it into the broadcast.
|
||||
pub fn create_track(&mut self, name: &str) -> Result<track::Publisher, CacheError> {
|
||||
let (publisher, subscriber) = track::new(name);
|
||||
self.state.lock_mut().insert(subscriber)?;
|
||||
Ok(publisher)
|
||||
}
|
||||
|
||||
/// Insert a track into the broadcast.
|
||||
pub fn insert_track(&mut self, track: track::Subscriber) -> Result<(), CacheError> {
|
||||
self.state.lock_mut().insert(track)
|
||||
}
|
||||
|
||||
/// Block until the next track requested by a subscriber.
|
||||
pub async fn next_track(&mut self) -> Result<track::Publisher, CacheError> {
|
||||
loop {
|
||||
let notify = {
|
||||
let state = self.state.lock();
|
||||
if state.has_next()? {
|
||||
return Ok(state.into_mut().next());
|
||||
}
|
||||
|
||||
state.changed()
|
||||
};
|
||||
|
||||
notify.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Close the broadcast with an error.
|
||||
pub fn close(self, err: CacheError) -> Result<(), CacheError> {
|
||||
self.state.lock_mut().close(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Publisher {
|
||||
type Target = Info;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.info
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Publisher {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Publisher")
|
||||
.field("state", &self.state)
|
||||
.field("info", &self.info)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribe to a broadcast by requesting tracks.
|
||||
///
|
||||
/// This can be cloned to create handles.
|
||||
#[derive(Clone)]
|
||||
pub struct Subscriber {
|
||||
state: Watch<State>,
|
||||
info: Arc<Info>,
|
||||
_dropped: Arc<Dropped>,
|
||||
}
|
||||
|
||||
impl Subscriber {
|
||||
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
|
||||
let _dropped = Arc::new(Dropped::new(state.clone()));
|
||||
Self { state, info, _dropped }
|
||||
}
|
||||
|
||||
/// Get a track from the broadcast by name.
|
||||
/// If the track does not exist, it will be created and potentially fufilled by the publisher (via Unknown).
|
||||
/// Otherwise, it will return [CacheError::NotFound].
|
||||
pub fn get_track(&self, name: &str) -> Result<track::Subscriber, CacheError> {
|
||||
let state = self.state.lock();
|
||||
if let Some(track) = state.get(name)? {
|
||||
return Ok(track);
|
||||
}
|
||||
|
||||
// Request a new track if it does not exist.
|
||||
state.into_mut().request(name)
|
||||
}
|
||||
|
||||
/// Check if the broadcast is closed, either because the publisher was dropped or called [Publisher::close].
|
||||
pub fn is_closed(&self) -> Option<CacheError> {
|
||||
self.state.lock().closed.as_ref().err().cloned()
|
||||
}
|
||||
|
||||
/// Wait until if the broadcast is closed, either because the publisher was dropped or called [Publisher::close].
|
||||
pub async fn closed(&self) -> CacheError {
|
||||
loop {
|
||||
let notify = {
|
||||
let state = self.state.lock();
|
||||
if let Some(err) = state.closed.as_ref().err() {
|
||||
return err.clone();
|
||||
}
|
||||
|
||||
state.changed()
|
||||
};
|
||||
|
||||
notify.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Subscriber {
|
||||
type Target = Info;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.info
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Subscriber {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Subscriber")
|
||||
.field("state", &self.state)
|
||||
.field("info", &self.info)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
// A handle that closes the broadcast when dropped:
|
||||
// - when all Subscribers are dropped or
|
||||
// - when Publisher and Unknown are dropped.
|
||||
struct Dropped {
|
||||
state: Watch<State>,
|
||||
}
|
||||
|
||||
impl Dropped {
|
||||
fn new(state: Watch<State>) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dropped {
|
||||
fn drop(&mut self) {
|
||||
self.state.lock_mut().close(CacheError::Closed).ok();
|
||||
}
|
||||
}
|
||||
51
moq-transport/src/cache/error.rs
vendored
Normal file
51
moq-transport/src/cache/error.rs
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::MoqError;
|
||||
|
||||
#[derive(Clone, Debug, Error)]
|
||||
pub enum CacheError {
|
||||
/// A clean termination, represented as error code 0.
|
||||
/// This error is automatically used when publishers or subscribers are dropped without calling close.
|
||||
#[error("closed")]
|
||||
Closed,
|
||||
|
||||
/// An ANNOUNCE_RESET or SUBSCRIBE_RESET was sent by the publisher.
|
||||
#[error("reset code={0:?}")]
|
||||
Reset(u32),
|
||||
|
||||
/// An ANNOUNCE_STOP or SUBSCRIBE_STOP was sent by the subscriber.
|
||||
#[error("stop")]
|
||||
Stop,
|
||||
|
||||
/// The requested resource was not found.
|
||||
#[error("not found")]
|
||||
NotFound,
|
||||
|
||||
/// A resource already exists with that ID.
|
||||
#[error("duplicate")]
|
||||
Duplicate,
|
||||
}
|
||||
|
||||
impl MoqError for CacheError {
|
||||
/// An integer code that is sent over the wire.
|
||||
fn code(&self) -> u32 {
|
||||
match self {
|
||||
Self::Closed => 0,
|
||||
Self::Reset(code) => *code,
|
||||
Self::Stop => 206,
|
||||
Self::NotFound => 404,
|
||||
Self::Duplicate => 409,
|
||||
}
|
||||
}
|
||||
|
||||
/// A reason that is sent over the wire.
|
||||
fn reason(&self) -> String {
|
||||
match self {
|
||||
Self::Closed => "closed".to_owned(),
|
||||
Self::Reset(code) => format!("reset code: {}", code),
|
||||
Self::Stop => "stop".to_owned(),
|
||||
Self::NotFound => "not found".to_owned(),
|
||||
Self::Duplicate => "duplicate".to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
208
moq-transport/src/cache/fragment.rs
vendored
Normal file
208
moq-transport/src/cache/fragment.rs
vendored
Normal file
@@ -0,0 +1,208 @@
|
||||
//! A fragment is a stream of bytes with a header, split into a [Publisher] and [Subscriber] handle.
|
||||
//!
|
||||
//! A [Publisher] writes an ordered stream of bytes in chunks.
|
||||
//! There's no framing, so these chunks can be of any size or position, and won't be maintained over the network.
|
||||
//!
|
||||
//! A [Subscriber] reads an ordered stream of bytes in chunks.
|
||||
//! These chunks are returned directly from the QUIC connection, so they may be of any size or position.
|
||||
//! You can clone the [Subscriber] and each will read a copy of of all future chunks. (fanout)
|
||||
//!
|
||||
//! The fragment is closed with [CacheError::Closed] when all publishers or subscribers are dropped.
|
||||
use core::fmt;
|
||||
use std::{ops::Deref, sync::Arc};
|
||||
|
||||
use crate::VarInt;
|
||||
use bytes::Bytes;
|
||||
|
||||
use super::{CacheError, Watch};
|
||||
|
||||
/// Create a new segment with the given info.
|
||||
pub fn new(info: Info) -> (Publisher, Subscriber) {
|
||||
let state = Watch::new(State::default());
|
||||
let info = Arc::new(info);
|
||||
|
||||
let publisher = Publisher::new(state.clone(), info.clone());
|
||||
let subscriber = Subscriber::new(state, info);
|
||||
|
||||
(publisher, subscriber)
|
||||
}
|
||||
|
||||
/// Static information about the segment.
|
||||
#[derive(Debug)]
|
||||
pub struct Info {
|
||||
// The sequence number of the fragment within the segment.
|
||||
// NOTE: These may be received out of order or with gaps.
|
||||
pub sequence: VarInt,
|
||||
|
||||
// The size of the fragment, optionally None if this is the last fragment in a segment.
|
||||
// TODO enforce this size.
|
||||
pub size: Option<usize>,
|
||||
}
|
||||
|
||||
struct State {
|
||||
// The data that has been received thus far.
|
||||
chunks: Vec<Bytes>,
|
||||
|
||||
// Set when the publisher is dropped.
|
||||
closed: Result<(), CacheError>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn close(&mut self, err: CacheError) -> Result<(), CacheError> {
|
||||
self.closed.clone()?;
|
||||
self.closed = Err(err);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
chunks: Vec::new(),
|
||||
closed: Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for State {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
// We don't want to print out the contents, so summarize.
|
||||
f.debug_struct("State").field("closed", &self.closed).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to write data to a segment and notify subscribers.
|
||||
pub struct Publisher {
|
||||
// Mutable segment state.
|
||||
state: Watch<State>,
|
||||
|
||||
// Immutable segment state.
|
||||
info: Arc<Info>,
|
||||
|
||||
// Closes the segment when all Publishers are dropped.
|
||||
_dropped: Arc<Dropped>,
|
||||
}
|
||||
|
||||
impl Publisher {
|
||||
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
|
||||
let _dropped = Arc::new(Dropped::new(state.clone()));
|
||||
Self { state, info, _dropped }
|
||||
}
|
||||
|
||||
/// Write a new chunk of bytes.
|
||||
pub fn chunk(&mut self, chunk: Bytes) -> Result<(), CacheError> {
|
||||
let mut state = self.state.lock_mut();
|
||||
state.closed.clone()?;
|
||||
state.chunks.push(chunk);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close the segment with an error.
|
||||
pub fn close(self, err: CacheError) -> Result<(), CacheError> {
|
||||
self.state.lock_mut().close(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Publisher {
|
||||
type Target = Info;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.info
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Publisher {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Publisher")
|
||||
.field("state", &self.state)
|
||||
.field("info", &self.info)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Notified when a segment has new data available.
|
||||
#[derive(Clone)]
|
||||
pub struct Subscriber {
|
||||
// Modify the segment state.
|
||||
state: Watch<State>,
|
||||
|
||||
// Immutable segment state.
|
||||
info: Arc<Info>,
|
||||
|
||||
// The number of chunks that we've read.
|
||||
// NOTE: Cloned subscribers inherit this index, but then run in parallel.
|
||||
index: usize,
|
||||
|
||||
// Dropped when all Subscribers are dropped.
|
||||
_dropped: Arc<Dropped>,
|
||||
}
|
||||
|
||||
impl Subscriber {
|
||||
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
|
||||
let _dropped = Arc::new(Dropped::new(state.clone()));
|
||||
|
||||
Self {
|
||||
state,
|
||||
info,
|
||||
index: 0,
|
||||
_dropped,
|
||||
}
|
||||
}
|
||||
|
||||
/// Block until the next chunk of bytes is available.
|
||||
pub async fn chunk(&mut self) -> Result<Option<Bytes>, CacheError> {
|
||||
loop {
|
||||
let notify = {
|
||||
let state = self.state.lock();
|
||||
if self.index < state.chunks.len() {
|
||||
let chunk = state.chunks[self.index].clone();
|
||||
self.index += 1;
|
||||
return Ok(Some(chunk));
|
||||
}
|
||||
|
||||
match &state.closed {
|
||||
Err(CacheError::Closed) => return Ok(None),
|
||||
Err(err) => return Err(err.clone()),
|
||||
Ok(()) => state.changed(),
|
||||
}
|
||||
};
|
||||
|
||||
notify.await; // Try again when the state changes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Subscriber {
|
||||
type Target = Info;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.info
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Subscriber {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Subscriber")
|
||||
.field("state", &self.state)
|
||||
.field("info", &self.info)
|
||||
.field("index", &self.index)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
struct Dropped {
|
||||
// Modify the segment state.
|
||||
state: Watch<State>,
|
||||
}
|
||||
|
||||
impl Dropped {
|
||||
fn new(state: Watch<State>) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dropped {
|
||||
fn drop(&mut self) {
|
||||
self.state.lock_mut().close(CacheError::Closed).ok();
|
||||
}
|
||||
}
|
||||
21
moq-transport/src/cache/mod.rs
vendored
Normal file
21
moq-transport/src/cache/mod.rs
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
//! Allows a publisher to push updates, automatically caching and fanning it out to any subscribers.
|
||||
//!
|
||||
//! The hierarchy is: [broadcast] -> [track] -> [segment] -> [fragment] -> [Bytes](bytes::Bytes)
|
||||
//!
|
||||
//! The naming scheme doesn't match the spec because it's more strict, and bikeshedding of course:
|
||||
//!
|
||||
//! - [broadcast] is kinda like "track namespace"
|
||||
//! - [track] is "track"
|
||||
//! - [segment] is "group" but MUST use a single stream.
|
||||
//! - [fragment] is "object" but MUST have the same properties as the segment.
|
||||
|
||||
pub mod broadcast;
|
||||
mod error;
|
||||
pub mod fragment;
|
||||
pub mod segment;
|
||||
pub mod track;
|
||||
|
||||
pub(crate) mod watch;
|
||||
pub(crate) use watch::*;
|
||||
|
||||
pub use error::*;
|
||||
226
moq-transport/src/cache/segment.rs
vendored
Normal file
226
moq-transport/src/cache/segment.rs
vendored
Normal file
@@ -0,0 +1,226 @@
|
||||
//! A segment is a stream of fragments with a header, split into a [Publisher] and [Subscriber] handle.
|
||||
//!
|
||||
//! A [Publisher] writes an ordered stream of fragments.
|
||||
//! Each fragment can have a sequence number, allowing the subscriber to detect gaps fragments.
|
||||
//!
|
||||
//! A [Subscriber] reads an ordered stream of fragments.
|
||||
//! The subscriber can be cloned, in which case each subscriber receives a copy of each fragment. (fanout)
|
||||
//!
|
||||
//! The segment is closed with [CacheError::Closed] when all publishers or subscribers are dropped.
|
||||
use core::fmt;
|
||||
use std::{ops::Deref, sync::Arc, time};
|
||||
|
||||
use crate::VarInt;
|
||||
|
||||
use super::{fragment, CacheError, Watch};
|
||||
|
||||
/// Create a new segment with the given info.
|
||||
pub fn new(info: Info) -> (Publisher, Subscriber) {
|
||||
let state = Watch::new(State::default());
|
||||
let info = Arc::new(info);
|
||||
|
||||
let publisher = Publisher::new(state.clone(), info.clone());
|
||||
let subscriber = Subscriber::new(state, info);
|
||||
|
||||
(publisher, subscriber)
|
||||
}
|
||||
|
||||
/// Static information about the segment.
|
||||
#[derive(Debug)]
|
||||
pub struct Info {
|
||||
// The sequence number of the segment within the track.
|
||||
// NOTE: These may be received out of order or with gaps.
|
||||
pub sequence: VarInt,
|
||||
|
||||
// The priority of the segment within the BROADCAST.
|
||||
pub priority: u32,
|
||||
|
||||
// Cache the segment for at most this long.
|
||||
pub expires: Option<time::Duration>,
|
||||
}
|
||||
|
||||
struct State {
|
||||
// The data that has been received thus far.
|
||||
fragments: Vec<fragment::Subscriber>,
|
||||
|
||||
// Set when the publisher is dropped.
|
||||
closed: Result<(), CacheError>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn close(&mut self, err: CacheError) -> Result<(), CacheError> {
|
||||
self.closed.clone()?;
|
||||
self.closed = Err(err);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fragments: Vec::new(),
|
||||
closed: Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for State {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("State")
|
||||
.field("fragments", &self.fragments)
|
||||
.field("closed", &self.closed)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to write data to a segment and notify subscribers.
|
||||
pub struct Publisher {
|
||||
// Mutable segment state.
|
||||
state: Watch<State>,
|
||||
|
||||
// Immutable segment state.
|
||||
info: Arc<Info>,
|
||||
|
||||
// Closes the segment when all Publishers are dropped.
|
||||
_dropped: Arc<Dropped>,
|
||||
}
|
||||
|
||||
impl Publisher {
|
||||
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
|
||||
let _dropped = Arc::new(Dropped::new(state.clone()));
|
||||
Self { state, info, _dropped }
|
||||
}
|
||||
|
||||
// Not public because it's a footgun.
|
||||
pub(crate) fn push_fragment(
|
||||
&mut self,
|
||||
sequence: VarInt,
|
||||
size: Option<usize>,
|
||||
) -> Result<fragment::Publisher, CacheError> {
|
||||
let (publisher, subscriber) = fragment::new(fragment::Info { sequence, size });
|
||||
|
||||
let mut state = self.state.lock_mut();
|
||||
state.closed.clone()?;
|
||||
state.fragments.push(subscriber);
|
||||
Ok(publisher)
|
||||
}
|
||||
|
||||
/// Write a fragment
|
||||
pub fn fragment(&mut self, sequence: VarInt, size: usize) -> Result<fragment::Publisher, CacheError> {
|
||||
self.push_fragment(sequence, Some(size))
|
||||
}
|
||||
|
||||
/// Write the last fragment, which means size can be unknown.
|
||||
pub fn final_fragment(mut self, sequence: VarInt) -> Result<fragment::Publisher, CacheError> {
|
||||
self.push_fragment(sequence, None)
|
||||
}
|
||||
|
||||
/// Close the segment with an error.
|
||||
pub fn close(self, err: CacheError) -> Result<(), CacheError> {
|
||||
self.state.lock_mut().close(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Publisher {
|
||||
type Target = Info;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.info
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Publisher {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Publisher")
|
||||
.field("state", &self.state)
|
||||
.field("info", &self.info)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Notified when a segment has new data available.
|
||||
#[derive(Clone)]
|
||||
pub struct Subscriber {
|
||||
// Modify the segment state.
|
||||
state: Watch<State>,
|
||||
|
||||
// Immutable segment state.
|
||||
info: Arc<Info>,
|
||||
|
||||
// The number of chunks that we've read.
|
||||
// NOTE: Cloned subscribers inherit this index, but then run in parallel.
|
||||
index: usize,
|
||||
|
||||
// Dropped when all Subscribers are dropped.
|
||||
_dropped: Arc<Dropped>,
|
||||
}
|
||||
|
||||
impl Subscriber {
|
||||
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
|
||||
let _dropped = Arc::new(Dropped::new(state.clone()));
|
||||
|
||||
Self {
|
||||
state,
|
||||
info,
|
||||
index: 0,
|
||||
_dropped,
|
||||
}
|
||||
}
|
||||
|
||||
/// Block until the next chunk of bytes is available.
|
||||
pub async fn fragment(&mut self) -> Result<Option<fragment::Subscriber>, CacheError> {
|
||||
loop {
|
||||
let notify = {
|
||||
let state = self.state.lock();
|
||||
if self.index < state.fragments.len() {
|
||||
let fragment = state.fragments[self.index].clone();
|
||||
self.index += 1;
|
||||
return Ok(Some(fragment));
|
||||
}
|
||||
|
||||
match &state.closed {
|
||||
Err(CacheError::Closed) => return Ok(None),
|
||||
Err(err) => return Err(err.clone()),
|
||||
Ok(()) => state.changed(),
|
||||
}
|
||||
};
|
||||
|
||||
notify.await; // Try again when the state changes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Subscriber {
|
||||
type Target = Info;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.info
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Subscriber {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Subscriber")
|
||||
.field("state", &self.state)
|
||||
.field("info", &self.info)
|
||||
.field("index", &self.index)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
struct Dropped {
|
||||
// Modify the segment state.
|
||||
state: Watch<State>,
|
||||
}
|
||||
|
||||
impl Dropped {
|
||||
fn new(state: Watch<State>) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dropped {
|
||||
fn drop(&mut self) {
|
||||
self.state.lock_mut().close(CacheError::Closed).ok();
|
||||
}
|
||||
}
|
||||
337
moq-transport/src/cache/track.rs
vendored
Normal file
337
moq-transport/src/cache/track.rs
vendored
Normal file
@@ -0,0 +1,337 @@
|
||||
//! A track is a collection of semi-reliable and semi-ordered segments, split into a [Publisher] and [Subscriber] handle.
|
||||
//!
|
||||
//! A [Publisher] creates segments with a sequence number and priority.
|
||||
//! The sequest number is used to determine the order of segments, while the priority is used to determine which segment to transmit first.
|
||||
//! This may seem counter-intuitive, but is designed for live streaming where the newest segments may be higher priority.
|
||||
//! A cloned [Publisher] can be used to create segments in parallel, but will error if a duplicate sequence number is used.
|
||||
//!
|
||||
//! A [Subscriber] may not receive all segments in order or at all.
|
||||
//! These segments are meant to be transmitted over congested networks and the key to MoQ Tranport is to not block on them.
|
||||
//! Segments will be cached for a potentially limited duration added to the unreliable nature.
|
||||
//! A cloned [Subscriber] will receive a copy of all new segment going forward (fanout).
|
||||
//!
|
||||
//! The track is closed with [CacheError::Closed] when all publishers or subscribers are dropped.
|
||||
|
||||
use std::{collections::BinaryHeap, fmt, ops::Deref, sync::Arc, time};
|
||||
|
||||
use indexmap::IndexMap;
|
||||
|
||||
use super::{segment, CacheError, Watch};
|
||||
use crate::VarInt;
|
||||
|
||||
/// Create a track with the given name.
|
||||
pub fn new(name: &str) -> (Publisher, Subscriber) {
|
||||
let state = Watch::new(State::default());
|
||||
let info = Arc::new(Info { name: name.to_string() });
|
||||
|
||||
let publisher = Publisher::new(state.clone(), info.clone());
|
||||
let subscriber = Subscriber::new(state, info);
|
||||
|
||||
(publisher, subscriber)
|
||||
}
|
||||
|
||||
/// Static information about a track.
|
||||
#[derive(Debug)]
|
||||
pub struct Info {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
struct State {
|
||||
// Store segments in received order so subscribers can detect changes.
|
||||
// The key is the segment sequence, which could have gaps.
|
||||
// A None value means the segment has expired.
|
||||
lookup: IndexMap<VarInt, Option<segment::Subscriber>>,
|
||||
|
||||
// Store when segments will expire in a priority queue.
|
||||
expires: BinaryHeap<SegmentExpiration>,
|
||||
|
||||
// The number of None entries removed from the start of the lookup.
|
||||
pruned: usize,
|
||||
|
||||
// Set when the publisher is closed/dropped, or all subscribers are dropped.
|
||||
closed: Result<(), CacheError>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn close(&mut self, err: CacheError) -> Result<(), CacheError> {
|
||||
self.closed.clone()?;
|
||||
self.closed = Err(err);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, segment: segment::Subscriber) -> Result<(), CacheError> {
|
||||
self.closed.clone()?;
|
||||
|
||||
let entry = match self.lookup.entry(segment.sequence) {
|
||||
indexmap::map::Entry::Occupied(_entry) => return Err(CacheError::Duplicate),
|
||||
indexmap::map::Entry::Vacant(entry) => entry,
|
||||
};
|
||||
|
||||
if let Some(expires) = segment.expires {
|
||||
self.expires.push(SegmentExpiration {
|
||||
sequence: segment.sequence,
|
||||
expires: time::Instant::now() + expires,
|
||||
});
|
||||
}
|
||||
|
||||
entry.insert(Some(segment));
|
||||
|
||||
// Expire any existing segments on insert.
|
||||
// This means if you don't insert then you won't expire... but it's probably fine since the cache won't grow.
|
||||
// TODO Use a timer to expire segments at the correct time instead
|
||||
self.expire();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Try expiring any segments
|
||||
pub fn expire(&mut self) {
|
||||
let now = time::Instant::now();
|
||||
while let Some(segment) = self.expires.peek() {
|
||||
if segment.expires > now {
|
||||
break;
|
||||
}
|
||||
|
||||
// Update the entry to None while preserving the index.
|
||||
match self.lookup.entry(segment.sequence) {
|
||||
indexmap::map::Entry::Occupied(mut entry) => entry.insert(None),
|
||||
indexmap::map::Entry::Vacant(_) => panic!("expired segment not found"),
|
||||
};
|
||||
|
||||
self.expires.pop();
|
||||
}
|
||||
|
||||
// Remove None entries from the start of the lookup.
|
||||
while let Some((_, None)) = self.lookup.get_index(0) {
|
||||
self.lookup.shift_remove_index(0);
|
||||
self.pruned += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
lookup: Default::default(),
|
||||
expires: Default::default(),
|
||||
pruned: 0,
|
||||
closed: Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for State {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("State")
|
||||
.field("lookup", &self.lookup)
|
||||
.field("pruned", &self.pruned)
|
||||
.field("closed", &self.closed)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates new segments for a track.
|
||||
pub struct Publisher {
|
||||
state: Watch<State>,
|
||||
info: Arc<Info>,
|
||||
_dropped: Arc<Dropped>,
|
||||
}
|
||||
|
||||
impl Publisher {
|
||||
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
|
||||
let _dropped = Arc::new(Dropped::new(state.clone()));
|
||||
Self { state, info, _dropped }
|
||||
}
|
||||
|
||||
/// Insert a new segment.
|
||||
pub fn insert_segment(&mut self, segment: segment::Subscriber) -> Result<(), CacheError> {
|
||||
self.state.lock_mut().insert(segment)
|
||||
}
|
||||
|
||||
/// Create an insert a segment with the given info.
|
||||
pub fn create_segment(&mut self, info: segment::Info) -> Result<segment::Publisher, CacheError> {
|
||||
let (publisher, subscriber) = segment::new(info);
|
||||
self.insert_segment(subscriber)?;
|
||||
Ok(publisher)
|
||||
}
|
||||
|
||||
/// Close the segment with an error.
|
||||
pub fn close(self, err: CacheError) -> Result<(), CacheError> {
|
||||
self.state.lock_mut().close(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Publisher {
|
||||
type Target = Info;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.info
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Publisher {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Publisher")
|
||||
.field("state", &self.state)
|
||||
.field("info", &self.info)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives new segments for a track.
|
||||
#[derive(Clone)]
|
||||
pub struct Subscriber {
|
||||
state: Watch<State>,
|
||||
info: Arc<Info>,
|
||||
|
||||
// The index of the next segment to return.
|
||||
index: usize,
|
||||
|
||||
// If there are multiple segments to return, we put them in here to return them in priority order.
|
||||
pending: BinaryHeap<SegmentPriority>,
|
||||
|
||||
// Dropped when all subscribers are dropped.
|
||||
_dropped: Arc<Dropped>,
|
||||
}
|
||||
|
||||
impl Subscriber {
|
||||
fn new(state: Watch<State>, info: Arc<Info>) -> Self {
|
||||
let _dropped = Arc::new(Dropped::new(state.clone()));
|
||||
Self {
|
||||
state,
|
||||
info,
|
||||
index: 0,
|
||||
pending: Default::default(),
|
||||
_dropped,
|
||||
}
|
||||
}
|
||||
|
||||
/// Block until the next segment arrives
|
||||
pub async fn segment(&mut self) -> Result<Option<segment::Subscriber>, CacheError> {
|
||||
loop {
|
||||
let notify = {
|
||||
let state = self.state.lock();
|
||||
|
||||
// Get our adjusted index, which could be negative if we've removed more broadcasts than read.
|
||||
let mut index = self.index.saturating_sub(state.pruned);
|
||||
|
||||
// Push all new segments into a priority queue.
|
||||
while index < state.lookup.len() {
|
||||
let (_, segment) = state.lookup.get_index(index).unwrap();
|
||||
|
||||
// Skip None values (expired segments).
|
||||
// TODO These might actually be expired, so we should check the expiration time.
|
||||
if let Some(segment) = segment {
|
||||
self.pending.push(SegmentPriority(segment.clone()));
|
||||
}
|
||||
|
||||
index += 1;
|
||||
}
|
||||
|
||||
self.index = state.pruned + index;
|
||||
|
||||
// Return the higher priority segment.
|
||||
if let Some(segment) = self.pending.pop() {
|
||||
return Ok(Some(segment.0));
|
||||
}
|
||||
|
||||
// Otherwise check if we need to return an error.
|
||||
match &state.closed {
|
||||
Err(CacheError::Closed) => return Ok(None),
|
||||
Err(err) => return Err(err.clone()),
|
||||
Ok(()) => state.changed(),
|
||||
}
|
||||
};
|
||||
|
||||
notify.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Subscriber {
|
||||
type Target = Info;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.info
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Subscriber {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Subscriber")
|
||||
.field("state", &self.state)
|
||||
.field("info", &self.info)
|
||||
.field("index", &self.index)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
// Closes the track on Drop.
|
||||
struct Dropped {
|
||||
state: Watch<State>,
|
||||
}
|
||||
|
||||
impl Dropped {
|
||||
fn new(state: Watch<State>) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dropped {
|
||||
fn drop(&mut self) {
|
||||
self.state.lock_mut().close(CacheError::Closed).ok();
|
||||
}
|
||||
}
|
||||
|
||||
// Used to order segments by expiration time.
|
||||
struct SegmentExpiration {
|
||||
sequence: VarInt,
|
||||
expires: time::Instant,
|
||||
}
|
||||
|
||||
impl Ord for SegmentExpiration {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
// Reverse order so the earliest expiration is at the top of the heap.
|
||||
other.expires.cmp(&self.expires)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for SegmentExpiration {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for SegmentExpiration {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.expires == other.expires
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for SegmentExpiration {}
|
||||
|
||||
// Used to order segments by priority
|
||||
#[derive(Clone)]
|
||||
struct SegmentPriority(pub segment::Subscriber);
|
||||
|
||||
impl Ord for SegmentPriority {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
// Reverse order so the highest priority is at the top of the heap.
|
||||
// TODO I let CodePilot generate this code so yolo
|
||||
other.0.priority.cmp(&self.0.priority)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for SegmentPriority {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for SegmentPriority {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.priority == other.0.priority
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for SegmentPriority {}
|
||||
180
moq-transport/src/cache/watch.rs
vendored
Normal file
180
moq-transport/src/cache/watch.rs
vendored
Normal file
@@ -0,0 +1,180 @@
|
||||
use std::{
|
||||
fmt,
|
||||
future::Future,
|
||||
ops::{Deref, DerefMut},
|
||||
pin::Pin,
|
||||
sync::{Arc, Mutex, MutexGuard},
|
||||
task,
|
||||
};
|
||||
|
||||
struct State<T> {
|
||||
value: T,
|
||||
wakers: Vec<task::Waker>,
|
||||
epoch: usize,
|
||||
}
|
||||
|
||||
impl<T> State<T> {
|
||||
pub fn new(value: T) -> Self {
|
||||
Self {
|
||||
value,
|
||||
wakers: Vec::new(),
|
||||
epoch: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(&mut self, waker: &task::Waker) {
|
||||
self.wakers.retain(|existing| !existing.will_wake(waker));
|
||||
self.wakers.push(waker.clone());
|
||||
}
|
||||
|
||||
pub fn notify(&mut self) {
|
||||
self.epoch += 1;
|
||||
for waker in self.wakers.drain(..) {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Default> Default for State<T> {
|
||||
fn default() -> Self {
|
||||
Self::new(T::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug> fmt::Debug for State<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.value.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Watch<T> {
|
||||
state: Arc<Mutex<State<T>>>,
|
||||
}
|
||||
|
||||
impl<T> Watch<T> {
|
||||
pub fn new(initial: T) -> Self {
|
||||
let state = Arc::new(Mutex::new(State::new(initial)));
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub fn lock(&self) -> WatchRef<T> {
|
||||
WatchRef {
|
||||
state: self.state.clone(),
|
||||
lock: self.state.lock().unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lock_mut(&self) -> WatchMut<T> {
|
||||
WatchMut {
|
||||
lock: self.state.lock().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Watch<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
state: self.state.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Default> Default for Watch<T> {
|
||||
fn default() -> Self {
|
||||
Self::new(T::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug> fmt::Debug for Watch<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self.state.try_lock() {
|
||||
Ok(lock) => lock.value.fmt(f),
|
||||
Err(_) => write!(f, "<locked>"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WatchRef<'a, T> {
|
||||
state: Arc<Mutex<State<T>>>,
|
||||
lock: MutexGuard<'a, State<T>>,
|
||||
}
|
||||
|
||||
impl<'a, T> WatchRef<'a, T> {
|
||||
// Release the lock and wait for a notification when next updated.
|
||||
pub fn changed(self) -> WatchChanged<T> {
|
||||
WatchChanged {
|
||||
state: self.state,
|
||||
epoch: self.lock.epoch,
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade to a mutable references that automatically calls notify on drop.
|
||||
pub fn into_mut(self) -> WatchMut<'a, T> {
|
||||
WatchMut { lock: self.lock }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Deref for WatchRef<'a, T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.lock.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: fmt::Debug> fmt::Debug for WatchRef<'a, T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.lock.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WatchMut<'a, T> {
|
||||
lock: MutexGuard<'a, State<T>>,
|
||||
}
|
||||
|
||||
impl<'a, T> Deref for WatchMut<'a, T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.lock.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> DerefMut for WatchMut<'a, T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.lock.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Drop for WatchMut<'a, T> {
|
||||
fn drop(&mut self) {
|
||||
self.lock.notify();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: fmt::Debug> fmt::Debug for WatchMut<'a, T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.lock.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WatchChanged<T> {
|
||||
state: Arc<Mutex<State<T>>>,
|
||||
epoch: usize,
|
||||
}
|
||||
|
||||
impl<T> Future for WatchChanged<T> {
|
||||
type Output = ();
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
|
||||
// TODO is there an API we can make that doesn't drop this lock?
|
||||
let mut state = self.state.lock().unwrap();
|
||||
|
||||
if state.epoch > self.epoch {
|
||||
task::Poll::Ready(())
|
||||
} else {
|
||||
state.register(cx.waker());
|
||||
task::Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
55
moq-transport/src/coding/decode.rs
Normal file
55
moq-transport/src/coding/decode.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use super::{BoundsExceeded, VarInt};
|
||||
use std::{io, str};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
// I'm too lazy to add these trait bounds to every message type.
|
||||
// TODO Use trait aliases when they're stable, or add these bounds to every method.
|
||||
pub trait AsyncRead: tokio::io::AsyncRead + Unpin + Send {}
|
||||
impl AsyncRead for webtransport_quinn::RecvStream {}
|
||||
impl<T> AsyncRead for tokio::io::Take<&mut T> where T: AsyncRead {}
|
||||
impl<T: AsRef<[u8]> + Unpin + Send> AsyncRead for io::Cursor<T> {}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait Decode: Sized {
|
||||
async fn decode<R: AsyncRead>(r: &mut R) -> Result<Self, DecodeError>;
|
||||
}
|
||||
|
||||
/// A decode error.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum DecodeError {
|
||||
#[error("unexpected end of buffer")]
|
||||
UnexpectedEnd,
|
||||
|
||||
#[error("invalid string")]
|
||||
InvalidString(#[from] str::Utf8Error),
|
||||
|
||||
#[error("invalid message: {0:?}")]
|
||||
InvalidMessage(VarInt),
|
||||
|
||||
#[error("invalid role: {0:?}")]
|
||||
InvalidRole(VarInt),
|
||||
|
||||
#[error("invalid subscribe location")]
|
||||
InvalidSubscribeLocation,
|
||||
|
||||
#[error("varint bounds exceeded")]
|
||||
BoundsExceeded(#[from] BoundsExceeded),
|
||||
|
||||
// TODO move these to ParamError
|
||||
#[error("duplicate parameter")]
|
||||
DupliateParameter,
|
||||
|
||||
#[error("missing parameter")]
|
||||
MissingParameter,
|
||||
|
||||
#[error("invalid parameter")]
|
||||
InvalidParameter,
|
||||
|
||||
#[error("io error: {0}")]
|
||||
IoError(#[from] std::io::Error),
|
||||
|
||||
// Used to signal that the stream has ended.
|
||||
#[error("no more messages")]
|
||||
Final,
|
||||
}
|
||||
27
moq-transport/src/coding/encode.rs
Normal file
27
moq-transport/src/coding/encode.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
use super::BoundsExceeded;
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
// I'm too lazy to add these trait bounds to every message type.
|
||||
// TODO Use trait aliases when they're stable, or add these bounds to every method.
|
||||
pub trait AsyncWrite: tokio::io::AsyncWrite + Unpin + Send {}
|
||||
impl AsyncWrite for webtransport_quinn::SendStream {}
|
||||
impl AsyncWrite for Vec<u8> {}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait Encode: Sized {
|
||||
async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError>;
|
||||
}
|
||||
|
||||
/// An encode error.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum EncodeError {
|
||||
#[error("varint too large")]
|
||||
BoundsExceeded(#[from] BoundsExceeded),
|
||||
|
||||
#[error("invalid value")]
|
||||
InvalidValue,
|
||||
|
||||
#[error("i/o error: {0}")]
|
||||
IoError(#[from] std::io::Error),
|
||||
}
|
||||
11
moq-transport/src/coding/mod.rs
Normal file
11
moq-transport/src/coding/mod.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
mod decode;
|
||||
mod encode;
|
||||
mod params;
|
||||
mod string;
|
||||
mod varint;
|
||||
|
||||
pub use decode::*;
|
||||
pub use encode::*;
|
||||
pub use params::*;
|
||||
pub use string::*;
|
||||
pub use varint::*;
|
||||
85
moq-transport/src/coding/params.rs
Normal file
85
moq-transport/src/coding/params.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use std::io::Cursor;
|
||||
use std::{cmp::max, collections::HashMap};
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite, Decode, Encode};
|
||||
|
||||
use crate::{
|
||||
coding::{DecodeError, EncodeError},
|
||||
VarInt,
|
||||
};
|
||||
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct Params(pub HashMap<VarInt, Vec<u8>>);
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Decode for Params {
|
||||
async fn decode<R: AsyncRead>(mut r: &mut R) -> Result<Self, DecodeError> {
|
||||
let mut params = HashMap::new();
|
||||
|
||||
// I hate this shit so much; let me encode my role and get on with my life.
|
||||
let count = VarInt::decode(r).await?;
|
||||
for _ in 0..count.into_inner() {
|
||||
let kind = VarInt::decode(r).await?;
|
||||
if params.contains_key(&kind) {
|
||||
return Err(DecodeError::DupliateParameter);
|
||||
}
|
||||
|
||||
let size = VarInt::decode(r).await?;
|
||||
|
||||
// Don't allocate the entire requested size to avoid a possible attack
|
||||
// Instead, we allocate up to 1024 and keep appending as we read further.
|
||||
let mut pr = r.take(size.into_inner());
|
||||
let mut buf = Vec::with_capacity(max(1024, pr.limit() as usize));
|
||||
pr.read_to_end(&mut buf).await?;
|
||||
params.insert(kind, buf);
|
||||
|
||||
r = pr.into_inner();
|
||||
}
|
||||
|
||||
Ok(Params(params))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Encode for Params {
|
||||
async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError> {
|
||||
VarInt::try_from(self.0.len())?.encode(w).await?;
|
||||
|
||||
for (kind, value) in self.0.iter() {
|
||||
kind.encode(w).await?;
|
||||
VarInt::try_from(value.len())?.encode(w).await?;
|
||||
w.write_all(value).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Params {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub async fn set<P: Encode>(&mut self, kind: VarInt, p: P) -> Result<(), EncodeError> {
|
||||
let mut value = Vec::new();
|
||||
p.encode(&mut value).await?;
|
||||
self.0.insert(kind, value);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn has(&self, kind: VarInt) -> bool {
|
||||
self.0.contains_key(&kind)
|
||||
}
|
||||
|
||||
pub async fn get<P: Decode>(&mut self, kind: VarInt) -> Result<Option<P>, DecodeError> {
|
||||
if let Some(value) = self.0.remove(&kind) {
|
||||
let mut cursor = Cursor::new(value);
|
||||
Ok(Some(P::decode(&mut cursor).await?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
29
moq-transport/src/coding/string.rs
Normal file
29
moq-transport/src/coding/string.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use std::cmp::min;
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use crate::VarInt;
|
||||
|
||||
use super::{Decode, DecodeError, Encode, EncodeError};
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Encode for String {
|
||||
async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError> {
|
||||
let size = VarInt::try_from(self.len())?;
|
||||
size.encode(w).await?;
|
||||
w.write_all(self.as_ref()).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Decode for String {
|
||||
/// Decode a string with a varint length prefix.
|
||||
async fn decode<R: AsyncRead>(r: &mut R) -> Result<Self, DecodeError> {
|
||||
let size = VarInt::decode(r).await?.into_inner();
|
||||
let mut str = String::with_capacity(min(1024, size) as usize);
|
||||
r.take(size).read_to_string(&mut str).await?;
|
||||
Ok(str)
|
||||
}
|
||||
}
|
||||
232
moq-transport/src/coding/varint.rs
Normal file
232
moq-transport/src/coding/varint.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
// Based on quinn-proto
|
||||
// https://github.com/quinn-rs/quinn/blob/main/quinn-proto/src/varint.rs
|
||||
// Licensed via Apache 2.0 and MIT
|
||||
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
use std::fmt;
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use thiserror::Error;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use super::{Decode, DecodeError, Encode, EncodeError};
|
||||
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Error)]
|
||||
#[error("value out of range")]
|
||||
pub struct BoundsExceeded;
|
||||
|
||||
/// An integer less than 2^62
|
||||
///
|
||||
/// Values of this type are suitable for encoding as QUIC variable-length integer.
|
||||
// It would be neat if we could express to Rust that the top two bits are available for use as enum
|
||||
// discriminants
|
||||
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
|
||||
pub struct VarInt(u64);
|
||||
|
||||
impl VarInt {
|
||||
/// The largest possible value.
|
||||
pub const MAX: Self = Self((1 << 62) - 1);
|
||||
|
||||
/// The smallest possible value.
|
||||
pub const ZERO: Self = Self(0);
|
||||
|
||||
/// Construct a `VarInt` infallibly using the largest available type.
|
||||
/// Larger values need to use `try_from` instead.
|
||||
pub const fn from_u32(x: u32) -> Self {
|
||||
Self(x as u64)
|
||||
}
|
||||
|
||||
/// Extract the integer value
|
||||
pub const fn into_inner(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<VarInt> for u64 {
|
||||
fn from(x: VarInt) -> Self {
|
||||
x.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<VarInt> for usize {
|
||||
fn from(x: VarInt) -> Self {
|
||||
x.0 as usize
|
||||
}
|
||||
}
|
||||
|
||||
impl From<VarInt> for u128 {
|
||||
fn from(x: VarInt) -> Self {
|
||||
x.0 as u128
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for VarInt {
|
||||
fn from(x: u8) -> Self {
|
||||
Self(x.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u16> for VarInt {
|
||||
fn from(x: u16) -> Self {
|
||||
Self(x.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u32> for VarInt {
|
||||
fn from(x: u32) -> Self {
|
||||
Self(x.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u64> for VarInt {
|
||||
type Error = BoundsExceeded;
|
||||
|
||||
/// Succeeds iff `x` < 2^62
|
||||
fn try_from(x: u64) -> Result<Self, BoundsExceeded> {
|
||||
if x <= Self::MAX.into_inner() {
|
||||
Ok(Self(x))
|
||||
} else {
|
||||
Err(BoundsExceeded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u128> for VarInt {
|
||||
type Error = BoundsExceeded;
|
||||
|
||||
/// Succeeds iff `x` < 2^62
|
||||
fn try_from(x: u128) -> Result<Self, BoundsExceeded> {
|
||||
if x <= Self::MAX.into() {
|
||||
Ok(Self(x as u64))
|
||||
} else {
|
||||
Err(BoundsExceeded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<usize> for VarInt {
|
||||
type Error = BoundsExceeded;
|
||||
|
||||
/// Succeeds iff `x` < 2^62
|
||||
fn try_from(x: usize) -> Result<Self, BoundsExceeded> {
|
||||
Self::try_from(x as u64)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<VarInt> for u32 {
|
||||
type Error = BoundsExceeded;
|
||||
|
||||
/// Succeeds iff `x` < 2^32
|
||||
fn try_from(x: VarInt) -> Result<Self, BoundsExceeded> {
|
||||
if x.0 <= u32::MAX.into() {
|
||||
Ok(x.0 as u32)
|
||||
} else {
|
||||
Err(BoundsExceeded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<VarInt> for u16 {
|
||||
type Error = BoundsExceeded;
|
||||
|
||||
/// Succeeds iff `x` < 2^16
|
||||
fn try_from(x: VarInt) -> Result<Self, BoundsExceeded> {
|
||||
if x.0 <= u16::MAX.into() {
|
||||
Ok(x.0 as u16)
|
||||
} else {
|
||||
Err(BoundsExceeded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<VarInt> for u8 {
|
||||
type Error = BoundsExceeded;
|
||||
|
||||
/// Succeeds iff `x` < 2^8
|
||||
fn try_from(x: VarInt) -> Result<Self, BoundsExceeded> {
|
||||
if x.0 <= u8::MAX.into() {
|
||||
Ok(x.0 as u8)
|
||||
} else {
|
||||
Err(BoundsExceeded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for VarInt {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for VarInt {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Decode for VarInt {
|
||||
/// Decode a varint from the given reader.
|
||||
async fn decode<R: AsyncRead>(r: &mut R) -> Result<Self, DecodeError> {
|
||||
let b = r.read_u8().await?;
|
||||
Self::decode_byte(b, r).await
|
||||
}
|
||||
}
|
||||
|
||||
impl VarInt {
|
||||
/// Decode a varint given the first byte, reading the rest as needed.
|
||||
/// This is silly but useful for determining if the stream has ended.
|
||||
pub async fn decode_byte<R: AsyncRead>(b: u8, r: &mut R) -> Result<Self, DecodeError> {
|
||||
let tag = b >> 6;
|
||||
|
||||
let mut buf = [0u8; 8];
|
||||
buf[0] = b & 0b0011_1111;
|
||||
|
||||
let x = match tag {
|
||||
0b00 => u64::from(buf[0]),
|
||||
0b01 => {
|
||||
r.read_exact(buf[1..2].as_mut()).await?;
|
||||
u64::from(u16::from_be_bytes(buf[..2].try_into().unwrap()))
|
||||
}
|
||||
0b10 => {
|
||||
r.read_exact(buf[1..4].as_mut()).await?;
|
||||
u64::from(u32::from_be_bytes(buf[..4].try_into().unwrap()))
|
||||
}
|
||||
0b11 => {
|
||||
r.read_exact(buf[1..8].as_mut()).await?;
|
||||
u64::from_be_bytes(buf)
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
Ok(Self(x))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Encode for VarInt {
|
||||
/// Encode a varint to the given writer.
|
||||
async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError> {
|
||||
let x = self.0;
|
||||
if x < 2u64.pow(6) {
|
||||
w.write_u8(x as u8).await?;
|
||||
} else if x < 2u64.pow(14) {
|
||||
w.write_u16(0b01 << 14 | x as u16).await?;
|
||||
} else if x < 2u64.pow(30) {
|
||||
w.write_u32(0b10 << 30 | x as u32).await?;
|
||||
} else if x < 2u64.pow(62) {
|
||||
w.write_u64(0b11 << 62 | x).await?;
|
||||
} else {
|
||||
unreachable!("malformed VarInt");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// This is a fork of quinn::VarInt.
|
||||
impl From<quinn::VarInt> for VarInt {
|
||||
fn from(v: quinn::VarInt) -> Self {
|
||||
Self(v.into_inner())
|
||||
}
|
||||
}
|
||||
7
moq-transport/src/error.rs
Normal file
7
moq-transport/src/error.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
pub trait MoqError {
|
||||
/// An integer code that is sent over the wire.
|
||||
fn code(&self) -> u32;
|
||||
|
||||
/// An optional reason sometimes sent over the wire.
|
||||
fn reason(&self) -> String;
|
||||
}
|
||||
18
moq-transport/src/lib.rs
Normal file
18
moq-transport/src/lib.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
//! An implementation of the MoQ Transport protocol.
|
||||
//!
|
||||
//! MoQ Transport is a pub/sub protocol over QUIC.
|
||||
//! While originally designed for live media, MoQ Transport is generic and can be used for other live applications.
|
||||
//! The specification is a work in progress and will change.
|
||||
//! See the [specification](https://datatracker.ietf.org/doc/draft-ietf-moq-transport/) and [github](https://github.com/moq-wg/moq-transport) for any updates.
|
||||
//!
|
||||
//! This implementation has some required extensions until the draft stablizes. See: [Extensions](crate::setup::Extensions)
|
||||
mod coding;
|
||||
mod error;
|
||||
|
||||
pub mod cache;
|
||||
pub mod message;
|
||||
pub mod session;
|
||||
pub mod setup;
|
||||
|
||||
pub use coding::VarInt;
|
||||
pub use error::MoqError;
|
||||
30
moq-transport/src/message/announce.rs
Normal file
30
moq-transport/src/message/announce.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, Params};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the publisher to announce the availability of a group of tracks.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Announce {
|
||||
/// The track namespace
|
||||
pub namespace: String,
|
||||
|
||||
/// Optional parameters
|
||||
pub params: Params,
|
||||
}
|
||||
|
||||
impl Announce {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let namespace = String::decode(r).await?;
|
||||
let params = Params::decode(r).await?;
|
||||
|
||||
Ok(Self { namespace, params })
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.namespace.encode(w).await?;
|
||||
self.params.encode(w).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
23
moq-transport/src/message/announce_ok.rs
Normal file
23
moq-transport/src/message/announce_ok.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use crate::{
|
||||
coding::{AsyncRead, AsyncWrite, Decode, DecodeError, Encode, EncodeError},
|
||||
setup::Extensions,
|
||||
};
|
||||
|
||||
/// Sent by the subscriber to accept an Announce.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AnnounceOk {
|
||||
// Echo back the namespace that was announced.
|
||||
// TODO Propose using an ID to save bytes.
|
||||
pub namespace: String,
|
||||
}
|
||||
|
||||
impl AnnounceOk {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let namespace = String::decode(r).await?;
|
||||
Ok(Self { namespace })
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.namespace.encode(w).await
|
||||
}
|
||||
}
|
||||
39
moq-transport/src/message/announce_reset.rs
Normal file
39
moq-transport/src/message/announce_reset.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the subscriber to reject an Announce.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AnnounceError {
|
||||
// Echo back the namespace that was reset
|
||||
pub namespace: String,
|
||||
|
||||
// An error code.
|
||||
pub code: u32,
|
||||
|
||||
// An optional, human-readable reason.
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
impl AnnounceError {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let namespace = String::decode(r).await?;
|
||||
let code = VarInt::decode(r).await?.try_into()?;
|
||||
let reason = String::decode(r).await?;
|
||||
|
||||
Ok(Self {
|
||||
namespace,
|
||||
code,
|
||||
reason,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.namespace.encode(w).await?;
|
||||
VarInt::from_u32(self.code).encode(w).await?;
|
||||
self.reason.encode(w).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
21
moq-transport/src/message/go_away.rs
Normal file
21
moq-transport/src/message/go_away.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the server to indicate that the client should connect to a different server.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GoAway {
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
impl GoAway {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let url = String::decode(r).await?;
|
||||
Ok(Self { url })
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.url.encode(w).await
|
||||
}
|
||||
}
|
||||
160
moq-transport/src/message/mod.rs
Normal file
160
moq-transport/src/message/mod.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
//! Low-level message sent over the wire, as defined in the specification.
|
||||
//!
|
||||
//! All of these messages are sent over a bidirectional QUIC stream.
|
||||
//! This introduces some head-of-line blocking but preserves ordering.
|
||||
//! The only exception are OBJECT "messages", which are sent over dedicated QUIC streams.
|
||||
//!
|
||||
//! Messages sent by the publisher:
|
||||
//! - [Announce]
|
||||
//! - [Unannounce]
|
||||
//! - [SubscribeOk]
|
||||
//! - [SubscribeError]
|
||||
//! - [SubscribeReset]
|
||||
//! - [Object]
|
||||
//!
|
||||
//! Messages sent by the subscriber:
|
||||
//! - [Subscribe]
|
||||
//! - [Unsubscribe]
|
||||
//! - [AnnounceOk]
|
||||
//! - [AnnounceError]
|
||||
//!
|
||||
//! Example flow:
|
||||
//! ```test
|
||||
//! -> ANNOUNCE namespace="foo"
|
||||
//! <- ANNOUNCE_OK namespace="foo"
|
||||
//! <- SUBSCRIBE id=0 namespace="foo" name="bar"
|
||||
//! -> SUBSCRIBE_OK id=0
|
||||
//! -> OBJECT id=0 sequence=69 priority=4 expires=30
|
||||
//! -> OBJECT id=0 sequence=70 priority=4 expires=30
|
||||
//! -> OBJECT id=0 sequence=70 priority=4 expires=30
|
||||
//! <- SUBSCRIBE_STOP id=0
|
||||
//! -> SUBSCRIBE_RESET id=0 code=206 reason="closed by peer"
|
||||
//! ```
|
||||
mod announce;
|
||||
mod announce_ok;
|
||||
mod announce_reset;
|
||||
mod go_away;
|
||||
mod object;
|
||||
mod subscribe;
|
||||
mod subscribe_error;
|
||||
mod subscribe_fin;
|
||||
mod subscribe_ok;
|
||||
mod subscribe_reset;
|
||||
mod unannounce;
|
||||
mod unsubscribe;
|
||||
|
||||
pub use announce::*;
|
||||
pub use announce_ok::*;
|
||||
pub use announce_reset::*;
|
||||
pub use go_away::*;
|
||||
pub use object::*;
|
||||
pub use subscribe::*;
|
||||
pub use subscribe_error::*;
|
||||
pub use subscribe_fin::*;
|
||||
pub use subscribe_ok::*;
|
||||
pub use subscribe_reset::*;
|
||||
pub use unannounce::*;
|
||||
pub use unsubscribe::*;
|
||||
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
// Use a macro to generate the message types rather than copy-paste.
|
||||
// This implements a decode/encode method that uses the specified type.
|
||||
macro_rules! message_types {
|
||||
{$($name:ident = $val:expr,)*} => {
|
||||
/// All supported message types.
|
||||
#[derive(Clone)]
|
||||
pub enum Message {
|
||||
$($name($name)),*
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let t = VarInt::decode(r).await?;
|
||||
|
||||
match t.into_inner() {
|
||||
$($val => {
|
||||
let msg = $name::decode(r, ext).await?;
|
||||
Ok(Self::$name(msg))
|
||||
})*
|
||||
_ => Err(DecodeError::InvalidMessage(t)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, ext: &Extensions) -> Result<(), EncodeError> {
|
||||
match self {
|
||||
$(Self::$name(ref m) => {
|
||||
VarInt::from_u32($val).encode(w).await?;
|
||||
m.encode(w, ext).await
|
||||
},)*
|
||||
}
|
||||
}
|
||||
|
||||
pub fn id(&self) -> VarInt {
|
||||
match self {
|
||||
$(Self::$name(_) => {
|
||||
VarInt::from_u32($val)
|
||||
},)*
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
$(Self::$name(_) => {
|
||||
stringify!($name)
|
||||
},)*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$(impl From<$name> for Message {
|
||||
fn from(m: $name) -> Self {
|
||||
Message::$name(m)
|
||||
}
|
||||
})*
|
||||
|
||||
impl fmt::Debug for Message {
|
||||
// Delegate to the message formatter
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
$(Self::$name(ref m) => m.fmt(f),)*
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Each message is prefixed with the given VarInt type.
|
||||
message_types! {
|
||||
// NOTE: Object and Setup are in other modules.
|
||||
// Object = 0x0
|
||||
// ObjectUnbounded = 0x2
|
||||
// SetupClient = 0x40
|
||||
// SetupServer = 0x41
|
||||
|
||||
// SUBSCRIBE family, sent by subscriber
|
||||
Subscribe = 0x3,
|
||||
Unsubscribe = 0xa,
|
||||
|
||||
// SUBSCRIBE family, sent by publisher
|
||||
SubscribeOk = 0x4,
|
||||
SubscribeError = 0x5,
|
||||
SubscribeFin = 0xb,
|
||||
SubscribeReset = 0xc,
|
||||
|
||||
// ANNOUNCE family, sent by publisher
|
||||
Announce = 0x6,
|
||||
Unannounce = 0x9,
|
||||
|
||||
// ANNOUNCE family, sent by subscriber
|
||||
AnnounceOk = 0x7,
|
||||
AnnounceError = 0x8,
|
||||
|
||||
// Misc
|
||||
GoAway = 0x10,
|
||||
}
|
||||
108
moq-transport/src/message/object.rs
Normal file
108
moq-transport/src/message/object.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
use std::{io, time};
|
||||
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
use crate::setup;
|
||||
|
||||
/// Sent by the publisher as the header of each data stream.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Object {
|
||||
// An ID for this track.
|
||||
// Proposal: https://github.com/moq-wg/moq-transport/issues/209
|
||||
pub track: VarInt,
|
||||
|
||||
// The sequence number within the track.
|
||||
pub group: VarInt,
|
||||
|
||||
// The sequence number within the group.
|
||||
pub sequence: VarInt,
|
||||
|
||||
// The priority, where **smaller** values are sent first.
|
||||
pub priority: u32,
|
||||
|
||||
// Cache the object for at most this many seconds.
|
||||
// Zero means never expire.
|
||||
pub expires: Option<time::Duration>,
|
||||
|
||||
/// An optional size, allowing multiple OBJECTs on the same stream.
|
||||
pub size: Option<VarInt>,
|
||||
}
|
||||
|
||||
impl Object {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, extensions: &setup::Extensions) -> Result<Self, DecodeError> {
|
||||
// Try reading the first byte, returning a special error if the stream naturally ended.
|
||||
let typ = match r.read_u8().await {
|
||||
Ok(b) => VarInt::decode_byte(b, r).await?,
|
||||
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Err(DecodeError::Final),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
|
||||
let size_present = match typ.into_inner() {
|
||||
0 => false,
|
||||
2 => true,
|
||||
_ => return Err(DecodeError::InvalidMessage(typ)),
|
||||
};
|
||||
|
||||
let track = VarInt::decode(r).await?;
|
||||
let group = VarInt::decode(r).await?;
|
||||
let sequence = VarInt::decode(r).await?;
|
||||
let priority = VarInt::decode(r).await?.try_into()?;
|
||||
|
||||
let expires = match extensions.object_expires {
|
||||
true => match VarInt::decode(r).await?.into_inner() {
|
||||
0 => None,
|
||||
secs => Some(time::Duration::from_secs(secs)),
|
||||
},
|
||||
false => None,
|
||||
};
|
||||
|
||||
// The presence of the size field depends on the type.
|
||||
let size = match size_present {
|
||||
true => Some(VarInt::decode(r).await?),
|
||||
false => None,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
track,
|
||||
group,
|
||||
sequence,
|
||||
priority,
|
||||
expires,
|
||||
size,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, extensions: &setup::Extensions) -> Result<(), EncodeError> {
|
||||
// The kind changes based on the presence of the size.
|
||||
let kind = match self.size {
|
||||
Some(_) => VarInt::from_u32(2),
|
||||
None => VarInt::ZERO,
|
||||
};
|
||||
|
||||
kind.encode(w).await?;
|
||||
self.track.encode(w).await?;
|
||||
self.group.encode(w).await?;
|
||||
self.sequence.encode(w).await?;
|
||||
VarInt::from_u32(self.priority).encode(w).await?;
|
||||
|
||||
// Round up if there's any decimal points.
|
||||
let expires = match self.expires {
|
||||
None => 0,
|
||||
Some(time::Duration::ZERO) => return Err(EncodeError::InvalidValue), // there's no way of expressing zero currently.
|
||||
Some(expires) if expires.subsec_nanos() > 0 => expires.as_secs() + 1,
|
||||
Some(expires) => expires.as_secs(),
|
||||
};
|
||||
|
||||
if extensions.object_expires {
|
||||
VarInt::try_from(expires)?.encode(w).await?;
|
||||
}
|
||||
|
||||
if let Some(size) = self.size {
|
||||
size.encode(w).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
142
moq-transport/src/message/subscribe.rs
Normal file
142
moq-transport/src/message/subscribe.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, Params, VarInt};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the subscriber to request all future objects for the given track.
|
||||
///
|
||||
/// Objects will use the provided ID instead of the full track name, to save bytes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Subscribe {
|
||||
/// An ID we choose so we can map to the track_name.
|
||||
// Proposal: https://github.com/moq-wg/moq-transport/issues/209
|
||||
pub id: VarInt,
|
||||
|
||||
/// The track namespace.
|
||||
///
|
||||
/// Must be None if `extensions.subscribe_split` is false.
|
||||
pub namespace: Option<String>,
|
||||
|
||||
/// The track name.
|
||||
pub name: String,
|
||||
|
||||
/// The start/end group/object.
|
||||
pub start_group: SubscribeLocation,
|
||||
pub start_object: SubscribeLocation,
|
||||
pub end_group: SubscribeLocation,
|
||||
pub end_object: SubscribeLocation,
|
||||
|
||||
/// Optional parameters
|
||||
pub params: Params,
|
||||
}
|
||||
|
||||
impl Subscribe {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let id = VarInt::decode(r).await?;
|
||||
|
||||
let namespace = match ext.subscribe_split {
|
||||
true => Some(String::decode(r).await?),
|
||||
false => None,
|
||||
};
|
||||
|
||||
let name = String::decode(r).await?;
|
||||
|
||||
let start_group = SubscribeLocation::decode(r).await?;
|
||||
let start_object = SubscribeLocation::decode(r).await?;
|
||||
let end_group = SubscribeLocation::decode(r).await?;
|
||||
let end_object = SubscribeLocation::decode(r).await?;
|
||||
|
||||
// You can't have a start object without a start group.
|
||||
if start_group == SubscribeLocation::None && start_object != SubscribeLocation::None {
|
||||
return Err(DecodeError::InvalidSubscribeLocation);
|
||||
}
|
||||
|
||||
// You can't have an end object without an end group.
|
||||
if end_group == SubscribeLocation::None && end_object != SubscribeLocation::None {
|
||||
return Err(DecodeError::InvalidSubscribeLocation);
|
||||
}
|
||||
|
||||
// NOTE: There's some more location restrictions in the draft, but they're enforced at a higher level.
|
||||
|
||||
let params = Params::decode(r).await?;
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
namespace,
|
||||
name,
|
||||
start_group,
|
||||
start_object,
|
||||
end_group,
|
||||
end_object,
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.id.encode(w).await?;
|
||||
|
||||
if self.namespace.is_some() != ext.subscribe_split {
|
||||
panic!("namespace must be None if subscribe_split is false");
|
||||
}
|
||||
|
||||
if ext.subscribe_split {
|
||||
self.namespace.as_ref().unwrap().encode(w).await?;
|
||||
}
|
||||
|
||||
self.name.encode(w).await?;
|
||||
|
||||
self.start_group.encode(w).await?;
|
||||
self.start_object.encode(w).await?;
|
||||
self.end_group.encode(w).await?;
|
||||
self.end_object.encode(w).await?;
|
||||
|
||||
self.params.encode(w).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Signal where the subscription should begin, relative to the current cache.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SubscribeLocation {
|
||||
None,
|
||||
Absolute(VarInt),
|
||||
Latest(VarInt),
|
||||
Future(VarInt),
|
||||
}
|
||||
|
||||
impl SubscribeLocation {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R) -> Result<Self, DecodeError> {
|
||||
let kind = VarInt::decode(r).await?;
|
||||
|
||||
match kind.into_inner() {
|
||||
0 => Ok(Self::None),
|
||||
1 => Ok(Self::Absolute(VarInt::decode(r).await?)),
|
||||
2 => Ok(Self::Latest(VarInt::decode(r).await?)),
|
||||
3 => Ok(Self::Future(VarInt::decode(r).await?)),
|
||||
_ => Err(DecodeError::InvalidSubscribeLocation),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError> {
|
||||
match self {
|
||||
Self::None => {
|
||||
VarInt::from_u32(0).encode(w).await?;
|
||||
}
|
||||
Self::Absolute(val) => {
|
||||
VarInt::from_u32(1).encode(w).await?;
|
||||
val.encode(w).await?;
|
||||
}
|
||||
Self::Latest(val) => {
|
||||
VarInt::from_u32(2).encode(w).await?;
|
||||
val.encode(w).await?;
|
||||
}
|
||||
Self::Future(val) => {
|
||||
VarInt::from_u32(3).encode(w).await?;
|
||||
val.encode(w).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
36
moq-transport/src/message/subscribe_error.rs
Normal file
36
moq-transport/src/message/subscribe_error.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the publisher to reject a Subscribe.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SubscribeError {
|
||||
// NOTE: No full track name because of this proposal: https://github.com/moq-wg/moq-transport/issues/209
|
||||
|
||||
// The ID for this subscription.
|
||||
pub id: VarInt,
|
||||
|
||||
// An error code.
|
||||
pub code: u32,
|
||||
|
||||
// An optional, human-readable reason.
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
impl SubscribeError {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let id = VarInt::decode(r).await?;
|
||||
let code = VarInt::decode(r).await?.try_into()?;
|
||||
let reason = String::decode(r).await?;
|
||||
|
||||
Ok(Self { id, code, reason })
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.id.encode(w).await?;
|
||||
VarInt::from_u32(self.code).encode(w).await?;
|
||||
self.reason.encode(w).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
37
moq-transport/src/message/subscribe_fin.rs
Normal file
37
moq-transport/src/message/subscribe_fin.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the publisher to cleanly terminate a Subscribe.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SubscribeFin {
|
||||
// NOTE: No full track name because of this proposal: https://github.com/moq-wg/moq-transport/issues/209
|
||||
/// The ID for this subscription.
|
||||
pub id: VarInt,
|
||||
|
||||
/// The final group/object sent on this subscription.
|
||||
pub final_group: VarInt,
|
||||
pub final_object: VarInt,
|
||||
}
|
||||
|
||||
impl SubscribeFin {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let id = VarInt::decode(r).await?;
|
||||
let final_group = VarInt::decode(r).await?;
|
||||
let final_object = VarInt::decode(r).await?;
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
final_group,
|
||||
final_object,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.id.encode(w).await?;
|
||||
self.final_group.encode(w).await?;
|
||||
self.final_object.encode(w).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
31
moq-transport/src/message/subscribe_ok.rs
Normal file
31
moq-transport/src/message/subscribe_ok.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the publisher to accept a Subscribe.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SubscribeOk {
|
||||
// NOTE: No full track name because of this proposal: https://github.com/moq-wg/moq-transport/issues/209
|
||||
/// The ID for this track.
|
||||
pub id: VarInt,
|
||||
|
||||
/// The subscription will expire in this many milliseconds.
|
||||
pub expires: VarInt,
|
||||
}
|
||||
|
||||
impl SubscribeOk {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let id = VarInt::decode(r).await?;
|
||||
let expires = VarInt::decode(r).await?;
|
||||
Ok(Self { id, expires })
|
||||
}
|
||||
}
|
||||
|
||||
impl SubscribeOk {
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.id.encode(w).await?;
|
||||
self.expires.encode(w).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
50
moq-transport/src/message/subscribe_reset.rs
Normal file
50
moq-transport/src/message/subscribe_reset.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the publisher to terminate a Subscribe.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SubscribeReset {
|
||||
// NOTE: No full track name because of this proposal: https://github.com/moq-wg/moq-transport/issues/209
|
||||
/// The ID for this subscription.
|
||||
pub id: VarInt,
|
||||
|
||||
/// An error code.
|
||||
pub code: u32,
|
||||
|
||||
/// An optional, human-readable reason.
|
||||
pub reason: String,
|
||||
|
||||
/// The final group/object sent on this subscription.
|
||||
pub final_group: VarInt,
|
||||
pub final_object: VarInt,
|
||||
}
|
||||
|
||||
impl SubscribeReset {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let id = VarInt::decode(r).await?;
|
||||
let code = VarInt::decode(r).await?.try_into()?;
|
||||
let reason = String::decode(r).await?;
|
||||
let final_group = VarInt::decode(r).await?;
|
||||
let final_object = VarInt::decode(r).await?;
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
code,
|
||||
reason,
|
||||
final_group,
|
||||
final_object,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.id.encode(w).await?;
|
||||
VarInt::from_u32(self.code).encode(w).await?;
|
||||
self.reason.encode(w).await?;
|
||||
|
||||
self.final_group.encode(w).await?;
|
||||
self.final_object.encode(w).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
25
moq-transport/src/message/unannounce.rs
Normal file
25
moq-transport/src/message/unannounce.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the publisher to terminate an Announce.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Unannounce {
|
||||
// Echo back the namespace that was reset
|
||||
pub namespace: String,
|
||||
}
|
||||
|
||||
impl Unannounce {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let namespace = String::decode(r).await?;
|
||||
|
||||
Ok(Self { namespace })
|
||||
}
|
||||
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.namespace.encode(w).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
27
moq-transport/src/message/unsubscribe.rs
Normal file
27
moq-transport/src/message/unsubscribe.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
use crate::setup::Extensions;
|
||||
|
||||
/// Sent by the subscriber to terminate a Subscribe.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Unsubscribe {
|
||||
// NOTE: No full track name because of this proposal: https://github.com/moq-wg/moq-transport/issues/209
|
||||
|
||||
// The ID for this subscription.
|
||||
pub id: VarInt,
|
||||
}
|
||||
|
||||
impl Unsubscribe {
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R, _ext: &Extensions) -> Result<Self, DecodeError> {
|
||||
let id = VarInt::decode(r).await?;
|
||||
Ok(Self { id })
|
||||
}
|
||||
}
|
||||
|
||||
impl Unsubscribe {
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W, _ext: &Extensions) -> Result<(), EncodeError> {
|
||||
self.id.encode(w).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
76
moq-transport/src/session/client.rs
Normal file
76
moq-transport/src/session/client.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use super::{Control, Publisher, SessionError, Subscriber};
|
||||
use crate::{cache::broadcast, setup};
|
||||
use webtransport_quinn::Session;
|
||||
|
||||
/// An endpoint that connects to a URL to publish and/or consume live streams.
|
||||
pub struct Client {}
|
||||
|
||||
impl Client {
|
||||
/// Connect using an established WebTransport session, performing the MoQ handshake as a publisher.
|
||||
pub async fn publisher(session: Session, source: broadcast::Subscriber) -> Result<Publisher, SessionError> {
|
||||
let control = Self::send_setup(&session, setup::Role::Publisher).await?;
|
||||
let publisher = Publisher::new(session, control, source);
|
||||
Ok(publisher)
|
||||
}
|
||||
|
||||
/// Connect using an established WebTransport session, performing the MoQ handshake as a subscriber.
|
||||
pub async fn subscriber(session: Session, source: broadcast::Publisher) -> Result<Subscriber, SessionError> {
|
||||
let control = Self::send_setup(&session, setup::Role::Subscriber).await?;
|
||||
let subscriber = Subscriber::new(session, control, source);
|
||||
Ok(subscriber)
|
||||
}
|
||||
|
||||
// TODO support performing both roles
|
||||
/*
|
||||
pub async fn connect(self) -> anyhow::Result<(Publisher, Subscriber)> {
|
||||
self.connect_role(setup::Role::Both).await
|
||||
}
|
||||
*/
|
||||
|
||||
async fn send_setup(session: &Session, role: setup::Role) -> Result<Control, SessionError> {
|
||||
let mut control = session.open_bi().await?;
|
||||
|
||||
let versions: setup::Versions = [setup::Version::DRAFT_01, setup::Version::KIXEL_01].into();
|
||||
|
||||
let client = setup::Client {
|
||||
role,
|
||||
versions: versions.clone(),
|
||||
params: Default::default(),
|
||||
|
||||
// Offer all extensions
|
||||
extensions: setup::Extensions {
|
||||
object_expires: true,
|
||||
subscriber_id: true,
|
||||
subscribe_split: true,
|
||||
},
|
||||
};
|
||||
|
||||
log::debug!("sending client SETUP: {:?}", client);
|
||||
client.encode(&mut control.0).await?;
|
||||
|
||||
let mut server = setup::Server::decode(&mut control.1).await?;
|
||||
|
||||
log::debug!("received server SETUP: {:?}", server);
|
||||
|
||||
match server.version {
|
||||
setup::Version::DRAFT_01 => {
|
||||
// We always require this extension
|
||||
server.extensions.require_subscriber_id()?;
|
||||
|
||||
if server.role.is_publisher() {
|
||||
// We only require object expires if we're a subscriber, so we don't cache objects indefinitely.
|
||||
server.extensions.require_object_expires()?;
|
||||
}
|
||||
}
|
||||
setup::Version::KIXEL_01 => {
|
||||
// KIXEL_01 didn't support extensions; all were enabled.
|
||||
server.extensions = client.extensions.clone()
|
||||
}
|
||||
_ => return Err(SessionError::Version(versions, [server.version].into())),
|
||||
}
|
||||
|
||||
let control = Control::new(control.0, control.1, server.extensions);
|
||||
|
||||
Ok(control)
|
||||
}
|
||||
}
|
||||
45
moq-transport/src/session/control.rs
Normal file
45
moq-transport/src/session/control.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
// A helper class to guard sending control messages behind a Mutex.
|
||||
|
||||
use std::{fmt, sync::Arc};
|
||||
|
||||
use tokio::sync::Mutex;
|
||||
use webtransport_quinn::{RecvStream, SendStream};
|
||||
|
||||
use super::SessionError;
|
||||
use crate::{message::Message, setup::Extensions};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Control {
|
||||
send: Arc<Mutex<SendStream>>,
|
||||
recv: Arc<Mutex<RecvStream>>,
|
||||
pub ext: Extensions,
|
||||
}
|
||||
|
||||
impl Control {
|
||||
pub fn new(send: SendStream, recv: RecvStream, ext: Extensions) -> Self {
|
||||
Self {
|
||||
send: Arc::new(Mutex::new(send)),
|
||||
recv: Arc::new(Mutex::new(recv)),
|
||||
ext,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn send<T: Into<Message> + fmt::Debug>(&self, msg: T) -> Result<(), SessionError> {
|
||||
let mut stream = self.send.lock().await;
|
||||
log::info!("sending message: {:?}", msg);
|
||||
msg.into()
|
||||
.encode(&mut *stream, &self.ext)
|
||||
.await
|
||||
.map_err(|e| SessionError::Unknown(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// It's likely a mistake to call this from two different tasks, but it's easier to just support it.
|
||||
pub async fn recv(&self) -> Result<Message, SessionError> {
|
||||
let mut stream = self.recv.lock().await;
|
||||
let msg = Message::decode(&mut *stream, &self.ext)
|
||||
.await
|
||||
.map_err(|e| SessionError::Unknown(e.to_string()))?;
|
||||
Ok(msg)
|
||||
}
|
||||
}
|
||||
107
moq-transport/src/session/error.rs
Normal file
107
moq-transport/src/session/error.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
use crate::{cache, coding, setup, MoqError, VarInt};
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum SessionError {
|
||||
#[error("webtransport error: {0}")]
|
||||
Session(#[from] webtransport_quinn::SessionError),
|
||||
|
||||
#[error("cache error: {0}")]
|
||||
Cache(#[from] cache::CacheError),
|
||||
|
||||
#[error("encode error: {0}")]
|
||||
Encode(#[from] coding::EncodeError),
|
||||
|
||||
#[error("decode error: {0}")]
|
||||
Decode(#[from] coding::DecodeError),
|
||||
|
||||
#[error("unsupported versions: client={0:?} server={1:?}")]
|
||||
Version(setup::Versions, setup::Versions),
|
||||
|
||||
#[error("incompatible roles: client={0:?} server={1:?}")]
|
||||
RoleIncompatible(setup::Role, setup::Role),
|
||||
|
||||
/// An error occured while reading from the QUIC stream.
|
||||
#[error("failed to read from stream: {0}")]
|
||||
Read(#[from] webtransport_quinn::ReadError),
|
||||
|
||||
/// An error occured while writing to the QUIC stream.
|
||||
#[error("failed to write to stream: {0}")]
|
||||
Write(#[from] webtransport_quinn::WriteError),
|
||||
|
||||
/// The role negiotiated in the handshake was violated. For example, a publisher sent a SUBSCRIBE, or a subscriber sent an OBJECT.
|
||||
#[error("role violation: msg={0}")]
|
||||
RoleViolation(VarInt),
|
||||
|
||||
/// Our enforced stream mapping was disrespected.
|
||||
#[error("stream mapping conflict")]
|
||||
StreamMapping,
|
||||
|
||||
/// The priority was invalid.
|
||||
#[error("invalid priority: {0}")]
|
||||
InvalidPriority(VarInt),
|
||||
|
||||
/// The size was invalid.
|
||||
#[error("invalid size: {0}")]
|
||||
InvalidSize(VarInt),
|
||||
|
||||
/// A required extension was not offered.
|
||||
#[error("required extension not offered: {0:?}")]
|
||||
RequiredExtension(VarInt),
|
||||
|
||||
/// Some VarInt was too large and we were too lazy to handle it
|
||||
#[error("varint bounds exceeded")]
|
||||
BoundsExceeded(#[from] coding::BoundsExceeded),
|
||||
|
||||
/// An unclassified error because I'm lazy. TODO classify these errors
|
||||
#[error("unknown error: {0}")]
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
impl MoqError for SessionError {
|
||||
/// An integer code that is sent over the wire.
|
||||
fn code(&self) -> u32 {
|
||||
match self {
|
||||
Self::Cache(err) => err.code(),
|
||||
Self::RoleIncompatible(..) => 406,
|
||||
Self::RoleViolation(..) => 405,
|
||||
Self::StreamMapping => 409,
|
||||
Self::Unknown(_) => 500,
|
||||
Self::Write(_) => 501,
|
||||
Self::Read(_) => 502,
|
||||
Self::Session(_) => 503,
|
||||
Self::Version(..) => 406,
|
||||
Self::Encode(_) => 500,
|
||||
Self::Decode(_) => 500,
|
||||
Self::InvalidPriority(_) => 400,
|
||||
Self::InvalidSize(_) => 400,
|
||||
Self::RequiredExtension(_) => 426,
|
||||
Self::BoundsExceeded(_) => 500,
|
||||
}
|
||||
}
|
||||
|
||||
/// A reason that is sent over the wire.
|
||||
fn reason(&self) -> String {
|
||||
match self {
|
||||
Self::Cache(err) => err.reason(),
|
||||
Self::RoleViolation(kind) => format!("role violation for message type {:?}", kind),
|
||||
Self::RoleIncompatible(client, server) => {
|
||||
format!(
|
||||
"role incompatible: client wanted {:?} but server wanted {:?}",
|
||||
client, server
|
||||
)
|
||||
}
|
||||
Self::Read(err) => format!("read error: {}", err),
|
||||
Self::Write(err) => format!("write error: {}", err),
|
||||
Self::Session(err) => format!("session error: {}", err),
|
||||
Self::Unknown(err) => format!("unknown error: {}", err),
|
||||
Self::Version(client, server) => format!("unsupported versions: client={:?} server={:?}", client, server),
|
||||
Self::Encode(err) => format!("encode error: {}", err),
|
||||
Self::Decode(err) => format!("decode error: {}", err),
|
||||
Self::StreamMapping => "streaming mapping conflict".to_owned(),
|
||||
Self::InvalidPriority(priority) => format!("invalid priority: {}", priority),
|
||||
Self::InvalidSize(size) => format!("invalid size: {}", size),
|
||||
Self::RequiredExtension(id) => format!("required extension was missing: {:?}", id),
|
||||
Self::BoundsExceeded(_) => "varint bounds exceeded".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
27
moq-transport/src/session/mod.rs
Normal file
27
moq-transport/src/session/mod.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
//! A MoQ Transport session, on top of a WebTransport session, on top of a QUIC connection.
|
||||
//!
|
||||
//! The handshake is relatively simple but split into different steps.
|
||||
//! All of these handshakes slightly differ depending on if the endpoint is a client or server.
|
||||
//! 1. Complete the QUIC handhake.
|
||||
//! 2. Complete the WebTransport handshake.
|
||||
//! 3. Complete the MoQ handshake.
|
||||
//!
|
||||
//! Use [Client] or [Server] for the MoQ handshake depending on the endpoint.
|
||||
//! Then, decide if you want to create a [Publisher] or [Subscriber], or both (TODO).
|
||||
//!
|
||||
//! A [Publisher] can announce broadcasts, which will automatically be served over the network.
|
||||
//! A [Subscriber] can subscribe to broadcasts, which will automatically be served over the network.
|
||||
|
||||
mod client;
|
||||
mod control;
|
||||
mod error;
|
||||
mod publisher;
|
||||
mod server;
|
||||
mod subscriber;
|
||||
|
||||
pub use client::*;
|
||||
pub(crate) use control::*;
|
||||
pub use error::*;
|
||||
pub use publisher::*;
|
||||
pub use server::*;
|
||||
pub use subscriber::*;
|
||||
237
moq-transport/src/session/publisher.rs
Normal file
237
moq-transport/src/session/publisher.rs
Normal file
@@ -0,0 +1,237 @@
|
||||
use std::{
|
||||
collections::{hash_map, HashMap},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use tokio::task::AbortHandle;
|
||||
use webtransport_quinn::Session;
|
||||
|
||||
use crate::{
|
||||
cache::{broadcast, segment, track, CacheError},
|
||||
message,
|
||||
message::Message,
|
||||
MoqError, VarInt,
|
||||
};
|
||||
|
||||
use super::{Control, SessionError};
|
||||
|
||||
/// Serves broadcasts over the network, automatically handling subscriptions and caching.
|
||||
// TODO Clone specific fields when a task actually needs it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Publisher {
|
||||
// A map of active subscriptions, containing an abort handle to cancel them.
|
||||
subscribes: Arc<Mutex<HashMap<VarInt, AbortHandle>>>,
|
||||
webtransport: Session,
|
||||
control: Control,
|
||||
source: broadcast::Subscriber,
|
||||
}
|
||||
|
||||
impl Publisher {
|
||||
pub(crate) fn new(webtransport: Session, control: Control, source: broadcast::Subscriber) -> Self {
|
||||
Self {
|
||||
webtransport,
|
||||
control,
|
||||
subscribes: Default::default(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
// TODO Serve a broadcast without sending an ANNOUNCE.
|
||||
// fn serve(&mut self, broadcast: broadcast::Subscriber) -> Result<(), SessionError> {
|
||||
|
||||
// TODO Wait until the next subscribe that doesn't route to an ANNOUNCE.
|
||||
// pub async fn subscribed(&mut self) -> Result<track::Producer, SessionError> {
|
||||
|
||||
pub async fn run(mut self) -> Result<(), SessionError> {
|
||||
let res = self.run_inner().await;
|
||||
|
||||
// Terminate all active subscribes on error.
|
||||
self.subscribes
|
||||
.lock()
|
||||
.unwrap()
|
||||
.drain()
|
||||
.for_each(|(_, abort)| abort.abort());
|
||||
|
||||
res
|
||||
}
|
||||
|
||||
pub async fn run_inner(&mut self) -> Result<(), SessionError> {
|
||||
loop {
|
||||
tokio::select! {
|
||||
stream = self.webtransport.accept_uni() => {
|
||||
stream?;
|
||||
return Err(SessionError::RoleViolation(VarInt::ZERO));
|
||||
}
|
||||
// NOTE: this is not cancel safe, but it's fine since the other branchs are fatal.
|
||||
msg = self.control.recv() => {
|
||||
let msg = msg?;
|
||||
|
||||
log::info!("message received: {:?}", msg);
|
||||
if let Err(err) = self.recv_message(&msg).await {
|
||||
log::warn!("message error: {:?} {:?}", err, msg);
|
||||
}
|
||||
},
|
||||
// No more broadcasts are available.
|
||||
err = self.source.closed() => {
|
||||
self.webtransport.close(err.code(), err.reason().as_bytes());
|
||||
return Ok(());
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn recv_message(&mut self, msg: &Message) -> Result<(), SessionError> {
|
||||
match msg {
|
||||
Message::AnnounceOk(msg) => self.recv_announce_ok(msg).await,
|
||||
Message::AnnounceError(msg) => self.recv_announce_error(msg).await,
|
||||
Message::Subscribe(msg) => self.recv_subscribe(msg).await,
|
||||
Message::Unsubscribe(msg) => self.recv_unsubscribe(msg).await,
|
||||
_ => Err(SessionError::RoleViolation(msg.id())),
|
||||
}
|
||||
}
|
||||
|
||||
async fn recv_announce_ok(&mut self, _msg: &message::AnnounceOk) -> Result<(), SessionError> {
|
||||
// We didn't send an announce.
|
||||
Err(CacheError::NotFound.into())
|
||||
}
|
||||
|
||||
async fn recv_announce_error(&mut self, _msg: &message::AnnounceError) -> Result<(), SessionError> {
|
||||
// We didn't send an announce.
|
||||
Err(CacheError::NotFound.into())
|
||||
}
|
||||
|
||||
async fn recv_subscribe(&mut self, msg: &message::Subscribe) -> Result<(), SessionError> {
|
||||
// Assume that the subscribe ID is unique for now.
|
||||
let abort = match self.start_subscribe(msg.clone()) {
|
||||
Ok(abort) => abort,
|
||||
Err(err) => return self.reset_subscribe(msg.id, err).await,
|
||||
};
|
||||
|
||||
// Insert the abort handle into the lookup table.
|
||||
match self.subscribes.lock().unwrap().entry(msg.id) {
|
||||
hash_map::Entry::Occupied(_) => return Err(CacheError::Duplicate.into()), // TODO fatal, because we already started the task
|
||||
hash_map::Entry::Vacant(entry) => entry.insert(abort),
|
||||
};
|
||||
|
||||
self.control
|
||||
.send(message::SubscribeOk {
|
||||
id: msg.id,
|
||||
expires: VarInt::ZERO,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn reset_subscribe<E: MoqError>(&mut self, id: VarInt, err: E) -> Result<(), SessionError> {
|
||||
let msg = message::SubscribeReset {
|
||||
id,
|
||||
code: err.code(),
|
||||
reason: err.reason(),
|
||||
|
||||
// TODO properly populate these
|
||||
// But first: https://github.com/moq-wg/moq-transport/issues/313
|
||||
final_group: VarInt::ZERO,
|
||||
final_object: VarInt::ZERO,
|
||||
};
|
||||
|
||||
self.control.send(msg).await
|
||||
}
|
||||
|
||||
fn start_subscribe(&mut self, msg: message::Subscribe) -> Result<AbortHandle, SessionError> {
|
||||
// We currently don't use the namespace field in SUBSCRIBE
|
||||
// Make sure the namespace is empty if it's provided.
|
||||
if msg.namespace.as_ref().map_or(false, |namespace| !namespace.is_empty()) {
|
||||
return Err(CacheError::NotFound.into());
|
||||
}
|
||||
|
||||
let mut track = self.source.get_track(&msg.name)?;
|
||||
|
||||
// TODO only clone the fields we need
|
||||
let mut this = self.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
log::info!("serving track: name={}", track.name);
|
||||
|
||||
let res = this.run_subscribe(msg.id, &mut track).await;
|
||||
if let Err(err) = &res {
|
||||
log::warn!("failed to serve track: name={} err={:#?}", track.name, err);
|
||||
}
|
||||
|
||||
// Make sure we send a reset at the end.
|
||||
let err = res.err().unwrap_or(CacheError::Closed.into());
|
||||
this.reset_subscribe(msg.id, err).await.ok();
|
||||
|
||||
// We're all done, so clean up the abort handle.
|
||||
this.subscribes.lock().unwrap().remove(&msg.id);
|
||||
});
|
||||
|
||||
Ok(handle.abort_handle())
|
||||
}
|
||||
|
||||
async fn run_subscribe(&self, id: VarInt, track: &mut track::Subscriber) -> Result<(), SessionError> {
|
||||
// TODO add an Ok method to track::Publisher so we can send SUBSCRIBE_OK
|
||||
|
||||
while let Some(mut segment) = track.segment().await? {
|
||||
// TODO only clone the fields we need
|
||||
let this = self.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = this.run_segment(id, &mut segment).await {
|
||||
log::warn!("failed to serve segment: {:?}", err)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_segment(&self, id: VarInt, segment: &mut segment::Subscriber) -> Result<(), SessionError> {
|
||||
log::trace!("serving group: {:?}", segment);
|
||||
|
||||
let mut stream = self.webtransport.open_uni().await?;
|
||||
|
||||
// Convert the u32 to a i32, since the Quinn set_priority is signed.
|
||||
let priority = (segment.priority as i64 - i32::MAX as i64) as i32;
|
||||
stream.set_priority(priority).ok();
|
||||
|
||||
while let Some(mut fragment) = segment.fragment().await? {
|
||||
log::trace!("serving fragment: {:?}", fragment);
|
||||
|
||||
let object = message::Object {
|
||||
track: id,
|
||||
|
||||
// Properties of the segment
|
||||
group: segment.sequence,
|
||||
priority: segment.priority,
|
||||
expires: segment.expires,
|
||||
|
||||
// Properties of the fragment
|
||||
sequence: fragment.sequence,
|
||||
size: fragment.size.map(VarInt::try_from).transpose()?,
|
||||
};
|
||||
|
||||
object
|
||||
.encode(&mut stream, &self.control.ext)
|
||||
.await
|
||||
.map_err(|e| SessionError::Unknown(e.to_string()))?;
|
||||
|
||||
while let Some(chunk) = fragment.chunk().await? {
|
||||
//log::trace!("writing chunk: {:?}", chunk);
|
||||
stream.write_all(&chunk).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn recv_unsubscribe(&mut self, msg: &message::Unsubscribe) -> Result<(), SessionError> {
|
||||
let abort = self
|
||||
.subscribes
|
||||
.lock()
|
||||
.unwrap()
|
||||
.remove(&msg.id)
|
||||
.ok_or(CacheError::NotFound)?;
|
||||
abort.abort();
|
||||
|
||||
self.reset_subscribe(msg.id, CacheError::Stop).await
|
||||
}
|
||||
}
|
||||
116
moq-transport/src/session/server.rs
Normal file
116
moq-transport/src/session/server.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
use super::{Control, Publisher, SessionError, Subscriber};
|
||||
use crate::{cache::broadcast, setup};
|
||||
|
||||
use webtransport_quinn::{RecvStream, SendStream, Session};
|
||||
|
||||
/// An endpoint that accepts connections, publishing and/or consuming live streams.
|
||||
pub struct Server {}
|
||||
|
||||
impl Server {
|
||||
/// Accept an established Webtransport session, performing the MoQ handshake.
|
||||
///
|
||||
/// This returns a [Request] half-way through the handshake that allows the application to accept or deny the session.
|
||||
pub async fn accept(session: Session) -> Result<Request, SessionError> {
|
||||
let mut control = session.accept_bi().await?;
|
||||
|
||||
let mut client = setup::Client::decode(&mut control.1).await?;
|
||||
|
||||
log::debug!("received client SETUP: {:?}", client);
|
||||
|
||||
if client.versions.contains(&setup::Version::DRAFT_01) {
|
||||
// We always require subscriber ID.
|
||||
client.extensions.require_subscriber_id()?;
|
||||
|
||||
// We require OBJECT_EXPIRES for publishers only.
|
||||
if client.role.is_publisher() {
|
||||
client.extensions.require_object_expires()?;
|
||||
}
|
||||
|
||||
// We don't require SUBSCRIBE_SPLIT since it's easy enough to support, but it's clearly an oversight.
|
||||
// client.extensions.require(&Extension::SUBSCRIBE_SPLIT)?;
|
||||
} else if client.versions.contains(&setup::Version::KIXEL_01) {
|
||||
// Extensions didn't exist in KIXEL_01, so we set them manually.
|
||||
client.extensions = setup::Extensions {
|
||||
object_expires: true,
|
||||
subscriber_id: true,
|
||||
subscribe_split: true,
|
||||
};
|
||||
} else {
|
||||
return Err(SessionError::Version(
|
||||
client.versions,
|
||||
[setup::Version::DRAFT_01, setup::Version::KIXEL_01].into(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Request {
|
||||
session,
|
||||
client,
|
||||
control,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A partially complete MoQ Transport handshake.
|
||||
pub struct Request {
|
||||
session: Session,
|
||||
client: setup::Client,
|
||||
control: (SendStream, RecvStream),
|
||||
}
|
||||
|
||||
impl Request {
|
||||
/// Accept the session as a publisher, using the provided broadcast to serve subscriptions.
|
||||
pub async fn publisher(mut self, source: broadcast::Subscriber) -> Result<Publisher, SessionError> {
|
||||
let setup = self.setup(setup::Role::Publisher)?;
|
||||
setup.encode(&mut self.control.0).await?;
|
||||
|
||||
let control = Control::new(self.control.0, self.control.1, setup.extensions);
|
||||
let publisher = Publisher::new(self.session, control, source);
|
||||
Ok(publisher)
|
||||
}
|
||||
|
||||
/// Accept the session as a subscriber only.
|
||||
pub async fn subscriber(mut self, source: broadcast::Publisher) -> Result<Subscriber, SessionError> {
|
||||
let setup = self.setup(setup::Role::Subscriber)?;
|
||||
setup.encode(&mut self.control.0).await?;
|
||||
|
||||
let control = Control::new(self.control.0, self.control.1, setup.extensions);
|
||||
let subscriber = Subscriber::new(self.session, control, source);
|
||||
Ok(subscriber)
|
||||
}
|
||||
|
||||
// TODO Accept the session and perform both roles.
|
||||
/*
|
||||
pub async fn accept(self) -> anyhow::Result<(Publisher, Subscriber)> {
|
||||
self.ok(setup::Role::Both).await
|
||||
}
|
||||
*/
|
||||
|
||||
fn setup(&mut self, role: setup::Role) -> Result<setup::Server, SessionError> {
|
||||
let server = setup::Server {
|
||||
role,
|
||||
version: setup::Version::DRAFT_01,
|
||||
extensions: self.client.extensions.clone(),
|
||||
params: Default::default(),
|
||||
};
|
||||
|
||||
log::debug!("sending server SETUP: {:?}", server);
|
||||
|
||||
// We need to sure we support the opposite of the client's role.
|
||||
// ex. if the client is a publisher, we must be a subscriber ONLY.
|
||||
if !self.client.role.is_compatible(server.role) {
|
||||
return Err(SessionError::RoleIncompatible(self.client.role, server.role));
|
||||
}
|
||||
|
||||
Ok(server)
|
||||
}
|
||||
|
||||
/// Reject the request, closing the Webtransport session.
|
||||
pub fn reject(self, code: u32) {
|
||||
self.session.close(code, b"")
|
||||
}
|
||||
|
||||
/// The role advertised by the client.
|
||||
pub fn role(&self) -> setup::Role {
|
||||
self.client.role
|
||||
}
|
||||
}
|
||||
211
moq-transport/src/session/subscriber.rs
Normal file
211
moq-transport/src/session/subscriber.rs
Normal file
@@ -0,0 +1,211 @@
|
||||
use webtransport_quinn::{RecvStream, Session};
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{atomic, Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
cache::{broadcast, segment, track, CacheError},
|
||||
coding::DecodeError,
|
||||
message,
|
||||
message::Message,
|
||||
session::{Control, SessionError},
|
||||
VarInt,
|
||||
};
|
||||
|
||||
/// Receives broadcasts over the network, automatically handling subscriptions and caching.
|
||||
// TODO Clone specific fields when a task actually needs it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Subscriber {
|
||||
// The webtransport session.
|
||||
webtransport: Session,
|
||||
|
||||
// The list of active subscriptions, each guarded by an mutex.
|
||||
subscribes: Arc<Mutex<HashMap<VarInt, track::Publisher>>>,
|
||||
|
||||
// The sequence number for the next subscription.
|
||||
next: Arc<atomic::AtomicU32>,
|
||||
|
||||
// A channel for sending messages.
|
||||
control: Control,
|
||||
|
||||
// All unknown subscribes comes here.
|
||||
source: broadcast::Publisher,
|
||||
}
|
||||
|
||||
impl Subscriber {
|
||||
pub(crate) fn new(webtransport: Session, control: Control, source: broadcast::Publisher) -> Self {
|
||||
Self {
|
||||
webtransport,
|
||||
subscribes: Default::default(),
|
||||
next: Default::default(),
|
||||
control,
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(self) -> Result<(), SessionError> {
|
||||
let inbound = self.clone().run_inbound();
|
||||
let streams = self.clone().run_streams();
|
||||
let source = self.clone().run_source();
|
||||
|
||||
// Return the first error.
|
||||
tokio::select! {
|
||||
res = inbound => res,
|
||||
res = streams => res,
|
||||
res = source => res,
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_inbound(mut self) -> Result<(), SessionError> {
|
||||
loop {
|
||||
let msg = self.control.recv().await?;
|
||||
|
||||
log::info!("message received: {:?}", msg);
|
||||
if let Err(err) = self.recv_message(&msg) {
|
||||
log::warn!("message error: {:?} {:?}", err, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn recv_message(&mut self, msg: &Message) -> Result<(), SessionError> {
|
||||
match msg {
|
||||
Message::Announce(_) => Ok(()), // don't care
|
||||
Message::Unannounce(_) => Ok(()), // also don't care
|
||||
Message::SubscribeOk(_msg) => Ok(()), // don't care
|
||||
Message::SubscribeReset(msg) => self.recv_subscribe_error(msg.id, CacheError::Reset(msg.code)),
|
||||
Message::SubscribeFin(msg) => self.recv_subscribe_error(msg.id, CacheError::Closed),
|
||||
Message::SubscribeError(msg) => self.recv_subscribe_error(msg.id, CacheError::Reset(msg.code)),
|
||||
Message::GoAway(_msg) => unimplemented!("GOAWAY"),
|
||||
_ => Err(SessionError::RoleViolation(msg.id())),
|
||||
}
|
||||
}
|
||||
|
||||
fn recv_subscribe_error(&mut self, id: VarInt, err: CacheError) -> Result<(), SessionError> {
|
||||
let mut subscribes = self.subscribes.lock().unwrap();
|
||||
let subscribe = subscribes.remove(&id).ok_or(CacheError::NotFound)?;
|
||||
subscribe.close(err)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_streams(self) -> Result<(), SessionError> {
|
||||
loop {
|
||||
// Accept all incoming unidirectional streams.
|
||||
let stream = self.webtransport.accept_uni().await?;
|
||||
let this = self.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = this.run_stream(stream).await {
|
||||
log::warn!("failed to receive stream: err={:#?}", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_stream(self, mut stream: RecvStream) -> Result<(), SessionError> {
|
||||
// Decode the object on the data stream.
|
||||
let mut object = message::Object::decode(&mut stream, &self.control.ext)
|
||||
.await
|
||||
.map_err(|e| SessionError::Unknown(e.to_string()))?;
|
||||
|
||||
log::trace!("first object: {:?}", object);
|
||||
|
||||
// A new scope is needed because the async compiler is dumb
|
||||
let mut segment = {
|
||||
let mut subscribes = self.subscribes.lock().unwrap();
|
||||
let track = subscribes.get_mut(&object.track).ok_or(CacheError::NotFound)?;
|
||||
|
||||
track.create_segment(segment::Info {
|
||||
sequence: object.group,
|
||||
priority: object.priority,
|
||||
expires: object.expires,
|
||||
})?
|
||||
};
|
||||
|
||||
log::trace!("received segment: {:?}", segment);
|
||||
|
||||
// Create the first fragment
|
||||
let mut fragment = segment.push_fragment(object.sequence, object.size.map(usize::from))?;
|
||||
let mut remain = object.size.map(usize::from);
|
||||
|
||||
loop {
|
||||
if let Some(0) = remain {
|
||||
// Decode the next object from the stream.
|
||||
let next = match message::Object::decode(&mut stream, &self.control.ext).await {
|
||||
Ok(next) => next,
|
||||
|
||||
// No more objects
|
||||
Err(DecodeError::Final) => break,
|
||||
|
||||
// Unknown error
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
|
||||
log::trace!("next object: {:?}", object);
|
||||
|
||||
// NOTE: This is a custom restriction; not part of the moq-transport draft.
|
||||
// We require every OBJECT to contain the same priority since prioritization is done per-stream.
|
||||
// We also require every OBJECT to contain the same group so we know when the group ends, and can detect gaps.
|
||||
if next.priority != object.priority && next.group != object.group {
|
||||
return Err(SessionError::StreamMapping);
|
||||
}
|
||||
|
||||
object = next;
|
||||
|
||||
// Create a new object.
|
||||
fragment = segment.push_fragment(object.sequence, object.size.map(usize::from))?;
|
||||
remain = object.size.map(usize::from);
|
||||
|
||||
log::trace!("next fragment: {:?}", fragment);
|
||||
}
|
||||
|
||||
match stream.read_chunk(remain.unwrap_or(usize::MAX), true).await? {
|
||||
// Unbounded object has ended
|
||||
None if remain.is_none() => break,
|
||||
|
||||
// Bounded object ended early, oops.
|
||||
None => return Err(DecodeError::UnexpectedEnd.into()),
|
||||
|
||||
// NOTE: This does not make a copy!
|
||||
// Bytes are immutable and ref counted.
|
||||
Some(data) => {
|
||||
remain = remain.map(|r| r - data.bytes.len());
|
||||
|
||||
log::trace!("next chunk: {:?}", data);
|
||||
fragment.chunk(data.bytes)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_source(mut self) -> Result<(), SessionError> {
|
||||
loop {
|
||||
// NOTE: This returns Closed when the source is closed.
|
||||
let track = self.source.next_track().await?;
|
||||
let name = track.name.clone();
|
||||
|
||||
let id = VarInt::from_u32(self.next.fetch_add(1, atomic::Ordering::SeqCst));
|
||||
self.subscribes.lock().unwrap().insert(id, track);
|
||||
|
||||
let msg = message::Subscribe {
|
||||
id,
|
||||
namespace: self.control.ext.subscribe_split.then(|| "".to_string()),
|
||||
name,
|
||||
|
||||
// TODO correctly support these
|
||||
start_group: message::SubscribeLocation::Latest(VarInt::ZERO),
|
||||
start_object: message::SubscribeLocation::Absolute(VarInt::ZERO),
|
||||
end_group: message::SubscribeLocation::None,
|
||||
end_object: message::SubscribeLocation::None,
|
||||
|
||||
params: Default::default(),
|
||||
};
|
||||
|
||||
self.control.send(msg).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
72
moq-transport/src/setup/client.rs
Normal file
72
moq-transport/src/setup/client.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
use super::{Extensions, Role, Versions};
|
||||
use crate::{
|
||||
coding::{Decode, DecodeError, Encode, EncodeError, Params},
|
||||
VarInt,
|
||||
};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
|
||||
/// Sent by the client to setup the session.
|
||||
// NOTE: This is not a message type, but rather the control stream header.
|
||||
// Proposal: https://github.com/moq-wg/moq-transport/issues/138
|
||||
#[derive(Debug)]
|
||||
pub struct Client {
|
||||
/// The list of supported versions in preferred order.
|
||||
pub versions: Versions,
|
||||
|
||||
/// Indicate if the client is a publisher, a subscriber, or both.
|
||||
pub role: Role,
|
||||
|
||||
/// A list of known/offered extensions.
|
||||
pub extensions: Extensions,
|
||||
|
||||
/// Unknown parameters.
|
||||
pub params: Params,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// Decode a client setup message.
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R) -> Result<Self, DecodeError> {
|
||||
let typ = VarInt::decode(r).await?;
|
||||
if typ.into_inner() != 0x40 {
|
||||
return Err(DecodeError::InvalidMessage(typ));
|
||||
}
|
||||
|
||||
let versions = Versions::decode(r).await?;
|
||||
let mut params = Params::decode(r).await?;
|
||||
|
||||
let role = params
|
||||
.get::<Role>(VarInt::from_u32(0))
|
||||
.await?
|
||||
.ok_or(DecodeError::MissingParameter)?;
|
||||
|
||||
// Make sure the PATH parameter isn't used
|
||||
// TODO: This assumes WebTransport support only
|
||||
if params.has(VarInt::from_u32(1)) {
|
||||
return Err(DecodeError::InvalidParameter);
|
||||
}
|
||||
|
||||
let extensions = Extensions::load(&mut params).await?;
|
||||
|
||||
Ok(Self {
|
||||
versions,
|
||||
role,
|
||||
extensions,
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode a server setup message.
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError> {
|
||||
VarInt::from_u32(0x40).encode(w).await?;
|
||||
self.versions.encode(w).await?;
|
||||
|
||||
let mut params = self.params.clone();
|
||||
params.set(VarInt::from_u32(0), self.role).await?;
|
||||
self.extensions.store(&mut params).await?;
|
||||
|
||||
params.encode(w).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
84
moq-transport/src/setup/extension.rs
Normal file
84
moq-transport/src/setup/extension.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, Params};
|
||||
use crate::session::SessionError;
|
||||
use crate::VarInt;
|
||||
use paste::paste;
|
||||
|
||||
/// This is a custom extension scheme to allow/require draft PRs.
|
||||
///
|
||||
/// By convention, the extension number is the PR number + 0xe0000.
|
||||
|
||||
macro_rules! extensions {
|
||||
{$($name:ident = $val:expr,)*} => {
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Extensions {
|
||||
$(
|
||||
pub $name: bool,
|
||||
)*
|
||||
}
|
||||
|
||||
impl Extensions {
|
||||
pub async fn load(params: &mut Params) -> Result<Self, DecodeError> {
|
||||
let mut extensions = Self::default();
|
||||
|
||||
$(
|
||||
if let Some(_) = params.get::<ExtensionExists>(VarInt::from_u32($val)).await? {
|
||||
extensions.$name = true
|
||||
}
|
||||
)*
|
||||
|
||||
Ok(extensions)
|
||||
}
|
||||
|
||||
pub async fn store(&self, params: &mut Params) -> Result<(), EncodeError> {
|
||||
$(
|
||||
if self.$name {
|
||||
params.set(VarInt::from_u32($val), ExtensionExists{}).await?;
|
||||
}
|
||||
)*
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
paste! {
|
||||
$(
|
||||
pub fn [<require_ $name>](&self) -> Result<(), SessionError> {
|
||||
match self.$name {
|
||||
true => Ok(()),
|
||||
false => Err(SessionError::RequiredExtension(VarInt::from_u32($val))),
|
||||
}
|
||||
}
|
||||
)*
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ExtensionExists;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Decode for ExtensionExists {
|
||||
async fn decode<R: AsyncRead>(_r: &mut R) -> Result<Self, DecodeError> {
|
||||
Ok(ExtensionExists {})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Encode for ExtensionExists {
|
||||
async fn encode<W: AsyncWrite>(&self, _w: &mut W) -> Result<(), EncodeError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
extensions! {
|
||||
// required for publishers: OBJECT contains expires VarInt in seconds: https://github.com/moq-wg/moq-transport/issues/249
|
||||
// TODO write up a PR
|
||||
object_expires = 0xe00f9,
|
||||
|
||||
// required: SUBSCRIBE chooses track ID: https://github.com/moq-wg/moq-transport/pull/258
|
||||
subscriber_id = 0xe0102,
|
||||
|
||||
// optional: SUBSCRIBE contains namespace/name tuple: https://github.com/moq-wg/moq-transport/pull/277
|
||||
subscribe_split = 0xe0115,
|
||||
}
|
||||
17
moq-transport/src/setup/mod.rs
Normal file
17
moq-transport/src/setup/mod.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
//! Messages used for the MoQ Transport handshake.
|
||||
//!
|
||||
//! After establishing the WebTransport session, the client creates a bidirectional QUIC stream.
|
||||
//! The client sends the [Client] message and the server responds with the [Server] message.
|
||||
//! Both sides negotate the [Version] and [Role].
|
||||
|
||||
mod client;
|
||||
mod extension;
|
||||
mod role;
|
||||
mod server;
|
||||
mod version;
|
||||
|
||||
pub use client::*;
|
||||
pub use extension::*;
|
||||
pub use role::*;
|
||||
pub use server::*;
|
||||
pub use version::*;
|
||||
74
moq-transport/src/setup/role.rs
Normal file
74
moq-transport/src/setup/role.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
|
||||
/// Indicates the endpoint is a publisher, subscriber, or both.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Role {
|
||||
Publisher,
|
||||
Subscriber,
|
||||
Both,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
/// Returns true if the role is publisher.
|
||||
pub fn is_publisher(&self) -> bool {
|
||||
match self {
|
||||
Self::Publisher | Self::Both => true,
|
||||
Self::Subscriber => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if the role is a subscriber.
|
||||
pub fn is_subscriber(&self) -> bool {
|
||||
match self {
|
||||
Self::Subscriber | Self::Both => true,
|
||||
Self::Publisher => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if two endpoints are compatible.
|
||||
pub fn is_compatible(&self, other: Role) -> bool {
|
||||
self.is_publisher() == other.is_subscriber() && self.is_subscriber() == other.is_publisher()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Role> for VarInt {
|
||||
fn from(r: Role) -> Self {
|
||||
VarInt::from_u32(match r {
|
||||
Role::Publisher => 0x1,
|
||||
Role::Subscriber => 0x2,
|
||||
Role::Both => 0x3,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<VarInt> for Role {
|
||||
type Error = DecodeError;
|
||||
|
||||
fn try_from(v: VarInt) -> Result<Self, Self::Error> {
|
||||
match v.into_inner() {
|
||||
0x1 => Ok(Self::Publisher),
|
||||
0x2 => Ok(Self::Subscriber),
|
||||
0x3 => Ok(Self::Both),
|
||||
_ => Err(DecodeError::InvalidRole(v)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Decode for Role {
|
||||
/// Decode the role.
|
||||
async fn decode<R: AsyncRead>(r: &mut R) -> Result<Self, DecodeError> {
|
||||
let v = VarInt::decode(r).await?;
|
||||
v.try_into()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Encode for Role {
|
||||
/// Encode the role.
|
||||
async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError> {
|
||||
VarInt::from(*self).encode(w).await
|
||||
}
|
||||
}
|
||||
71
moq-transport/src/setup/server.rs
Normal file
71
moq-transport/src/setup/server.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use super::{Extensions, Role, Version};
|
||||
use crate::{
|
||||
coding::{Decode, DecodeError, Encode, EncodeError, Params},
|
||||
VarInt,
|
||||
};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
|
||||
/// Sent by the server in response to a client setup.
|
||||
// NOTE: This is not a message type, but rather the control stream header.
|
||||
// Proposal: https://github.com/moq-wg/moq-transport/issues/138
|
||||
#[derive(Debug)]
|
||||
pub struct Server {
|
||||
/// The list of supported versions in preferred order.
|
||||
pub version: Version,
|
||||
|
||||
/// Indicate if the server is a publisher, a subscriber, or both.
|
||||
// Proposal: moq-wg/moq-transport#151
|
||||
pub role: Role,
|
||||
|
||||
/// Custom extensions.
|
||||
pub extensions: Extensions,
|
||||
|
||||
/// Unknown parameters.
|
||||
pub params: Params,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Decode the server setup.
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R) -> Result<Self, DecodeError> {
|
||||
let typ = VarInt::decode(r).await?;
|
||||
if typ.into_inner() != 0x41 {
|
||||
return Err(DecodeError::InvalidMessage(typ));
|
||||
}
|
||||
|
||||
let version = Version::decode(r).await?;
|
||||
let mut params = Params::decode(r).await?;
|
||||
|
||||
let role = params
|
||||
.get::<Role>(VarInt::from_u32(0))
|
||||
.await?
|
||||
.ok_or(DecodeError::MissingParameter)?;
|
||||
|
||||
// Make sure the PATH parameter isn't used
|
||||
if params.has(VarInt::from_u32(1)) {
|
||||
return Err(DecodeError::InvalidParameter);
|
||||
}
|
||||
|
||||
let extensions = Extensions::load(&mut params).await?;
|
||||
|
||||
Ok(Self {
|
||||
version,
|
||||
role,
|
||||
extensions,
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode the server setup.
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError> {
|
||||
VarInt::from_u32(0x41).encode(w).await?;
|
||||
self.version.encode(w).await?;
|
||||
|
||||
let mut params = self.params.clone();
|
||||
params.set(VarInt::from_u32(0), self.role).await?;
|
||||
self.extensions.store(&mut params).await?;
|
||||
params.encode(w).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
155
moq-transport/src/setup/version.rs
Normal file
155
moq-transport/src/setup/version.rs
Normal file
@@ -0,0 +1,155 @@
|
||||
use crate::coding::{Decode, DecodeError, Encode, EncodeError, VarInt};
|
||||
|
||||
use crate::coding::{AsyncRead, AsyncWrite};
|
||||
|
||||
use std::ops::Deref;
|
||||
|
||||
/// A version number negotiated during the setup.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Version(pub VarInt);
|
||||
|
||||
impl Version {
|
||||
/// https://www.ietf.org/archive/id/draft-ietf-moq-transport-00.html
|
||||
pub const DRAFT_00: Version = Version(VarInt::from_u32(0xff000000));
|
||||
|
||||
/// https://www.ietf.org/archive/id/draft-ietf-moq-transport-01.html
|
||||
pub const DRAFT_01: Version = Version(VarInt::from_u32(0xff000001));
|
||||
|
||||
/// Fork of draft-ietf-moq-transport-00.
|
||||
///
|
||||
/// Rough list of differences:
|
||||
///
|
||||
/// # Messages
|
||||
/// - Messages are sent over a control stream or a data stream.
|
||||
/// - Data streams: each unidirectional stream contains a single OBJECT message.
|
||||
/// - Control stream: a (client-initiated) bidirectional stream containing SETUP and then all other messages.
|
||||
/// - Messages do not contain a length; unknown messages are fatal.
|
||||
///
|
||||
/// # SETUP
|
||||
/// - SETUP is split into SETUP_CLIENT and SETUP_SERVER with separate IDs.
|
||||
/// - SETUP uses version `0xff00` for draft-00.
|
||||
/// - SETUP no longer contains optional parameters; all are encoded in order and possibly zero.
|
||||
/// - SETUP `role` indicates the role of the sender, not the role of the server.
|
||||
/// - SETUP `path` field removed; use WebTransport for path.
|
||||
///
|
||||
/// # SUBSCRIBE
|
||||
/// - SUBSCRIBE `full_name` is split into separate `namespace` and `name` fields.
|
||||
/// - SUBSCRIBE no longer contains optional parameters; all are encoded in order and possibly zero.
|
||||
/// - SUBSCRIBE no longer contains the `auth` parameter; use WebTransport for auth.
|
||||
/// - SUBSCRIBE no longer contains the `group` parameter; concept no longer exists.
|
||||
/// - SUBSCRIBE contains the `id` instead of SUBSCRIBE_OK.
|
||||
/// - SUBSCRIBE_OK and SUBSCRIBE_ERROR reference the subscription `id` the instead of the track `full_name`.
|
||||
/// - SUBSCRIBE_ERROR was renamed to SUBSCRIBE_RESET, sent by publisher to terminate a SUBSCRIBE.
|
||||
/// - SUBSCRIBE_STOP was added, sent by the subscriber to terminate a SUBSCRIBE.
|
||||
/// - SUBSCRIBE_OK no longer has `expires`.
|
||||
///
|
||||
/// # ANNOUNCE
|
||||
/// - ANNOUNCE no longer contains optional parameters; all are encoded in order and possibly zero.
|
||||
/// - ANNOUNCE no longer contains the `auth` field; use WebTransport for auth.
|
||||
/// - ANNOUNCE_ERROR was renamed to ANNOUNCE_RESET, sent by publisher to terminate an ANNOUNCE.
|
||||
/// - ANNOUNCE_STOP was added, sent by the subscriber to terminate an ANNOUNCE.
|
||||
///
|
||||
/// # OBJECT
|
||||
/// - OBJECT uses a dedicated QUIC stream.
|
||||
/// - OBJECT has no size and continues until stream FIN.
|
||||
/// - OBJECT `priority` is a i32 instead of a varint. (for practical reasons)
|
||||
/// - OBJECT `expires` was added, a varint in seconds.
|
||||
/// - OBJECT `group` was removed.
|
||||
///
|
||||
/// # GROUP
|
||||
/// - GROUP concept was removed, replaced with OBJECT as a QUIC stream.
|
||||
pub const KIXEL_00: Version = Version(VarInt::from_u32(0xbad00));
|
||||
|
||||
/// Fork of draft-ietf-moq-transport-01.
|
||||
///
|
||||
/// Most of the KIXEL_00 changes made it into the draft, or were reverted.
|
||||
/// This was only used for a short time until extensions were created.
|
||||
///
|
||||
/// - SUBSCRIBE contains a separate track namespace and track name field (accidental revert). [#277](https://github.com/moq-wg/moq-transport/pull/277)
|
||||
/// - SUBSCRIBE contains the `track_id` instead of SUBSCRIBE_OK. [#145](https://github.com/moq-wg/moq-transport/issues/145)
|
||||
/// - SUBSCRIBE_* reference `track_id` the instead of the `track_full_name`. [#145](https://github.com/moq-wg/moq-transport/issues/145)
|
||||
/// - OBJECT `priority` is still a VarInt, but the max value is a u32 (implementation reasons)
|
||||
/// - OBJECT messages within the same `group` MUST be on the same QUIC stream.
|
||||
pub const KIXEL_01: Version = Version(VarInt::from_u32(0xbad01));
|
||||
}
|
||||
|
||||
impl From<VarInt> for Version {
|
||||
fn from(v: VarInt) -> Self {
|
||||
Self(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Version> for VarInt {
|
||||
fn from(v: Version) -> Self {
|
||||
v.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Version {
|
||||
/// Decode the version number.
|
||||
pub async fn decode<R: AsyncRead>(r: &mut R) -> Result<Self, DecodeError> {
|
||||
let v = VarInt::decode(r).await?;
|
||||
Ok(Self(v))
|
||||
}
|
||||
|
||||
/// Encode the version number.
|
||||
pub async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError> {
|
||||
self.0.encode(w).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A list of versions in arbitrary order.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Versions(Vec<Version>);
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Decode for Versions {
|
||||
/// Decode the version list.
|
||||
async fn decode<R: AsyncRead>(r: &mut R) -> Result<Self, DecodeError> {
|
||||
let count = VarInt::decode(r).await?.into_inner();
|
||||
let mut vs = Vec::new();
|
||||
|
||||
for _ in 0..count {
|
||||
let v = Version::decode(r).await?;
|
||||
vs.push(v);
|
||||
}
|
||||
|
||||
Ok(Self(vs))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Encode for Versions {
|
||||
/// Encode the version list.
|
||||
async fn encode<W: AsyncWrite>(&self, w: &mut W) -> Result<(), EncodeError> {
|
||||
let size: VarInt = self.0.len().try_into()?;
|
||||
size.encode(w).await?;
|
||||
|
||||
for v in &self.0 {
|
||||
v.encode(w).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Versions {
|
||||
type Target = Vec<Version>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<Version>> for Versions {
|
||||
fn from(vs: Vec<Version>) -> Self {
|
||||
Self(vs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> From<[Version; N]> for Versions {
|
||||
fn from(vs: [Version; N]) -> Self {
|
||||
Self(vs.to_vec())
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
To be used as follows:
|
||||
|
||||
```rust
|
||||
// Create the parsebin element
|
||||
let parsebin = gst::ElementFactory::make("parsebin", None).expect("Failed to create parsebin element");
|
||||
|
||||
// Create the h264parse element
|
||||
let h264parse = gst::ElementFactory::make("h264parse", None).expect("Failed to create h264parse element");
|
||||
|
||||
// Create the mp4mux element for fmp4
|
||||
let mp4mux = gst::ElementFactory::make("mp4mux", None).expect("Failed to create mp4mux element");
|
||||
mp4mux.set_property("fragment-duration", &2000u32).unwrap(); // Fragment duration in milliseconds
|
||||
mp4mux.set_property_from_str("streamable", "true"); // For streaming output
|
||||
|
||||
// Add elements to the pipeline
|
||||
pipeline.add_many(&[&waylandsrc, &parsebin, &h264parse, &mp4mux, &moqsink])?;
|
||||
|
||||
// Link the elements together
|
||||
waylandsrc.link(&parsebin)?;
|
||||
parsebin.link(&h264parse)?;
|
||||
h264parse.link(&mp4mux)?;
|
||||
mp4mux.link(&moqsink)?;
|
||||
```
|
||||
22
src/lib.rs
22
src/lib.rs
@@ -1,22 +0,0 @@
|
||||
#![allow(clippy::non_send_fields_in_send_ty, unused_doc_comments)]
|
||||
|
||||
use gst::glib;
|
||||
|
||||
mod warpsink;
|
||||
|
||||
fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
|
||||
warpsink::register(plugin)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
gst::plugin_define!(
|
||||
warp,
|
||||
env!("CARGO_PKG_DESCRIPTION"),
|
||||
plugin_init,
|
||||
concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
|
||||
"MIT/X11",
|
||||
env!("CARGO_PKG_NAME"),
|
||||
env!("CARGO_PKG_NAME"),
|
||||
env!("CARGO_PKG_REPOSITORY"),
|
||||
env!("BUILD_REL_DATE")
|
||||
);
|
||||
36
wayland-display-core/Cargo.toml
Normal file
36
wayland-display-core/Cargo.toml
Normal file
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "wayland-display-core"
|
||||
authors = ["Victoria Brekenfeld <git@drakulix.de>", "Alessandro Beltramo <github.com/ABeltramo>"]
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
description = "Wayland Compositor producing GStreamer buffers"
|
||||
rust-version = "1.70"
|
||||
|
||||
[lib]
|
||||
name = "waylanddisplaycore"
|
||||
crate-type = ["cdylib", "staticlib", "rlib"]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
gst.workspace = true
|
||||
gst-video.workspace = true
|
||||
tracing.workspace = true
|
||||
once_cell.workspace = true
|
||||
wayland-backend = "0.1.0"
|
||||
wayland-scanner = "0.30.0"
|
||||
|
||||
[dependencies.smithay]
|
||||
git = "https://github.com/smithay/Smithay"
|
||||
rev = "b1c682742a"
|
||||
default-features = false
|
||||
features = [
|
||||
"backend_drm",
|
||||
"backend_egl",
|
||||
"backend_libinput",
|
||||
"backend_udev",
|
||||
"renderer_gl",
|
||||
"use_system_lib",
|
||||
"desktop",
|
||||
"wayland_frontend"
|
||||
]
|
||||
21
wayland-display-core/LICENSE
Normal file
21
wayland-display-core/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Games on Whales https://github.com/games-on-whales/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
70
wayland-display-core/README.md
Normal file
70
wayland-display-core/README.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# gst-wayland-display
|
||||
|
||||
A micro Wayland compositor that can be used as a Gstreamer plugin
|
||||
|
||||
## Install
|
||||
|
||||
see [cargo-c](https://github.com/lu-zero/cargo-c)
|
||||
|
||||
```bash
|
||||
git clone ...
|
||||
cd gst-wayland-display
|
||||
cargo cinstall --prefix=/usr/local
|
||||
```
|
||||
|
||||
## GStreamer plugin
|
||||
|
||||
TODO
|
||||
|
||||
## C Bindings
|
||||
|
||||
CmakeLists.txt
|
||||
|
||||
```cmake
|
||||
pkg_check_modules(libgstwaylanddisplay REQUIRED IMPORTED_TARGET libgstwaylanddisplay)
|
||||
target_link_libraries(<YOUR_PROJECT_HERE> PUBLIC PkgConfig::libgstwaylanddisplay)
|
||||
```
|
||||
|
||||
Include in your code:
|
||||
|
||||
```c
|
||||
#include <libgstwaylanddisplay/libgstwaylanddisplay.h>
|
||||
```
|
||||
|
||||
Example usage:
|
||||
|
||||
```c++
|
||||
auto w_state = display_init("/dev/dri/renderD128"); // Pass a render node
|
||||
|
||||
display_add_input_device(w_state, "/dev/input/event20"); // Mouse
|
||||
display_add_input_device(w_state, "/dev/input/event21"); // Keyboard
|
||||
|
||||
// Setting video as 1920x1080@60
|
||||
auto video_info = gst_caps_new_simple("video/x-raw",
|
||||
"width", G_TYPE_INT, 1920,
|
||||
"height", G_TYPE_INT, 1080,
|
||||
"framerate", GST_TYPE_FRACTION, 60, 1,
|
||||
"format", G_TYPE_STRING, "RGBx",
|
||||
NULL);
|
||||
display_set_video_info(w_state, video_info);
|
||||
|
||||
// Get a list of the devices needed, ex: ["/dev/dri/renderD128", "/dev/dri/card0"]
|
||||
auto n_devices = display_get_devices_len(w_state);
|
||||
const char *devs[n_devices];
|
||||
display_get_devices(w_state, devs, n_devices);
|
||||
|
||||
// Get a list of the env vars needed, notably the wayland socket
|
||||
// ex: ["WAYLAND_DISPLAY=wayland-1"]
|
||||
auto n_envs = display_get_envvars_len(w_state);
|
||||
const char *envs[n_envs];
|
||||
display_get_envvars(w_state, envs, n_envs);
|
||||
|
||||
// Example of polling for new video data
|
||||
GstBuffer * v_buffer;
|
||||
while(true){
|
||||
v_buffer = display_get_frame(w_state);
|
||||
// TODO: do something with the video data
|
||||
}
|
||||
|
||||
display_finish(w_state); // Cleanup
|
||||
```
|
||||
BIN
wayland-display-core/resources/cursor.rgba
Normal file
BIN
wayland-display-core/resources/cursor.rgba
Normal file
Binary file not shown.
189
wayland-display-core/resources/protocols/wayland-drm.xml
Normal file
189
wayland-display-core/resources/protocols/wayland-drm.xml
Normal file
@@ -0,0 +1,189 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<protocol name="drm">
|
||||
|
||||
<copyright>
|
||||
Copyright © 2008-2011 Kristian Høgsberg
|
||||
Copyright © 2010-2011 Intel Corporation
|
||||
|
||||
Permission to use, copy, modify, distribute, and sell this
|
||||
software and its documentation for any purpose is hereby granted
|
||||
without fee, provided that\n the above copyright notice appear in
|
||||
all copies and that both that copyright notice and this permission
|
||||
notice appear in supporting documentation, and that the name of
|
||||
the copyright holders not be used in advertising or publicity
|
||||
pertaining to distribution of the software without specific,
|
||||
written prior permission. The copyright holders make no
|
||||
representations about the suitability of this software for any
|
||||
purpose. It is provided "as is" without express or implied
|
||||
warranty.
|
||||
|
||||
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
</copyright>
|
||||
|
||||
<!-- drm support. This object is created by the server and published
|
||||
using the display's global event. -->
|
||||
<interface name="wl_drm" version="2">
|
||||
<enum name="error">
|
||||
<entry name="authenticate_fail" value="0"/>
|
||||
<entry name="invalid_format" value="1"/>
|
||||
<entry name="invalid_name" value="2"/>
|
||||
</enum>
|
||||
|
||||
<enum name="format">
|
||||
<!-- The drm format codes match the #defines in drm_fourcc.h.
|
||||
The formats actually supported by the compositor will be
|
||||
reported by the format event. New codes must not be added,
|
||||
unless directly taken from drm_fourcc.h. -->
|
||||
<entry name="c8" value="0x20203843"/>
|
||||
<entry name="rgb332" value="0x38424752"/>
|
||||
<entry name="bgr233" value="0x38524742"/>
|
||||
<entry name="xrgb4444" value="0x32315258"/>
|
||||
<entry name="xbgr4444" value="0x32314258"/>
|
||||
<entry name="rgbx4444" value="0x32315852"/>
|
||||
<entry name="bgrx4444" value="0x32315842"/>
|
||||
<entry name="argb4444" value="0x32315241"/>
|
||||
<entry name="abgr4444" value="0x32314241"/>
|
||||
<entry name="rgba4444" value="0x32314152"/>
|
||||
<entry name="bgra4444" value="0x32314142"/>
|
||||
<entry name="xrgb1555" value="0x35315258"/>
|
||||
<entry name="xbgr1555" value="0x35314258"/>
|
||||
<entry name="rgbx5551" value="0x35315852"/>
|
||||
<entry name="bgrx5551" value="0x35315842"/>
|
||||
<entry name="argb1555" value="0x35315241"/>
|
||||
<entry name="abgr1555" value="0x35314241"/>
|
||||
<entry name="rgba5551" value="0x35314152"/>
|
||||
<entry name="bgra5551" value="0x35314142"/>
|
||||
<entry name="rgb565" value="0x36314752"/>
|
||||
<entry name="bgr565" value="0x36314742"/>
|
||||
<entry name="rgb888" value="0x34324752"/>
|
||||
<entry name="bgr888" value="0x34324742"/>
|
||||
<entry name="xrgb8888" value="0x34325258"/>
|
||||
<entry name="xbgr8888" value="0x34324258"/>
|
||||
<entry name="rgbx8888" value="0x34325852"/>
|
||||
<entry name="bgrx8888" value="0x34325842"/>
|
||||
<entry name="argb8888" value="0x34325241"/>
|
||||
<entry name="abgr8888" value="0x34324241"/>
|
||||
<entry name="rgba8888" value="0x34324152"/>
|
||||
<entry name="bgra8888" value="0x34324142"/>
|
||||
<entry name="xrgb2101010" value="0x30335258"/>
|
||||
<entry name="xbgr2101010" value="0x30334258"/>
|
||||
<entry name="rgbx1010102" value="0x30335852"/>
|
||||
<entry name="bgrx1010102" value="0x30335842"/>
|
||||
<entry name="argb2101010" value="0x30335241"/>
|
||||
<entry name="abgr2101010" value="0x30334241"/>
|
||||
<entry name="rgba1010102" value="0x30334152"/>
|
||||
<entry name="bgra1010102" value="0x30334142"/>
|
||||
<entry name="yuyv" value="0x56595559"/>
|
||||
<entry name="yvyu" value="0x55595659"/>
|
||||
<entry name="uyvy" value="0x59565955"/>
|
||||
<entry name="vyuy" value="0x59555956"/>
|
||||
<entry name="ayuv" value="0x56555941"/>
|
||||
<entry name="xyuv8888" value="0x56555958"/>
|
||||
<entry name="nv12" value="0x3231564e"/>
|
||||
<entry name="nv21" value="0x3132564e"/>
|
||||
<entry name="nv16" value="0x3631564e"/>
|
||||
<entry name="nv61" value="0x3136564e"/>
|
||||
<entry name="yuv410" value="0x39565559"/>
|
||||
<entry name="yvu410" value="0x39555659"/>
|
||||
<entry name="yuv411" value="0x31315559"/>
|
||||
<entry name="yvu411" value="0x31315659"/>
|
||||
<entry name="yuv420" value="0x32315559"/>
|
||||
<entry name="yvu420" value="0x32315659"/>
|
||||
<entry name="yuv422" value="0x36315559"/>
|
||||
<entry name="yvu422" value="0x36315659"/>
|
||||
<entry name="yuv444" value="0x34325559"/>
|
||||
<entry name="yvu444" value="0x34325659"/>
|
||||
<entry name="abgr16f" value="0x48344241"/>
|
||||
<entry name="xbgr16f" value="0x48344258"/>
|
||||
</enum>
|
||||
|
||||
<!-- Call this request with the magic received from drmGetMagic().
|
||||
It will be passed on to the drmAuthMagic() or
|
||||
DRIAuthConnection() call. This authentication must be
|
||||
completed before create_buffer could be used. -->
|
||||
<request name="authenticate">
|
||||
<arg name="id" type="uint"/>
|
||||
</request>
|
||||
|
||||
<!-- Create a wayland buffer for the named DRM buffer. The DRM
|
||||
surface must have a name using the flink ioctl -->
|
||||
<request name="create_buffer">
|
||||
<arg name="id" type="new_id" interface="wl_buffer"/>
|
||||
<arg name="name" type="uint"/>
|
||||
<arg name="width" type="int"/>
|
||||
<arg name="height" type="int"/>
|
||||
<arg name="stride" type="uint"/>
|
||||
<arg name="format" type="uint"/>
|
||||
</request>
|
||||
|
||||
<!-- Create a wayland buffer for the named DRM buffer. The DRM
|
||||
surface must have a name using the flink ioctl -->
|
||||
<request name="create_planar_buffer">
|
||||
<arg name="id" type="new_id" interface="wl_buffer"/>
|
||||
<arg name="name" type="uint"/>
|
||||
<arg name="width" type="int"/>
|
||||
<arg name="height" type="int"/>
|
||||
<arg name="format" type="uint"/>
|
||||
<arg name="offset0" type="int"/>
|
||||
<arg name="stride0" type="int"/>
|
||||
<arg name="offset1" type="int"/>
|
||||
<arg name="stride1" type="int"/>
|
||||
<arg name="offset2" type="int"/>
|
||||
<arg name="stride2" type="int"/>
|
||||
</request>
|
||||
|
||||
<!-- Notification of the path of the drm device which is used by
|
||||
the server. The client should use this device for creating
|
||||
local buffers. Only buffers created from this device should
|
||||
be be passed to the server using this drm object's
|
||||
create_buffer request. -->
|
||||
<event name="device">
|
||||
<arg name="name" type="string"/>
|
||||
</event>
|
||||
|
||||
<event name="format">
|
||||
<arg name="format" type="uint"/>
|
||||
</event>
|
||||
|
||||
<!-- Raised if the authenticate request succeeded -->
|
||||
<event name="authenticated"/>
|
||||
|
||||
<enum name="capability" since="2">
|
||||
<description summary="wl_drm capability bitmask">
|
||||
Bitmask of capabilities.
|
||||
</description>
|
||||
<entry name="prime" value="1" summary="wl_drm prime available"/>
|
||||
</enum>
|
||||
|
||||
<event name="capabilities">
|
||||
<arg name="value" type="uint"/>
|
||||
</event>
|
||||
|
||||
<!-- Version 2 additions -->
|
||||
|
||||
<!-- Create a wayland buffer for the prime fd. Use for regular and planar
|
||||
buffers. Pass 0 for offset and stride for unused planes. -->
|
||||
<request name="create_prime_buffer" since="2">
|
||||
<arg name="id" type="new_id" interface="wl_buffer"/>
|
||||
<arg name="name" type="fd"/>
|
||||
<arg name="width" type="int"/>
|
||||
<arg name="height" type="int"/>
|
||||
<arg name="format" type="uint"/>
|
||||
<arg name="offset0" type="int"/>
|
||||
<arg name="stride0" type="int"/>
|
||||
<arg name="offset1" type="int"/>
|
||||
<arg name="stride1" type="int"/>
|
||||
<arg name="offset2" type="int"/>
|
||||
<arg name="stride2" type="int"/>
|
||||
</request>
|
||||
|
||||
</interface>
|
||||
|
||||
</protocol>
|
||||
156
wayland-display-core/src/comp/focus.rs
Normal file
156
wayland-display-core/src/comp/focus.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
use smithay::{
|
||||
backend::input::KeyState,
|
||||
desktop::{PopupKind, Window},
|
||||
input::{
|
||||
keyboard::{KeyboardTarget, KeysymHandle, ModifiersState},
|
||||
pointer::{AxisFrame, ButtonEvent, MotionEvent, PointerTarget, RelativeMotionEvent},
|
||||
Seat,
|
||||
},
|
||||
reexports::wayland_server::{backend::ObjectId, protocol::wl_surface::WlSurface},
|
||||
utils::{IsAlive, Serial},
|
||||
wayland::seat::WaylandFocus,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum FocusTarget {
|
||||
Wayland(Window),
|
||||
Popup(PopupKind),
|
||||
}
|
||||
|
||||
impl IsAlive for FocusTarget {
|
||||
fn alive(&self) -> bool {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => w.alive(),
|
||||
FocusTarget::Popup(p) => p.alive(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Window> for FocusTarget {
|
||||
fn from(w: Window) -> Self {
|
||||
FocusTarget::Wayland(w)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PopupKind> for FocusTarget {
|
||||
fn from(p: PopupKind) -> Self {
|
||||
FocusTarget::Popup(p)
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyboardTarget<super::State> for FocusTarget {
|
||||
fn enter(
|
||||
&self,
|
||||
seat: &Seat<super::State>,
|
||||
data: &mut super::State,
|
||||
keys: Vec<KeysymHandle<'_>>,
|
||||
serial: Serial,
|
||||
) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => KeyboardTarget::enter(w, seat, data, keys, serial),
|
||||
FocusTarget::Popup(p) => {
|
||||
KeyboardTarget::enter(p.wl_surface(), seat, data, keys, serial)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn leave(&self, seat: &Seat<super::State>, data: &mut super::State, serial: Serial) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => KeyboardTarget::leave(w, seat, data, serial),
|
||||
FocusTarget::Popup(p) => KeyboardTarget::leave(p.wl_surface(), seat, data, serial),
|
||||
}
|
||||
}
|
||||
|
||||
fn key(
|
||||
&self,
|
||||
seat: &Seat<super::State>,
|
||||
data: &mut super::State,
|
||||
key: KeysymHandle<'_>,
|
||||
state: KeyState,
|
||||
serial: Serial,
|
||||
time: u32,
|
||||
) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => w.key(seat, data, key, state, serial, time),
|
||||
FocusTarget::Popup(p) => p.wl_surface().key(seat, data, key, state, serial, time),
|
||||
}
|
||||
}
|
||||
|
||||
fn modifiers(
|
||||
&self,
|
||||
seat: &Seat<super::State>,
|
||||
data: &mut super::State,
|
||||
modifiers: ModifiersState,
|
||||
serial: Serial,
|
||||
) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => w.modifiers(seat, data, modifiers, serial),
|
||||
FocusTarget::Popup(p) => p.wl_surface().modifiers(seat, data, modifiers, serial),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PointerTarget<super::State> for FocusTarget {
|
||||
fn enter(&self, seat: &Seat<super::State>, data: &mut super::State, event: &MotionEvent) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => PointerTarget::enter(w, seat, data, event),
|
||||
FocusTarget::Popup(p) => PointerTarget::enter(p.wl_surface(), seat, data, event),
|
||||
}
|
||||
}
|
||||
|
||||
fn motion(&self, seat: &Seat<super::State>, data: &mut super::State, event: &MotionEvent) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => w.motion(seat, data, event),
|
||||
FocusTarget::Popup(p) => p.wl_surface().motion(seat, data, event),
|
||||
}
|
||||
}
|
||||
|
||||
fn relative_motion(
|
||||
&self,
|
||||
seat: &Seat<super::State>,
|
||||
data: &mut super::State,
|
||||
event: &RelativeMotionEvent,
|
||||
) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => w.relative_motion(seat, data, event),
|
||||
FocusTarget::Popup(p) => p.wl_surface().relative_motion(seat, data, event),
|
||||
}
|
||||
}
|
||||
|
||||
fn button(&self, seat: &Seat<super::State>, data: &mut super::State, event: &ButtonEvent) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => w.button(seat, data, event),
|
||||
FocusTarget::Popup(p) => p.wl_surface().button(seat, data, event),
|
||||
}
|
||||
}
|
||||
|
||||
fn axis(&self, seat: &Seat<super::State>, data: &mut super::State, frame: AxisFrame) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => w.axis(seat, data, frame),
|
||||
FocusTarget::Popup(p) => p.wl_surface().axis(seat, data, frame),
|
||||
}
|
||||
}
|
||||
|
||||
fn leave(&self, seat: &Seat<super::State>, data: &mut super::State, serial: Serial, time: u32) {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => PointerTarget::leave(w, seat, data, serial, time),
|
||||
FocusTarget::Popup(p) => PointerTarget::leave(p.wl_surface(), seat, data, serial, time),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WaylandFocus for FocusTarget {
|
||||
fn wl_surface(&self) -> Option<WlSurface> {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => w.wl_surface(),
|
||||
FocusTarget::Popup(p) => Some(p.wl_surface().clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn same_client_as(&self, object_id: &ObjectId) -> bool {
|
||||
match self {
|
||||
FocusTarget::Wayland(w) => w.same_client_as(object_id),
|
||||
FocusTarget::Popup(p) => p.wl_surface().same_client_as(object_id),
|
||||
}
|
||||
}
|
||||
}
|
||||
264
wayland-display-core/src/comp/input.rs
Normal file
264
wayland-display-core/src/comp/input.rs
Normal file
@@ -0,0 +1,264 @@
|
||||
use super::{focus::FocusTarget, State};
|
||||
use smithay::{
|
||||
backend::{
|
||||
input::{
|
||||
Axis, AxisSource, Event, InputEvent, KeyState, KeyboardKeyEvent, PointerAxisEvent,
|
||||
PointerButtonEvent, PointerMotionEvent,
|
||||
},
|
||||
libinput::LibinputInputBackend,
|
||||
},
|
||||
input::{
|
||||
keyboard::{keysyms, FilterResult},
|
||||
pointer::{AxisFrame, ButtonEvent, MotionEvent, RelativeMotionEvent},
|
||||
},
|
||||
reexports::{
|
||||
input::LibinputInterface,
|
||||
nix::{fcntl, fcntl::OFlag, sys::stat},
|
||||
wayland_server::protocol::wl_pointer,
|
||||
},
|
||||
utils::{Logical, Point, Serial, SERIAL_COUNTER},
|
||||
};
|
||||
use std::{
|
||||
os::{fd::FromRawFd, unix::io::OwnedFd},
|
||||
path::Path,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
pub struct NixInterface;
|
||||
|
||||
impl LibinputInterface for NixInterface {
|
||||
fn open_restricted(&mut self, path: &Path, flags: i32) -> Result<OwnedFd, i32> {
|
||||
fcntl::open(path, OFlag::from_bits_truncate(flags), stat::Mode::empty())
|
||||
.map(|fd| unsafe { OwnedFd::from_raw_fd(fd) })
|
||||
.map_err(|err| err as i32)
|
||||
}
|
||||
fn close_restricted(&mut self, fd: OwnedFd) {
|
||||
let _ = fd;
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn process_input_event(&mut self, event: InputEvent<LibinputInputBackend>) {
|
||||
match event {
|
||||
InputEvent::Keyboard { event, .. } => {
|
||||
let keycode = event.key_code();
|
||||
let state = event.state();
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
let time = event.time_msec();
|
||||
let keyboard = self.seat.get_keyboard().unwrap();
|
||||
|
||||
keyboard.input::<(), _>(
|
||||
self,
|
||||
keycode,
|
||||
state,
|
||||
serial,
|
||||
time,
|
||||
|data, modifiers, handle| {
|
||||
if state == KeyState::Pressed {
|
||||
if modifiers.ctrl
|
||||
&& modifiers.shift
|
||||
&& !modifiers.alt
|
||||
&& !modifiers.logo
|
||||
{
|
||||
match handle.modified_sym() {
|
||||
keysyms::KEY_Tab => {
|
||||
if let Some(element) = data.space.elements().last().cloned()
|
||||
{
|
||||
data.surpressed_keys.insert(keysyms::KEY_Tab);
|
||||
let location =
|
||||
data.space.element_location(&element).unwrap();
|
||||
data.space.map_element(element.clone(), location, true);
|
||||
data.seat.get_keyboard().unwrap().set_focus(
|
||||
data,
|
||||
Some(FocusTarget::from(element)),
|
||||
serial,
|
||||
);
|
||||
return FilterResult::Intercept(());
|
||||
}
|
||||
}
|
||||
keysyms::KEY_Q => {
|
||||
if let Some(target) =
|
||||
data.seat.get_keyboard().unwrap().current_focus()
|
||||
{
|
||||
match target {
|
||||
FocusTarget::Wayland(window) => {
|
||||
window.toplevel().send_close();
|
||||
}
|
||||
_ => return FilterResult::Forward,
|
||||
};
|
||||
data.surpressed_keys.insert(keysyms::KEY_Q);
|
||||
return FilterResult::Intercept(());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if data.surpressed_keys.remove(&handle.modified_sym()) {
|
||||
return FilterResult::Intercept(());
|
||||
}
|
||||
}
|
||||
|
||||
FilterResult::Forward
|
||||
},
|
||||
);
|
||||
}
|
||||
InputEvent::PointerMotion { event, .. } => {
|
||||
self.last_pointer_movement = Instant::now();
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
let delta = event.delta();
|
||||
self.pointer_location += delta;
|
||||
self.pointer_location = self.clamp_coords(self.pointer_location);
|
||||
|
||||
let pointer = self.seat.get_pointer().unwrap();
|
||||
let under = self
|
||||
.space
|
||||
.element_under(self.pointer_location)
|
||||
.map(|(w, pos)| (w.clone().into(), pos));
|
||||
pointer.motion(
|
||||
self,
|
||||
under.clone(),
|
||||
&MotionEvent {
|
||||
location: self.pointer_location,
|
||||
serial,
|
||||
time: event.time_msec(),
|
||||
},
|
||||
);
|
||||
pointer.relative_motion(
|
||||
self,
|
||||
under,
|
||||
&RelativeMotionEvent {
|
||||
delta,
|
||||
delta_unaccel: event.delta_unaccel(),
|
||||
utime: event.time(),
|
||||
},
|
||||
)
|
||||
}
|
||||
InputEvent::PointerMotionAbsolute { event } => {
|
||||
self.last_pointer_movement = Instant::now();
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
if let Some(output) = self.output.as_ref() {
|
||||
let output_size = output
|
||||
.current_mode()
|
||||
.unwrap()
|
||||
.size
|
||||
.to_f64()
|
||||
.to_logical(output.current_scale().fractional_scale())
|
||||
.to_i32_round();
|
||||
self.pointer_location = (
|
||||
event.absolute_x_transformed(output_size.w),
|
||||
event.absolute_y_transformed(output_size.h),
|
||||
)
|
||||
.into();
|
||||
|
||||
let pointer = self.seat.get_pointer().unwrap();
|
||||
let under = self
|
||||
.space
|
||||
.element_under(self.pointer_location)
|
||||
.map(|(w, pos)| (w.clone().into(), pos));
|
||||
pointer.motion(
|
||||
self,
|
||||
under.clone(),
|
||||
&MotionEvent {
|
||||
location: self.pointer_location,
|
||||
serial,
|
||||
time: event.time_msec(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
InputEvent::PointerButton { event, .. } => {
|
||||
self.last_pointer_movement = Instant::now();
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
let button = event.button_code();
|
||||
|
||||
let state = wl_pointer::ButtonState::from(event.state());
|
||||
if wl_pointer::ButtonState::Pressed == state {
|
||||
self.update_keyboard_focus(serial);
|
||||
};
|
||||
self.seat.get_pointer().unwrap().button(
|
||||
self,
|
||||
&ButtonEvent {
|
||||
button,
|
||||
state: state.try_into().unwrap(),
|
||||
serial,
|
||||
time: event.time_msec(),
|
||||
},
|
||||
);
|
||||
}
|
||||
InputEvent::PointerAxis { event, .. } => {
|
||||
self.last_pointer_movement = Instant::now();
|
||||
let horizontal_amount = event
|
||||
.amount(Axis::Horizontal)
|
||||
.or_else(|| event.amount_discrete(Axis::Horizontal).map(|x| x * 2.0))
|
||||
.unwrap_or(0.0);
|
||||
let vertical_amount = event
|
||||
.amount(Axis::Vertical)
|
||||
.or_else(|| event.amount_discrete(Axis::Vertical).map(|y| y * 2.0))
|
||||
.unwrap_or(0.0);
|
||||
let horizontal_amount_discrete = event.amount_discrete(Axis::Horizontal);
|
||||
let vertical_amount_discrete = event.amount_discrete(Axis::Vertical);
|
||||
|
||||
{
|
||||
let mut frame = AxisFrame::new(event.time_msec()).source(event.source());
|
||||
if horizontal_amount != 0.0 {
|
||||
frame = frame.value(Axis::Horizontal, horizontal_amount);
|
||||
if let Some(discrete) = horizontal_amount_discrete {
|
||||
frame = frame.discrete(Axis::Horizontal, discrete as i32);
|
||||
}
|
||||
} else if event.source() == AxisSource::Finger {
|
||||
frame = frame.stop(Axis::Horizontal);
|
||||
}
|
||||
if vertical_amount != 0.0 {
|
||||
frame = frame.value(Axis::Vertical, vertical_amount);
|
||||
if let Some(discrete) = vertical_amount_discrete {
|
||||
frame = frame.discrete(Axis::Vertical, discrete as i32);
|
||||
}
|
||||
} else if event.source() == AxisSource::Finger {
|
||||
frame = frame.stop(Axis::Vertical);
|
||||
}
|
||||
self.seat.get_pointer().unwrap().axis(self, frame);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn clamp_coords(&self, pos: Point<f64, Logical>) -> Point<f64, Logical> {
|
||||
if let Some(output) = self.output.as_ref() {
|
||||
if let Some(mode) = output.current_mode() {
|
||||
return (
|
||||
pos.x.max(0.0).min(mode.size.w as f64),
|
||||
pos.y.max(0.0).min(mode.size.h as f64),
|
||||
)
|
||||
.into();
|
||||
}
|
||||
}
|
||||
pos
|
||||
}
|
||||
|
||||
fn update_keyboard_focus(&mut self, serial: Serial) {
|
||||
let pointer = self.seat.get_pointer().unwrap();
|
||||
let keyboard = self.seat.get_keyboard().unwrap();
|
||||
// change the keyboard focus unless the pointer or keyboard is grabbed
|
||||
// We test for any matching surface type here but always use the root
|
||||
// (in case of a window the toplevel) surface for the focus.
|
||||
// So for example if a user clicks on a subsurface or popup the toplevel
|
||||
// will receive the keyboard focus. Directly assigning the focus to the
|
||||
// matching surface leads to issues with clients dismissing popups and
|
||||
// subsurface menus (for example firefox-wayland).
|
||||
// see here for a discussion about that issue:
|
||||
// https://gitlab.freedesktop.org/wayland/wayland/-/issues/294
|
||||
if !pointer.is_grabbed() && !keyboard.is_grabbed() {
|
||||
if let Some((window, _)) = self
|
||||
.space
|
||||
.element_under(self.pointer_location)
|
||||
.map(|(w, p)| (w.clone(), p))
|
||||
{
|
||||
self.space.raise_element(&window, true);
|
||||
keyboard.set_focus(self, Some(FocusTarget::from(window)), serial);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
521
wayland-display-core/src/comp/mod.rs
Normal file
521
wayland-display-core/src/comp/mod.rs
Normal file
@@ -0,0 +1,521 @@
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
ffi::CString,
|
||||
os::unix::prelude::AsRawFd,
|
||||
sync::{mpsc::Sender, Arc, Mutex, Weak},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use super::Command;
|
||||
use gst_video::VideoInfo;
|
||||
use once_cell::sync::Lazy;
|
||||
use smithay::{
|
||||
backend::{
|
||||
allocator::dmabuf::Dmabuf,
|
||||
drm::{DrmNode, NodeType},
|
||||
egl::{EGLContext, EGLDevice, EGLDisplay},
|
||||
libinput::LibinputInputBackend,
|
||||
renderer::{
|
||||
damage::{DamageTrackedRenderer, DamageTrackedRendererError as DTRError},
|
||||
element::memory::MemoryRenderBuffer,
|
||||
gles2::{Gles2Renderbuffer, Gles2Renderer},
|
||||
Bind, Offscreen,
|
||||
},
|
||||
},
|
||||
desktop::{
|
||||
utils::{
|
||||
send_frames_surface_tree, surface_presentation_feedback_flags_from_states,
|
||||
surface_primary_scanout_output, update_surface_primary_scanout_output,
|
||||
OutputPresentationFeedback,
|
||||
},
|
||||
PopupManager, Space, Window,
|
||||
},
|
||||
input::{keyboard::XkbConfig, pointer::CursorImageStatus, Seat, SeatState},
|
||||
output::{Mode as OutputMode, Output, PhysicalProperties, Subpixel},
|
||||
reexports::{
|
||||
calloop::{
|
||||
channel::{Channel, Event},
|
||||
generic::Generic,
|
||||
timer::{TimeoutAction, Timer},
|
||||
EventLoop, Interest, LoopHandle, Mode, PostAction,
|
||||
},
|
||||
input::Libinput,
|
||||
wayland_protocols::wp::presentation_time::server::wp_presentation_feedback,
|
||||
wayland_server::{
|
||||
backend::{ClientData, ClientId, DisconnectReason},
|
||||
Display, DisplayHandle,
|
||||
},
|
||||
},
|
||||
utils::{Clock, Logical, Monotonic, Physical, Point, Rectangle, Size, Transform},
|
||||
wayland::{
|
||||
compositor::{with_states, CompositorState},
|
||||
data_device::DataDeviceState,
|
||||
dmabuf::{DmabufGlobal, DmabufState},
|
||||
output::OutputManagerState,
|
||||
presentation::PresentationState,
|
||||
shell::xdg::{XdgShellState, XdgToplevelSurfaceData},
|
||||
shm::ShmState,
|
||||
socket::ListeningSocketSource,
|
||||
viewporter::ViewporterState,
|
||||
relative_pointer::RelativePointerManagerState,
|
||||
},
|
||||
};
|
||||
use wayland_backend::server::GlobalId;
|
||||
|
||||
mod focus;
|
||||
mod input;
|
||||
mod rendering;
|
||||
|
||||
pub use self::focus::*;
|
||||
pub use self::input::*;
|
||||
pub use self::rendering::*;
|
||||
use crate::{utils::RenderTarget, wayland::protocols::wl_drm::create_drm_global};
|
||||
|
||||
static EGL_DISPLAYS: Lazy<Mutex<HashMap<Option<DrmNode>, Weak<EGLDisplay>>>> =
|
||||
Lazy::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
struct ClientState;
|
||||
impl ClientData for ClientState {
|
||||
fn initialized(&self, _client_id: ClientId) {}
|
||||
fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
|
||||
}
|
||||
|
||||
pub(crate) struct Data {
|
||||
pub(crate) display: Display<State>,
|
||||
pub(crate) state: State,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) struct State {
|
||||
handle: LoopHandle<'static, Data>,
|
||||
should_quit: bool,
|
||||
clock: Clock<Monotonic>,
|
||||
|
||||
// render
|
||||
dtr: Option<DamageTrackedRenderer>,
|
||||
renderbuffer: Option<Gles2Renderbuffer>,
|
||||
pub renderer: Gles2Renderer,
|
||||
egl_display_ref: Arc<EGLDisplay>,
|
||||
dmabuf_global: Option<(DmabufGlobal, GlobalId)>,
|
||||
last_render: Option<Instant>,
|
||||
|
||||
// management
|
||||
pub output: Option<Output>,
|
||||
pub video_info: Option<VideoInfo>,
|
||||
pub seat: Seat<Self>,
|
||||
pub space: Space<Window>,
|
||||
pub popups: PopupManager,
|
||||
pointer_location: Point<f64, Logical>,
|
||||
last_pointer_movement: Instant,
|
||||
cursor_element: MemoryRenderBuffer,
|
||||
pub cursor_state: CursorImageStatus,
|
||||
surpressed_keys: HashSet<u32>,
|
||||
pub pending_windows: Vec<Window>,
|
||||
input_context: Libinput,
|
||||
|
||||
// wayland state
|
||||
pub dh: DisplayHandle,
|
||||
pub compositor_state: CompositorState,
|
||||
pub data_device_state: DataDeviceState,
|
||||
pub dmabuf_state: DmabufState,
|
||||
output_state: OutputManagerState,
|
||||
presentation_state: PresentationState,
|
||||
relative_ptr_state: RelativePointerManagerState,
|
||||
pub seat_state: SeatState<Self>,
|
||||
pub shell_state: XdgShellState,
|
||||
pub shm_state: ShmState,
|
||||
viewporter_state: ViewporterState,
|
||||
}
|
||||
|
||||
pub fn get_egl_device_for_node(drm_node: &DrmNode) -> EGLDevice {
|
||||
let drm_node = drm_node
|
||||
.node_with_type(NodeType::Render)
|
||||
.and_then(Result::ok)
|
||||
.unwrap_or(drm_node.clone());
|
||||
EGLDevice::enumerate()
|
||||
.expect("Failed to enumerate EGLDevices")
|
||||
.find(|d| d.try_get_render_node().unwrap_or_default() == Some(drm_node))
|
||||
.expect("Unable to find EGLDevice for drm-node")
|
||||
}
|
||||
|
||||
pub(crate) fn init(
|
||||
command_src: Channel<Command>,
|
||||
render: impl Into<RenderTarget>,
|
||||
devices_tx: Sender<Vec<CString>>,
|
||||
envs_tx: Sender<Vec<CString>>,
|
||||
) {
|
||||
let clock = Clock::new().expect("Failed to initialize clock");
|
||||
let mut display = Display::<State>::new().unwrap();
|
||||
let dh = display.handle();
|
||||
|
||||
// init state
|
||||
let compositor_state = CompositorState::new::<State>(&dh);
|
||||
let data_device_state = DataDeviceState::new::<State>(&dh);
|
||||
let mut dmabuf_state = DmabufState::new();
|
||||
let output_state = OutputManagerState::new_with_xdg_output::<State>(&dh);
|
||||
let presentation_state = PresentationState::new::<State>(&dh, clock.id() as _);
|
||||
let relative_ptr_state = RelativePointerManagerState::new::<State>(&dh);
|
||||
let mut seat_state = SeatState::new();
|
||||
let shell_state = XdgShellState::new::<State>(&dh);
|
||||
let viewporter_state = ViewporterState::new::<State>(&dh);
|
||||
|
||||
let render_target = render.into();
|
||||
let render_node: Option<DrmNode> = render_target.clone().into();
|
||||
|
||||
// init render backend
|
||||
let (egl_display_ref, context) = {
|
||||
let mut displays = EGL_DISPLAYS.lock().unwrap();
|
||||
let maybe_display = displays
|
||||
.get(&render_node)
|
||||
.and_then(|weak_display| weak_display.upgrade());
|
||||
|
||||
let egl = match maybe_display {
|
||||
Some(display) => display,
|
||||
None => {
|
||||
let device = match render_node.as_ref() {
|
||||
Some(render_node) => get_egl_device_for_node(render_node),
|
||||
None => EGLDevice::enumerate()
|
||||
.expect("Failed to enumerate EGLDevices")
|
||||
.find(|device| {
|
||||
device
|
||||
.extensions()
|
||||
.iter()
|
||||
.any(|e| e == "EGL_MESA_device_software")
|
||||
})
|
||||
.expect("Failed to find software device"),
|
||||
};
|
||||
let display =
|
||||
Arc::new(EGLDisplay::new(device).expect("Failed to initialize EGL display"));
|
||||
displays.insert(render_node, Arc::downgrade(&display));
|
||||
display
|
||||
}
|
||||
};
|
||||
let context = EGLContext::new(&egl).expect("Failed to initialize EGL context");
|
||||
(egl, context)
|
||||
};
|
||||
let renderer = unsafe { Gles2Renderer::new(context) }.expect("Failed to initialize renderer");
|
||||
let _ = devices_tx.send(render_target.as_devices());
|
||||
|
||||
let shm_state = ShmState::new::<State>(&dh, vec![]);
|
||||
let dmabuf_global = if let RenderTarget::Hardware(node) = render_target {
|
||||
let formats = Bind::<Dmabuf>::supported_formats(&renderer)
|
||||
.expect("Failed to query formats")
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// dma buffer
|
||||
let dmabuf_global = dmabuf_state.create_global::<State>(&dh, formats.clone());
|
||||
// wl_drm (mesa protocol, so we don't need EGL_WL_bind_display)
|
||||
let wl_drm_global = create_drm_global::<State>(
|
||||
&dh,
|
||||
node.dev_path().expect("Failed to determine DrmNode path?"),
|
||||
formats.clone(),
|
||||
&dmabuf_global,
|
||||
);
|
||||
|
||||
Some((dmabuf_global, wl_drm_global))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let cursor_element =
|
||||
MemoryRenderBuffer::from_memory(CURSOR_DATA_BYTES, (64, 64), 1, Transform::Normal, None);
|
||||
|
||||
// init input backend
|
||||
let libinput_context = Libinput::new_from_path(NixInterface);
|
||||
let input_context = libinput_context.clone();
|
||||
let libinput_backend = LibinputInputBackend::new(libinput_context);
|
||||
|
||||
let space = Space::default();
|
||||
|
||||
let mut seat = seat_state.new_wl_seat(&dh, "seat-0");
|
||||
seat.add_keyboard(XkbConfig::default(), 200, 25)
|
||||
.expect("Failed to add keyboard to seat");
|
||||
seat.add_pointer();
|
||||
|
||||
let mut event_loop =
|
||||
EventLoop::<Data>::try_new_high_precision().expect("Unable to create event_loop");
|
||||
let state = State {
|
||||
handle: event_loop.handle(),
|
||||
should_quit: false,
|
||||
clock,
|
||||
|
||||
renderer,
|
||||
egl_display_ref,
|
||||
dtr: None,
|
||||
renderbuffer: None,
|
||||
dmabuf_global,
|
||||
video_info: None,
|
||||
last_render: None,
|
||||
|
||||
space,
|
||||
popups: PopupManager::default(),
|
||||
seat,
|
||||
output: None,
|
||||
pointer_location: (0., 0.).into(),
|
||||
last_pointer_movement: Instant::now(),
|
||||
cursor_element,
|
||||
cursor_state: CursorImageStatus::Default,
|
||||
surpressed_keys: HashSet::new(),
|
||||
pending_windows: Vec::new(),
|
||||
input_context,
|
||||
|
||||
dh: display.handle(),
|
||||
compositor_state,
|
||||
data_device_state,
|
||||
dmabuf_state,
|
||||
output_state,
|
||||
presentation_state,
|
||||
relative_ptr_state,
|
||||
seat_state,
|
||||
shell_state,
|
||||
shm_state,
|
||||
viewporter_state,
|
||||
};
|
||||
|
||||
// init event loop
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(libinput_backend, move |event, _, data| {
|
||||
data.state.process_input_event(event)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(command_src, move |event, _, data| {
|
||||
match event {
|
||||
Event::Msg(Command::VideoInfo(info)) => {
|
||||
let size: Size<i32, Physical> =
|
||||
(info.width() as i32, info.height() as i32).into();
|
||||
let framerate = info.fps();
|
||||
let duration = Duration::from_secs_f64(
|
||||
framerate.numer() as f64 / framerate.denom() as f64,
|
||||
);
|
||||
|
||||
// init wayland objects
|
||||
let output = data.state.output.get_or_insert_with(|| {
|
||||
let output = Output::new(
|
||||
"HEADLESS-1".into(),
|
||||
PhysicalProperties {
|
||||
make: "Virtual".into(),
|
||||
model: "Wolf".into(),
|
||||
size: (0, 0).into(),
|
||||
subpixel: Subpixel::Unknown,
|
||||
},
|
||||
);
|
||||
output.create_global::<State>(&data.display.handle());
|
||||
output
|
||||
});
|
||||
let mode = OutputMode {
|
||||
size: size.into(),
|
||||
refresh: (duration.as_secs_f64() * 1000.0).round() as i32,
|
||||
};
|
||||
output.change_current_state(Some(mode), None, None, None);
|
||||
output.set_preferred(mode);
|
||||
let dtr = DamageTrackedRenderer::from_output(&output);
|
||||
|
||||
data.state.space.map_output(&output, (0, 0));
|
||||
data.state.dtr = Some(dtr);
|
||||
data.state.pointer_location = (size.w as f64 / 2.0, size.h as f64 / 2.0).into();
|
||||
data.state.renderbuffer = Some(
|
||||
data.state
|
||||
.renderer
|
||||
.create_buffer((info.width() as i32, info.height() as i32).into())
|
||||
.expect("Failed to create renderbuffer"),
|
||||
);
|
||||
data.state.video_info = Some(info);
|
||||
|
||||
let new_size = size
|
||||
.to_f64()
|
||||
.to_logical(output.current_scale().fractional_scale())
|
||||
.to_i32_round();
|
||||
for window in data.state.space.elements() {
|
||||
let toplevel = window.toplevel();
|
||||
let max_size = Rectangle::from_loc_and_size(
|
||||
(0, 0),
|
||||
with_states(toplevel.wl_surface(), |states| {
|
||||
states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.map(|attrs| attrs.lock().unwrap().max_size)
|
||||
})
|
||||
.unwrap_or(new_size),
|
||||
);
|
||||
|
||||
let new_size = max_size
|
||||
.intersection(Rectangle::from_loc_and_size((0, 0), new_size))
|
||||
.map(|rect| rect.size);
|
||||
toplevel.with_pending_state(|state| state.size = new_size);
|
||||
toplevel.send_configure();
|
||||
}
|
||||
}
|
||||
Event::Msg(Command::InputDevice(path)) => {
|
||||
tracing::info!(path, "Adding input device.");
|
||||
data.state.input_context.path_add_device(&path);
|
||||
}
|
||||
Event::Msg(Command::Buffer(buffer_sender)) => {
|
||||
let wait = if let Some(last_render) = data.state.last_render {
|
||||
let framerate = data.state.video_info.as_ref().unwrap().fps();
|
||||
let duration = Duration::from_secs_f64(
|
||||
framerate.denom() as f64 / framerate.numer() as f64,
|
||||
);
|
||||
let time_passed = Instant::now().duration_since(last_render);
|
||||
if time_passed < duration {
|
||||
Some(duration - time_passed)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let render = move |data: &mut Data, now: Instant| {
|
||||
if let Err(_) = match data.state.create_frame() {
|
||||
Ok((buf, damage, render_element_states)) => {
|
||||
data.state.last_render = Some(now);
|
||||
let res = buffer_sender.send(Ok(buf));
|
||||
|
||||
if let Some(output) = data.state.output.as_ref() {
|
||||
let mut output_presentation_feedback =
|
||||
OutputPresentationFeedback::new(output);
|
||||
for window in data.state.space.elements() {
|
||||
window.with_surfaces(|surface, states| {
|
||||
update_surface_primary_scanout_output(
|
||||
surface,
|
||||
output,
|
||||
states,
|
||||
&render_element_states,
|
||||
|next_output, _, _, _| next_output,
|
||||
);
|
||||
});
|
||||
window.send_frame(
|
||||
output,
|
||||
data.state.clock.now(),
|
||||
Some(Duration::ZERO),
|
||||
|_, _| Some(output.clone()),
|
||||
);
|
||||
window.take_presentation_feedback(
|
||||
&mut output_presentation_feedback,
|
||||
surface_primary_scanout_output,
|
||||
|surface, _| {
|
||||
surface_presentation_feedback_flags_from_states(
|
||||
surface,
|
||||
&render_element_states,
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
if damage.is_some() {
|
||||
output_presentation_feedback.presented(
|
||||
data.state.clock.now(),
|
||||
output
|
||||
.current_mode()
|
||||
.map(|mode| mode.refresh as u32)
|
||||
.unwrap_or_default(),
|
||||
0,
|
||||
wp_presentation_feedback::Kind::Vsync,
|
||||
);
|
||||
}
|
||||
if let CursorImageStatus::Surface(wl_surface) =
|
||||
&data.state.cursor_state
|
||||
{
|
||||
send_frames_surface_tree(
|
||||
wl_surface,
|
||||
output,
|
||||
data.state.clock.now(),
|
||||
None,
|
||||
|_, _| Some(output.clone()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::error!(?err, "Rendering failed.");
|
||||
buffer_sender.send(Err(match err {
|
||||
DTRError::OutputNoMode(_) => unreachable!(),
|
||||
DTRError::Rendering(err) => err.into(),
|
||||
}))
|
||||
}
|
||||
} {
|
||||
data.state.should_quit = true;
|
||||
}
|
||||
};
|
||||
|
||||
match wait {
|
||||
Some(duration) => {
|
||||
if let Err(err) = data.state.handle.insert_source(
|
||||
Timer::from_duration(duration),
|
||||
move |now, _, data| {
|
||||
render(data, now);
|
||||
TimeoutAction::Drop
|
||||
},
|
||||
) {
|
||||
tracing::error!(?err, "Event loop error.");
|
||||
data.state.should_quit = true;
|
||||
};
|
||||
}
|
||||
None => render(data, Instant::now()),
|
||||
};
|
||||
}
|
||||
Event::Msg(Command::Quit) | Event::Closed => {
|
||||
data.state.should_quit = true;
|
||||
}
|
||||
};
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let source = ListeningSocketSource::new_auto().unwrap();
|
||||
let socket_name = source.socket_name().to_string_lossy().into_owned();
|
||||
tracing::info!(?socket_name, "Listening on wayland socket.");
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(source, |client_stream, _, data| {
|
||||
if let Err(err) = data
|
||||
.display
|
||||
.handle()
|
||||
.insert_client(client_stream, std::sync::Arc::new(ClientState))
|
||||
{
|
||||
tracing::error!(?err, "Error adding wayland client.");
|
||||
};
|
||||
})
|
||||
.expect("Failed to init wayland socket source");
|
||||
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(
|
||||
Generic::new(
|
||||
display.backend().poll_fd().as_raw_fd(),
|
||||
Interest::READ,
|
||||
Mode::Level,
|
||||
),
|
||||
|_, _, data| {
|
||||
data.display.dispatch_clients(&mut data.state).unwrap();
|
||||
Ok(PostAction::Continue)
|
||||
},
|
||||
)
|
||||
.expect("Failed to init wayland server source");
|
||||
|
||||
let env_vars = vec![CString::new(format!("WAYLAND_DISPLAY={}", socket_name)).unwrap()];
|
||||
if let Err(err) = envs_tx.send(env_vars) {
|
||||
tracing::warn!(?err, "Failed to post environment to application.");
|
||||
}
|
||||
|
||||
let mut data = Data { display, state };
|
||||
let signal = event_loop.get_signal();
|
||||
if let Err(err) = event_loop.run(None, &mut data, |data| {
|
||||
data.display
|
||||
.flush_clients()
|
||||
.expect("Failed to flush clients");
|
||||
data.state.space.refresh();
|
||||
data.state.popups.cleanup();
|
||||
|
||||
if data.state.should_quit {
|
||||
signal.stop();
|
||||
}
|
||||
}) {
|
||||
tracing::error!(?err, "Event loop broke.");
|
||||
}
|
||||
}
|
||||
121
wayland-display-core/src/comp/rendering.rs
Normal file
121
wayland-display-core/src/comp/rendering.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use smithay::{
|
||||
backend::renderer::{
|
||||
damage::DamageTrackedRendererError as DTRError,
|
||||
element::{
|
||||
memory::MemoryRenderBufferRenderElement, surface::WaylandSurfaceRenderElement,
|
||||
RenderElementStates,
|
||||
},
|
||||
gles2::Gles2Renderer,
|
||||
Bind, ExportMem, ImportAll, ImportMem, Renderer, Unbind,
|
||||
},
|
||||
desktop::space::render_output,
|
||||
input::pointer::CursorImageStatus,
|
||||
render_elements,
|
||||
utils::{Physical, Rectangle},
|
||||
};
|
||||
|
||||
use super::State;
|
||||
|
||||
pub const CURSOR_DATA_BYTES: &[u8] = include_bytes!("../../resources/cursor.rgba");
|
||||
|
||||
render_elements! {
|
||||
CursorElement<R> where R: Renderer + ImportAll + ImportMem;
|
||||
Surface=WaylandSurfaceRenderElement<R>,
|
||||
Memory=MemoryRenderBufferRenderElement<R>
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn create_frame(
|
||||
&mut self,
|
||||
) -> Result<
|
||||
(
|
||||
gst::Buffer,
|
||||
Option<Vec<Rectangle<i32, Physical>>>,
|
||||
RenderElementStates,
|
||||
),
|
||||
DTRError<Gles2Renderer>,
|
||||
> {
|
||||
assert!(self.output.is_some());
|
||||
assert!(self.dtr.is_some());
|
||||
assert!(self.video_info.is_some());
|
||||
assert!(self.renderbuffer.is_some());
|
||||
|
||||
let elements =
|
||||
if Instant::now().duration_since(self.last_pointer_movement) < Duration::from_secs(5) {
|
||||
match &self.cursor_state {
|
||||
CursorImageStatus::Default => vec![CursorElement::Memory(
|
||||
MemoryRenderBufferRenderElement::from_buffer(
|
||||
&mut self.renderer,
|
||||
self.pointer_location.to_physical_precise_round(1),
|
||||
&self.cursor_element,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(DTRError::Rendering)?,
|
||||
)],
|
||||
CursorImageStatus::Surface(wl_surface) => {
|
||||
smithay::backend::renderer::element::surface::render_elements_from_surface_tree(
|
||||
&mut self.renderer,
|
||||
wl_surface,
|
||||
self.pointer_location.to_physical_precise_round(1),
|
||||
1.,
|
||||
)
|
||||
}
|
||||
CursorImageStatus::Hidden => vec![],
|
||||
}
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
|
||||
self.renderer
|
||||
.bind(self.renderbuffer.clone().unwrap())
|
||||
.map_err(DTRError::Rendering)?;
|
||||
let (damage, render_element_states) = render_output(
|
||||
self.output.as_ref().unwrap(),
|
||||
&mut self.renderer,
|
||||
1,
|
||||
[&self.space],
|
||||
&*elements,
|
||||
self.dtr.as_mut().unwrap(),
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
)?;
|
||||
|
||||
let mapping = self
|
||||
.renderer
|
||||
.copy_framebuffer(Rectangle::from_loc_and_size(
|
||||
(0, 0),
|
||||
(
|
||||
self.video_info.as_ref().unwrap().width() as i32,
|
||||
self.video_info.as_ref().unwrap().height() as i32,
|
||||
),
|
||||
))
|
||||
.expect("Failed to export framebuffer");
|
||||
let map = self
|
||||
.renderer
|
||||
.map_texture(&mapping)
|
||||
.expect("Failed to download framebuffer");
|
||||
|
||||
let buffer = {
|
||||
let mut buffer = gst::Buffer::with_size(map.len()).expect("failed to create buffer");
|
||||
{
|
||||
let buffer = buffer.get_mut().unwrap();
|
||||
|
||||
let mut vframe = gst_video::VideoFrameRef::from_buffer_ref_writable(
|
||||
buffer,
|
||||
self.video_info.as_ref().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let plane_data = vframe.plane_data_mut(0).unwrap();
|
||||
plane_data.clone_from_slice(map);
|
||||
}
|
||||
|
||||
buffer
|
||||
};
|
||||
self.renderer.unbind().map_err(DTRError::Rendering)?;
|
||||
|
||||
Ok((buffer, damage, render_element_states))
|
||||
}
|
||||
}
|
||||
134
wayland-display-core/src/lib.rs
Normal file
134
wayland-display-core/src/lib.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
use gst_video::VideoInfo;
|
||||
|
||||
use smithay::backend::drm::CreateDrmNodeError;
|
||||
use smithay::backend::SwapBuffersError;
|
||||
use smithay::reexports::calloop::channel::Sender;
|
||||
|
||||
use std::ffi::{CString};
|
||||
use std::str::FromStr;
|
||||
use std::sync::mpsc::{self, Receiver, SyncSender};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use utils::RenderTarget;
|
||||
|
||||
pub(crate) mod comp;
|
||||
pub(crate) mod utils;
|
||||
pub(crate) mod wayland;
|
||||
|
||||
pub(crate) enum Command {
|
||||
InputDevice(String),
|
||||
VideoInfo(VideoInfo),
|
||||
Buffer(SyncSender<Result<gst::Buffer, SwapBuffersError>>),
|
||||
Quit,
|
||||
}
|
||||
|
||||
pub struct WaylandDisplay {
|
||||
thread_handle: Option<JoinHandle<()>>,
|
||||
command_tx: Sender<Command>,
|
||||
|
||||
pub devices: MaybeRecv<Vec<CString>>,
|
||||
pub envs: MaybeRecv<Vec<CString>>,
|
||||
}
|
||||
|
||||
pub enum MaybeRecv<T: Clone> {
|
||||
Rx(Receiver<T>),
|
||||
Value(T),
|
||||
}
|
||||
|
||||
impl<T: Clone> MaybeRecv<T> {
|
||||
pub fn get(&mut self) -> &T {
|
||||
match self {
|
||||
MaybeRecv::Rx(recv) => {
|
||||
let value = recv.recv().unwrap();
|
||||
*self = MaybeRecv::Value(value.clone());
|
||||
self.get()
|
||||
}
|
||||
MaybeRecv::Value(val) => val,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WaylandDisplay {
|
||||
pub fn new(render_node: Option<String>) -> Result<WaylandDisplay, CreateDrmNodeError> {
|
||||
let (channel_tx, channel_rx) = std::sync::mpsc::sync_channel(0);
|
||||
let (devices_tx, devices_rx) = std::sync::mpsc::channel();
|
||||
let (envs_tx, envs_rx) = std::sync::mpsc::channel();
|
||||
let render_target = RenderTarget::from_str(
|
||||
&render_node.unwrap_or_else(|| String::from("/dev/dri/renderD128")),
|
||||
)?;
|
||||
|
||||
let thread_handle = std::thread::spawn(move || {
|
||||
if let Err(err) = std::panic::catch_unwind(|| {
|
||||
// calloops channel is not "UnwindSafe", but the std channel is... *sigh* lets workaround it creatively
|
||||
let (command_tx, command_src) = smithay::reexports::calloop::channel::channel();
|
||||
channel_tx.send(command_tx).unwrap();
|
||||
comp::init(command_src, render_target, devices_tx, envs_tx);
|
||||
}) {
|
||||
tracing::error!(?err, "Compositor thread panic'ed!");
|
||||
}
|
||||
});
|
||||
let command_tx = channel_rx.recv().unwrap();
|
||||
|
||||
Ok(WaylandDisplay {
|
||||
thread_handle: Some(thread_handle),
|
||||
command_tx,
|
||||
devices: MaybeRecv::Rx(devices_rx),
|
||||
envs: MaybeRecv::Rx(envs_rx),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn devices(&mut self) -> impl Iterator<Item = &str> {
|
||||
self.devices
|
||||
.get()
|
||||
.iter()
|
||||
.map(|string| string.to_str().unwrap())
|
||||
}
|
||||
|
||||
pub fn env_vars(&mut self) -> impl Iterator<Item = &str> {
|
||||
self.envs
|
||||
.get()
|
||||
.iter()
|
||||
.map(|string| string.to_str().unwrap())
|
||||
}
|
||||
|
||||
pub fn add_input_device(&self, path: impl Into<String>) {
|
||||
let _ = self.command_tx.send(Command::InputDevice(path.into()));
|
||||
}
|
||||
|
||||
pub fn set_video_info(&self, info: VideoInfo) {
|
||||
let _ = self.command_tx.send(Command::VideoInfo(info));
|
||||
}
|
||||
|
||||
pub fn frame(&self) -> Result<gst::Buffer, gst::FlowError> {
|
||||
let (buffer_tx, buffer_rx) = mpsc::sync_channel(0);
|
||||
if let Err(err) = self.command_tx.send(Command::Buffer(buffer_tx)) {
|
||||
tracing::warn!(?err, "Failed to send buffer command.");
|
||||
return Err(gst::FlowError::Eos);
|
||||
}
|
||||
|
||||
match buffer_rx.recv() {
|
||||
Ok(Ok(buffer)) => Ok(buffer),
|
||||
Ok(Err(err)) => match err {
|
||||
SwapBuffersError::AlreadySwapped => unreachable!(),
|
||||
SwapBuffersError::ContextLost(_) => Err(gst::FlowError::Eos),
|
||||
SwapBuffersError::TemporaryFailure(_) => Err(gst::FlowError::Error),
|
||||
},
|
||||
Err(err) => {
|
||||
tracing::warn!(?err, "Failed to recv buffer ack.");
|
||||
Err(gst::FlowError::Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WaylandDisplay {
|
||||
fn drop(&mut self) {
|
||||
if let Err(err) = self.command_tx.send(Command::Quit) {
|
||||
tracing::warn!("Failed to send stop command: {}", err);
|
||||
return;
|
||||
};
|
||||
if self.thread_handle.take().unwrap().join().is_err() {
|
||||
tracing::warn!("Failed to join compositor thread");
|
||||
};
|
||||
}
|
||||
}
|
||||
3
wayland-display-core/src/utils/mod.rs
Normal file
3
wayland-display-core/src/utils/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
mod target;
|
||||
|
||||
pub use self::target::*;
|
||||
88
wayland-display-core/src/utils/target.rs
Normal file
88
wayland-display-core/src/utils/target.rs
Normal file
@@ -0,0 +1,88 @@
|
||||
use std::{ffi::CString, os::unix::fs::MetadataExt, str::FromStr};
|
||||
|
||||
use smithay::{
|
||||
backend::{
|
||||
drm::{CreateDrmNodeError, DrmNode, NodeType},
|
||||
udev,
|
||||
},
|
||||
reexports::nix::sys::stat::major,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum RenderTarget {
|
||||
Hardware(DrmNode),
|
||||
Software,
|
||||
}
|
||||
|
||||
impl FromStr for RenderTarget {
|
||||
type Err = CreateDrmNodeError;
|
||||
fn from_str(s: &str) -> Result<Self, CreateDrmNodeError> {
|
||||
Ok(match s {
|
||||
"software" => RenderTarget::Software,
|
||||
path => RenderTarget::Hardware(DrmNode::from_path(path)?),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<Option<DrmNode>> for RenderTarget {
|
||||
fn into(self) -> Option<DrmNode> {
|
||||
match self {
|
||||
RenderTarget::Hardware(node) => Some(node),
|
||||
RenderTarget::Software => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<RenderTarget> for DrmNode {
|
||||
fn into(self) -> RenderTarget {
|
||||
RenderTarget::Hardware(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
const NVIDIA_MAJOR: u64 = 195;
|
||||
|
||||
// no clue how this number is on BSDs, feel free to contribute
|
||||
|
||||
impl RenderTarget {
|
||||
pub fn as_devices(&self) -> Vec<CString> {
|
||||
match self {
|
||||
RenderTarget::Hardware(node) => {
|
||||
let mut devices = Vec::new();
|
||||
if let Some(primary) = node.dev_path_with_type(NodeType::Primary) {
|
||||
devices.push(primary);
|
||||
}
|
||||
if let Some(render) = node.dev_path_with_type(NodeType::Render) {
|
||||
devices.push(render);
|
||||
}
|
||||
if udev::driver(node.dev_id())
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|s| s.to_str() == Some("nvidia"))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
// no idea how match nvidia device nodes to kms/dri-nodes, so lets map all nvidia-nodes to be sure
|
||||
for entry in std::fs::read_dir("/dev").expect("Unable to access /dev") {
|
||||
if let Ok(entry) = entry {
|
||||
if let Ok(metadata) = entry.metadata() {
|
||||
if metadata.is_file() && major(metadata.dev()) == NVIDIA_MAJOR {
|
||||
devices.push(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
devices
|
||||
.into_iter()
|
||||
.flat_map(|path| {
|
||||
path.to_str()
|
||||
.map(String::from)
|
||||
.and_then(|string| CString::new(string).ok())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
RenderTarget::Software => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
147
wayland-display-core/src/wayland/handlers/compositor.rs
Normal file
147
wayland-display-core/src/wayland/handlers/compositor.rs
Normal file
@@ -0,0 +1,147 @@
|
||||
use smithay::{
|
||||
backend::renderer::utils::{on_commit_buffer_handler},
|
||||
delegate_compositor,
|
||||
desktop::PopupKind,
|
||||
reexports::{
|
||||
wayland_protocols::xdg::shell::server::xdg_toplevel::State as XdgState,
|
||||
wayland_server::protocol::{wl_buffer::WlBuffer, wl_surface::WlSurface},
|
||||
},
|
||||
utils::{Size, SERIAL_COUNTER},
|
||||
wayland::{
|
||||
buffer::BufferHandler,
|
||||
compositor::{with_states, CompositorHandler, CompositorState},
|
||||
seat::WaylandFocus,
|
||||
shell::xdg::{XdgPopupSurfaceData, XdgToplevelSurfaceData},
|
||||
},
|
||||
};
|
||||
|
||||
use crate::comp::{FocusTarget, State};
|
||||
|
||||
impl BufferHandler for State {
|
||||
fn buffer_destroyed(&mut self, _buffer: &WlBuffer) {}
|
||||
}
|
||||
|
||||
impl CompositorHandler for State {
|
||||
fn compositor_state(&mut self) -> &mut CompositorState {
|
||||
&mut self.compositor_state
|
||||
}
|
||||
|
||||
fn commit(&mut self, surface: &WlSurface) {
|
||||
on_commit_buffer_handler(surface);
|
||||
|
||||
if let Some(window) = self
|
||||
.space
|
||||
.elements()
|
||||
.find(|w| w.wl_surface().as_ref() == Some(surface))
|
||||
{
|
||||
window.on_commit();
|
||||
}
|
||||
self.popups.commit(surface);
|
||||
|
||||
// send the initial configure if relevant
|
||||
if let Some(idx) = self
|
||||
.pending_windows
|
||||
.iter_mut()
|
||||
.position(|w| w.wl_surface().as_ref() == Some(surface))
|
||||
{
|
||||
let window = self.pending_windows.swap_remove(idx);
|
||||
|
||||
let toplevel = window.toplevel();
|
||||
let (initial_configure_sent, max_size) = with_states(surface, |states| {
|
||||
let attributes = states.data_map.get::<XdgToplevelSurfaceData>().unwrap();
|
||||
let attributes_guard = attributes.lock().unwrap();
|
||||
|
||||
(
|
||||
attributes_guard.initial_configure_sent,
|
||||
attributes_guard.max_size,
|
||||
)
|
||||
});
|
||||
|
||||
if self.output.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
if !initial_configure_sent {
|
||||
if max_size.w == 0 && max_size.h == 0 {
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.size = Some(
|
||||
self.output
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.current_mode()
|
||||
.unwrap()
|
||||
.size
|
||||
.to_f64()
|
||||
.to_logical(
|
||||
self.output
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.current_scale()
|
||||
.fractional_scale(),
|
||||
)
|
||||
.to_i32_round(),
|
||||
);
|
||||
state.states.set(XdgState::Fullscreen);
|
||||
});
|
||||
}
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.states.set(XdgState::Activated);
|
||||
});
|
||||
toplevel.send_configure();
|
||||
self.pending_windows.push(window);
|
||||
} else {
|
||||
let window_size = toplevel.current_state().size.unwrap_or((0, 0).into());
|
||||
let output_size: Size<i32, _> = self
|
||||
.output
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.current_mode()
|
||||
.unwrap()
|
||||
.size
|
||||
.to_f64()
|
||||
.to_logical(
|
||||
self.output
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.current_scale()
|
||||
.fractional_scale(),
|
||||
)
|
||||
.to_i32_round();
|
||||
let loc = (
|
||||
(output_size.w / 2) - (window_size.w / 2),
|
||||
(output_size.h / 2) - (window_size.h / 2),
|
||||
);
|
||||
self.space.map_element(window.clone(), loc, true);
|
||||
self.seat.get_keyboard().unwrap().set_focus(
|
||||
self,
|
||||
Some(FocusTarget::from(window)),
|
||||
SERIAL_COUNTER.next_serial(),
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(popup) = self.popups.find_popup(surface) {
|
||||
let PopupKind::Xdg(ref popup) = popup;
|
||||
let initial_configure_sent = with_states(surface, |states| {
|
||||
states
|
||||
.data_map
|
||||
.get::<XdgPopupSurfaceData>()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.unwrap()
|
||||
.initial_configure_sent
|
||||
});
|
||||
if !initial_configure_sent {
|
||||
// NOTE: This should never fail as the initial configure is always
|
||||
// allowed.
|
||||
popup.send_configure().expect("initial configure failed");
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
delegate_compositor!(State);
|
||||
18
wayland-display-core/src/wayland/handlers/data_device.rs
Normal file
18
wayland-display-core/src/wayland/handlers/data_device.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use smithay::{
|
||||
delegate_data_device,
|
||||
wayland::data_device::{
|
||||
ClientDndGrabHandler, DataDeviceHandler, DataDeviceState, ServerDndGrabHandler,
|
||||
},
|
||||
};
|
||||
|
||||
use crate::comp::State;
|
||||
|
||||
impl ServerDndGrabHandler for State {}
|
||||
impl ClientDndGrabHandler for State {}
|
||||
impl DataDeviceHandler for State {
|
||||
fn data_device_state(&self) -> &DataDeviceState {
|
||||
&self.data_device_state
|
||||
}
|
||||
}
|
||||
|
||||
delegate_data_device!(State);
|
||||
26
wayland-display-core/src/wayland/handlers/dmabuf.rs
Normal file
26
wayland-display-core/src/wayland/handlers/dmabuf.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use smithay::{
|
||||
backend::{allocator::dmabuf::Dmabuf, renderer::ImportDma},
|
||||
delegate_dmabuf,
|
||||
wayland::dmabuf::{DmabufGlobal, DmabufHandler, DmabufState, ImportError},
|
||||
};
|
||||
|
||||
use crate::comp::State;
|
||||
|
||||
impl DmabufHandler for State {
|
||||
fn dmabuf_state(&mut self) -> &mut DmabufState {
|
||||
&mut self.dmabuf_state
|
||||
}
|
||||
|
||||
fn dmabuf_imported(
|
||||
&mut self,
|
||||
_global: &DmabufGlobal,
|
||||
dmabuf: Dmabuf,
|
||||
) -> Result<(), ImportError> {
|
||||
self.renderer
|
||||
.import_dmabuf(&dmabuf, None)
|
||||
.map(|_| ())
|
||||
.map_err(|_| ImportError::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
delegate_dmabuf!(State);
|
||||
11
wayland-display-core/src/wayland/handlers/mod.rs
Normal file
11
wayland-display-core/src/wayland/handlers/mod.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
pub mod compositor;
|
||||
pub mod data_device;
|
||||
pub mod dmabuf;
|
||||
pub mod output;
|
||||
pub mod presentation;
|
||||
pub mod relative_pointer;
|
||||
pub mod seat;
|
||||
pub mod shm;
|
||||
pub mod viewporter;
|
||||
pub mod wl_drm;
|
||||
pub mod xdg;
|
||||
5
wayland-display-core/src/wayland/handlers/output.rs
Normal file
5
wayland-display-core/src/wayland/handlers/output.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
use smithay::delegate_output;
|
||||
|
||||
use crate::comp::State;
|
||||
|
||||
delegate_output!(State);
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use crate::comp::State;
|
||||
use smithay::delegate_presentation;
|
||||
|
||||
delegate_presentation!(State);
|
||||
@@ -0,0 +1,5 @@
|
||||
use smithay::delegate_relative_pointer;
|
||||
|
||||
use crate::comp::State;
|
||||
|
||||
delegate_relative_pointer!(State);
|
||||
35
wayland-display-core/src/wayland/handlers/seat.rs
Normal file
35
wayland-display-core/src/wayland/handlers/seat.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use smithay::{
|
||||
delegate_seat,
|
||||
input::{pointer::CursorImageStatus, Seat, SeatHandler, SeatState},
|
||||
reexports::wayland_server::Resource,
|
||||
wayland::data_device::set_data_device_focus,
|
||||
};
|
||||
|
||||
use crate::comp::{FocusTarget, State};
|
||||
|
||||
impl SeatHandler for State {
|
||||
type KeyboardFocus = FocusTarget;
|
||||
type PointerFocus = FocusTarget;
|
||||
|
||||
fn seat_state(&mut self) -> &mut SeatState<Self> {
|
||||
&mut self.seat_state
|
||||
}
|
||||
|
||||
fn focus_changed(&mut self, seat: &Seat<Self>, focus: Option<&Self::KeyboardFocus>) {
|
||||
if let Some(surface) = focus {
|
||||
let client = match surface {
|
||||
FocusTarget::Wayland(w) => w.toplevel().wl_surface().client(),
|
||||
FocusTarget::Popup(p) => p.wl_surface().client(),
|
||||
};
|
||||
set_data_device_focus(&self.dh, seat, client);
|
||||
} else {
|
||||
set_data_device_focus(&self.dh, seat, None);
|
||||
}
|
||||
}
|
||||
|
||||
fn cursor_image(&mut self, _seat: &Seat<Self>, image: CursorImageStatus) {
|
||||
self.cursor_state = image;
|
||||
}
|
||||
}
|
||||
|
||||
delegate_seat!(State);
|
||||
14
wayland-display-core/src/wayland/handlers/shm.rs
Normal file
14
wayland-display-core/src/wayland/handlers/shm.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use smithay::{
|
||||
delegate_shm,
|
||||
wayland::shm::{ShmHandler, ShmState},
|
||||
};
|
||||
|
||||
use crate::comp::State;
|
||||
|
||||
impl ShmHandler for State {
|
||||
fn shm_state(&self) -> &ShmState {
|
||||
&self.shm_state
|
||||
}
|
||||
}
|
||||
|
||||
delegate_shm!(State);
|
||||
5
wayland-display-core/src/wayland/handlers/viewporter.rs
Normal file
5
wayland-display-core/src/wayland/handlers/viewporter.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
use smithay::delegate_viewporter;
|
||||
|
||||
use crate::comp::State;
|
||||
|
||||
delegate_viewporter!(State);
|
||||
3
wayland-display-core/src/wayland/handlers/wl_drm.rs
Normal file
3
wayland-display-core/src/wayland/handlers/wl_drm.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
use crate::{comp::State, wayland::protocols::wl_drm::delegate_wl_drm};
|
||||
|
||||
delegate_wl_drm!(State);
|
||||
83
wayland-display-core/src/wayland/handlers/xdg.rs
Normal file
83
wayland-display-core/src/wayland/handlers/xdg.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use smithay::{
|
||||
delegate_xdg_shell,
|
||||
desktop::{
|
||||
find_popup_root_surface, PopupKeyboardGrab, PopupKind, PopupPointerGrab,
|
||||
PopupUngrabStrategy, Window,
|
||||
},
|
||||
input::{pointer::Focus, Seat},
|
||||
reexports::wayland_server::protocol::wl_seat::WlSeat,
|
||||
utils::Serial,
|
||||
wayland::{
|
||||
seat::WaylandFocus,
|
||||
shell::xdg::{
|
||||
PopupSurface, PositionerState, ToplevelSurface, XdgShellHandler, XdgShellState,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
use crate::comp::{FocusTarget, State};
|
||||
|
||||
impl XdgShellHandler for State {
|
||||
fn xdg_shell_state(&mut self) -> &mut XdgShellState {
|
||||
&mut self.shell_state
|
||||
}
|
||||
|
||||
fn new_toplevel(&mut self, surface: ToplevelSurface) {
|
||||
let window = Window::new(surface);
|
||||
self.pending_windows.push(window);
|
||||
}
|
||||
|
||||
fn new_popup(&mut self, surface: PopupSurface, positioner: PositionerState) {
|
||||
// TODO: properly recompute the geometry with the whole of positioner state
|
||||
surface.with_pending_state(|state| {
|
||||
// NOTE: This is not really necessary as the default geometry
|
||||
// is already set the same way, but for demonstrating how
|
||||
// to set the initial popup geometry this code is left as
|
||||
// an example
|
||||
state.geometry = positioner.get_geometry();
|
||||
});
|
||||
if let Err(err) = self.popups.track_popup(PopupKind::from(surface)) {
|
||||
tracing::warn!(?err, "Failed to track popup.");
|
||||
}
|
||||
}
|
||||
|
||||
fn grab(&mut self, surface: PopupSurface, seat: WlSeat, serial: Serial) {
|
||||
let seat: Seat<State> = Seat::from_resource(&seat).unwrap();
|
||||
let kind = PopupKind::Xdg(surface.clone());
|
||||
if let Some(root) = find_popup_root_surface(&kind).ok().and_then(|root| {
|
||||
self.space
|
||||
.elements()
|
||||
.find(|w| w.wl_surface().map(|s| s == root).unwrap_or(false))
|
||||
.cloned()
|
||||
.map(FocusTarget::from)
|
||||
}) {
|
||||
let ret = self.popups.grab_popup(root, surface.into(), &seat, serial);
|
||||
if let Ok(mut grab) = ret {
|
||||
if let Some(keyboard) = seat.get_keyboard() {
|
||||
if keyboard.is_grabbed()
|
||||
&& !(keyboard.has_grab(serial)
|
||||
|| keyboard.has_grab(grab.previous_serial().unwrap_or(serial)))
|
||||
{
|
||||
grab.ungrab(PopupUngrabStrategy::All);
|
||||
return;
|
||||
}
|
||||
keyboard.set_focus(self, grab.current_grab(), serial);
|
||||
keyboard.set_grab(PopupKeyboardGrab::new(&grab), serial);
|
||||
}
|
||||
if let Some(pointer) = seat.get_pointer() {
|
||||
if pointer.is_grabbed()
|
||||
&& !(pointer.has_grab(serial)
|
||||
|| pointer
|
||||
.has_grab(grab.previous_serial().unwrap_or_else(|| grab.serial())))
|
||||
{
|
||||
grab.ungrab(PopupUngrabStrategy::All);
|
||||
return;
|
||||
}
|
||||
pointer.set_grab(self, PopupPointerGrab::new(&grab), serial, Focus::Clear);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
delegate_xdg_shell!(State);
|
||||
2
wayland-display-core/src/wayland/mod.rs
Normal file
2
wayland-display-core/src/wayland/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod handlers;
|
||||
pub mod protocols;
|
||||
1
wayland-display-core/src/wayland/protocols/mod.rs
Normal file
1
wayland-display-core/src/wayland/protocols/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod wl_drm;
|
||||
255
wayland-display-core/src/wayland/protocols/wl_drm.rs
Normal file
255
wayland-display-core/src/wayland/protocols/wl_drm.rs
Normal file
@@ -0,0 +1,255 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// Re-export only the actual code, and then only use this re-export
|
||||
// The `generated` module below is just some boilerplate to properly isolate stuff
|
||||
// and avoid exposing internal details.
|
||||
//
|
||||
// You can use all the types from my_protocol as if they went from `wayland_client::protocol`.
|
||||
pub use generated::wl_drm;
|
||||
|
||||
mod generated {
|
||||
use smithay::reexports::wayland_server::{self, protocol::*};
|
||||
|
||||
pub mod __interfaces {
|
||||
use smithay::reexports::wayland_server::protocol::__interfaces::*;
|
||||
use wayland_backend;
|
||||
wayland_scanner::generate_interfaces!("resources/protocols/wayland-drm.xml");
|
||||
}
|
||||
use self::__interfaces::*;
|
||||
|
||||
wayland_scanner::generate_server_code!("resources/protocols/wayland-drm.xml");
|
||||
}
|
||||
|
||||
use smithay::{
|
||||
backend::allocator::{
|
||||
dmabuf::{Dmabuf, DmabufFlags},
|
||||
Format, Fourcc, Modifier,
|
||||
},
|
||||
reexports::wayland_server::{
|
||||
backend::GlobalId, protocol::wl_buffer::WlBuffer, Client, DataInit, Dispatch,
|
||||
DisplayHandle, GlobalDispatch, New, Resource,
|
||||
},
|
||||
wayland::{
|
||||
buffer::BufferHandler,
|
||||
dmabuf::{DmabufGlobal, DmabufHandler, ImportError},
|
||||
},
|
||||
};
|
||||
|
||||
use std::{convert::TryFrom, path::PathBuf, sync::Arc};
|
||||
|
||||
pub struct WlDrmState;
|
||||
|
||||
/// Data associated with a drm global.
|
||||
pub struct DrmGlobalData {
|
||||
filter: Box<dyn for<'a> Fn(&'a Client) -> bool + Send + Sync>,
|
||||
formats: Arc<Vec<Fourcc>>,
|
||||
device_path: PathBuf,
|
||||
dmabuf_global: DmabufGlobal,
|
||||
}
|
||||
|
||||
pub struct DrmInstanceData {
|
||||
formats: Arc<Vec<Fourcc>>,
|
||||
dmabuf_global: DmabufGlobal,
|
||||
}
|
||||
|
||||
impl<D> GlobalDispatch<wl_drm::WlDrm, DrmGlobalData, D> for WlDrmState
|
||||
where
|
||||
D: GlobalDispatch<wl_drm::WlDrm, DrmGlobalData>
|
||||
+ Dispatch<wl_drm::WlDrm, DrmInstanceData>
|
||||
+ BufferHandler
|
||||
+ DmabufHandler
|
||||
+ 'static,
|
||||
{
|
||||
fn bind(
|
||||
_state: &mut D,
|
||||
_dh: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<wl_drm::WlDrm>,
|
||||
global_data: &DrmGlobalData,
|
||||
data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
let data = DrmInstanceData {
|
||||
formats: global_data.formats.clone(),
|
||||
dmabuf_global: global_data.dmabuf_global.clone(),
|
||||
};
|
||||
let drm_instance = data_init.init(resource, data);
|
||||
|
||||
drm_instance.device(global_data.device_path.to_string_lossy().into_owned());
|
||||
if drm_instance.version() >= 2 {
|
||||
drm_instance.capabilities(wl_drm::Capability::Prime as u32);
|
||||
}
|
||||
for format in global_data.formats.iter() {
|
||||
if let Ok(converted) = wl_drm::Format::try_from(*format as u32) {
|
||||
drm_instance.format(converted as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn can_view(client: Client, global_data: &DrmGlobalData) -> bool {
|
||||
(global_data.filter)(&client)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> Dispatch<wl_drm::WlDrm, DrmInstanceData, D> for WlDrmState
|
||||
where
|
||||
D: GlobalDispatch<wl_drm::WlDrm, DrmGlobalData>
|
||||
+ Dispatch<wl_drm::WlDrm, DrmInstanceData>
|
||||
+ Dispatch<WlBuffer, Dmabuf>
|
||||
+ BufferHandler
|
||||
+ DmabufHandler
|
||||
+ 'static,
|
||||
{
|
||||
fn request(
|
||||
state: &mut D,
|
||||
_client: &Client,
|
||||
drm: &wl_drm::WlDrm,
|
||||
request: wl_drm::Request,
|
||||
data: &DrmInstanceData,
|
||||
_dh: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, D>,
|
||||
) {
|
||||
match request {
|
||||
wl_drm::Request::Authenticate { .. } => drm.authenticated(),
|
||||
wl_drm::Request::CreateBuffer { .. } => drm.post_error(
|
||||
wl_drm::Error::InvalidName,
|
||||
String::from("Flink handles are unsupported, use PRIME"),
|
||||
),
|
||||
wl_drm::Request::CreatePlanarBuffer { .. } => drm.post_error(
|
||||
wl_drm::Error::InvalidName,
|
||||
String::from("Flink handles are unsupported, use PRIME"),
|
||||
),
|
||||
wl_drm::Request::CreatePrimeBuffer {
|
||||
id,
|
||||
name,
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
offset0,
|
||||
stride0,
|
||||
..
|
||||
} => {
|
||||
let format = match Fourcc::try_from(format) {
|
||||
Ok(format) => {
|
||||
if !data.formats.contains(&format) {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
String::from("Format not advertised by wl_drm"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
format
|
||||
}
|
||||
Err(_) => {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
String::from("Format unknown / not advertised by wl_drm"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if width < 1 || height < 1 {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
String::from("width or height not positive"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut dma = Dmabuf::builder((width, height), format, DmabufFlags::empty());
|
||||
dma.add_plane(name, 0, offset0 as u32, stride0 as u32, Modifier::Invalid);
|
||||
match dma.build() {
|
||||
Some(dmabuf) => {
|
||||
match state.dmabuf_imported(&data.dmabuf_global, dmabuf.clone()) {
|
||||
Ok(_) => {
|
||||
// import was successful
|
||||
data_init.init(id, dmabuf);
|
||||
}
|
||||
|
||||
Err(ImportError::InvalidFormat) => {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
"format and plane combination are not valid",
|
||||
);
|
||||
}
|
||||
|
||||
Err(ImportError::Failed) => {
|
||||
// Buffer import failed. The protocol documentation heavily implies killing the
|
||||
// client is the right thing to do here.
|
||||
drm.post_error(wl_drm::Error::InvalidName, "buffer import failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Buffer import failed. The protocol documentation heavily implies killing the
|
||||
// client is the right thing to do here.
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidName,
|
||||
"dmabuf global was destroyed on server",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_drm_global<D>(
|
||||
display: &DisplayHandle,
|
||||
device_path: PathBuf,
|
||||
formats: Vec<Format>,
|
||||
dmabuf_global: &DmabufGlobal,
|
||||
) -> GlobalId
|
||||
where
|
||||
D: GlobalDispatch<wl_drm::WlDrm, DrmGlobalData>
|
||||
+ Dispatch<wl_drm::WlDrm, DrmInstanceData>
|
||||
+ BufferHandler
|
||||
+ DmabufHandler
|
||||
+ 'static,
|
||||
{
|
||||
create_drm_global_with_filter::<D, _>(display, device_path, formats, dmabuf_global, |_| true)
|
||||
}
|
||||
|
||||
pub fn create_drm_global_with_filter<D, F>(
|
||||
display: &DisplayHandle,
|
||||
device_path: PathBuf,
|
||||
formats: Vec<Format>,
|
||||
dmabuf_global: &DmabufGlobal,
|
||||
client_filter: F,
|
||||
) -> GlobalId
|
||||
where
|
||||
D: GlobalDispatch<wl_drm::WlDrm, DrmGlobalData>
|
||||
+ Dispatch<wl_drm::WlDrm, DrmInstanceData>
|
||||
+ BufferHandler
|
||||
+ DmabufHandler
|
||||
+ 'static,
|
||||
F: for<'a> Fn(&'a Client) -> bool + Send + Sync + 'static,
|
||||
{
|
||||
let formats = Arc::new(
|
||||
formats
|
||||
.into_iter()
|
||||
.filter(|f| f.modifier == Modifier::Invalid)
|
||||
.map(|f| f.code)
|
||||
.collect(),
|
||||
);
|
||||
let data = DrmGlobalData {
|
||||
filter: Box::new(client_filter),
|
||||
formats,
|
||||
device_path,
|
||||
dmabuf_global: dmabuf_global.clone(),
|
||||
};
|
||||
|
||||
display.create_global::<D, wl_drm::WlDrm, _>(2, data)
|
||||
}
|
||||
|
||||
macro_rules! delegate_wl_drm {
|
||||
($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty) => {
|
||||
smithay::reexports::wayland_server::delegate_global_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
$crate::wayland::protocols::wl_drm::wl_drm::WlDrm: $crate::wayland::protocols::wl_drm::DrmGlobalData
|
||||
] => $crate::wayland::protocols::wl_drm::WlDrmState);
|
||||
smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
|
||||
$crate::wayland::protocols::wl_drm::wl_drm::WlDrm: $crate::wayland::protocols::wl_drm::DrmInstanceData
|
||||
] => $crate::wayland::protocols::wl_drm::WlDrmState);
|
||||
};
|
||||
}
|
||||
pub(crate) use delegate_wl_drm;
|
||||
Reference in New Issue
Block a user