Initial commit, lots of cleanup and stuff to do, it may not work.
This commit is contained in:
373
gumble/LICENSE
Normal file
373
gumble/LICENSE
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.
|
50
gumble/README.md
Normal file
50
gumble/README.md
Normal file
@ -0,0 +1,50 @@
|
||||
# Note
|
||||
|
||||
Added from git.2mb.codes/~cmb/barnard/gumble for ease of future work and development.
|
||||
|
||||
# gumble
|
||||
|
||||
## Sub-projects
|
||||
|
||||
- gumble [](https://godoc.org/layeh.com/gumble/gumble)
|
||||
- Client library
|
||||
- gumbleopenal
|
||||
- [OpenAL](http://kcat.strangesoft.net/openal.html) audio system for gumble
|
||||
- gumbleffmpeg
|
||||
- [ffmpeg](https://www.ffmpeg.org/) audio source for gumble
|
||||
- gumbleutil
|
||||
- Extras that can make working with gumble easier
|
||||
|
||||
## Example
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble"
|
||||
"layeh.com/gumble/gumbleutil"
|
||||
)
|
||||
|
||||
func main() {
|
||||
gumbleutil.Main(gumbleutil.Listener{
|
||||
UserChange: func(e *gumble.UserChangeEvent) {
|
||||
if e.Type.Has(gumble.UserChangeConnected) {
|
||||
e.User.Send("Welcome to the server, " + e.User.Name + "!")
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
## Related projects
|
||||
|
||||
- [barnard](https://layeh.com/barnard)
|
||||
- terminal-based Mumble client
|
||||
- [piepan](https://layeh.com/piepan)
|
||||
- an easy to use framework for writing Mumble bots using Lua
|
||||
|
||||
## License
|
||||
|
||||
MPL 2.0
|
||||
|
||||
## Author
|
||||
|
||||
Tim Cooper (<tim.cooper@layeh.com>)
|
BIN
gumble/_examples/mumble-audio-player/chimes.ogg
Normal file
BIN
gumble/_examples/mumble-audio-player/chimes.ogg
Normal file
Binary file not shown.
53
gumble/_examples/mumble-audio-player/main.go
Normal file
53
gumble/_examples/mumble-audio-player/main.go
Normal file
@ -0,0 +1,53 @@
|
||||
package main // import "git.2mb.codes/~cmb/barnard/gumble/_examples/mumble-audio-player"
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumbleffmpeg"
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
|
||||
_ "git.2mb.codes/~cmb/barnard/gumble/opus"
|
||||
)
|
||||
|
||||
func main() {
|
||||
files := make(map[string]string)
|
||||
var stream *gumbleffmpeg.Stream
|
||||
|
||||
flag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage of %s: [flags] [audio files...]\n", os.Args[0])
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
|
||||
gumbleutil.Main(gumbleutil.AutoBitrate, gumbleutil.Listener{
|
||||
Connect: func(e *gumble.ConnectEvent) {
|
||||
for _, file := range flag.Args() {
|
||||
key := filepath.Base(file)
|
||||
files[key] = file
|
||||
}
|
||||
|
||||
fmt.Printf("audio player loaded! (%d files)\n", len(files))
|
||||
},
|
||||
|
||||
TextMessage: func(e *gumble.TextMessageEvent) {
|
||||
if e.Sender == nil {
|
||||
return
|
||||
}
|
||||
file, ok := files[e.Message]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if stream != nil && stream.State() == gumbleffmpeg.StatePlaying {
|
||||
return
|
||||
}
|
||||
stream = gumbleffmpeg.New(e.Client, gumbleffmpeg.SourceFile(file))
|
||||
if err := stream.Play(); err != nil {
|
||||
fmt.Printf("%s\n", err)
|
||||
} else {
|
||||
fmt.Printf("Playing %s\n", file)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
63
gumble/cmd/mumble-ping/main.go
Normal file
63
gumble/cmd/mumble-ping/main.go
Normal file
@ -0,0 +1,63 @@
|
||||
package main // import "git.2mb.codes/~cmb/barnard/gumble/cmd/mumble-ping"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "usage: %s [flags] <destination>\n", os.Args[0])
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
interval := flag.Duration("interval", time.Second*1, "ping packet retransmission interval")
|
||||
timeout := flag.Duration("timeout", time.Second*5, "ping timeout until failure")
|
||||
jsonOutput := flag.Bool("json", false, "output success response as JSON")
|
||||
flag.Parse()
|
||||
if flag.NArg() != 1 {
|
||||
flag.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
server := flag.Arg(0)
|
||||
|
||||
host, port, err := net.SplitHostPort(server)
|
||||
if err != nil {
|
||||
host = server
|
||||
port = strconv.Itoa(gumble.DefaultPort)
|
||||
}
|
||||
|
||||
resp, err := gumble.Ping(net.JoinHostPort(host, port), *interval, *timeout)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
|
||||
os.Exit(1)
|
||||
}
|
||||
major, minor, patch := resp.Version.SemanticVersion()
|
||||
|
||||
if !*jsonOutput {
|
||||
fmt.Printf("Address: %s\n", resp.Address)
|
||||
fmt.Printf("Ping: %s\n", resp.Ping)
|
||||
fmt.Printf("Version: %d.%d.%d\n", major, minor, patch)
|
||||
fmt.Printf("Connected Users: %d\n", resp.ConnectedUsers)
|
||||
fmt.Printf("Maximum Users: %d\n", resp.MaximumUsers)
|
||||
fmt.Printf("Maximum Bitrate: %d\n", resp.MaximumBitrate)
|
||||
} else {
|
||||
output := map[string]interface{}{
|
||||
"address": resp.Address.String(),
|
||||
"ping": float64(resp.Ping) / float64(time.Millisecond),
|
||||
"version": fmt.Sprintf("%d.%d.%d", major, minor, patch),
|
||||
"connected_users": resp.ConnectedUsers,
|
||||
"maximum_users": resp.MaximumUsers,
|
||||
"maximum_bitrate": resp.MaximumBitrate,
|
||||
}
|
||||
encoder := json.NewEncoder(os.Stdout)
|
||||
encoder.Encode(output)
|
||||
}
|
||||
}
|
37
gumble/gumble/MumbleProto/LICENSE
Normal file
37
gumble/gumble/MumbleProto/LICENSE
Normal file
@ -0,0 +1,37 @@
|
||||
Copyright (C) 2005-2013, Thorvald Natvig <thorvald@natvig.com>
|
||||
Copyright (C) 2007, Stefan Gehn <mETz AT gehn DOT net>
|
||||
Copyright (C) 2007, Sebastian Schlingmann <mit_service@users.sourceforge.net>
|
||||
Copyright (C) 2008-2013, Mikkel Krautz <mikkel@krautz.dk>
|
||||
Copyright (C) 2008, Andreas Messer <andi@bupfen.de>
|
||||
Copyright (C) 2007, Trenton Schulz
|
||||
Copyright (C) 2008-2013, Stefan Hacker <dd0t@users.sourceforge.net>
|
||||
Copyright (C) 2008-2011, Snares <snares@users.sourceforge.net>
|
||||
Copyright (C) 2009-2013, Benjamin Jemlich <pcgod@users.sourceforge.net>
|
||||
Copyright (C) 2009-2013, Kissaki <kissaki@gmx.de>
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
- Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
- Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
- Neither the name of the Mumble Developers nor the names of its
|
||||
contributors may be used to endorse or promote products derived from this
|
||||
software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
2359
gumble/gumble/MumbleProto/Mumble.pb.go
Normal file
2359
gumble/gumble/MumbleProto/Mumble.pb.go
Normal file
File diff suppressed because it is too large
Load Diff
5
gumble/gumble/MumbleProto/generate.go
Normal file
5
gumble/gumble/MumbleProto/generate.go
Normal file
@ -0,0 +1,5 @@
|
||||
//go:generate wget -O Mumble.proto https://raw.githubusercontent.com/mumble-voip/mumble/master/src/Mumble.proto
|
||||
//go:generate protoc --go_out=. Mumble.proto
|
||||
//go:generate rm -f Mumble.proto
|
||||
//go:generate sed -i "s/^\\(package MumbleProto\\)$/\\1 \\/\\/ import \"layeh.com\\/gumble\\/gumble\\/MumbleProto\"/" Mumble.pb.go
|
||||
package MumbleProto
|
16
gumble/gumble/accesstokens.go
Normal file
16
gumble/gumble/accesstokens.go
Normal file
@ -0,0 +1,16 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// AccessTokens are additional passwords that can be provided to the server to
|
||||
// gain access to restricted channels.
|
||||
type AccessTokens []string
|
||||
|
||||
func (a AccessTokens) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.Authenticate{
|
||||
Tokens: a,
|
||||
}
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
116
gumble/gumble/acl.go
Normal file
116
gumble/gumble/acl.go
Normal file
@ -0,0 +1,116 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// ACL contains a list of ACLGroups and ACLRules linked to a channel.
|
||||
type ACL struct {
|
||||
// The channel to which the ACL belongs.
|
||||
Channel *Channel
|
||||
// The ACL's groups.
|
||||
Groups []*ACLGroup
|
||||
// The ACL's rules.
|
||||
Rules []*ACLRule
|
||||
// Does the ACL inherits the parent channel's ACLs?
|
||||
Inherits bool
|
||||
}
|
||||
|
||||
func (a *ACL) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.ACL{
|
||||
ChannelId: &a.Channel.ID,
|
||||
Groups: make([]*MumbleProto.ACL_ChanGroup, len(a.Groups)),
|
||||
Acls: make([]*MumbleProto.ACL_ChanACL, len(a.Rules)),
|
||||
InheritAcls: &a.Inherits,
|
||||
Query: proto.Bool(false),
|
||||
}
|
||||
|
||||
for i, group := range a.Groups {
|
||||
packet.Groups[i] = &MumbleProto.ACL_ChanGroup{
|
||||
Name: &group.Name,
|
||||
Inherit: &group.InheritUsers,
|
||||
Inheritable: &group.Inheritable,
|
||||
Add: make([]uint32, 0, len(group.UsersAdd)),
|
||||
Remove: make([]uint32, 0, len(group.UsersRemove)),
|
||||
}
|
||||
for _, user := range group.UsersAdd {
|
||||
packet.Groups[i].Add = append(packet.Groups[i].Add, user.UserID)
|
||||
}
|
||||
for _, user := range group.UsersRemove {
|
||||
packet.Groups[i].Remove = append(packet.Groups[i].Remove, user.UserID)
|
||||
}
|
||||
}
|
||||
|
||||
for i, rule := range a.Rules {
|
||||
packet.Acls[i] = &MumbleProto.ACL_ChanACL{
|
||||
ApplyHere: &rule.AppliesCurrent,
|
||||
ApplySubs: &rule.AppliesChildren,
|
||||
Grant: proto.Uint32(uint32(rule.Granted)),
|
||||
Deny: proto.Uint32(uint32(rule.Denied)),
|
||||
}
|
||||
if rule.User != nil {
|
||||
packet.Acls[i].UserId = &rule.User.UserID
|
||||
}
|
||||
if rule.Group != nil {
|
||||
packet.Acls[i].Group = &rule.Group.Name
|
||||
}
|
||||
}
|
||||
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// ACLUser is a registered user who is part of or can be part of an ACL group
|
||||
// or rule.
|
||||
type ACLUser struct {
|
||||
// The user ID of the user.
|
||||
UserID uint32
|
||||
// The name of the user.
|
||||
Name string
|
||||
}
|
||||
|
||||
// ACLGroup is a named group of registered users which can be used in an
|
||||
// ACLRule.
|
||||
type ACLGroup struct {
|
||||
// The ACL group name.
|
||||
Name string
|
||||
// Is the group inherited from the parent channel's ACL?
|
||||
Inherited bool
|
||||
// Are group members are inherited from the parent channel's ACL?
|
||||
InheritUsers bool
|
||||
// Can the group be inherited by child channels?
|
||||
Inheritable bool
|
||||
// The users who are explicitly added to, explicitly removed from, and
|
||||
// inherited into the group.
|
||||
UsersAdd, UsersRemove, UsersInherited map[uint32]*ACLUser
|
||||
}
|
||||
|
||||
// ACL group names that are built-in.
|
||||
const (
|
||||
ACLGroupEveryone = "all"
|
||||
ACLGroupAuthenticated = "auth"
|
||||
ACLGroupInsideChannel = "in"
|
||||
ACLGroupOutsideChannel = "out"
|
||||
)
|
||||
|
||||
// ACLRule is a set of granted and denied permissions given to an ACLUser or
|
||||
// ACLGroup.
|
||||
type ACLRule struct {
|
||||
// Does the rule apply to the channel in which the rule is defined?
|
||||
AppliesCurrent bool
|
||||
// Does the rule apply to the children of the channel in which the rule is
|
||||
// defined?
|
||||
AppliesChildren bool
|
||||
// Is the rule inherited from the parent channel's ACL?
|
||||
Inherited bool
|
||||
|
||||
// The permissions granted by the rule.
|
||||
Granted Permission
|
||||
// The permissions denied by the rule.
|
||||
Denied Permission
|
||||
|
||||
// The ACL user the rule applies to. Can be nil.
|
||||
User *ACLUser
|
||||
// The ACL group the rule applies to. Can be nil.
|
||||
Group *ACLGroup
|
||||
}
|
86
gumble/gumble/audio.go
Normal file
86
gumble/gumble/audio.go
Normal file
@ -0,0 +1,86 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// AudioSampleRate is the audio sample rate (in hertz) for incoming and
|
||||
// outgoing audio.
|
||||
AudioSampleRate = 48000
|
||||
|
||||
// AudioDefaultInterval is the default interval that audio packets are sent
|
||||
// at.
|
||||
AudioDefaultInterval = 10 * time.Millisecond
|
||||
|
||||
// AudioMonoChannels is the number of channels used for voice transmission
|
||||
AudioMonoChannels = 1
|
||||
|
||||
// AudioChannels is the number of channels used for playback
|
||||
AudioChannels = 2
|
||||
|
||||
// AudioDefaultFrameSize is the number of audio frames that should be sent in
|
||||
// a 10ms window (mono samples)
|
||||
AudioDefaultFrameSize = AudioSampleRate / 100
|
||||
|
||||
// AudioMaximumFrameSize is the maximum audio frame size from another user
|
||||
// that will be processed (accounting for stereo)
|
||||
AudioMaximumFrameSize = (AudioSampleRate / 1000 * 60) * AudioChannels
|
||||
|
||||
// AudioDefaultDataBytes is the default number of bytes that an audio frame
|
||||
// can use.
|
||||
AudioDefaultDataBytes = 40
|
||||
)
|
||||
|
||||
// AudioListener is the interface that must be implemented by types wishing to
|
||||
// receive incoming audio data from the server.
|
||||
//
|
||||
// OnAudioStream is called when an audio stream for a user starts. It is the
|
||||
// implementer's responsibility to continuously process AudioStreamEvent.C
|
||||
// until it is closed.
|
||||
type AudioListener interface {
|
||||
OnAudioStream(e *AudioStreamEvent)
|
||||
}
|
||||
|
||||
// AudioStreamEvent is event that is passed to AudioListener.OnAudioStream.
|
||||
type AudioStreamEvent struct {
|
||||
Client *Client
|
||||
User *User
|
||||
C <-chan *AudioPacket
|
||||
}
|
||||
|
||||
// AudioBuffer is a slice of PCM audio samples.
|
||||
type AudioBuffer []int16
|
||||
|
||||
func (a AudioBuffer) writeAudio(client *Client, seq int64, final bool) error {
|
||||
encoder := client.AudioEncoder
|
||||
if encoder == nil {
|
||||
return nil
|
||||
}
|
||||
dataBytes := client.Config.AudioDataBytes
|
||||
raw, err := encoder.Encode(a, len(a), dataBytes)
|
||||
if final {
|
||||
defer encoder.Reset()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var targetID byte
|
||||
if target := client.VoiceTarget; target != nil {
|
||||
targetID = byte(target.ID)
|
||||
}
|
||||
return client.Conn.WriteAudio(byte(4), targetID, seq, final, raw, nil, nil, nil)
|
||||
}
|
||||
|
||||
// AudioPacket contains incoming audio samples and information.
|
||||
type AudioPacket struct {
|
||||
Client *Client
|
||||
Sender *User
|
||||
Target *VoiceTarget
|
||||
|
||||
AudioBuffer
|
||||
|
||||
HasPosition bool
|
||||
X, Y, Z float32
|
||||
}
|
55
gumble/gumble/audiocodec.go
Normal file
55
gumble/gumble/audiocodec.go
Normal file
@ -0,0 +1,55 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
audioCodecIDOpus = 4
|
||||
)
|
||||
|
||||
var (
|
||||
audioCodecsLock sync.Mutex
|
||||
audioCodecs [8]AudioCodec
|
||||
)
|
||||
|
||||
// RegisterAudioCodec registers an audio codec that can be used for encoding
|
||||
// and decoding outgoing and incoming audio data. The function panics if the
|
||||
// ID is invalid.
|
||||
func RegisterAudioCodec(id int, codec AudioCodec) {
|
||||
audioCodecsLock.Lock()
|
||||
defer audioCodecsLock.Unlock()
|
||||
|
||||
if id < 0 || id >= len(audioCodecs) {
|
||||
panic("id out of range")
|
||||
}
|
||||
audioCodecs[id] = codec
|
||||
}
|
||||
|
||||
func getAudioCodec(id int) AudioCodec {
|
||||
audioCodecsLock.Lock()
|
||||
defer audioCodecsLock.Unlock()
|
||||
return audioCodecs[id]
|
||||
}
|
||||
|
||||
// AudioCodec can create a encoder and a decoder for outgoing and incoming
|
||||
// data.
|
||||
type AudioCodec interface {
|
||||
ID() int
|
||||
NewEncoder() AudioEncoder
|
||||
NewDecoder() AudioDecoder
|
||||
}
|
||||
|
||||
// AudioEncoder encodes a chunk of PCM audio samples to a certain type.
|
||||
type AudioEncoder interface {
|
||||
ID() int
|
||||
Encode(pcm []int16, mframeSize, maxDataBytes int) ([]byte, error)
|
||||
Reset()
|
||||
}
|
||||
|
||||
// AudioDecoder decodes an encoded byte slice to a chunk of PCM audio samples.
|
||||
type AudioDecoder interface {
|
||||
ID() int
|
||||
Decode(data []byte, frameSize int) ([]int16, error)
|
||||
Reset()
|
||||
}
|
46
gumble/gumble/audiolisteners.go
Normal file
46
gumble/gumble/audiolisteners.go
Normal file
@ -0,0 +1,46 @@
|
||||
package gumble
|
||||
|
||||
type audioEventItem struct {
|
||||
parent *AudioListeners
|
||||
prev, next *audioEventItem
|
||||
listener AudioListener
|
||||
streams map[*User]chan *AudioPacket
|
||||
}
|
||||
|
||||
func (e *audioEventItem) Detach() {
|
||||
if e.prev == nil {
|
||||
e.parent.head = e.next
|
||||
} else {
|
||||
e.prev.next = e.next
|
||||
}
|
||||
if e.next == nil {
|
||||
e.parent.tail = e.prev
|
||||
} else {
|
||||
e.next.prev = e.prev
|
||||
}
|
||||
}
|
||||
|
||||
// AudioListeners is a list of audio listeners. Each attached listener is
|
||||
// called in sequence when a new user audio stream begins.
|
||||
type AudioListeners struct {
|
||||
head, tail *audioEventItem
|
||||
}
|
||||
|
||||
// Attach adds a new audio listener to the end of the current list of listeners.
|
||||
func (e *AudioListeners) Attach(listener AudioListener) Detacher {
|
||||
item := &audioEventItem{
|
||||
parent: e,
|
||||
prev: e.tail,
|
||||
listener: listener,
|
||||
streams: make(map[*User]chan *AudioPacket),
|
||||
}
|
||||
if e.head == nil {
|
||||
e.head = item
|
||||
}
|
||||
if e.tail == nil {
|
||||
e.tail = item
|
||||
} else {
|
||||
e.tail.next = item
|
||||
}
|
||||
return item
|
||||
}
|
101
gumble/gumble/bans.go
Normal file
101
gumble/gumble/bans.go
Normal file
@ -0,0 +1,101 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// BanList is a list of server ban entries.
|
||||
//
|
||||
// Whenever a ban is changed, it does not come into effect until the ban list
|
||||
// is sent back to the server.
|
||||
type BanList []*Ban
|
||||
|
||||
// Add creates a new ban list entry with the given parameters.
|
||||
func (b *BanList) Add(address net.IP, mask net.IPMask, reason string, duration time.Duration) *Ban {
|
||||
ban := &Ban{
|
||||
Address: address,
|
||||
Mask: mask,
|
||||
Reason: reason,
|
||||
Duration: duration,
|
||||
}
|
||||
*b = append(*b, ban)
|
||||
return ban
|
||||
}
|
||||
|
||||
// Ban represents an entry in the server ban list.
|
||||
//
|
||||
// This type should not be initialized manually. Instead, create new ban
|
||||
// entries using BanList.Add().
|
||||
type Ban struct {
|
||||
// The banned IP address.
|
||||
Address net.IP
|
||||
// The IP mask that the ban applies to.
|
||||
Mask net.IPMask
|
||||
// The name of the banned user.
|
||||
Name string
|
||||
// The certificate hash of the banned user.
|
||||
Hash string
|
||||
// The reason for the ban.
|
||||
Reason string
|
||||
// The start time from which the ban applies.
|
||||
Start time.Time
|
||||
// How long the ban is for.
|
||||
Duration time.Duration
|
||||
|
||||
unban bool
|
||||
}
|
||||
|
||||
// SetAddress sets the banned IP address.
|
||||
func (b *Ban) SetAddress(address net.IP) {
|
||||
b.Address = address
|
||||
}
|
||||
|
||||
// SetMask sets the IP mask that the ban applies to.
|
||||
func (b *Ban) SetMask(mask net.IPMask) {
|
||||
b.Mask = mask
|
||||
}
|
||||
|
||||
// SetReason changes the reason for the ban.
|
||||
func (b *Ban) SetReason(reason string) {
|
||||
b.Reason = reason
|
||||
}
|
||||
|
||||
// SetDuration changes the duration of the ban.
|
||||
func (b *Ban) SetDuration(duration time.Duration) {
|
||||
b.Duration = duration
|
||||
}
|
||||
|
||||
// Unban will unban the user from the server.
|
||||
func (b *Ban) Unban() {
|
||||
b.unban = true
|
||||
}
|
||||
|
||||
// Ban will ban the user from the server. This is only useful if Unban() was
|
||||
// called on the ban entry.
|
||||
func (b *Ban) Ban() {
|
||||
b.unban = false
|
||||
}
|
||||
|
||||
func (b BanList) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.BanList{
|
||||
Query: proto.Bool(false),
|
||||
}
|
||||
|
||||
for _, ban := range b {
|
||||
if !ban.unban {
|
||||
maskSize, _ := ban.Mask.Size()
|
||||
packet.Bans = append(packet.Bans, &MumbleProto.BanList_BanEntry{
|
||||
Address: ban.Address,
|
||||
Mask: proto.Uint32(uint32(maskSize)),
|
||||
Reason: &ban.Reason,
|
||||
Duration: proto.Uint32(uint32(ban.Duration / time.Second)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
207
gumble/gumble/channel.go
Normal file
207
gumble/gumble/channel.go
Normal file
@ -0,0 +1,207 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// Channel represents a channel in the server's channel tree.
|
||||
type Channel struct {
|
||||
// The channel's unique ID.
|
||||
ID uint32
|
||||
// The channel's name.
|
||||
Name string
|
||||
// The channel's parent. nil if the channel is the root channel.
|
||||
Parent *Channel
|
||||
// The channels directly underneath the channel.
|
||||
Children Channels
|
||||
// The channels that are linked to the channel.
|
||||
Links Channels
|
||||
// The users currently in the channel.
|
||||
Users Users
|
||||
// The channel's description. Contains the empty string if the channel does
|
||||
// not have a description, or if it needs to be requested.
|
||||
Description string
|
||||
// The channel's description hash. nil if Channel.Description has
|
||||
// been populated.
|
||||
DescriptionHash []byte
|
||||
// The maximum number of users allowed in the channel. If the value is zero,
|
||||
// the maximum number of users per-channel is dictated by the server's
|
||||
// "usersperchannel" setting.
|
||||
MaxUsers uint32
|
||||
// The position at which the channel should be displayed in an ordered list.
|
||||
Position int32
|
||||
// Is the channel temporary?
|
||||
Temporary bool
|
||||
|
||||
client *Client
|
||||
}
|
||||
|
||||
// IsRoot returns true if the channel is the server's root channel.
|
||||
func (c *Channel) IsRoot() bool {
|
||||
return c.ID == 0
|
||||
}
|
||||
|
||||
// Add will add a sub-channel to the given channel.
|
||||
func (c *Channel) Add(name string, temporary bool) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
Parent: &c.ID,
|
||||
Name: &name,
|
||||
Temporary: &temporary,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Remove will remove the given channel and all sub-channels from the server's
|
||||
// channel tree.
|
||||
func (c *Channel) Remove() {
|
||||
packet := MumbleProto.ChannelRemove{
|
||||
ChannelId: &c.ID,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetName will set the name of the channel. This will have no effect if the
|
||||
// channel is the server's root channel.
|
||||
func (c *Channel) SetName(name string) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
Name: &name,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetDescription will set the description of the channel.
|
||||
func (c *Channel) SetDescription(description string) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
Description: &description,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetPosition will set the position of the channel.
|
||||
func (c *Channel) SetPosition(position int32) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
Position: &position,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetMaxUsers will set the maximum number of users allowed in the channel.
|
||||
func (c *Channel) SetMaxUsers(maxUsers uint32) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
MaxUsers: &maxUsers,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Find returns a channel whose path (by channel name) from the current channel
|
||||
// is equal to the arguments passed.
|
||||
//
|
||||
// For example, given the following server channel tree:
|
||||
// Root
|
||||
// Child 1
|
||||
// Child 2
|
||||
// Child 2.1
|
||||
// Child 2.2
|
||||
// Child 2.2.1
|
||||
// Child 3
|
||||
// To get the "Child 2.2.1" channel:
|
||||
// root.Find("Child 2", "Child 2.2", "Child 2.2.1")
|
||||
func (c *Channel) Find(names ...string) *Channel {
|
||||
if len(names) == 0 {
|
||||
return c
|
||||
}
|
||||
for _, child := range c.Children {
|
||||
if child.Name == names[0] {
|
||||
return child.Find(names[1:]...)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequestDescription requests that the actual channel description
|
||||
// (i.e. non-hashed) be sent to the client.
|
||||
func (c *Channel) RequestDescription() {
|
||||
packet := MumbleProto.RequestBlob{
|
||||
ChannelDescription: []uint32{c.ID},
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestACL requests that the channel's ACL to be sent to the client.
|
||||
func (c *Channel) RequestACL() {
|
||||
packet := MumbleProto.ACL{
|
||||
ChannelId: &c.ID,
|
||||
Query: proto.Bool(true),
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestPermission requests that the channel's permission information to be
|
||||
// sent to the client.
|
||||
//
|
||||
// Note: the server will not reply to the request if the client has up-to-date
|
||||
// permission information.
|
||||
func (c *Channel) RequestPermission() {
|
||||
packet := MumbleProto.PermissionQuery{
|
||||
ChannelId: &c.ID,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Send will send a text message to the channel.
|
||||
func (c *Channel) Send(message string, recursive bool) {
|
||||
textMessage := TextMessage{
|
||||
Message: message,
|
||||
}
|
||||
if recursive {
|
||||
textMessage.Trees = []*Channel{c}
|
||||
} else {
|
||||
textMessage.Channels = []*Channel{c}
|
||||
}
|
||||
c.client.Send(&textMessage)
|
||||
}
|
||||
|
||||
// Permission returns the permissions the user has in the channel, or nil if
|
||||
// the permissions are unknown.
|
||||
func (c *Channel) Permission() *Permission {
|
||||
return c.client.permissions[c.ID]
|
||||
}
|
||||
|
||||
// Link links the given channels to the channel.
|
||||
func (c *Channel) Link(channel ...*Channel) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
LinksAdd: make([]uint32, len(channel)),
|
||||
}
|
||||
for i, ch := range channel {
|
||||
packet.LinksAdd[i] = ch.ID
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Unlink unlinks the given channels from the channel. If no arguments are
|
||||
// passed, all linked channels are unlinked.
|
||||
func (c *Channel) Unlink(channel ...*Channel) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
}
|
||||
if len(channel) == 0 {
|
||||
packet.LinksRemove = make([]uint32, len(c.Links))
|
||||
i := 0
|
||||
for channelID := range c.Links {
|
||||
packet.LinksRemove[i] = channelID
|
||||
i++
|
||||
}
|
||||
} else {
|
||||
packet.LinksRemove = make([]uint32, len(channel))
|
||||
for i, ch := range channel {
|
||||
packet.LinksRemove[i] = ch.ID
|
||||
}
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
28
gumble/gumble/channels.go
Normal file
28
gumble/gumble/channels.go
Normal file
@ -0,0 +1,28 @@
|
||||
package gumble
|
||||
|
||||
// Channels is a map of server channels.
|
||||
type Channels map[uint32]*Channel
|
||||
|
||||
// create adds a new channel with the given id to the collection. If a channel
|
||||
// with the given id already exists, it is overwritten.
|
||||
func (c Channels) create(id uint32) *Channel {
|
||||
channel := &Channel{
|
||||
ID: id,
|
||||
Links: Channels{},
|
||||
Children: Channels{},
|
||||
Users: Users{},
|
||||
}
|
||||
c[id] = channel
|
||||
return channel
|
||||
}
|
||||
|
||||
// Find returns a channel whose path (by channel name) from the server root
|
||||
// channel is equal to the arguments passed. nil is returned if c does not
|
||||
// containt the root channel.
|
||||
func (c Channels) Find(names ...string) *Channel {
|
||||
root := c[0]
|
||||
if names == nil || root == nil {
|
||||
return root
|
||||
}
|
||||
return root.Find(names...)
|
||||
}
|
289
gumble/gumble/client.go
Normal file
289
gumble/gumble/client.go
Normal file
@ -0,0 +1,289 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"math"
|
||||
"net"
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// State is the current state of the client's connection to the server.
|
||||
type State int
|
||||
|
||||
const (
|
||||
// StateDisconnected means the client is no longer connected to the server.
|
||||
StateDisconnected State = iota
|
||||
|
||||
// StateConnected means the client is connected to the server and is
|
||||
// syncing initial information. This is an internal state that will
|
||||
// never be returned by Client.State().
|
||||
StateConnected
|
||||
|
||||
// StateSynced means the client is connected to a server and has been sent
|
||||
// the server state.
|
||||
StateSynced
|
||||
)
|
||||
|
||||
// ClientVersion is the protocol version that Client implements.
|
||||
const ClientVersion = 1<<16 | 3<<8 | 0
|
||||
|
||||
// Client is the type used to create a connection to a server.
|
||||
type Client struct {
|
||||
// The User associated with the client.
|
||||
Self *User
|
||||
// The client's configuration.
|
||||
Config *Config
|
||||
// The underlying Conn to the server.
|
||||
Conn *Conn
|
||||
|
||||
// The users currently connected to the server.
|
||||
Users Users
|
||||
// The connected server's channels.
|
||||
Channels Channels
|
||||
permissions map[uint32]*Permission
|
||||
tmpACL *ACL
|
||||
|
||||
// Ping stats
|
||||
tcpPacketsReceived uint32
|
||||
tcpPingTimes [12]float32
|
||||
tcpPingAvg uint32
|
||||
tcpPingVar uint32
|
||||
|
||||
// A collection containing the server's context actions.
|
||||
ContextActions ContextActions
|
||||
|
||||
// The audio encoder used when sending audio to the server.
|
||||
AudioEncoder AudioEncoder
|
||||
audioCodec AudioCodec
|
||||
// To whom transmitted audio will be sent. The VoiceTarget must have already
|
||||
// been sent to the server for targeting to work correctly. Setting to nil
|
||||
// will disable voice targeting (i.e. switch back to regular speaking).
|
||||
VoiceTarget *VoiceTarget
|
||||
|
||||
state uint32
|
||||
|
||||
// volatile is held by the client when the internal data structures are being
|
||||
// modified.
|
||||
volatile rpwMutex
|
||||
|
||||
connect chan *RejectError
|
||||
end chan struct{}
|
||||
disconnectEvent DisconnectEvent
|
||||
}
|
||||
|
||||
// Dial is an alias of DialWithDialer(new(net.Dialer), config, nil).
|
||||
func Dial(config *Config) (*Client, error) {
|
||||
return DialWithDialer(new(net.Dialer), config, nil)
|
||||
}
|
||||
|
||||
// DialWithDialer connects to the Mumble server at the address given in config.
|
||||
//
|
||||
// The function returns after the connection has been established, the initial
|
||||
// server information has been synced, and the OnConnect handlers have been
|
||||
// called.
|
||||
//
|
||||
// nil and an error is returned if server synchronization does not complete by
|
||||
// min(time.Now() + dialer.Timeout, dialer.Deadline), or if the server rejects
|
||||
// the client.
|
||||
func DialWithDialer(dialer *net.Dialer, config *Config, tlsConfig *tls.Config) (*Client, error) {
|
||||
start := time.Now()
|
||||
|
||||
conn, err := tls.DialWithDialer(dialer, "tcp", config.Address, tlsConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client := &Client{
|
||||
Conn: NewConn(conn),
|
||||
Config: config,
|
||||
Users: make(Users),
|
||||
Channels: make(Channels),
|
||||
|
||||
permissions: make(map[uint32]*Permission),
|
||||
|
||||
state: uint32(StateConnected),
|
||||
|
||||
connect: make(chan *RejectError),
|
||||
end: make(chan struct{}),
|
||||
}
|
||||
|
||||
go client.readRoutine()
|
||||
|
||||
// Initial packets
|
||||
versionPacket := MumbleProto.Version{
|
||||
Version: proto.Uint32(ClientVersion),
|
||||
Release: proto.String("gumble"),
|
||||
Os: proto.String(runtime.GOOS),
|
||||
OsVersion: proto.String(runtime.GOARCH),
|
||||
}
|
||||
authenticationPacket := MumbleProto.Authenticate{
|
||||
Username: &client.Config.Username,
|
||||
Password: &client.Config.Password,
|
||||
Opus: proto.Bool(getAudioCodec(audioCodecIDOpus) != nil),
|
||||
Tokens: client.Config.Tokens,
|
||||
}
|
||||
client.Conn.WriteProto(&versionPacket)
|
||||
client.Conn.WriteProto(&authenticationPacket)
|
||||
|
||||
go client.pingRoutine()
|
||||
|
||||
var timeout <-chan time.Time
|
||||
{
|
||||
var deadline time.Time
|
||||
if !dialer.Deadline.IsZero() {
|
||||
deadline = dialer.Deadline
|
||||
}
|
||||
if dialer.Timeout > 0 {
|
||||
diff := start.Add(dialer.Timeout)
|
||||
if deadline.IsZero() || diff.Before(deadline) {
|
||||
deadline = diff
|
||||
}
|
||||
}
|
||||
if !deadline.IsZero() {
|
||||
timer := time.NewTimer(deadline.Sub(start))
|
||||
defer timer.Stop()
|
||||
timeout = timer.C
|
||||
}
|
||||
}
|
||||
|
||||
select {
|
||||
case <-timeout:
|
||||
client.Conn.Close()
|
||||
return nil, errors.New("gumble: synchronization timeout")
|
||||
case err := <-client.connect:
|
||||
if err != nil {
|
||||
client.Conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
}
|
||||
|
||||
// State returns the current state of the client.
|
||||
func (c *Client) State() State {
|
||||
return State(atomic.LoadUint32(&c.state))
|
||||
}
|
||||
|
||||
// AudioOutgoing creates a new channel that outgoing audio data can be written
|
||||
// to. The channel must be closed after the audio stream is completed. Only
|
||||
// a single channel should be open at any given time (i.e. close the channel
|
||||
// before opening another).
|
||||
func (c *Client) AudioOutgoing() chan<- AudioBuffer {
|
||||
ch := make(chan AudioBuffer)
|
||||
go func() {
|
||||
var seq int64
|
||||
previous := <-ch
|
||||
for p := range ch {
|
||||
previous.writeAudio(c, seq, false)
|
||||
previous = p
|
||||
seq = (seq + 1) % math.MaxInt32
|
||||
}
|
||||
if previous != nil {
|
||||
previous.writeAudio(c, seq, true)
|
||||
}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
// pingRoutine sends ping packets to the server at regular intervals.
|
||||
func (c *Client) pingRoutine() {
|
||||
ticker := time.NewTicker(time.Second * 5)
|
||||
defer ticker.Stop()
|
||||
|
||||
var timestamp uint64
|
||||
var tcpPingAvg float32
|
||||
var tcpPingVar float32
|
||||
packet := MumbleProto.Ping{
|
||||
Timestamp: ×tamp,
|
||||
TcpPackets: &c.tcpPacketsReceived,
|
||||
TcpPingAvg: &tcpPingAvg,
|
||||
TcpPingVar: &tcpPingVar,
|
||||
}
|
||||
|
||||
t := time.Now()
|
||||
for {
|
||||
timestamp = uint64(t.UnixNano())
|
||||
tcpPingAvg = math.Float32frombits(atomic.LoadUint32(&c.tcpPingAvg))
|
||||
tcpPingVar = math.Float32frombits(atomic.LoadUint32(&c.tcpPingVar))
|
||||
c.Conn.WriteProto(&packet)
|
||||
|
||||
select {
|
||||
case <-c.end:
|
||||
return
|
||||
case t = <-ticker.C:
|
||||
// continue to top of loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readRoutine reads protocol buffer messages from the server.
|
||||
func (c *Client) readRoutine() {
|
||||
c.disconnectEvent = DisconnectEvent{
|
||||
Client: c,
|
||||
Type: DisconnectError,
|
||||
}
|
||||
|
||||
for {
|
||||
pType, data, err := c.Conn.ReadPacket()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if int(pType) < len(handlers) {
|
||||
handlers[pType](c, data)
|
||||
}
|
||||
}
|
||||
|
||||
wasSynced := c.State() == StateSynced
|
||||
atomic.StoreUint32(&c.state, uint32(StateDisconnected))
|
||||
close(c.end)
|
||||
if wasSynced {
|
||||
c.Config.Listeners.onDisconnect(&c.disconnectEvent)
|
||||
}
|
||||
}
|
||||
|
||||
// RequestUserList requests that the server's registered user list be sent to
|
||||
// the client.
|
||||
func (c *Client) RequestUserList() {
|
||||
packet := MumbleProto.UserList{}
|
||||
c.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestBanList requests that the server's ban list be sent to the client.
|
||||
func (c *Client) RequestBanList() {
|
||||
packet := MumbleProto.BanList{
|
||||
Query: proto.Bool(true),
|
||||
}
|
||||
c.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Disconnect disconnects the client from the server.
|
||||
func (c *Client) Disconnect() error {
|
||||
if c.State() == StateDisconnected {
|
||||
return errors.New("gumble: client is already disconnected")
|
||||
}
|
||||
c.disconnectEvent.Type = DisconnectUser
|
||||
c.Conn.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Do executes f in a thread-safe manner. It ensures that Client and its
|
||||
// associated data will not be changed during the lifetime of the function
|
||||
// call.
|
||||
func (c *Client) Do(f func()) {
|
||||
c.volatile.RLock()
|
||||
defer c.volatile.RUnlock()
|
||||
|
||||
f()
|
||||
}
|
||||
|
||||
// Send will send a Message to the server.
|
||||
func (c *Client) Send(message Message) {
|
||||
message.writeMessage(c)
|
||||
}
|
57
gumble/gumble/config.go
Normal file
57
gumble/gumble/config.go
Normal file
@ -0,0 +1,57 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config holds the Mumble configuration used by Client. A single Config should
|
||||
// not be shared between multiple Client instances.
|
||||
type Config struct {
|
||||
// User name used when authenticating with the server.
|
||||
Username string
|
||||
// Password used when authenticating with the server. A password is not
|
||||
// usually required to connect to a server.
|
||||
Password string
|
||||
//the address to use
|
||||
Address string
|
||||
// The initial access tokens to the send to the server. Access tokens can be
|
||||
// resent to the server using:
|
||||
// client.Send(config.Tokens)
|
||||
Tokens AccessTokens
|
||||
|
||||
// AudioInterval is the interval at which audio packets are sent. Valid
|
||||
// values are: 10ms, 20ms, 40ms, and 60ms.
|
||||
AudioInterval time.Duration
|
||||
// AudioDataBytes is the number of bytes that an audio frame can use.
|
||||
AudioDataBytes int
|
||||
|
||||
// The event listeners used when client events are triggered.
|
||||
Listeners Listeners
|
||||
AudioListeners AudioListeners
|
||||
Buffers int
|
||||
}
|
||||
|
||||
// NewConfig returns a new Config struct with default values set.
|
||||
func NewConfig() *Config {
|
||||
return &Config{
|
||||
Buffers: 8,
|
||||
AudioInterval: AudioDefaultInterval,
|
||||
AudioDataBytes: AudioDefaultDataBytes,
|
||||
}
|
||||
}
|
||||
|
||||
// Attach is an alias of c.Listeners.Attach.
|
||||
func (c *Config) Attach(l EventListener) Detacher {
|
||||
return c.Listeners.Attach(l)
|
||||
}
|
||||
|
||||
// AttachAudio is an alias of c.AudioListeners.Attach.
|
||||
func (c *Config) AttachAudio(l AudioListener) Detacher {
|
||||
return c.AudioListeners.Attach(l)
|
||||
}
|
||||
|
||||
// AudioFrameSize returns the appropriate audio frame size, based off of the
|
||||
// audio interval.
|
||||
func (c *Config) AudioFrameSize() int {
|
||||
return int(c.AudioInterval/AudioDefaultInterval) * AudioDefaultFrameSize
|
||||
}
|
200
gumble/gumble/conn.go
Normal file
200
gumble/gumble/conn.go
Normal file
@ -0,0 +1,200 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/varint"
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// DefaultPort is the default port on which Mumble servers listen.
|
||||
const DefaultPort = 64738
|
||||
|
||||
// Conn represents a control protocol connection to a Mumble client/server.
|
||||
type Conn struct {
|
||||
sync.Mutex
|
||||
net.Conn
|
||||
|
||||
MaximumPacketBytes int
|
||||
Timeout time.Duration
|
||||
|
||||
buffer []byte
|
||||
}
|
||||
|
||||
// NewConn creates a new Conn with the given net.Conn.
|
||||
func NewConn(conn net.Conn) *Conn {
|
||||
return &Conn{
|
||||
Conn: conn,
|
||||
Timeout: time.Second * 20,
|
||||
MaximumPacketBytes: 1024 * 1024 * 10,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadPacket reads a packet from the server. Returns the packet type, the
|
||||
// packet data, and nil on success.
|
||||
//
|
||||
// This function should only be called by a single go routine.
|
||||
func (c *Conn) ReadPacket() (uint16, []byte, error) {
|
||||
c.Conn.SetReadDeadline(time.Now().Add(c.Timeout))
|
||||
var header [6]byte
|
||||
if _, err := io.ReadFull(c.Conn, header[:]); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
pType := binary.BigEndian.Uint16(header[:])
|
||||
pLength := binary.BigEndian.Uint32(header[2:])
|
||||
pLengthInt := int(pLength)
|
||||
if pLengthInt > c.MaximumPacketBytes {
|
||||
return 0, nil, errors.New("gumble: packet larger than maximum allowed size")
|
||||
}
|
||||
if pLengthInt > len(c.buffer) {
|
||||
c.buffer = make([]byte, pLengthInt)
|
||||
}
|
||||
if _, err := io.ReadFull(c.Conn, c.buffer[:pLengthInt]); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return pType, c.buffer[:pLengthInt], nil
|
||||
}
|
||||
|
||||
// WriteAudio writes an audio packet to the connection.
|
||||
func (c *Conn) WriteAudio(format, target byte, sequence int64, final bool, data []byte, X, Y, Z *float32) error {
|
||||
var buff [1 + varint.MaxVarintLen*2]byte
|
||||
buff[0] = (format << 5) | target
|
||||
n := varint.Encode(buff[1:], sequence)
|
||||
if n == 0 {
|
||||
return errors.New("gumble: varint out of range")
|
||||
}
|
||||
l := int64(len(data))
|
||||
if final {
|
||||
l |= 0x2000
|
||||
}
|
||||
m := varint.Encode(buff[1+n:], l)
|
||||
if m == 0 {
|
||||
return errors.New("gumble: varint out of range")
|
||||
}
|
||||
header := buff[:1+n+m]
|
||||
|
||||
var positionalLength int
|
||||
if X != nil {
|
||||
positionalLength = 3 * 4
|
||||
}
|
||||
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
if err := c.writeHeader(1, uint32(len(header)+len(data)+positionalLength)); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.Conn.Write(header); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.Conn.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if positionalLength > 0 {
|
||||
if err := binary.Write(c.Conn, binary.LittleEndian, *X); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := binary.Write(c.Conn, binary.LittleEndian, *Y); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := binary.Write(c.Conn, binary.LittleEndian, *Z); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// WritePacket writes a data packet of the given type to the connection.
|
||||
func (c *Conn) WritePacket(ptype uint16, data []byte) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if err := c.writeHeader(uint16(ptype), uint32(len(data))); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.Conn.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) writeHeader(pType uint16, pLength uint32) error {
|
||||
var header [6]byte
|
||||
binary.BigEndian.PutUint16(header[:], pType)
|
||||
binary.BigEndian.PutUint32(header[2:], pLength)
|
||||
if _, err := c.Conn.Write(header[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteProto writes a protocol buffer message to the connection.
|
||||
func (c *Conn) WriteProto(message proto.Message) error {
|
||||
var protoType uint16
|
||||
switch message.(type) {
|
||||
case *MumbleProto.Version:
|
||||
protoType = 0
|
||||
case *MumbleProto.Authenticate:
|
||||
protoType = 2
|
||||
case *MumbleProto.Ping:
|
||||
protoType = 3
|
||||
case *MumbleProto.Reject:
|
||||
protoType = 4
|
||||
case *MumbleProto.ServerSync:
|
||||
protoType = 5
|
||||
case *MumbleProto.ChannelRemove:
|
||||
protoType = 6
|
||||
case *MumbleProto.ChannelState:
|
||||
protoType = 7
|
||||
case *MumbleProto.UserRemove:
|
||||
protoType = 8
|
||||
case *MumbleProto.UserState:
|
||||
protoType = 9
|
||||
case *MumbleProto.BanList:
|
||||
protoType = 10
|
||||
case *MumbleProto.TextMessage:
|
||||
protoType = 11
|
||||
case *MumbleProto.PermissionDenied:
|
||||
protoType = 12
|
||||
case *MumbleProto.ACL:
|
||||
protoType = 13
|
||||
case *MumbleProto.QueryUsers:
|
||||
protoType = 14
|
||||
case *MumbleProto.CryptSetup:
|
||||
protoType = 15
|
||||
case *MumbleProto.ContextActionModify:
|
||||
protoType = 16
|
||||
case *MumbleProto.ContextAction:
|
||||
protoType = 17
|
||||
case *MumbleProto.UserList:
|
||||
protoType = 18
|
||||
case *MumbleProto.VoiceTarget:
|
||||
protoType = 19
|
||||
case *MumbleProto.PermissionQuery:
|
||||
protoType = 20
|
||||
case *MumbleProto.CodecVersion:
|
||||
protoType = 21
|
||||
case *MumbleProto.UserStats:
|
||||
protoType = 22
|
||||
case *MumbleProto.RequestBlob:
|
||||
protoType = 23
|
||||
case *MumbleProto.ServerConfig:
|
||||
protoType = 24
|
||||
case *MumbleProto.SuggestConfig:
|
||||
protoType = 25
|
||||
default:
|
||||
return errors.New("gumble: unknown message type")
|
||||
}
|
||||
data, err := proto.Marshal(message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.WritePacket(protoType, data)
|
||||
}
|
57
gumble/gumble/contextaction.go
Normal file
57
gumble/gumble/contextaction.go
Normal file
@ -0,0 +1,57 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// ContextActionType is a bitmask of contexts where a ContextAction can be
|
||||
// triggered.
|
||||
type ContextActionType int
|
||||
|
||||
// Supported ContextAction contexts.
|
||||
const (
|
||||
ContextActionServer ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Server)
|
||||
ContextActionChannel ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Channel)
|
||||
ContextActionUser ContextActionType = ContextActionType(MumbleProto.ContextActionModify_User)
|
||||
)
|
||||
|
||||
// ContextAction is an triggerable item that has been added by a server-side
|
||||
// plugin.
|
||||
type ContextAction struct {
|
||||
// The context action type.
|
||||
Type ContextActionType
|
||||
// The name of the context action.
|
||||
Name string
|
||||
// The user-friendly description of the context action.
|
||||
Label string
|
||||
|
||||
client *Client
|
||||
}
|
||||
|
||||
// Trigger will trigger the context action in the context of the server.
|
||||
func (c *ContextAction) Trigger() {
|
||||
packet := MumbleProto.ContextAction{
|
||||
Action: &c.Name,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// TriggerUser will trigger the context action in the context of the given
|
||||
// user.
|
||||
func (c *ContextAction) TriggerUser(user *User) {
|
||||
packet := MumbleProto.ContextAction{
|
||||
Session: &user.Session,
|
||||
Action: &c.Name,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// TriggerChannel will trigger the context action in the context of the given
|
||||
// channel.
|
||||
func (c *ContextAction) TriggerChannel(channel *Channel) {
|
||||
packet := MumbleProto.ContextAction{
|
||||
ChannelId: &channel.ID,
|
||||
Action: &c.Name,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
12
gumble/gumble/contextactions.go
Normal file
12
gumble/gumble/contextactions.go
Normal file
@ -0,0 +1,12 @@
|
||||
package gumble
|
||||
|
||||
// ContextActions is a map of ContextActions.
|
||||
type ContextActions map[string]*ContextAction
|
||||
|
||||
func (c ContextActions) create(action string) *ContextAction {
|
||||
contextAction := &ContextAction{
|
||||
Name: action,
|
||||
}
|
||||
c[action] = contextAction
|
||||
return contextAction
|
||||
}
|
7
gumble/gumble/detacher.go
Normal file
7
gumble/gumble/detacher.go
Normal file
@ -0,0 +1,7 @@
|
||||
package gumble
|
||||
|
||||
// Detacher is an interface that event listeners implement. After the Detach
|
||||
// method is called, the listener will no longer receive events.
|
||||
type Detacher interface {
|
||||
Detach()
|
||||
}
|
45
gumble/gumble/doc.go
Normal file
45
gumble/gumble/doc.go
Normal file
@ -0,0 +1,45 @@
|
||||
// Package gumble is a client for the Mumble voice chat software.
|
||||
//
|
||||
// Getting started
|
||||
//
|
||||
// 1. Create a new Config to hold your connection settings:
|
||||
//
|
||||
// config := gumble.NewConfig()
|
||||
// config.Username = "gumble-test"
|
||||
//
|
||||
// 2. Attach event listeners to the configuration:
|
||||
//
|
||||
// config.Attach(gumbleutil.Listener{
|
||||
// TextMessage: func(e *gumble.TextMessageEvent) {
|
||||
// fmt.Printf("Received text message: %s\n", e.Message)
|
||||
// },
|
||||
// })
|
||||
//
|
||||
// 3. Connect to the server:
|
||||
//
|
||||
// client, err := gumble.Dial("example.com:64738", config)
|
||||
// if err != nil {
|
||||
// panic(err)
|
||||
// }
|
||||
//
|
||||
// Audio codecs
|
||||
//
|
||||
// Currently, only the Opus codec (https://www.opus-codec.org/) is supported
|
||||
// for transmitting and receiving audio. It can be enabled by importing the
|
||||
// following package for its side effect:
|
||||
// import (
|
||||
// _ "git.2mb.codes/~cmb/barnard/gumble/opus"
|
||||
// )
|
||||
//
|
||||
// To ensure that gumble clients can always transmit and receive audio to and
|
||||
// from your server, add the following line to your murmur configuration file:
|
||||
//
|
||||
// opusthreshold=0
|
||||
//
|
||||
// Thread safety
|
||||
//
|
||||
// As a general rule, a Client everything that is associated with it
|
||||
// (Users, Channels, Config, etc.), is thread-unsafe. Accessing or modifying
|
||||
// those structures should only be done from inside of an event listener or via
|
||||
// Client.Do.
|
||||
package gumble // import "git.2mb.codes/~cmb/barnard/gumble/gumble"
|
222
gumble/gumble/event.go
Normal file
222
gumble/gumble/event.go
Normal file
@ -0,0 +1,222 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// EventListener is the interface that must be implemented by a type if it
|
||||
// wishes to be notified of Client events.
|
||||
//
|
||||
// Listener methods are executed synchronously as event happen. They also block
|
||||
// network reads from happening until all handlers for an event are called.
|
||||
// Therefore, it is not recommended to do any long processing from inside of
|
||||
// these methods.
|
||||
type EventListener interface {
|
||||
OnConnect(e *ConnectEvent)
|
||||
OnDisconnect(e *DisconnectEvent)
|
||||
OnTextMessage(e *TextMessageEvent)
|
||||
OnUserChange(e *UserChangeEvent)
|
||||
OnChannelChange(e *ChannelChangeEvent)
|
||||
OnPermissionDenied(e *PermissionDeniedEvent)
|
||||
OnUserList(e *UserListEvent)
|
||||
OnACL(e *ACLEvent)
|
||||
OnBanList(e *BanListEvent)
|
||||
OnContextActionChange(e *ContextActionChangeEvent)
|
||||
OnServerConfig(e *ServerConfigEvent)
|
||||
}
|
||||
|
||||
// ConnectEvent is the event that is passed to EventListener.OnConnect.
|
||||
type ConnectEvent struct {
|
||||
Client *Client
|
||||
WelcomeMessage *string
|
||||
MaximumBitrate *int
|
||||
}
|
||||
|
||||
// DisconnectType specifies why a Client disconnected from a server.
|
||||
type DisconnectType int
|
||||
|
||||
// Client disconnect reasons.
|
||||
const (
|
||||
DisconnectError DisconnectType = iota + 1
|
||||
DisconnectKicked
|
||||
DisconnectBanned
|
||||
DisconnectUser
|
||||
)
|
||||
|
||||
// Has returns true if the DisconnectType has changeType part of its bitmask.
|
||||
func (d DisconnectType) Has(changeType DisconnectType) bool {
|
||||
return d&changeType == changeType
|
||||
}
|
||||
|
||||
// DisconnectEvent is the event that is passed to EventListener.OnDisconnect.
|
||||
type DisconnectEvent struct {
|
||||
Client *Client
|
||||
Type DisconnectType
|
||||
|
||||
String string
|
||||
}
|
||||
|
||||
// TextMessageEvent is the event that is passed to EventListener.OnTextMessage.
|
||||
type TextMessageEvent struct {
|
||||
Client *Client
|
||||
TextMessage
|
||||
}
|
||||
|
||||
// UserChangeType is a bitmask of items that changed for a user.
|
||||
type UserChangeType int
|
||||
|
||||
// User change items.
|
||||
const (
|
||||
UserChangeConnected UserChangeType = 1 << iota
|
||||
UserChangeDisconnected
|
||||
UserChangeKicked
|
||||
UserChangeBanned
|
||||
UserChangeRegistered
|
||||
UserChangeUnregistered
|
||||
UserChangeName
|
||||
UserChangeChannel
|
||||
UserChangeComment
|
||||
UserChangeAudio
|
||||
UserChangeTexture
|
||||
UserChangePrioritySpeaker
|
||||
UserChangeRecording
|
||||
UserChangeStats
|
||||
)
|
||||
|
||||
// Has returns true if the UserChangeType has changeType part of its bitmask.
|
||||
func (u UserChangeType) Has(changeType UserChangeType) bool {
|
||||
return u&changeType == changeType
|
||||
}
|
||||
|
||||
// UserChangeEvent is the event that is passed to EventListener.OnUserChange.
|
||||
type UserChangeEvent struct {
|
||||
Client *Client
|
||||
Type UserChangeType
|
||||
User *User
|
||||
Actor *User
|
||||
|
||||
String string
|
||||
}
|
||||
|
||||
// ChannelChangeType is a bitmask of items that changed for a channel.
|
||||
type ChannelChangeType int
|
||||
|
||||
// Channel change items.
|
||||
const (
|
||||
ChannelChangeCreated ChannelChangeType = 1 << iota
|
||||
ChannelChangeRemoved
|
||||
ChannelChangeMoved
|
||||
ChannelChangeName
|
||||
ChannelChangeLinks
|
||||
ChannelChangeDescription
|
||||
ChannelChangePosition
|
||||
ChannelChangePermission
|
||||
ChannelChangeMaxUsers
|
||||
)
|
||||
|
||||
// Has returns true if the ChannelChangeType has changeType part of its
|
||||
// bitmask.
|
||||
func (c ChannelChangeType) Has(changeType ChannelChangeType) bool {
|
||||
return c&changeType == changeType
|
||||
}
|
||||
|
||||
// ChannelChangeEvent is the event that is passed to
|
||||
// EventListener.OnChannelChange.
|
||||
type ChannelChangeEvent struct {
|
||||
Client *Client
|
||||
Type ChannelChangeType
|
||||
Channel *Channel
|
||||
}
|
||||
|
||||
// PermissionDeniedType specifies why a Client was denied permission to perform
|
||||
// a particular action.
|
||||
type PermissionDeniedType int
|
||||
|
||||
// Permission denied types.
|
||||
const (
|
||||
PermissionDeniedOther PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Text)
|
||||
PermissionDeniedPermission PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Permission)
|
||||
PermissionDeniedSuperUser PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_SuperUser)
|
||||
PermissionDeniedInvalidChannelName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelName)
|
||||
PermissionDeniedTextTooLong PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TextTooLong)
|
||||
PermissionDeniedTemporaryChannel PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TemporaryChannel)
|
||||
PermissionDeniedMissingCertificate PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_MissingCertificate)
|
||||
PermissionDeniedInvalidUserName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_UserName)
|
||||
PermissionDeniedChannelFull PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelFull)
|
||||
PermissionDeniedNestingLimit PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_NestingLimit)
|
||||
)
|
||||
|
||||
// Has returns true if the PermissionDeniedType has changeType part of its
|
||||
// bitmask.
|
||||
func (p PermissionDeniedType) Has(changeType PermissionDeniedType) bool {
|
||||
return p&changeType == changeType
|
||||
}
|
||||
|
||||
// PermissionDeniedEvent is the event that is passed to
|
||||
// EventListener.OnPermissionDenied.
|
||||
type PermissionDeniedEvent struct {
|
||||
Client *Client
|
||||
Type PermissionDeniedType
|
||||
Channel *Channel
|
||||
User *User
|
||||
|
||||
Permission Permission
|
||||
String string
|
||||
}
|
||||
|
||||
// UserListEvent is the event that is passed to EventListener.OnUserList.
|
||||
type UserListEvent struct {
|
||||
Client *Client
|
||||
UserList RegisteredUsers
|
||||
}
|
||||
|
||||
// ACLEvent is the event that is passed to EventListener.OnACL.
|
||||
type ACLEvent struct {
|
||||
Client *Client
|
||||
ACL *ACL
|
||||
}
|
||||
|
||||
// BanListEvent is the event that is passed to EventListener.OnBanList.
|
||||
type BanListEvent struct {
|
||||
Client *Client
|
||||
BanList BanList
|
||||
}
|
||||
|
||||
// ContextActionChangeType specifies how a ContextAction changed.
|
||||
type ContextActionChangeType int
|
||||
|
||||
// ContextAction change types.
|
||||
const (
|
||||
ContextActionAdd ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Add)
|
||||
ContextActionRemove ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Remove)
|
||||
)
|
||||
|
||||
// ContextActionChangeEvent is the event that is passed to
|
||||
// EventListener.OnContextActionChange.
|
||||
type ContextActionChangeEvent struct {
|
||||
Client *Client
|
||||
Type ContextActionChangeType
|
||||
ContextAction *ContextAction
|
||||
}
|
||||
|
||||
// ServerConfigEvent is the event that is passed to
|
||||
// EventListener.OnServerConfig.
|
||||
type ServerConfigEvent struct {
|
||||
Client *Client
|
||||
|
||||
MaximumBitrate *int
|
||||
WelcomeMessage *string
|
||||
AllowHTML *bool
|
||||
MaximumMessageLength *int
|
||||
MaximumImageMessageLength *int
|
||||
MaximumUsers *int
|
||||
|
||||
CodecAlpha *int32
|
||||
CodecBeta *int32
|
||||
CodecPreferAlpha *bool
|
||||
CodecOpus *bool
|
||||
|
||||
SuggestVersion *Version
|
||||
SuggestPositional *bool
|
||||
SuggestPushToTalk *bool
|
||||
}
|
1261
gumble/gumble/handlers.go
Normal file
1261
gumble/gumble/handlers.go
Normal file
File diff suppressed because it is too large
Load Diff
153
gumble/gumble/listeners.go
Normal file
153
gumble/gumble/listeners.go
Normal file
@ -0,0 +1,153 @@
|
||||
package gumble
|
||||
|
||||
type eventItem struct {
|
||||
parent *Listeners
|
||||
prev, next *eventItem
|
||||
listener EventListener
|
||||
}
|
||||
|
||||
func (e *eventItem) Detach() {
|
||||
if e.prev == nil {
|
||||
e.parent.head = e.next
|
||||
} else {
|
||||
e.prev.next = e.next
|
||||
}
|
||||
if e.next == nil {
|
||||
e.parent.tail = e.prev
|
||||
} else {
|
||||
e.next.prev = e.prev
|
||||
}
|
||||
}
|
||||
|
||||
// Listeners is a list of event listeners. Each attached listener is called in
|
||||
// sequence when a Client event is triggered.
|
||||
type Listeners struct {
|
||||
head, tail *eventItem
|
||||
}
|
||||
|
||||
// Attach adds a new event listener to the end of the current list of listeners.
|
||||
func (e *Listeners) Attach(listener EventListener) Detacher {
|
||||
item := &eventItem{
|
||||
parent: e,
|
||||
prev: e.tail,
|
||||
listener: listener,
|
||||
}
|
||||
if e.head == nil {
|
||||
e.head = item
|
||||
}
|
||||
if e.tail != nil {
|
||||
e.tail.next = item
|
||||
}
|
||||
e.tail = item
|
||||
return item
|
||||
}
|
||||
|
||||
func (e *Listeners) onConnect(event *ConnectEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnConnect(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onDisconnect(event *DisconnectEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnDisconnect(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onTextMessage(event *TextMessageEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnTextMessage(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onUserChange(event *UserChangeEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnUserChange(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onChannelChange(event *ChannelChangeEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnChannelChange(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onPermissionDenied(event *PermissionDeniedEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnPermissionDenied(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onUserList(event *UserListEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnUserList(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onACL(event *ACLEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnACL(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onBanList(event *BanListEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnBanList(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onContextActionChange(event *ContextActionChangeEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnContextActionChange(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onServerConfig(event *ServerConfigEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnServerConfig(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
13
gumble/gumble/message.go
Normal file
13
gumble/gumble/message.go
Normal file
@ -0,0 +1,13 @@
|
||||
package gumble
|
||||
|
||||
// Message is data that be encoded and sent to the server. The following
|
||||
// types implement this interface:
|
||||
// AccessTokens
|
||||
// ACL
|
||||
// BanList
|
||||
// RegisteredUsers
|
||||
// TextMessage
|
||||
// VoiceTarget
|
||||
type Message interface {
|
||||
writeMessage(client *Client) error
|
||||
}
|
33
gumble/gumble/permission.go
Normal file
33
gumble/gumble/permission.go
Normal file
@ -0,0 +1,33 @@
|
||||
package gumble
|
||||
|
||||
// Permission is a bitmask of permissions given to a certain user.
|
||||
type Permission int
|
||||
|
||||
// Permissions that can be applied in any channel.
|
||||
const (
|
||||
PermissionWrite Permission = 1 << iota
|
||||
PermissionTraverse
|
||||
PermissionEnter
|
||||
PermissionSpeak
|
||||
PermissionMuteDeafen
|
||||
PermissionMove
|
||||
PermissionMakeChannel
|
||||
PermissionLinkChannel
|
||||
PermissionWhisper
|
||||
PermissionTextMessage
|
||||
PermissionMakeTemporaryChannel
|
||||
)
|
||||
|
||||
// Permissions that can only be applied in the root channel.
|
||||
const (
|
||||
PermissionKick Permission = 0x10000 << iota
|
||||
PermissionBan
|
||||
PermissionRegister
|
||||
PermissionRegisterSelf
|
||||
)
|
||||
|
||||
// Has returns true if the Permission p contains Permission o has part of its
|
||||
// bitmask.
|
||||
func (p Permission) Has(o Permission) bool {
|
||||
return p&o == o
|
||||
}
|
108
gumble/gumble/ping.go
Normal file
108
gumble/gumble/ping.go
Normal file
@ -0,0 +1,108 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PingResponse contains information about a server that responded to a UDP
|
||||
// ping packet.
|
||||
type PingResponse struct {
|
||||
// The address of the pinged server.
|
||||
Address *net.UDPAddr
|
||||
// The round-trip time from the client to the server.
|
||||
Ping time.Duration
|
||||
// The server's version. Only the Version field and SemanticVersion method of
|
||||
// the value will be valid.
|
||||
Version Version
|
||||
// The number users currently connected to the server.
|
||||
ConnectedUsers int
|
||||
// The maximum number of users that can connect to the server.
|
||||
MaximumUsers int
|
||||
// The maximum audio bitrate per user for the server.
|
||||
MaximumBitrate int
|
||||
}
|
||||
|
||||
// Ping sends a UDP ping packet to the given server. If interval is positive,
|
||||
// the packet is retransmitted at every interval.
|
||||
//
|
||||
// Returns a PingResponse and nil on success. The function will return nil and
|
||||
// an error if a valid response is not received after the given timeout.
|
||||
func Ping(address string, interval, timeout time.Duration) (*PingResponse, error) {
|
||||
if timeout < 0 {
|
||||
return nil, errors.New("gumble: timeout must be positive")
|
||||
}
|
||||
deadline := time.Now().Add(timeout)
|
||||
conn, err := net.DialTimeout("udp", address, timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetReadDeadline(deadline)
|
||||
|
||||
var (
|
||||
idsLock sync.Mutex
|
||||
ids = make(map[string]time.Time)
|
||||
)
|
||||
|
||||
buildSendPacket := func() {
|
||||
var packet [12]byte
|
||||
if _, err := rand.Read(packet[4:]); err != nil {
|
||||
return
|
||||
}
|
||||
id := string(packet[4:])
|
||||
idsLock.Lock()
|
||||
ids[id] = time.Now()
|
||||
idsLock.Unlock()
|
||||
conn.Write(packet[:])
|
||||
}
|
||||
|
||||
if interval > 0 {
|
||||
end := make(chan struct{})
|
||||
defer close(end)
|
||||
go func() {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
buildSendPacket()
|
||||
case <-end:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
buildSendPacket()
|
||||
|
||||
for {
|
||||
var incoming [24]byte
|
||||
if _, err := io.ReadFull(conn, incoming[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := string(incoming[4:12])
|
||||
idsLock.Lock()
|
||||
sendTime, ok := ids[id]
|
||||
idsLock.Unlock()
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
return &PingResponse{
|
||||
Address: conn.RemoteAddr().(*net.UDPAddr),
|
||||
Ping: time.Since(sendTime),
|
||||
Version: Version{
|
||||
Version: binary.BigEndian.Uint32(incoming[0:]),
|
||||
},
|
||||
ConnectedUsers: int(binary.BigEndian.Uint32(incoming[12:])),
|
||||
MaximumUsers: int(binary.BigEndian.Uint32(incoming[16:])),
|
||||
MaximumBitrate: int(binary.BigEndian.Uint32(incoming[20:])),
|
||||
}, nil
|
||||
}
|
||||
}
|
61
gumble/gumble/reject.go
Normal file
61
gumble/gumble/reject.go
Normal file
@ -0,0 +1,61 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// RejectType describes why a client connection was rejected by the server.
|
||||
type RejectType int
|
||||
|
||||
// The possible reason why a client connection was rejected by the server.
|
||||
const (
|
||||
RejectNone RejectType = RejectType(MumbleProto.Reject_None)
|
||||
RejectVersion RejectType = RejectType(MumbleProto.Reject_WrongVersion)
|
||||
RejectUserName RejectType = RejectType(MumbleProto.Reject_InvalidUsername)
|
||||
RejectUserCredentials RejectType = RejectType(MumbleProto.Reject_WrongUserPW)
|
||||
RejectServerPassword RejectType = RejectType(MumbleProto.Reject_WrongServerPW)
|
||||
RejectUsernameInUse RejectType = RejectType(MumbleProto.Reject_UsernameInUse)
|
||||
RejectServerFull RejectType = RejectType(MumbleProto.Reject_ServerFull)
|
||||
RejectNoCertificate RejectType = RejectType(MumbleProto.Reject_NoCertificate)
|
||||
RejectAuthenticatorFail RejectType = RejectType(MumbleProto.Reject_AuthenticatorFail)
|
||||
)
|
||||
|
||||
// RejectError is returned by DialWithDialer when the server rejects the client
|
||||
// connection.
|
||||
type RejectError struct {
|
||||
Type RejectType
|
||||
Reason string
|
||||
}
|
||||
|
||||
// Error implements error.
|
||||
func (e RejectError) Error() string {
|
||||
var msg string
|
||||
switch e.Type {
|
||||
case RejectNone:
|
||||
msg = "none"
|
||||
case RejectVersion:
|
||||
msg = "wrong client version"
|
||||
case RejectUserName:
|
||||
msg = "invalid username"
|
||||
case RejectUserCredentials:
|
||||
msg = "incorrect user credentials"
|
||||
case RejectServerPassword:
|
||||
msg = "incorrect server password"
|
||||
case RejectUsernameInUse:
|
||||
msg = "username in use"
|
||||
case RejectServerFull:
|
||||
msg = "server full"
|
||||
case RejectNoCertificate:
|
||||
msg = "no certificate"
|
||||
case RejectAuthenticatorFail:
|
||||
msg = "authenticator fail"
|
||||
default:
|
||||
msg = "unknown type " + strconv.Itoa(int(e.Type))
|
||||
}
|
||||
if e.Reason != "" {
|
||||
msg += ": " + e.Reason
|
||||
}
|
||||
return msg
|
||||
}
|
36
gumble/gumble/rpwmutex.go
Normal file
36
gumble/gumble/rpwmutex.go
Normal file
@ -0,0 +1,36 @@
|
||||
package gumble
|
||||
|
||||
import "sync"
|
||||
|
||||
// rpwMutex is a reader-preferred RWMutex.
|
||||
type rpwMutex struct {
|
||||
w sync.Mutex
|
||||
r sync.Mutex
|
||||
n int
|
||||
}
|
||||
|
||||
func (m *rpwMutex) Lock() {
|
||||
m.w.Lock()
|
||||
}
|
||||
|
||||
func (m *rpwMutex) Unlock() {
|
||||
m.w.Unlock()
|
||||
}
|
||||
|
||||
func (m *rpwMutex) RLock() {
|
||||
m.r.Lock()
|
||||
m.n++
|
||||
if m.n == 1 {
|
||||
m.w.Lock()
|
||||
}
|
||||
m.r.Unlock()
|
||||
}
|
||||
|
||||
func (m *rpwMutex) RUnlock() {
|
||||
m.r.Lock()
|
||||
m.n--
|
||||
if m.n == 0 {
|
||||
m.w.Unlock()
|
||||
}
|
||||
m.r.Unlock()
|
||||
}
|
45
gumble/gumble/textmessage.go
Normal file
45
gumble/gumble/textmessage.go
Normal file
@ -0,0 +1,45 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// TextMessage is a chat message that can be received from and sent to the
|
||||
// server.
|
||||
type TextMessage struct {
|
||||
// User who sent the message (can be nil).
|
||||
Sender *User
|
||||
// Users that receive the message.
|
||||
Users []*User
|
||||
// Channels that receive the message.
|
||||
Channels []*Channel
|
||||
// Channels that receive the message and send it recursively to sub-channels.
|
||||
Trees []*Channel
|
||||
// Chat message.
|
||||
Message string
|
||||
}
|
||||
|
||||
func (t *TextMessage) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.TextMessage{
|
||||
Message: &t.Message,
|
||||
}
|
||||
if t.Users != nil {
|
||||
packet.Session = make([]uint32, len(t.Users))
|
||||
for i, user := range t.Users {
|
||||
packet.Session[i] = user.Session
|
||||
}
|
||||
}
|
||||
if t.Channels != nil {
|
||||
packet.ChannelId = make([]uint32, len(t.Channels))
|
||||
for i, channel := range t.Channels {
|
||||
packet.ChannelId[i] = channel.ID
|
||||
}
|
||||
}
|
||||
if t.Trees != nil {
|
||||
packet.TreeId = make([]uint32, len(t.Trees))
|
||||
for i, channel := range t.Trees {
|
||||
packet.TreeId[i] = channel.ID
|
||||
}
|
||||
}
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
242
gumble/gumble/user.go
Normal file
242
gumble/gumble/user.go
Normal file
@ -0,0 +1,242 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
"git.2mb.codes/~cmb/go-openal/openal"
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// User represents a user that is currently connected to the server.
|
||||
type User struct {
|
||||
// The user's unique session ID.
|
||||
Session uint32
|
||||
// The user's ID. Contains an invalid value if the user is not registered.
|
||||
UserID uint32
|
||||
// The user's name.
|
||||
Name string
|
||||
// The channel that the user is currently in.
|
||||
Channel *Channel
|
||||
|
||||
// Has the user has been muted?
|
||||
Muted bool
|
||||
// Has the user been deafened?
|
||||
Deafened bool
|
||||
// Has the user been suppressed?
|
||||
Suppressed bool
|
||||
// Has the user been muted by him/herself?
|
||||
SelfMuted bool
|
||||
// Has the user been deafened by him/herself?
|
||||
SelfDeafened bool
|
||||
// Is the user a priority speaker in the channel?
|
||||
PrioritySpeaker bool
|
||||
// Is the user recording audio?
|
||||
Recording bool
|
||||
|
||||
// The user's comment. Contains the empty string if the user does not have a
|
||||
// comment, or if the comment needs to be requested.
|
||||
Comment string
|
||||
// The user's comment hash. nil if User.Comment has been populated.
|
||||
CommentHash []byte
|
||||
// The hash of the user's certificate (can be empty).
|
||||
Hash string
|
||||
// The user's texture (avatar). nil if the user does not have a
|
||||
// texture, or if the texture needs to be requested.
|
||||
Texture []byte
|
||||
// The user's texture hash. nil if User.Texture has been populated.
|
||||
TextureHash []byte
|
||||
|
||||
// The user's stats. Contains nil if the stats have not yet been requested.
|
||||
Stats *UserStats
|
||||
|
||||
client *Client
|
||||
decoder AudioDecoder
|
||||
|
||||
AudioSource *openal.Source
|
||||
Boost uint16
|
||||
Volume float32
|
||||
}
|
||||
|
||||
func (u *User) GetClient() *Client {
|
||||
return u.client
|
||||
}
|
||||
|
||||
// SetTexture sets the user's texture.
|
||||
func (u *User) SetTexture(texture []byte) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Texture: texture,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetPrioritySpeaker sets if the user is a priority speaker in the channel.
|
||||
func (u *User) SetPrioritySpeaker(prioritySpeaker bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
PrioritySpeaker: &prioritySpeaker,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetRecording sets if the user is recording audio.
|
||||
func (u *User) SetRecording(recording bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Recording: &recording,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// IsRegistered returns true if the user's certificate has been registered with
|
||||
// the server. A registered user will have a valid user ID.
|
||||
func (u *User) IsRegistered() bool {
|
||||
return u.UserID > 0
|
||||
}
|
||||
|
||||
// Register will register the user with the server. If the client has
|
||||
// permission to do so, the user will shortly be given a UserID.
|
||||
func (u *User) Register() {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
UserId: proto.Uint32(0),
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetComment will set the user's comment to the given string. The user's
|
||||
// comment will be erased if the comment is set to the empty string.
|
||||
func (u *User) SetComment(comment string) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Comment: &comment,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Move will move the user to the given channel.
|
||||
func (u *User) Move(channel *Channel) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
ChannelId: &channel.ID,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Kick will kick the user from the server.
|
||||
func (u *User) Kick(reason string) {
|
||||
packet := MumbleProto.UserRemove{
|
||||
Session: &u.Session,
|
||||
Reason: &reason,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Ban will ban the user from the server.
|
||||
func (u *User) Ban(reason string) {
|
||||
packet := MumbleProto.UserRemove{
|
||||
Session: &u.Session,
|
||||
Reason: &reason,
|
||||
Ban: proto.Bool(true),
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetMuted sets whether the user can transmit audio or not.
|
||||
func (u *User) SetMuted(muted bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Mute: &muted,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetSuppressed sets whether the user is suppressed by the server or not.
|
||||
func (u *User) SetSuppressed(supressed bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Suppress: &supressed,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetDeafened sets whether the user can receive audio or not.
|
||||
func (u *User) SetDeafened(muted bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Deaf: &muted,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetSelfMuted sets whether the user can transmit audio or not.
|
||||
//
|
||||
// This method should only be called on Client.Self().
|
||||
func (u *User) SetSelfMuted(muted bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
SelfMute: &muted,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetSelfDeafened sets whether the user can receive audio or not.
|
||||
//
|
||||
// This method should only be called on Client.Self().
|
||||
func (u *User) SetSelfDeafened(muted bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
SelfDeaf: &muted,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestStats requests that the user's stats be sent to the client.
|
||||
func (u *User) RequestStats() {
|
||||
packet := MumbleProto.UserStats{
|
||||
Session: &u.Session,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestTexture requests that the user's actual texture (i.e. non-hashed) be
|
||||
// sent to the client.
|
||||
func (u *User) RequestTexture() {
|
||||
packet := MumbleProto.RequestBlob{
|
||||
SessionTexture: []uint32{u.Session},
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestComment requests that the user's actual comment (i.e. non-hashed) be
|
||||
// sent to the client.
|
||||
func (u *User) RequestComment() {
|
||||
packet := MumbleProto.RequestBlob{
|
||||
SessionComment: []uint32{u.Session},
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Send will send a text message to the user.
|
||||
func (u *User) Send(message string) {
|
||||
textMessage := TextMessage{
|
||||
Users: []*User{u},
|
||||
Message: message,
|
||||
}
|
||||
u.client.Send(&textMessage)
|
||||
}
|
||||
|
||||
// SetPlugin sets the user's plugin data.
|
||||
//
|
||||
// Plugins are currently only used for positional audio. Clients will receive
|
||||
// positional audio information from other users if their plugin context is the
|
||||
// same. The official Mumble client sets the context to:
|
||||
//
|
||||
// PluginShortName + "\x00" + AdditionalContextInformation
|
||||
func (u *User) SetPlugin(context []byte, identity string) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
PluginContext: context,
|
||||
PluginIdentity: &identity,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
74
gumble/gumble/userlist.go
Normal file
74
gumble/gumble/userlist.go
Normal file
@ -0,0 +1,74 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// RegisteredUser represents a registered user on the server.
|
||||
type RegisteredUser struct {
|
||||
// The registered user's ID.
|
||||
UserID uint32
|
||||
// The registered user's name.
|
||||
Name string
|
||||
// The last time the user was seen by the server.
|
||||
LastSeen time.Time
|
||||
// The last channel the user was seen in.
|
||||
LastChannel *Channel
|
||||
|
||||
changed bool
|
||||
deregister bool
|
||||
}
|
||||
|
||||
// SetName sets the new name for the user.
|
||||
func (r *RegisteredUser) SetName(name string) {
|
||||
r.Name = name
|
||||
r.changed = true
|
||||
}
|
||||
|
||||
// Deregister will remove the registered user from the server.
|
||||
func (r *RegisteredUser) Deregister() {
|
||||
r.deregister = true
|
||||
}
|
||||
|
||||
// Register will keep the user registered on the server. This is only useful if
|
||||
// Deregister() was called on the registered user.
|
||||
func (r *RegisteredUser) Register() {
|
||||
r.deregister = false
|
||||
}
|
||||
|
||||
// ACLUser returns an ACLUser for the given registered user.
|
||||
func (r *RegisteredUser) ACLUser() *ACLUser {
|
||||
return &ACLUser{
|
||||
UserID: r.UserID,
|
||||
Name: r.Name,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisteredUsers is a list of users who are registered on the server.
|
||||
//
|
||||
// Whenever a registered user is changed, it does not come into effect until
|
||||
// the registered user list is sent back to the server.
|
||||
type RegisteredUsers []*RegisteredUser
|
||||
|
||||
func (r RegisteredUsers) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.UserList{}
|
||||
|
||||
for _, user := range r {
|
||||
if user.deregister || user.changed {
|
||||
userListUser := &MumbleProto.UserList_User{
|
||||
UserId: &user.UserID,
|
||||
}
|
||||
if !user.deregister {
|
||||
userListUser.Name = &user.Name
|
||||
}
|
||||
packet.Users = append(packet.Users, userListUser)
|
||||
}
|
||||
}
|
||||
|
||||
if len(packet.Users) <= 0 {
|
||||
return nil
|
||||
}
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
34
gumble/gumble/users.go
Normal file
34
gumble/gumble/users.go
Normal file
@ -0,0 +1,34 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
// "git.2mb.codes/~cmb/go-openal/openal"
|
||||
)
|
||||
|
||||
// Users is a map of server users.
|
||||
//
|
||||
// When accessed through client.Users, it contains all users currently on the
|
||||
// server. When accessed through a specific channel
|
||||
// (e.g. client.Channels[0].Users), it contains only the users in the
|
||||
// channel.
|
||||
type Users map[uint32]*User
|
||||
|
||||
// create adds a new user with the given session to the collection. If a user
|
||||
// with the given session already exists, it is overwritten.
|
||||
func (u Users) create(session uint32) *User {
|
||||
user := &User{
|
||||
Session: session,
|
||||
}
|
||||
u[session] = user
|
||||
return user
|
||||
}
|
||||
|
||||
// Find returns the user with the given name. nil is returned if no user exists
|
||||
// with the given name.
|
||||
func (u Users) Find(name string) *User {
|
||||
for _, user := range u {
|
||||
if user.Name == name {
|
||||
return user
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
62
gumble/gumble/userstats.go
Normal file
62
gumble/gumble/userstats.go
Normal file
@ -0,0 +1,62 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// UserStats contains additional information about a user.
|
||||
type UserStats struct {
|
||||
// The owner of the stats.
|
||||
User *User
|
||||
|
||||
// Stats about UDP packets sent from the client.
|
||||
FromClient UserStatsUDP
|
||||
// Stats about UDP packets sent by the server.
|
||||
FromServer UserStatsUDP
|
||||
|
||||
// Number of UDP packets sent by the user.
|
||||
UDPPackets uint32
|
||||
// Average UDP ping.
|
||||
UDPPingAverage float32
|
||||
// UDP ping variance.
|
||||
UDPPingVariance float32
|
||||
|
||||
// Number of TCP packets sent by the user.
|
||||
TCPPackets uint32
|
||||
// Average TCP ping.
|
||||
TCPPingAverage float32
|
||||
// TCP ping variance.
|
||||
TCPPingVariance float32
|
||||
|
||||
// The user's version.
|
||||
Version Version
|
||||
// When the user connected to the server.
|
||||
Connected time.Time
|
||||
// How long the user has been idle.
|
||||
Idle time.Duration
|
||||
// How much bandwidth the user is current using.
|
||||
Bandwidth int
|
||||
// The user's certificate chain.
|
||||
Certificates []*x509.Certificate
|
||||
// Does the user have a strong certificate? A strong certificate is one that
|
||||
// is not self signed, nor expired, etc.
|
||||
StrongCertificate bool
|
||||
// A list of CELT versions supported by the user's client.
|
||||
CELTVersions []int32
|
||||
// Does the user's client supports the Opus audio codec?
|
||||
Opus bool
|
||||
|
||||
// The user's IP address.
|
||||
IP net.IP
|
||||
}
|
||||
|
||||
// UserStatsUDP contains stats about UDP packets that have been sent to or from
|
||||
// the server.
|
||||
type UserStatsUDP struct {
|
||||
Good uint32
|
||||
Late uint32
|
||||
Lost uint32
|
||||
Resync uint32
|
||||
}
|
1
gumble/gumble/varint/doc.go
Normal file
1
gumble/gumble/varint/doc.go
Normal file
@ -0,0 +1 @@
|
||||
package varint // import "git.2mb.codes/~cmb/barnard/gumble/gumble/varint"
|
52
gumble/gumble/varint/read.go
Normal file
52
gumble/gumble/varint/read.go
Normal file
@ -0,0 +1,52 @@
|
||||
package varint
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
)
|
||||
|
||||
// Decode reads the first varint encoded number from the given buffer.
|
||||
//
|
||||
// On success, the function returns the varint as an int64, and the number of
|
||||
// bytes read (0 if there was an error).
|
||||
func Decode(b []byte) (int64, int) {
|
||||
if len(b) == 0 {
|
||||
return 0, 0
|
||||
}
|
||||
// 0xxxxxxx 7-bit positive number
|
||||
if (b[0] & 0x80) == 0 {
|
||||
return int64(b[0]), 1
|
||||
}
|
||||
// 10xxxxxx + 1 byte 14-bit positive number
|
||||
if (b[0]&0xC0) == 0x80 && len(b) >= 2 {
|
||||
return int64(b[0]&0x3F)<<8 | int64(b[1]), 2
|
||||
}
|
||||
// 110xxxxx + 2 bytes 21-bit positive number
|
||||
if (b[0]&0xE0) == 0xC0 && len(b) >= 3 {
|
||||
return int64(b[0]&0x1F)<<16 | int64(b[1])<<8 | int64(b[2]), 3
|
||||
}
|
||||
// 1110xxxx + 3 bytes 28-bit positive number
|
||||
if (b[0]&0xF0) == 0xE0 && len(b) >= 4 {
|
||||
return int64(b[0]&0xF)<<24 | int64(b[1])<<16 | int64(b[2])<<8 | int64(b[3]), 4
|
||||
}
|
||||
// 111100__ + int (32-bit) 32-bit positive number
|
||||
if (b[0]&0xFC) == 0xF0 && len(b) >= 5 {
|
||||
return int64(binary.BigEndian.Uint32(b[1:])), 5
|
||||
}
|
||||
// 111101__ + long (64-bit) 64-bit number
|
||||
if (b[0]&0xFC) == 0xF4 && len(b) >= 9 {
|
||||
return int64(binary.BigEndian.Uint64(b[1:])), 9
|
||||
}
|
||||
// 111110__ + varint Negative recursive varint
|
||||
if b[0]&0xFC == 0xF8 {
|
||||
if v, n := Decode(b[1:]); n > 0 {
|
||||
return -v, n + 1
|
||||
}
|
||||
return 0, 0
|
||||
}
|
||||
// 111111xx Byte-inverted negative two bit number (~xx)
|
||||
if b[0]&0xFC == 0xFC {
|
||||
return ^int64(b[0] & 0x03), 1
|
||||
}
|
||||
|
||||
return 0, 0
|
||||
}
|
32
gumble/gumble/varint/varint_test.go
Normal file
32
gumble/gumble/varint/varint_test.go
Normal file
@ -0,0 +1,32 @@
|
||||
package varint // import "git.2mb.codes/~cmb/barnard/gumble/gumble/varint"
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRange(t *testing.T) {
|
||||
|
||||
fn := func(i int64) {
|
||||
var b [MaxVarintLen]byte
|
||||
size := Encode(b[:], i)
|
||||
if size == 0 {
|
||||
t.Error("Encode returned size 0\n")
|
||||
}
|
||||
s := b[:size]
|
||||
|
||||
val, size := Decode(s)
|
||||
if size == 0 {
|
||||
t.Error("Decode return size 0\n")
|
||||
}
|
||||
|
||||
if i != val {
|
||||
t.Errorf("Encoded %d (%v) equals decoded %d\n", i, s, val)
|
||||
}
|
||||
}
|
||||
|
||||
for i := int64(-10000); i <= 10000; i++ {
|
||||
fn(i)
|
||||
}
|
||||
|
||||
fn(134342525)
|
||||
fn(10282934828342)
|
||||
fn(1028293482834200000)
|
||||
}
|
64
gumble/gumble/varint/write.go
Normal file
64
gumble/gumble/varint/write.go
Normal file
@ -0,0 +1,64 @@
|
||||
package varint
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math"
|
||||
)
|
||||
|
||||
// MaxVarintLen is the maximum number of bytes required to encode a varint
|
||||
// number.
|
||||
const MaxVarintLen = 10
|
||||
|
||||
// Encode encodes the given value to varint format.
|
||||
func Encode(b []byte, value int64) int {
|
||||
// 111111xx Byte-inverted negative two bit number (~xx)
|
||||
if value <= -1 && value >= -4 {
|
||||
b[0] = 0xFC | byte(^value&0xFF)
|
||||
return 1
|
||||
}
|
||||
// 111110__ + varint Negative recursive varint
|
||||
if value < 0 {
|
||||
b[0] = 0xF8
|
||||
return 1 + Encode(b[1:], -value)
|
||||
}
|
||||
// 0xxxxxxx 7-bit positive number
|
||||
if value <= 0x7F {
|
||||
b[0] = byte(value)
|
||||
return 1
|
||||
}
|
||||
// 10xxxxxx + 1 byte 14-bit positive number
|
||||
if value <= 0x3FFF {
|
||||
b[0] = byte(((value >> 8) & 0x3F) | 0x80)
|
||||
b[1] = byte(value & 0xFF)
|
||||
return 2
|
||||
}
|
||||
// 110xxxxx + 2 bytes 21-bit positive number
|
||||
if value <= 0x1FFFFF {
|
||||
b[0] = byte((value>>16)&0x1F | 0xC0)
|
||||
b[1] = byte((value >> 8) & 0xFF)
|
||||
b[2] = byte(value & 0xFF)
|
||||
return 3
|
||||
}
|
||||
// 1110xxxx + 3 bytes 28-bit positive number
|
||||
if value <= 0xFFFFFFF {
|
||||
b[0] = byte((value>>24)&0xF | 0xE0)
|
||||
b[1] = byte((value >> 16) & 0xFF)
|
||||
b[2] = byte((value >> 8) & 0xFF)
|
||||
b[3] = byte(value & 0xFF)
|
||||
return 4
|
||||
}
|
||||
// 111100__ + int (32-bit) 32-bit positive number
|
||||
if value <= math.MaxInt32 {
|
||||
b[0] = 0xF0
|
||||
binary.BigEndian.PutUint32(b[1:], uint32(value))
|
||||
return 5
|
||||
}
|
||||
// 111101__ + long (64-bit) 64-bit number
|
||||
if value <= math.MaxInt64 {
|
||||
b[0] = 0xF4
|
||||
binary.BigEndian.PutUint64(b[1:], uint64(value))
|
||||
return 9
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
24
gumble/gumble/version.go
Normal file
24
gumble/gumble/version.go
Normal file
@ -0,0 +1,24 @@
|
||||
package gumble
|
||||
|
||||
// Version represents a Mumble client or server version.
|
||||
type Version struct {
|
||||
// The semantic version information as a single unsigned integer.
|
||||
//
|
||||
// Bits 0-15 are the major version, bits 16-23 are the minor version, and
|
||||
// bits 24-31 are the patch version.
|
||||
Version uint32
|
||||
// The name of the client.
|
||||
Release string
|
||||
// The operating system name.
|
||||
OS string
|
||||
// The operating system version.
|
||||
OSVersion string
|
||||
}
|
||||
|
||||
// SemanticVersion returns the version's semantic version components.
|
||||
func (v *Version) SemanticVersion() (major uint16, minor, patch uint8) {
|
||||
major = uint16(v.Version>>16) & 0xFFFF
|
||||
minor = uint8(v.Version>>8) & 0xFF
|
||||
patch = uint8(v.Version) & 0xFF
|
||||
return
|
||||
}
|
76
gumble/gumble/voicetarget.go
Normal file
76
gumble/gumble/voicetarget.go
Normal file
@ -0,0 +1,76 @@
|
||||
package gumble
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// VoiceTargetLoopback is a special voice target which causes any audio sent to
|
||||
// the server to be returned to the client.
|
||||
//
|
||||
// Its ID should not be modified, and it does not have to to be sent to the
|
||||
// server before use.
|
||||
var VoiceTargetLoopback *VoiceTarget = &VoiceTarget{
|
||||
ID: 31,
|
||||
}
|
||||
|
||||
type voiceTargetChannel struct {
|
||||
channel *Channel
|
||||
links, recursive bool
|
||||
group string
|
||||
}
|
||||
|
||||
// VoiceTarget represents a set of users and/or channels that the client can
|
||||
// whisper to.
|
||||
type VoiceTarget struct {
|
||||
// The voice target ID. This value must be in the range [1, 30].
|
||||
ID uint32
|
||||
users []*User
|
||||
channels []*voiceTargetChannel
|
||||
}
|
||||
|
||||
// Clear removes all users and channels from the voice target.
|
||||
func (v *VoiceTarget) Clear() {
|
||||
v.users = nil
|
||||
v.channels = nil
|
||||
}
|
||||
|
||||
// AddUser adds a user to the voice target.
|
||||
func (v *VoiceTarget) AddUser(user *User) {
|
||||
v.users = append(v.users, user)
|
||||
}
|
||||
|
||||
// AddChannel adds a user to the voice target. If group is non-empty, only
|
||||
// users belonging to that ACL group will be targeted.
|
||||
func (v *VoiceTarget) AddChannel(channel *Channel, recursive, links bool, group string) {
|
||||
v.channels = append(v.channels, &voiceTargetChannel{
|
||||
channel: channel,
|
||||
links: links,
|
||||
recursive: recursive,
|
||||
group: group,
|
||||
})
|
||||
}
|
||||
|
||||
func (v *VoiceTarget) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.VoiceTarget{
|
||||
Id: &v.ID,
|
||||
Targets: make([]*MumbleProto.VoiceTarget_Target, 0, len(v.users)+len(v.channels)),
|
||||
}
|
||||
for _, user := range v.users {
|
||||
packet.Targets = append(packet.Targets, &MumbleProto.VoiceTarget_Target{
|
||||
Session: []uint32{user.Session},
|
||||
})
|
||||
}
|
||||
for _, vtChannel := range v.channels {
|
||||
target := &MumbleProto.VoiceTarget_Target{
|
||||
ChannelId: &vtChannel.channel.ID,
|
||||
Links: &vtChannel.links,
|
||||
Children: &vtChannel.recursive,
|
||||
}
|
||||
if vtChannel.group != "" {
|
||||
target.Group = &vtChannel.group
|
||||
}
|
||||
packet.Targets = append(packet.Targets, target)
|
||||
}
|
||||
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
103
gumble/gumbleffmpeg/source.go
Normal file
103
gumble/gumbleffmpeg/source.go
Normal file
@ -0,0 +1,103 @@
|
||||
package gumbleffmpeg // import "git.2mb.codes/~cmb/barnard/gumble/gumbleffmpeg"
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
// Source is a Stream source.
|
||||
type Source interface {
|
||||
// must include the -i <filename>
|
||||
arguments() []string
|
||||
start(*exec.Cmd) error
|
||||
done()
|
||||
}
|
||||
|
||||
// sourceFile
|
||||
|
||||
type sourceFile string
|
||||
|
||||
// SourceFile is standard file source.
|
||||
func SourceFile(filename string) Source {
|
||||
return sourceFile(filename)
|
||||
}
|
||||
|
||||
func (s sourceFile) arguments() []string {
|
||||
return []string{"-i", string(s)}
|
||||
}
|
||||
|
||||
func (sourceFile) start(*exec.Cmd) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sourceFile) done() {
|
||||
}
|
||||
|
||||
// sourceReader
|
||||
|
||||
type sourceReader struct {
|
||||
r io.ReadCloser
|
||||
}
|
||||
|
||||
// SourceReader is a ReadCloser source.
|
||||
func SourceReader(r io.ReadCloser) Source {
|
||||
return &sourceReader{r}
|
||||
}
|
||||
|
||||
func (*sourceReader) arguments() []string {
|
||||
return []string{"-i", "-"}
|
||||
}
|
||||
|
||||
func (s *sourceReader) start(cmd *exec.Cmd) error {
|
||||
cmd.Stdin = s.r
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *sourceReader) done() {
|
||||
s.r.Close()
|
||||
}
|
||||
|
||||
// sourceExec
|
||||
|
||||
type sourceExec struct {
|
||||
name string
|
||||
arg []string
|
||||
|
||||
cmd *exec.Cmd
|
||||
}
|
||||
|
||||
// SourceExec uses the output of the given command and arguments as source
|
||||
// data.
|
||||
func SourceExec(name string, arg ...string) Source {
|
||||
return &sourceExec{
|
||||
name: name,
|
||||
arg: arg,
|
||||
}
|
||||
}
|
||||
|
||||
func (*sourceExec) arguments() []string {
|
||||
return []string{"-i", "-"}
|
||||
}
|
||||
|
||||
func (s *sourceExec) start(cmd *exec.Cmd) error {
|
||||
s.cmd = exec.Command(s.name, s.arg...)
|
||||
r, err := s.cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd.Stdin = r
|
||||
if err := s.cmd.Start(); err != nil {
|
||||
cmd.Stdin = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *sourceExec) done() {
|
||||
if s.cmd != nil {
|
||||
if p := s.cmd.Process; p != nil {
|
||||
p.Kill()
|
||||
}
|
||||
s.cmd.Wait()
|
||||
}
|
||||
}
|
203
gumble/gumbleffmpeg/stream.go
Normal file
203
gumble/gumbleffmpeg/stream.go
Normal file
@ -0,0 +1,203 @@
|
||||
package gumbleffmpeg // import "git.2mb.codes/~cmb/barnard/gumble/gumbleffmpeg"
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
)
|
||||
|
||||
// State represents the state of a Stream.
|
||||
type State int32
|
||||
|
||||
// Valid states of Stream.
|
||||
const (
|
||||
StateInitial State = iota + 1
|
||||
StatePlaying
|
||||
StatePaused
|
||||
StateStopped
|
||||
)
|
||||
|
||||
// Stream is an audio stream that encodes media through ffmpeg and sends it to
|
||||
// the server.
|
||||
//
|
||||
// A stream can only be used once; it cannot be started after it is stopped.
|
||||
type Stream struct {
|
||||
// Command to execute to play the file. Defaults to "ffmpeg".
|
||||
Command string
|
||||
// Playback volume (can be changed while the source is playing).
|
||||
Volume float32
|
||||
// Audio source (cannot be changed after stream starts).
|
||||
Source Source
|
||||
// Starting offset.
|
||||
Offset time.Duration
|
||||
|
||||
client *gumble.Client
|
||||
cmd *exec.Cmd
|
||||
pipe io.ReadCloser
|
||||
pause chan struct{}
|
||||
elapsed int64
|
||||
|
||||
state State
|
||||
|
||||
l sync.Mutex
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// New returns a new Stream for the given gumble Client and Source.
|
||||
func New(client *gumble.Client, source Source) *Stream {
|
||||
return &Stream{
|
||||
client: client,
|
||||
Volume: 1.0,
|
||||
Source: source,
|
||||
Command: "ffmpeg",
|
||||
pause: make(chan struct{}),
|
||||
state: StateInitial,
|
||||
}
|
||||
}
|
||||
|
||||
// Play begins playing
|
||||
func (s *Stream) Play() error {
|
||||
s.l.Lock()
|
||||
defer s.l.Unlock()
|
||||
|
||||
switch s.state {
|
||||
case StatePaused:
|
||||
s.state = StatePlaying
|
||||
go s.process()
|
||||
return nil
|
||||
case StatePlaying:
|
||||
return errors.New("gumbleffmpeg: stream already playing")
|
||||
case StateStopped:
|
||||
return errors.New("gumbleffmpeg: stream has stopped")
|
||||
}
|
||||
|
||||
// fresh stream
|
||||
if s.Source == nil {
|
||||
return errors.New("gumbleffmpeg: nil source")
|
||||
}
|
||||
|
||||
args := s.Source.arguments()
|
||||
if s.Offset > 0 {
|
||||
args = append([]string{"-ss", strconv.FormatFloat(s.Offset.Seconds(), 'f', -1, 64)}, args...)
|
||||
}
|
||||
args = append(args, "-ac", strconv.Itoa(gumble.AudioChannels), "-ar", strconv.Itoa(gumble.AudioSampleRate), "-f", "s16le", "-")
|
||||
cmd := exec.Command(s.Command, args...)
|
||||
var err error
|
||||
s.pipe, err = cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Source.start(cmd); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
s.Source.done()
|
||||
return err
|
||||
}
|
||||
s.wg.Add(1)
|
||||
s.cmd = cmd
|
||||
s.state = StatePlaying
|
||||
go s.process()
|
||||
return nil
|
||||
}
|
||||
|
||||
// State returns the state of the stream.
|
||||
func (s *Stream) State() State {
|
||||
s.l.Lock()
|
||||
defer s.l.Unlock()
|
||||
return s.state
|
||||
}
|
||||
|
||||
// Pause pauses a playing stream.
|
||||
func (s *Stream) Pause() error {
|
||||
s.l.Lock()
|
||||
if s.state != StatePlaying {
|
||||
s.l.Unlock()
|
||||
return errors.New("gumbleffmpeg: stream is not playing")
|
||||
}
|
||||
s.state = StatePaused
|
||||
s.l.Unlock()
|
||||
s.pause <- struct{}{}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop stops the stream.
|
||||
func (s *Stream) Stop() error {
|
||||
s.l.Lock()
|
||||
switch s.state {
|
||||
case StateStopped, StateInitial:
|
||||
s.l.Unlock()
|
||||
return errors.New("gumbleffmpeg: stream is not playing nor paused")
|
||||
}
|
||||
s.cleanup()
|
||||
s.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Wait returns once the stream has stopped playing.
|
||||
func (s *Stream) Wait() {
|
||||
s.wg.Wait()
|
||||
}
|
||||
|
||||
// Elapsed returns the amount of audio that has been played by the stream.
|
||||
func (s *Stream) Elapsed() time.Duration {
|
||||
return time.Duration(atomic.LoadInt64(&s.elapsed))
|
||||
}
|
||||
|
||||
func (s *Stream) process() {
|
||||
// s.state has been set to StatePlaying
|
||||
|
||||
interval := s.client.Config.AudioInterval
|
||||
frameSize := s.client.Config.AudioFrameSize()
|
||||
|
||||
byteBuffer := make([]byte, frameSize*2)
|
||||
|
||||
outgoing := s.client.AudioOutgoing()
|
||||
defer close(outgoing)
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-s.pause:
|
||||
return
|
||||
case <-ticker.C:
|
||||
if _, err := io.ReadFull(s.pipe, byteBuffer); err != nil {
|
||||
s.l.Lock()
|
||||
s.cleanup()
|
||||
return
|
||||
}
|
||||
int16Buffer := make([]int16, frameSize)
|
||||
for i := range int16Buffer {
|
||||
float := float32(int16(binary.LittleEndian.Uint16(byteBuffer[i*2 : (i+1)*2])))
|
||||
int16Buffer[i] = int16(s.Volume * float)
|
||||
}
|
||||
atomic.AddInt64(&s.elapsed, int64(interval))
|
||||
outgoing <- gumble.AudioBuffer(int16Buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Stream) cleanup() {
|
||||
defer s.l.Unlock()
|
||||
// s.l has been acquired
|
||||
if s.state == StateStopped {
|
||||
return
|
||||
}
|
||||
s.cmd.Process.Kill()
|
||||
s.cmd.Wait()
|
||||
s.Source.done()
|
||||
for len(s.pause) > 0 {
|
||||
<-s.pause
|
||||
}
|
||||
s.state = StateStopped
|
||||
s.wg.Done()
|
||||
}
|
300
gumble/gumbleopenal/stream.go
Normal file
300
gumble/gumbleopenal/stream.go
Normal file
@ -0,0 +1,300 @@
|
||||
package gumbleopenal
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"os/exec"
|
||||
"time"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
"git.2mb.codes/~cmb/go-openal/openal"
|
||||
)
|
||||
|
||||
const (
|
||||
maxBufferSize = 11520 // Max frame size (2880) * bytes per stereo sample (4)
|
||||
)
|
||||
|
||||
var (
|
||||
ErrState = errors.New("gumbleopenal: invalid state")
|
||||
ErrMic = errors.New("gumbleopenal: microphone disconnected or misconfigured")
|
||||
ErrInputDevice = errors.New("gumbleopenal: invalid input device or parameters")
|
||||
ErrOutputDevice = errors.New("gumbleopenal: invalid output device or parameters")
|
||||
)
|
||||
|
||||
func beep() {
|
||||
cmd := exec.Command("beep")
|
||||
cmdout, err := cmd.Output()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if cmdout != nil {
|
||||
}
|
||||
}
|
||||
|
||||
type Stream struct {
|
||||
client *gumble.Client
|
||||
link gumble.Detacher
|
||||
|
||||
deviceSource *openal.CaptureDevice
|
||||
sourceFrameSize int
|
||||
micVolume float32
|
||||
sourceStop chan bool
|
||||
|
||||
deviceSink *openal.Device
|
||||
contextSink *openal.Context
|
||||
}
|
||||
|
||||
func New(client *gumble.Client, inputDevice *string, outputDevice *string, test bool) (*Stream, error) {
|
||||
frmsz := 480
|
||||
if !test {
|
||||
frmsz = client.Config.AudioFrameSize()
|
||||
}
|
||||
|
||||
// Always use mono for input device
|
||||
idev := openal.CaptureOpenDevice(*inputDevice, gumble.AudioSampleRate, openal.FormatMono16, uint32(frmsz))
|
||||
if idev == nil {
|
||||
return nil, ErrInputDevice
|
||||
}
|
||||
|
||||
odev := openal.OpenDevice(*outputDevice)
|
||||
if odev == nil {
|
||||
idev.CaptureCloseDevice()
|
||||
return nil, ErrOutputDevice
|
||||
}
|
||||
|
||||
if test {
|
||||
idev.CaptureCloseDevice()
|
||||
odev.CloseDevice()
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
s := &Stream{
|
||||
client: client,
|
||||
sourceFrameSize: frmsz,
|
||||
micVolume: 1.0,
|
||||
}
|
||||
|
||||
s.deviceSource = idev
|
||||
if s.deviceSource == nil {
|
||||
return nil, ErrInputDevice
|
||||
}
|
||||
|
||||
s.deviceSink = odev
|
||||
if s.deviceSink == nil {
|
||||
return nil, ErrOutputDevice
|
||||
}
|
||||
s.contextSink = s.deviceSink.CreateContext()
|
||||
if s.contextSink == nil {
|
||||
s.Destroy()
|
||||
return nil, ErrOutputDevice
|
||||
}
|
||||
s.contextSink.Activate()
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Stream) AttachStream(client *gumble.Client) {
|
||||
s.link = client.Config.AttachAudio(s)
|
||||
}
|
||||
|
||||
func (s *Stream) Destroy() {
|
||||
if s.link != nil {
|
||||
s.link.Detach()
|
||||
}
|
||||
if s.deviceSource != nil {
|
||||
s.StopSource()
|
||||
s.deviceSource.CaptureCloseDevice()
|
||||
s.deviceSource = nil
|
||||
}
|
||||
if s.deviceSink != nil {
|
||||
s.contextSink.Destroy()
|
||||
s.deviceSink.CloseDevice()
|
||||
s.contextSink = nil
|
||||
s.deviceSink = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Stream) StartSource(inputDevice *string) error {
|
||||
if s.sourceStop != nil {
|
||||
return ErrState
|
||||
}
|
||||
if s.deviceSource == nil {
|
||||
return ErrMic
|
||||
}
|
||||
s.deviceSource.CaptureStart()
|
||||
s.sourceStop = make(chan bool)
|
||||
go s.sourceRoutine(inputDevice)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Stream) StopSource() error {
|
||||
if s.deviceSource == nil {
|
||||
return ErrMic
|
||||
}
|
||||
s.deviceSource.CaptureStop()
|
||||
if s.sourceStop == nil {
|
||||
return ErrState
|
||||
}
|
||||
close(s.sourceStop)
|
||||
s.sourceStop = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Stream) GetMicVolume() float32 {
|
||||
return s.micVolume
|
||||
}
|
||||
|
||||
func (s *Stream) SetMicVolume(change float32, relative bool) {
|
||||
var val float32
|
||||
if relative {
|
||||
val = s.GetMicVolume() + change
|
||||
} else {
|
||||
val = change
|
||||
}
|
||||
if val >= 1 {
|
||||
val = 1.0
|
||||
}
|
||||
if val <= 0 {
|
||||
val = 0
|
||||
}
|
||||
s.micVolume = val
|
||||
}
|
||||
|
||||
func (s *Stream) OnAudioStream(e *gumble.AudioStreamEvent) {
|
||||
go func(e *gumble.AudioStreamEvent) {
|
||||
var source = openal.NewSource()
|
||||
e.User.AudioSource = &source
|
||||
e.User.AudioSource.SetGain(e.User.Volume)
|
||||
|
||||
bufferCount := e.Client.Config.Buffers
|
||||
if bufferCount < 64 {
|
||||
bufferCount = 64
|
||||
}
|
||||
emptyBufs := openal.NewBuffers(bufferCount)
|
||||
|
||||
reclaim := func() {
|
||||
if n := source.BuffersProcessed(); n > 0 {
|
||||
reclaimedBufs := make(openal.Buffers, n)
|
||||
source.UnqueueBuffers(reclaimedBufs)
|
||||
emptyBufs = append(emptyBufs, reclaimedBufs...)
|
||||
}
|
||||
}
|
||||
|
||||
var raw [maxBufferSize]byte
|
||||
|
||||
for packet := range e.C {
|
||||
var boost uint16 = uint16(1)
|
||||
samples := len(packet.AudioBuffer)
|
||||
if samples > cap(raw)/2 {
|
||||
continue
|
||||
}
|
||||
|
||||
boost = e.User.Boost
|
||||
|
||||
// Check if sample count suggests stereo data
|
||||
// If it's not a multiple of 2, it must be mono
|
||||
// If it's more than standard frameSize, it's likely stereo
|
||||
isStereo := samples > gumble.AudioDefaultFrameSize && samples%2 == 0
|
||||
format := openal.FormatMono16
|
||||
if isStereo {
|
||||
format = openal.FormatStereo16
|
||||
// Adjust samples to represent stereo frame count
|
||||
samples = samples / 2
|
||||
}
|
||||
|
||||
// Process samples
|
||||
rawPtr := 0
|
||||
if isStereo {
|
||||
// Process stereo samples as pairs
|
||||
for i := 0; i < samples*2; i += 2 {
|
||||
// Process left channel
|
||||
sample := packet.AudioBuffer[i]
|
||||
if boost > 1 {
|
||||
sample = int16((int32(sample) * int32(boost)))
|
||||
}
|
||||
binary.LittleEndian.PutUint16(raw[rawPtr:], uint16(sample))
|
||||
rawPtr += 2
|
||||
|
||||
// Process right channel
|
||||
sample = packet.AudioBuffer[i+1]
|
||||
if boost > 1 {
|
||||
sample = int16((int32(sample) * int32(boost)))
|
||||
}
|
||||
binary.LittleEndian.PutUint16(raw[rawPtr:], uint16(sample))
|
||||
rawPtr += 2
|
||||
}
|
||||
} else {
|
||||
// Process mono samples
|
||||
for i := 0; i < samples; i++ {
|
||||
sample := packet.AudioBuffer[i]
|
||||
if boost > 1 {
|
||||
sample = int16((int32(sample) * int32(boost)))
|
||||
}
|
||||
binary.LittleEndian.PutUint16(raw[rawPtr:], uint16(sample))
|
||||
rawPtr += 2
|
||||
}
|
||||
}
|
||||
|
||||
reclaim()
|
||||
if len(emptyBufs) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
last := len(emptyBufs) - 1
|
||||
buffer := emptyBufs[last]
|
||||
emptyBufs = emptyBufs[:last]
|
||||
|
||||
// Set buffer data with correct format
|
||||
buffer.SetData(format, raw[:rawPtr], gumble.AudioSampleRate)
|
||||
source.QueueBuffer(buffer)
|
||||
|
||||
if source.State() != openal.Playing {
|
||||
source.Play()
|
||||
}
|
||||
}
|
||||
reclaim()
|
||||
emptyBufs.Delete()
|
||||
source.Delete()
|
||||
}(e)
|
||||
}
|
||||
|
||||
func (s *Stream) sourceRoutine(inputDevice *string) {
|
||||
interval := s.client.Config.AudioInterval
|
||||
frameSize := s.client.Config.AudioFrameSize()
|
||||
|
||||
if frameSize != s.sourceFrameSize {
|
||||
s.deviceSource.CaptureCloseDevice()
|
||||
s.sourceFrameSize = frameSize
|
||||
// Always use mono for input
|
||||
s.deviceSource = openal.CaptureOpenDevice(*inputDevice, gumble.AudioSampleRate, openal.FormatMono16, uint32(s.sourceFrameSize))
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
stop := s.sourceStop
|
||||
|
||||
outgoing := s.client.AudioOutgoing()
|
||||
defer close(outgoing)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
buff := s.deviceSource.CaptureSamples(uint32(frameSize))
|
||||
if len(buff) != frameSize*2 {
|
||||
continue
|
||||
}
|
||||
int16Buffer := make([]int16, frameSize)
|
||||
for i := range int16Buffer {
|
||||
sample := int16(binary.LittleEndian.Uint16(buff[i*2:]))
|
||||
if s.micVolume != 1.0 {
|
||||
sample = int16(float32(sample) * s.micVolume)
|
||||
}
|
||||
int16Buffer[i] = sample
|
||||
}
|
||||
outgoing <- gumble.AudioBuffer(int16Buffer)
|
||||
}
|
||||
}
|
||||
}
|
55
gumble/gumbleutil/acl.go
Normal file
55
gumble/gumbleutil/acl.go
Normal file
@ -0,0 +1,55 @@
|
||||
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
)
|
||||
|
||||
// UserGroups fetches the group names the given user belongs to in the given
|
||||
// channel. The slice of group names sent via the returned channel. On error,
|
||||
// the returned channel is closed without without sending a slice.
|
||||
func UserGroups(client *gumble.Client, user *gumble.User, channel *gumble.Channel) <-chan []string {
|
||||
ch := make(chan []string)
|
||||
|
||||
if !user.IsRegistered() {
|
||||
close(ch)
|
||||
return ch
|
||||
}
|
||||
|
||||
var detacher gumble.Detacher
|
||||
listener := Listener{
|
||||
Disconnect: func(e *gumble.DisconnectEvent) {
|
||||
detacher.Detach()
|
||||
close(ch)
|
||||
},
|
||||
ChannelChange: func(e *gumble.ChannelChangeEvent) {
|
||||
if e.Channel == channel && e.Type.Has(gumble.ChannelChangeRemoved) {
|
||||
detacher.Detach()
|
||||
close(ch)
|
||||
}
|
||||
},
|
||||
PermissionDenied: func(e *gumble.PermissionDeniedEvent) {
|
||||
if e.Channel == channel && e.Type == gumble.PermissionDeniedPermission && (e.Permission&gumble.PermissionWrite) != 0 {
|
||||
detacher.Detach()
|
||||
close(ch)
|
||||
}
|
||||
},
|
||||
ACL: func(e *gumble.ACLEvent) {
|
||||
if e.ACL.Channel != channel {
|
||||
return
|
||||
}
|
||||
var names []string
|
||||
for _, g := range e.ACL.Groups {
|
||||
if (g.UsersAdd[user.UserID] != nil || g.UsersInherited[user.UserID] != nil) && g.UsersRemove[user.UserID] == nil {
|
||||
names = append(names, g.Name)
|
||||
}
|
||||
}
|
||||
detacher.Detach()
|
||||
ch <- names
|
||||
close(ch)
|
||||
},
|
||||
}
|
||||
detacher = client.Config.Attach(&listener)
|
||||
channel.RequestACL()
|
||||
|
||||
return ch
|
||||
}
|
27
gumble/gumbleutil/bitrate.go
Normal file
27
gumble/gumbleutil/bitrate.go
Normal file
@ -0,0 +1,27 @@
|
||||
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
)
|
||||
|
||||
var autoBitrate = &Listener{
|
||||
Connect: func(e *gumble.ConnectEvent) {
|
||||
if e.MaximumBitrate != nil {
|
||||
const safety = 5
|
||||
interval := e.Client.Config.AudioInterval
|
||||
dataBytes := (*e.MaximumBitrate / (8 * (int(time.Second/interval) + safety))) - 32 - 10
|
||||
|
||||
e.Client.Config.AudioDataBytes = dataBytes
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
// AutoBitrate is a gumble.EventListener that automatically sets the client's
|
||||
// AudioDataBytes to suitable value, based on the server's bitrate.
|
||||
var AutoBitrate gumble.EventListener
|
||||
|
||||
func init() {
|
||||
AutoBitrate = autoBitrate
|
||||
}
|
18
gumble/gumbleutil/channel.go
Normal file
18
gumble/gumbleutil/channel.go
Normal file
@ -0,0 +1,18 @@
|
||||
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
)
|
||||
|
||||
// ChannelPath returns a slice of channel names, starting from the root channel
|
||||
// to the given channel.
|
||||
func ChannelPath(channel *gumble.Channel) []string {
|
||||
var pieces []string
|
||||
for ; channel != nil; channel = channel.Parent {
|
||||
pieces = append(pieces, channel.Name)
|
||||
}
|
||||
for i := 0; i < (len(pieces) / 2); i++ {
|
||||
pieces[len(pieces)-1-i], pieces[i] = pieces[i], pieces[len(pieces)-1-i]
|
||||
}
|
||||
return pieces
|
||||
}
|
2
gumble/gumbleutil/doc.go
Normal file
2
gumble/gumbleutil/doc.go
Normal file
@ -0,0 +1,2 @@
|
||||
// Package gumbleutil provides extras that can make working with gumble easier.
|
||||
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
|
100
gumble/gumbleutil/listener.go
Normal file
100
gumble/gumbleutil/listener.go
Normal file
@ -0,0 +1,100 @@
|
||||
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
)
|
||||
|
||||
// Listener is a struct that implements the gumble.EventListener interface. The
|
||||
// corresponding event function in the struct is called if it is non-nil.
|
||||
type Listener struct {
|
||||
Connect func(e *gumble.ConnectEvent)
|
||||
Disconnect func(e *gumble.DisconnectEvent)
|
||||
TextMessage func(e *gumble.TextMessageEvent)
|
||||
UserChange func(e *gumble.UserChangeEvent)
|
||||
ChannelChange func(e *gumble.ChannelChangeEvent)
|
||||
PermissionDenied func(e *gumble.PermissionDeniedEvent)
|
||||
UserList func(e *gumble.UserListEvent)
|
||||
ACL func(e *gumble.ACLEvent)
|
||||
BanList func(e *gumble.BanListEvent)
|
||||
ContextActionChange func(e *gumble.ContextActionChangeEvent)
|
||||
ServerConfig func(e *gumble.ServerConfigEvent)
|
||||
}
|
||||
|
||||
var _ gumble.EventListener = (*Listener)(nil)
|
||||
|
||||
// OnConnect implements gumble.EventListener.OnConnect.
|
||||
func (l Listener) OnConnect(e *gumble.ConnectEvent) {
|
||||
if l.Connect != nil {
|
||||
l.Connect(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnDisconnect implements gumble.EventListener.OnDisconnect.
|
||||
func (l Listener) OnDisconnect(e *gumble.DisconnectEvent) {
|
||||
if l.Disconnect != nil {
|
||||
l.Disconnect(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnTextMessage implements gumble.EventListener.OnTextMessage.
|
||||
func (l Listener) OnTextMessage(e *gumble.TextMessageEvent) {
|
||||
if l.TextMessage != nil {
|
||||
l.TextMessage(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnUserChange implements gumble.EventListener.OnUserChange.
|
||||
func (l Listener) OnUserChange(e *gumble.UserChangeEvent) {
|
||||
if l.UserChange != nil {
|
||||
l.UserChange(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnChannelChange implements gumble.EventListener.OnChannelChange.
|
||||
func (l Listener) OnChannelChange(e *gumble.ChannelChangeEvent) {
|
||||
if l.ChannelChange != nil {
|
||||
l.ChannelChange(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied.
|
||||
func (l Listener) OnPermissionDenied(e *gumble.PermissionDeniedEvent) {
|
||||
if l.PermissionDenied != nil {
|
||||
l.PermissionDenied(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnUserList implements gumble.EventListener.OnUserList.
|
||||
func (l Listener) OnUserList(e *gumble.UserListEvent) {
|
||||
if l.UserList != nil {
|
||||
l.UserList(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnACL implements gumble.EventListener.OnACL.
|
||||
func (l Listener) OnACL(e *gumble.ACLEvent) {
|
||||
if l.ACL != nil {
|
||||
l.ACL(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnBanList implements gumble.EventListener.OnBanList.
|
||||
func (l Listener) OnBanList(e *gumble.BanListEvent) {
|
||||
if l.BanList != nil {
|
||||
l.BanList(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnContextActionChange implements gumble.EventListener.OnContextActionChange.
|
||||
func (l Listener) OnContextActionChange(e *gumble.ContextActionChangeEvent) {
|
||||
if l.ContextActionChange != nil {
|
||||
l.ContextActionChange(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnServerConfig implements gumble.EventListener.OnServerConfig.
|
||||
func (l Listener) OnServerConfig(e *gumble.ServerConfigEvent) {
|
||||
if l.ServerConfig != nil {
|
||||
l.ServerConfig(e)
|
||||
}
|
||||
}
|
80
gumble/gumbleutil/listenerfunc.go
Normal file
80
gumble/gumbleutil/listenerfunc.go
Normal file
@ -0,0 +1,80 @@
|
||||
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
)
|
||||
|
||||
// ListenerFunc is a single listener function that implements the
|
||||
// gumble.EventListener interface. This is useful if you would like to use a
|
||||
// type-switch for handling the different event types.
|
||||
//
|
||||
// Example:
|
||||
// handler := func(e interface{}) {
|
||||
// switch e.(type) {
|
||||
// case *gumble.ConnectEvent:
|
||||
// println("Connected")
|
||||
// case *gumble.DisconnectEvent:
|
||||
// println("Disconnected")
|
||||
// // ...
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// client.Attach(gumbleutil.ListenerFunc(handler))
|
||||
type ListenerFunc func(e interface{})
|
||||
|
||||
var _ gumble.EventListener = ListenerFunc(nil)
|
||||
|
||||
// OnConnect implements gumble.EventListener.OnConnect.
|
||||
func (lf ListenerFunc) OnConnect(e *gumble.ConnectEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnDisconnect implements gumble.EventListener.OnDisconnect.
|
||||
func (lf ListenerFunc) OnDisconnect(e *gumble.DisconnectEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnTextMessage implements gumble.EventListener.OnTextMessage.
|
||||
func (lf ListenerFunc) OnTextMessage(e *gumble.TextMessageEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnUserChange implements gumble.EventListener.OnUserChange.
|
||||
func (lf ListenerFunc) OnUserChange(e *gumble.UserChangeEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnChannelChange implements gumble.EventListener.OnChannelChange.
|
||||
func (lf ListenerFunc) OnChannelChange(e *gumble.ChannelChangeEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied.
|
||||
func (lf ListenerFunc) OnPermissionDenied(e *gumble.PermissionDeniedEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnUserList implements gumble.EventListener.OnUserList.
|
||||
func (lf ListenerFunc) OnUserList(e *gumble.UserListEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnACL implements gumble.EventListener.OnACL.
|
||||
func (lf ListenerFunc) OnACL(e *gumble.ACLEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnBanList implements gumble.EventListener.OnBanList.
|
||||
func (lf ListenerFunc) OnBanList(e *gumble.BanListEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnContextActionChange implements gumble.EventListener.OnContextActionChange.
|
||||
func (lf ListenerFunc) OnContextActionChange(e *gumble.ContextActionChangeEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnServerConfig implements gumble.EventListener.OnServerConfig.
|
||||
func (lf ListenerFunc) OnServerConfig(e *gumble.ServerConfigEvent) {
|
||||
lf(e)
|
||||
}
|
79
gumble/gumbleutil/main.go
Normal file
79
gumble/gumbleutil/main.go
Normal file
@ -0,0 +1,79 @@
|
||||
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
)
|
||||
|
||||
// Main aids in the creation of a basic command line gumble bot. It accepts the
|
||||
// following flag arguments:
|
||||
// --server
|
||||
// --username
|
||||
// --password
|
||||
// --insecure
|
||||
// --certificate
|
||||
// --key
|
||||
func Main(listeners ...gumble.EventListener) {
|
||||
server := flag.String("server", "localhost:64738", "Mumble server address")
|
||||
username := flag.String("username", "gumble-bot", "client username")
|
||||
password := flag.String("password", "", "client password")
|
||||
insecure := flag.Bool("insecure", false, "skip server certificate verification")
|
||||
certificateFile := flag.String("certificate", "", "user certificate file (PEM)")
|
||||
keyFile := flag.String("key", "", "user certificate key file (PEM)")
|
||||
|
||||
if !flag.Parsed() {
|
||||
flag.Parse()
|
||||
}
|
||||
|
||||
host, port, err := net.SplitHostPort(*server)
|
||||
if err != nil {
|
||||
host = *server
|
||||
port = strconv.Itoa(gumble.DefaultPort)
|
||||
}
|
||||
|
||||
keepAlive := make(chan bool)
|
||||
|
||||
config := gumble.NewConfig()
|
||||
config.Username = *username
|
||||
config.Password = *password
|
||||
config.Address = net.JoinHostPort(host, port)
|
||||
|
||||
var tlsConfig tls.Config
|
||||
|
||||
if *insecure {
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
}
|
||||
if *certificateFile != "" {
|
||||
if *keyFile == "" {
|
||||
keyFile = certificateFile
|
||||
}
|
||||
if certificate, err := tls.LoadX509KeyPair(*certificateFile, *keyFile); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
|
||||
os.Exit(1)
|
||||
} else {
|
||||
tlsConfig.Certificates = append(tlsConfig.Certificates, certificate)
|
||||
}
|
||||
}
|
||||
config.Attach(AutoBitrate)
|
||||
for _, listener := range listeners {
|
||||
config.Attach(listener)
|
||||
}
|
||||
config.Attach(Listener{
|
||||
Disconnect: func(e *gumble.DisconnectEvent) {
|
||||
keepAlive <- true
|
||||
},
|
||||
})
|
||||
_, err = gumble.DialWithDialer(new(net.Dialer), config, &tlsConfig)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
<-keepAlive
|
||||
}
|
45
gumble/gumbleutil/textmessage.go
Normal file
45
gumble/gumbleutil/textmessage.go
Normal file
@ -0,0 +1,45 @@
|
||||
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"strings"
|
||||
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
)
|
||||
|
||||
// PlainText returns the Message string without HTML tags or entities.
|
||||
func PlainText(tm *gumble.TextMessage) string {
|
||||
d := xml.NewDecoder(strings.NewReader(tm.Message))
|
||||
d.Strict = false
|
||||
d.AutoClose = xml.HTMLAutoClose
|
||||
d.Entity = xml.HTMLEntity
|
||||
|
||||
var b bytes.Buffer
|
||||
newline := false
|
||||
for {
|
||||
t, _ := d.Token()
|
||||
if t == nil {
|
||||
break
|
||||
}
|
||||
switch node := t.(type) {
|
||||
case xml.CharData:
|
||||
if len(node) > 0 {
|
||||
b.Write(node)
|
||||
newline = false
|
||||
}
|
||||
case xml.StartElement:
|
||||
switch node.Name.Local {
|
||||
case "address", "article", "aside", "audio", "blockquote", "canvas", "dd", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "noscript", "ol", "output", "p", "pre", "section", "table", "tfoot", "ul", "video":
|
||||
if !newline {
|
||||
b.WriteByte('\n')
|
||||
newline = true
|
||||
}
|
||||
case "br":
|
||||
b.WriteByte('\n')
|
||||
newline = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
92
gumble/opus/opus.go
Normal file
92
gumble/opus/opus.go
Normal file
@ -0,0 +1,92 @@
|
||||
package opus
|
||||
|
||||
import (
|
||||
"git.2mb.codes/~cmb/barnard/gumble/gumble"
|
||||
"github.com/hraban/opus"
|
||||
)
|
||||
|
||||
var Codec gumble.AudioCodec
|
||||
|
||||
const (
|
||||
ID = 4
|
||||
VoiceChannels = 1 // Force mono for voice transmission
|
||||
)
|
||||
|
||||
func init() {
|
||||
Codec = &generator{}
|
||||
gumble.RegisterAudioCodec(4, Codec)
|
||||
}
|
||||
|
||||
// generator
|
||||
type generator struct {
|
||||
}
|
||||
|
||||
func (*generator) ID() int {
|
||||
return ID
|
||||
}
|
||||
|
||||
func (*generator) NewEncoder() gumble.AudioEncoder {
|
||||
// Force mono for voice transmission
|
||||
e, _ := opus.NewEncoder(gumble.AudioSampleRate, VoiceChannels, opus.AppVoIP)
|
||||
e.SetBitrateToMax()
|
||||
return &Encoder{
|
||||
e,
|
||||
}
|
||||
}
|
||||
|
||||
func (*generator) NewDecoder() gumble.AudioDecoder {
|
||||
// Create decoder with stereo support
|
||||
d, _ := opus.NewDecoder(gumble.AudioSampleRate, gumble.AudioChannels)
|
||||
return &Decoder{
|
||||
d,
|
||||
}
|
||||
}
|
||||
|
||||
// encoder
|
||||
type Encoder struct {
|
||||
*opus.Encoder
|
||||
}
|
||||
|
||||
func (*Encoder) ID() int {
|
||||
return ID
|
||||
}
|
||||
|
||||
func (e *Encoder) Encode(pcm []int16, _, maxDataBytes int) ([]byte, error) {
|
||||
buf := make([]byte, maxDataBytes)
|
||||
n, err := e.Encoder.Encode(pcm, buf)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
return buf[:n], nil
|
||||
}
|
||||
|
||||
func (e *Encoder) Reset() {
|
||||
e.Encoder.Reset()
|
||||
}
|
||||
|
||||
// decoder
|
||||
type Decoder struct {
|
||||
*opus.Decoder
|
||||
}
|
||||
|
||||
func (*Decoder) ID() int {
|
||||
return ID
|
||||
}
|
||||
|
||||
func (d *Decoder) Decode(data []byte, frameSize int) ([]int16, error) {
|
||||
// Allocate buffer for stereo - frameSize is per channel
|
||||
pcm := make([]int16, frameSize * gumble.AudioChannels)
|
||||
|
||||
// Decode the data
|
||||
n, err := d.Decoder.Decode(data, pcm)
|
||||
if err != nil {
|
||||
return []int16{}, err
|
||||
}
|
||||
|
||||
// Return the exact number of samples decoded
|
||||
return pcm[:n * gumble.AudioChannels], nil
|
||||
}
|
||||
|
||||
func (d *Decoder) Reset() {
|
||||
d.Decoder.Reset()
|
||||
}
|
Reference in New Issue
Block a user