master
blallo 2020-10-22 00:11:59 +02:00
commit 1f303b8819
Signed by: blallo
GPG Key ID: 0CBE577C9B72DC3F
17 changed files with 711 additions and 0 deletions

23
Dockerfile 100644
View File

@ -0,0 +1,23 @@
FROM golang:1.15 AS builder
ENV DEBIAN_FRONTEND=noninteractive
COPY ./broadcast /broadcast
WORKDIR /broadcast
RUN apt-get update \
&& apt-get install -y libmp3lame-dev \
&& go get -u ./... \
&& rm -rf /var/lib/apt/lists/*
FROM debian:stable
ENV DEBIAN_FRONTEND=noninteractive
COPY --from=builder /go/bin/broadcast /srv/
COPY ./entrypoint /entrypoint
WORKDIR /srv
RUN apt-get update \
&& apt-get install -y libmp3lame0 \
&& rm -rf /var/lib/apt/lists/*
ENTRYPOINT ["/entrypoint"]

19
README.md 100644
View File

@ -0,0 +1,19 @@
Broadcast
=========
## Build
```
docker-compose build
```
When you change the code, run it again.
## Run
```
docker-compose up
```
You can connect to a local instance of mumble on `localhost:64738` and to a
local instance of icecast2 on `localhost:8000`.

1
broadcast/external/goicy vendored 160000

@ -0,0 +1 @@
Subproject commit f76a17f16bb08d8ca7a94cee2b76f6ab8c34a89b

3
broadcast/go.mod 100644
View File

@ -0,0 +1,3 @@
module git.abbiamoundominio.org/unit/broadcast
go 1.15

104
broadcast/main.go 100644
View File

@ -0,0 +1,104 @@
package main
import (
"io"
"os"
"time"
"crypto/tls"
"fmt"
"github.com/sunicy/go-lame"
"net"
"layeh.com/gumble/gumble"
"layeh.com/gumble/gumbleutil"
_ "layeh.com/gumble/opus" // it's a good idea to load this: botamusique crashes because of a CodecNotSupportedError EXception
)
func audiolistener(e *gumble.AudioStreamEvent) {
}
type AudioListener struct {
name string
}
func (audiolistener AudioListener) OnAudioStream(e *gumble.AudioStreamEvent) {
fmt.Printf("Received AudioStreamEvent from %s\n", e.User.Name)
// fmt.Printf("%+v\n", e.User.Name)
// fmt.Printf(audio.Sender.Name)
go ReadPacket(e.C)
}
func PcmToMp3(pcmFileName, mp3FileName string) {
pcmFile, _ := os.OpenFile(pcmFileName, os.O_RDONLY, 0555)
mp3File, _ := os.OpenFile(mp3FileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
defer mp3File.Close()
wr, err := lame.NewWriter(mp3File)
if err != nil {
panic("cannot create lame writer, err: " + err.Error())
}
io.Copy(wr, pcmFile)
wr.Close()
}
type AudioEncoder struct {
}
// func (e AudioEncoder) Encode(pcm []int16, mframeSize, maxDataBytes int) ([]byte, error) {
// TODO: WRITE THIS ENCODER AND WRITE THE OUTPUTS TO SOME FILE (RECORDING)
// return []byte, nil
// }
func (e AudioEncoder) ID() {
}
func (e AudioEncoder) Reset() {
}
func ReadPacket(ch <-chan *gumble.AudioPacket) { // receive-only channel
pcm_out, _ := os.OpenFile("pcm_out.raw", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
defer pcm_out.Close()
//func (f *File) Write(b []byte) (n int, err error)
for packet := range ch {
fmt.Println(packet.Sender.Name)
// fmt.Printf("%:+v\n", packet)
// pkt := <-ch
// buf := pkt.AudioBuffer
// pcm_out.Write(UnsafeCastInt16sToBytes(buf))
}
}
func main() {
config := gumble.NewConfig()
config.Username = "bon-bot"
config.Attach(gumbleutil.Listener{
TextMessage: func(e *gumble.TextMessageEvent) {
fmt.Printf("Received text message: %s\n", e.Message)
},
})
l := AudioListener{name: "Eventprinter"}
config.AttachAudio(l)
client, err := gumble.DialWithDialer(&net.Dialer{}, "mumble:64738", config, &tls.Config{InsecureSkipVerify: true}) // TODO: fix cert or make it an option
if err != nil {
panic(err)
}
// var message TextMessage
//gumble.AudioListener
fmt.Printf("Channels:\n")
for idx, channel := range client.Channels {
fmt.Printf("\t%d - %s\n", idx, channel.Name)
}
for {
time.Sleep(1 * time.Second)
}
}

View File

@ -0,0 +1,199 @@
# Murmur configuration file.
#
# General notes:
# * Settings in this file are default settings and many of them can be overridden
# with virtual server specific configuration via the Ice or DBus interface.
# * Due to the way this configuration file is read some rules have to be
# followed when specifying variable values (as in variable = value):
# * Make sure to quote the value when using commas in strings or passwords.
# NOT variable = super,secret BUT variable = "super,secret"
# * Make sure to escape special characters like '\' or '"' correctly
# NOT variable = """ BUT variable = "\""
# NOT regex = \w* BUT regex = \\w*
# Path to database. If blank, will search for
# murmur.sqlite in default locations or create it if not found.
database=/data/mumble-server.sqlite
# If you wish to use something other than SQLite, you'll need to set the name
# of the database above, and also uncomment the below.
# Sticking with SQLite is strongly recommended, as it's the most well tested
# and by far the fastest solution.
#
#dbDriver=QMYSQL
#dbUsername=
#dbPassword=
#dbHost=
#dbPort=
#dbPrefix=murmur_
#dbOpts=
# Murmur defaults to not using D-Bus. If you wish to use dbus, which is one of the
# RPC methods available in Murmur, please specify so here.
#
dbus=system
# Alternate D-Bus service name. Only use if you are running distinct
# murmurd processes connected to the same D-Bus daemon.
#dbusservice=net.sourceforge.mumble.murmur
# If you want to use ZeroC Ice to communicate with Murmur, you need
# to specify the endpoint to use. Since there is no authentication
# with ICE, you should only use it if you trust all the users who have
# shell access to your machine.
# Please see the ICE documentation on how to specify endpoints.
ice="tcp -h 127.0.0.1 -p 6502"
# Ice primarily uses local sockets. This means anyone who has a
# user account on your machine can connect to the Ice services.
# You can set a plaintext "secret" on the Ice connection, and
# any script attempting to access must then have this secret
# (as context with name "secret").
# Access is split in read (look only) and write (modify)
# operations. Write access always includes read access,
# unless read is explicitly denied (see note below).
#
# Note that if this is uncommented and with empty content,
# access will be denied.
#icesecretread=
icesecretwrite=
# How many login attempts do we tolerate from one IP
# inside a given timeframe before we ban the connection?
# Note that this is global (shared between all virtual servers), and that
# it counts both successfull and unsuccessfull connection attempts.
# Set either Attempts or Timeframe to 0 to disable.
#autobanAttempts = 10
#autobanTimeframe = 120
#autobanTime = 300
# Specifies the file Murmur should log to. By default, Murmur
# logs to the file 'murmur.log'. If you leave this field blank
# on Unix-like systems, Murmur will force itself into foreground
# mode which logs to the console.
logfile=/data/mumble-server.log
# If set, Murmur will write its process ID to this file
# when running in daemon mode (when the -fg flag is not
# specified on the command line). Only available on
# Unix-like systems.
pidfile=/var/run/mumble-server/mumble-server.pid
# The below will be used as defaults for new configured servers.
# If you're just running one server (the default), it's easier to
# configure it here than through D-Bus or Ice.
#
# Welcome message sent to clients when they connect.
welcometext="<br />Welcome to this server running <b>Murmur</b>.<br />Enjoy your stay!<br />"
# Port to bind TCP and UDP sockets to.
port=64738
# Specific IP or hostname to bind to.
# If this is left blank (default), Murmur will bind to all available addresses.
#host=
# Password to join server.
serverpassword=
# Maximum bandwidth (in bits per second) clients are allowed
# to send speech at.
bandwidth=72000
# Maximum number of concurrent clients allowed.
users=100
# Amount of users with Opus support needed to force Opus usage, in percent.
# 0 = Always enable Opus, 100 = enable Opus if it's supported by all clients.
#opusthreshold=100
# Maximum depth of channel nesting. Note that some databases like MySQL using
# InnoDB will fail when operating on deeply nested channels.
#channelnestinglimit=10
# Regular expression used to validate channel names.
# (Note that you have to escape backslashes with \ )
#channelname=[ \\-=\\w\\#\\[\\]\\{\\}\\(\\)\\@\\|]+
# Regular expression used to validate user names.
# (Note that you have to escape backslashes with \ )
#username=[-=\\w\\[\\]\\{\\}\\(\\)\\@\\|\\.]+
# Maximum length of text messages in characters. 0 for no limit.
#textmessagelength=5000
# Maximum length of text messages in characters, with image data. 0 for no limit.
#imagemessagelength=131072
# Allow clients to use HTML in messages, user comments and channel descriptions?
#allowhtml=true
# Murmur retains the per-server log entries in an internal database which
# allows it to be accessed over D-Bus/ICE.
# How many days should such entries be kept?
# Set to 0 to keep forever, or -1 to disable logging to the DB.
#logdays=31
# To enable public server registration, the serverpassword must be blank, and
# this must all be filled out.
# The password here is used to create a registry for the server name; subsequent
# updates will need the same password. Don't lose your password.
# The URL is your own website, and only set the registerHostname for static IP
# addresses.
# Only uncomment the 'registerName' parameter if you wish to give your "Root" channel a custom name.
#
#registerName=Mumble Server
#registerPassword=secret
#registerUrl=https://www.mumble.info/
#registerHostname=
# If this option is enabled, the server will announce its presence via the
# bonjour service discovery protocol. To change the name announced by bonjour
# adjust the registerName variable.
# See http://developer.apple.com/networking/bonjour/index.html for more information
# about bonjour.
#bonjour=True
# If you have a proper SSL certificate, you can provide the filenames here.
# Otherwise, Murmur will create it's own certificate automatically.
#sslCert=
#sslKey=
# The sslCiphers option chooses the cipher suites to make available for use
# in SSL/TLS. This option is server-wide, and cannot be set on a
# per-virtual-server basis.
#
# This option is specified using OpenSSL cipher list notation (see
# https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT).
#
# It is recommended that you try your cipher string using 'openssl ciphers <string>'
# before setting it here, to get a feel for which cipher suites you will get.
#
# After setting this option, it is recommend that you inspect your Murmur log
# to ensure that Murmur is using the cipher suites that you expected it to.
#
# Note: Changing this option may impact the backwards compatibility of your
# Murmur server, and can remove the ability for older Mumble clients to be able
# to connect to it.
#sslCiphers=EECDH+AESGCM:AES256-SHA:AES128-SHA
# If Murmur is started as root, which user should it switch to?
# This option is ignored if Murmur isn't started with root privileges.
uname=mumble-server
# If this options is enabled, only clients which have a certificate are allowed
# to connect.
#certrequired=False
# If enabled, clients are sent information about the servers version and operating
# system.
#sendversion=True
# You can configure any of the configuration options for Ice here. We recommend
# leave the defaults as they are.
# Please note that this section has to be last in the configuration file.
#
[Ice]
Ice.Warn.UnknownProperties=1
Ice.MessageSizeMax=65536

View File

View File

@ -0,0 +1,6 @@
# resources
How to pass the PCM packets to icecast? Possibile solutions/resources
- just using gumbleopenal? https://github.com/layeh/gumble/blob/146f9205029b/gumbleopenal/stream.go#L80
- icecast streaming golang https://github.com/stunndard/goicy/blob/master/stream/stream.go
- converting PCM to mp3? https://github.com/xfrr/goffmpeg

33
broadcast/utils.go 100644
View File

@ -0,0 +1,33 @@
package main
import "unsafe"
import "reflect"
const BYTES_IN_INT32 = 4
const BYTES_IN_INT16 = 2
func UnsafeCaseInt32ToBytes(val int32) []byte {
hdr := reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&val)), Len: BYTES_IN_INT32, Cap: BYTES_IN_INT32}
return *(*[]byte)(unsafe.Pointer(&hdr))
}
func UnsafeCastInt32sToBytes(ints []int32) []byte {
length := len(ints) * BYTES_IN_INT32
hdr := reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&ints[0])), Len: length, Cap: length}
return *(*[]byte)(unsafe.Pointer(&hdr))
}
func UnsafeCaseInt16ToBytes(val int16) []byte {
hdr := reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&val)), Len: BYTES_IN_INT16, Cap: BYTES_IN_INT16}
return *(*[]byte)(unsafe.Pointer(&hdr))
}
func UnsafeCastInt16sToBytes(ints []int16) []byte {
length := len(ints) * BYTES_IN_INT16
hdr := reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&ints[0])), Len: length, Cap: length}
return *(*[]byte)(unsafe.Pointer(&hdr))
}

36
docker-compose.yml 100644
View File

@ -0,0 +1,36 @@
version: '3'
services:
broadcast:
image: unit/broadcast
build: .
depends_on:
- mumble
icecast:
image: infiniteproject/icecast
ports:
- "8000:80"
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000"]
interval: 30s
timeout: 1s
retries: 3
start_period: 4s
mumble:
image: coppit/mumble-server
ports:
- "64738:64738"
volumes:
- $PWD/mumble:/data
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:64738"]
interval: 30s
timeout: 1s
retries: 3
start_period: 4s

4
entrypoint 100755
View File

@ -0,0 +1,4 @@
#!/bin/bash
sleep 5
/srv/broadcast ${@}

View File

@ -0,0 +1,54 @@
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"layeh.com/gumble/gumble"
"layeh.com/gumble/gumbleffmpeg"
"layeh.com/gumble/gumbleutil"
_ "layeh.com/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) {
fmt.Printf(e.Message)
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)
}
},
})
}

Binary file not shown.

View File

@ -0,0 +1 @@
./mumble-audio-player -insecure -server zaphoda:64738 -username bitume

View File

@ -0,0 +1,199 @@
# Murmur configuration file.
#
# General notes:
# * Settings in this file are default settings and many of them can be overridden
# with virtual server specific configuration via the Ice or DBus interface.
# * Due to the way this configuration file is read some rules have to be
# followed when specifying variable values (as in variable = value):
# * Make sure to quote the value when using commas in strings or passwords.
# NOT variable = super,secret BUT variable = "super,secret"
# * Make sure to escape special characters like '\' or '"' correctly
# NOT variable = """ BUT variable = "\""
# NOT regex = \w* BUT regex = \\w*
# Path to database. If blank, will search for
# murmur.sqlite in default locations or create it if not found.
database=
# If you wish to use something other than SQLite, you'll need to set the name
# of the database above, and also uncomment the below.
# Sticking with SQLite is strongly recommended, as it's the most well tested
# and by far the fastest solution.
#
#dbDriver=QMYSQL
#dbUsername=
#dbPassword=
#dbHost=
#dbPort=
#dbPrefix=murmur_
#dbOpts=
# Murmur defaults to not using D-Bus. If you wish to use dbus, which is one of the
# RPC methods available in Murmur, please specify so here.
#
dbus=system
# Alternate D-Bus service name. Only use if you are running distinct
# murmurd processes connected to the same D-Bus daemon.
#dbusservice=net.sourceforge.mumble.murmur
# If you want to use ZeroC Ice to communicate with Murmur, you need
# to specify the endpoint to use. Since there is no authentication
# with ICE, you should only use it if you trust all the users who have
# shell access to your machine.
# Please see the ICE documentation on how to specify endpoints.
ice="tcp -h 127.0.0.1 -p 6502"
# Ice primarily uses local sockets. This means anyone who has a
# user account on your machine can connect to the Ice services.
# You can set a plaintext "secret" on the Ice connection, and
# any script attempting to access must then have this secret
# (as context with name "secret").
# Access is split in read (look only) and write (modify)
# operations. Write access always includes read access,
# unless read is explicitly denied (see note below).
#
# Note that if this is uncommented and with empty content,
# access will be denied.
#icesecretread=
icesecretwrite=
# How many login attempts do we tolerate from one IP
# inside a given timeframe before we ban the connection?
# Note that this is global (shared between all virtual servers), and that
# it counts both successfull and unsuccessfull connection attempts.
# Set either Attempts or Timeframe to 0 to disable.
#autobanAttempts = 10
#autobanTimeframe = 120
#autobanTime = 300
# Specifies the file Murmur should log to. By default, Murmur
# logs to the file 'murmur.log'. If you leave this field blank
# on Unix-like systems, Murmur will force itself into foreground
# mode which logs to the console.
logfile=/data/mumble-server.log
# If set, Murmur will write its process ID to this file
# when running in daemon mode (when the -fg flag is not
# specified on the command line). Only available on
# Unix-like systems.
pidfile=/var/run/mumble-server/mumble-server.pid
# The below will be used as defaults for new configured servers.
# If you're just running one server (the default), it's easier to
# configure it here than through D-Bus or Ice.
#
# Welcome message sent to clients when they connect.
welcometext="<br />Welcome to this server running <b>Murmur</b>.<br />Enjoy your stay!<br />"
# Port to bind TCP and UDP sockets to.
port=64738
# Specific IP or hostname to bind to.
# If this is left blank (default), Murmur will bind to all available addresses.
#host=
# Password to join server.
serverpassword=
# Maximum bandwidth (in bits per second) clients are allowed
# to send speech at.
bandwidth=72000
# Maximum number of concurrent clients allowed.
users=100
# Amount of users with Opus support needed to force Opus usage, in percent.
# 0 = Always enable Opus, 100 = enable Opus if it's supported by all clients.
#opusthreshold=100
# Maximum depth of channel nesting. Note that some databases like MySQL using
# InnoDB will fail when operating on deeply nested channels.
#channelnestinglimit=10
# Regular expression used to validate channel names.
# (Note that you have to escape backslashes with \ )
#channelname=[ \\-=\\w\\#\\[\\]\\{\\}\\(\\)\\@\\|]+
# Regular expression used to validate user names.
# (Note that you have to escape backslashes with \ )
#username=[-=\\w\\[\\]\\{\\}\\(\\)\\@\\|\\.]+
# Maximum length of text messages in characters. 0 for no limit.
#textmessagelength=5000
# Maximum length of text messages in characters, with image data. 0 for no limit.
#imagemessagelength=131072
# Allow clients to use HTML in messages, user comments and channel descriptions?
#allowhtml=true
# Murmur retains the per-server log entries in an internal database which
# allows it to be accessed over D-Bus/ICE.
# How many days should such entries be kept?
# Set to 0 to keep forever, or -1 to disable logging to the DB.
#logdays=31
# To enable public server registration, the serverpassword must be blank, and
# this must all be filled out.
# The password here is used to create a registry for the server name; subsequent
# updates will need the same password. Don't lose your password.
# The URL is your own website, and only set the registerHostname for static IP
# addresses.
# Only uncomment the 'registerName' parameter if you wish to give your "Root" channel a custom name.
#
#registerName=Mumble Server
#registerPassword=secret
#registerUrl=https://www.mumble.info/
#registerHostname=
# If this option is enabled, the server will announce its presence via the
# bonjour service discovery protocol. To change the name announced by bonjour
# adjust the registerName variable.
# See http://developer.apple.com/networking/bonjour/index.html for more information
# about bonjour.
#bonjour=True
# If you have a proper SSL certificate, you can provide the filenames here.
# Otherwise, Murmur will create it's own certificate automatically.
#sslCert=
#sslKey=
# The sslCiphers option chooses the cipher suites to make available for use
# in SSL/TLS. This option is server-wide, and cannot be set on a
# per-virtual-server basis.
#
# This option is specified using OpenSSL cipher list notation (see
# https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT).
#
# It is recommended that you try your cipher string using 'openssl ciphers <string>'
# before setting it here, to get a feel for which cipher suites you will get.
#
# After setting this option, it is recommend that you inspect your Murmur log
# to ensure that Murmur is using the cipher suites that you expected it to.
#
# Note: Changing this option may impact the backwards compatibility of your
# Murmur server, and can remove the ability for older Mumble clients to be able
# to connect to it.
#sslCiphers=EECDH+AESGCM:AES256-SHA:AES128-SHA
# If Murmur is started as root, which user should it switch to?
# This option is ignored if Murmur isn't started with root privileges.
uname=mumble-server
# If this options is enabled, only clients which have a certificate are allowed
# to connect.
#certrequired=False
# If enabled, clients are sent information about the servers version and operating
# system.
#sendversion=True
# You can configure any of the configuration options for Ice here. We recommend
# leave the defaults as they are.
# Please note that this section has to be last in the configuration file.
#
[Ice]
Ice.Warn.UnknownProperties=1
Ice.MessageSizeMax=65536

View File

29
mumbleclient.go 100644
View File

@ -0,0 +1,29 @@
package main
import (
"fmt"
"layeh.com/gumble/gumble"
"layeh.com/gumble/gumbleutil"
// _ "layeh.com/gumble/opus"
)
func main() {
config := gumble.NewConfig()
config.Username = "gumble-test"
config.Attach(gumbleutil.Listener{
TextMessage: func(e *gumble.TextMessageEvent) {
fmt.Printf("Received text message: %s\n", e.Message)
},
})
_, err := gumble.Dial("parla.abbiamoundominio.org:64738", config)
if err != nil {
panic(err)
}
// var message TextMessage
}