Initial commit

This commit is contained in:
batteredbunny 2023-06-13 00:07:14 +03:00
commit 694a7aa12b
24 changed files with 1215 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
result
.DS_Store
hls

52
api.go Normal file
View file

@ -0,0 +1,52 @@
package main
import (
"os"
"path"
"github.com/olahol/melody"
)
func (s *State) ViewersAmount() (viewers int, err error) {
var sessions []*melody.Session
if sessions, err = s.Websocket.Sessions(); err == nil {
viewers = len(sessions)
}
return
}
func (s *State) NowPlaying() string {
if s.CurrentFile == "" {
return "Nothing"
} else {
return s.CurrentFile
}
}
// TODO: make it possible to specific timestamp
func (s *State) PlayVideo(filename string, seconds int) (playme string, err error) {
if filename == "" {
playme, err = s.getRandomMediaFile()
if err != nil {
return
}
} else {
playme = filename
}
err = s.playFile(playme)
return
}
// returns if media can be watched
func (s *State) IsLivestreamReady() (bool, error) {
if _, err := os.Stat(path.Join(s.OutDir, OUTFILE)); os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
} else {
return true, nil
}
}

11
build.nix Normal file
View file

@ -0,0 +1,11 @@
{ pkgs, buildGoModule }: buildGoModule {
src = ./.;
name = "livestream";
vendorSha256 = "sha256-ArSYjtu/Gq4XtEDNzNg/nTRYRVOiSEp0D0wQvOtZVTk=";
ldflags = [
"-s"
"-w"
];
}

11
docker-compose.yml Normal file
View file

@ -0,0 +1,11 @@
services:
livestream:
container_name: livestream
image: livestream
volumes:
- ~/Downloads/media:/media
ports:
- 3000:3000
- 3001:3001
command: "--media /media"
restart: unless-stopped

15
docker.nix Normal file
View file

@ -0,0 +1,15 @@
{ pkgs, default, nix2container}: nix2container.packages.${pkgs.system}.nix2container.buildImage {
name = "livestream";
tag = "latest";
copyToRoot = with pkgs; [
cacert
ffmpeg
];
config = {
entrypoint = ["${default}/bin/livestream"];
workdir = "/app";
exposed_ports = [3000];
};
}

BIN
family_guy_wheel.mp4 Normal file

Binary file not shown.

111
flake.lock generated Normal file
View file

@ -0,0 +1,111 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1685518550,
"narHash": "sha256-o2d0KcvaXzTrPRIo0kOLV0/QXHhDQ5DTi+OxcjO8xqY=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "a1720a10a6cfe8234c0e93907ffe81be440f4cef",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"locked": {
"lastModified": 1653893745,
"narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nix2container": {
"inputs": {
"flake-utils": "flake-utils_2",
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1685771919,
"narHash": "sha256-3lVKWrhNXjHJB6QkZ2SJaOs4X/mmYXtY6ovPVpDMOHc=",
"owner": "nlewo",
"repo": "nix2container",
"rev": "95e2220911874064b5d809f8d35f7835184c4ddf",
"type": "github"
},
"original": {
"owner": "nlewo",
"repo": "nix2container",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1677612629,
"narHash": "sha256-yC+9LfhfwOd5sXFW8TLnDmqVMNYiHXYPGy9BbdpRqfU=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "111ca8e0378e88d9decaa1c6dd7597f35d8bc67f",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1686412476,
"narHash": "sha256-inl9SVk6o5h75XKC79qrDCAobTD1Jxh6kVYTZKHzewA=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "21951114383770f96ae528d0ae68824557768e81",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nix2container": "nix2container",
"nixpkgs": "nixpkgs_2"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

35
flake.nix Normal file
View file

@ -0,0 +1,35 @@
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
nix2container.url = "github:nlewo/nix2container";
};
outputs = { self, nixpkgs, flake-utils, nix2container, ... }:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = import nixpkgs {
inherit system;
};
# Needed on non linux systems since docker runs a linux vm
dockerCallPackage = if pkgs.stdenv.isLinux then
pkgs.callPackage
else
pkgs.pkgsCross."${pkgs.stdenv.hostPlatform.uname.processor}-multiplatform".callPackage;
in
with pkgs;
{
devShells.default = mkShell {
buildInputs = [
ffmpeg
openssl
pkg-config
go
];
};
packages.default = callPackage ./build.nix { };
packages.docker = callPackage ./docker.nix { default = dockerCallPackage ./build.nix { }; inherit nix2container; };
}
);
}

6
get_style.sh Executable file
View file

@ -0,0 +1,6 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash -p curl sass
cd static/css
curl https://raw.githubusercontent.com/ayes-web/common-web-styles/main/common.scss --remote-name
sass -C common.scss common.css
rm common.scss

36
go.mod Normal file
View file

@ -0,0 +1,36 @@
module livestream
go 1.20
require (
github.com/gin-gonic/gin v1.9.1
github.com/olahol/melody v1.1.3
)
require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.9.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

89
go.sum Normal file
View file

@ -0,0 +1,89 @@
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.14.1 h1:9c50NUPC30zyuKprjL3vNZ0m5oG+jU0zvx4AqHGnv4k=
github.com/go-playground/validator/v10 v10.14.1/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg=
github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/olahol/melody v1.1.3 h1:7Eo8egmejdrhdCM64uPgWj7NLSAVKl7Iv9NloFlzb60=
github.com/olahol/melody v1.1.3/go.mod h1:GgkTl6Y7yWj/HtfD48Q5vLKPVoZOH+Qqgfa7CvJgJM4=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

46
html/hls.html Normal file
View file

@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Livestream</title>
<link rel="stylesheet" href="/static/css/common.css">
<link rel="stylesheet" href="/static/css/style.css">
<script src="https://cdn.jsdelivr.net/npm/hls.js@1"></script>
<script src="https://unpkg.com/feather-icons"></script>
</head>
<body>
<div class="center-video">
<div id="video-box">
<div id="video-clicker-wrapper" onclick="pause()">
<video id="video" autoplay></video>
</div>
<div id="loading" class="hidden video-icon">
<i data-feather="loader"></i>
</div>
<div id="paused" class="hidden video-icon">
<i data-feather="play"></i>
</div>
<div id="menu">
<span id="pause" onclick="pause()"></span>
<span id="maximize" onclick="fullscreen()"><i data-feather="maximize"></i></span>
</div>
<div id="volume-menu">
<input id="volumeslider" type="range" max="1" min="0" step="0.1" oninput="setvolume(this.value)" />
<span id="muted" class="hidden"><i data-feather="volume-x"></i></span>
</div>
</div>
</div>
<h2 class="text-center">Currently playing: <span id="currently_playing">Nothing</span></h2>
<h2 class="text-center">Viewers: <span id="viewers">1</span></h2>
<script src="/static/js/script.js"></script>
</body>
</html>

17
html/loading.html Normal file
View file

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Starting up</title>
<link rel="stylesheet" href="/static/css/common.css">
<link rel="stylesheet" href="/static/css/loading.css">
<script src="/static/js/loading.js" type="module"></script>
</head>
<body>
<div id="starting">
<h1>Livestream is starting up!</h1>
<h2 id="please_wait">Please wait.</h2>
</div>
</body>
</html>

61
http.go Normal file
View file

@ -0,0 +1,61 @@
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func (s *State) NowPlayingAPI(c *gin.Context) {
c.String(http.StatusOK, s.NowPlaying())
}
type PlayAPIform struct {
Filename string `form:"filename"`
Seconds int `form:"seconds"`
}
func (s *State) PlayAPI(c *gin.Context) {
var form PlayAPIform
if err := c.BindQuery(&form); err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
if filename, err := s.PlayVideo(form.Filename, form.Seconds); err != nil {
c.String(http.StatusBadRequest, err.Error())
} else {
c.String(http.StatusOK, filename)
}
}
type PlayRandomAPIform struct {
Autoplay bool `form:"autoplay"`
}
func (s *State) PlayRandomAPI(c *gin.Context) {
var form PlayRandomAPIform
if err := c.BindQuery(&form); err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
s.PlayRandom(form.Autoplay)
}
func (s *State) StopPlayingAPI(c *gin.Context) {
fmt.Println("Stopping current video")
s.stopPlaying()
s.playFallback()
}
func (s *State) IsLivestreamReadyAPI(c *gin.Context) {
ready, err := s.IsLivestreamReady()
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.String(http.StatusOK, fmt.Sprint(ready))
}

151
main.go Normal file
View file

@ -0,0 +1,151 @@
package main
import (
"embed"
"errors"
"fmt"
"log"
"net/http"
"os"
_ "embed"
"flag"
"math/rand"
"github.com/gin-gonic/gin"
"github.com/olahol/melody"
)
type PlayState = int
const (
NotPlaying PlayState = iota
PlayingFallback
PlayingVideo
)
type State struct {
VideoProcess ffmpegProcess
PlayState PlayState
CurrentFile string
Config
Websocket *melody.Melody
}
type Config struct {
OutDir string
FallbackFile string
MediaFolder string
IgnoreHiddenFiles bool
PublicPort int
PrivatePort int
}
func (s *State) getRandomMediaFile() (foundFile string, err error) {
var files []string
files, err = listFilesRecursively(s.MediaFolder, s.IgnoreHiddenFiles)
if err != nil {
return
}
foundFile = files[rand.Intn(len(files))]
return
}
func newState(c Config) (state State, err error) {
state = State{
Config: c,
PlayState: NotPlaying,
}
return
}
//go:embed html/*
var embedHTML embed.FS
var ErrMediaFolderNotSpecified = errors.New("Please specify media folder to use")
func parseFlags() (config Config, err error) {
flag.StringVar(&config.OutDir, "out", "hls", "location to dump hls/m3u8 files")
flag.StringVar(&config.FallbackFile, "fallback", "family_guy_wheel.mp4", "Fallback video that is played when main stream is down")
flag.StringVar(&config.MediaFolder, "media", "", "Location of the media folder")
flag.IntVar(&config.PublicPort, "public_port", 3000, "Port to run public server on")
flag.IntVar(&config.PrivatePort, "private_port", 3001, "Port to run private server on")
flag.BoolVar(&config.IgnoreHiddenFiles, "hidden_files", true, "Ignores hidden files in random media picking")
flag.Parse()
if config.MediaFolder == "" {
err = ErrMediaFolderNotSpecified
}
return
}
func main() {
config, err := parseFlags()
if err != nil {
log.Fatal(err)
}
if err = os.RemoveAll(config.OutDir); err != nil {
log.Fatal(err)
}
if err = os.MkdirAll(config.OutDir, 0700); err != nil {
log.Fatal(err)
}
state, err := newState(config)
if err != nil {
log.Fatal(err)
}
state.setupWebsocket()
if err = state.playFallback(); err != nil {
log.Fatal(err)
}
public := gin.Default()
public.GET("/", func(c *gin.Context) {
ready, err := state.IsLivestreamReady()
if err != nil {
c.String(http.StatusInternalServerError, "Something went wrong")
return
}
if ready {
c.FileFromFS("html/hls.html", http.FS(embedHTML))
} else {
c.FileFromFS("html/loading.html", http.FS(embedHTML))
}
})
// public.StaticFileFS("/", "html/hls.html", http.FS(embedHTML))
public.Static("/static", "static")
public.Static("/media", config.OutDir)
public.Any("/ws", func(c *gin.Context) {
state.Websocket.HandleRequest(c.Writer, c.Request)
})
publicAPI := public.Group("/api")
publicAPI.GET("now_playing", state.NowPlayingAPI)
publicAPI.GET("is_livestream_ready", state.IsLivestreamReadyAPI)
private := gin.Default()
// TODO: autoplay feature that keeps playing random things after current one ends
privateAPI := private.Group("/api")
privateAPI.GET("play", state.PlayAPI)
privateAPI.GET("random", state.PlayRandomAPI)
privateAPI.GET("stop", state.StopPlayingAPI)
privateAPI.GET("now_playing", state.NowPlayingAPI)
fmt.Println("Starting public server on port", fmt.Sprint(config.PublicPort))
go public.Run(fmt.Sprintf(":%d", config.PublicPort))
fmt.Println("Starting private server on port", fmt.Sprint(config.PrivatePort))
log.Fatal(private.Run(fmt.Sprintf(":%d", config.PrivatePort)))
}

122
play.go Normal file
View file

@ -0,0 +1,122 @@
package main
import (
"context"
"log"
"os/exec"
"path"
"strings"
)
const OUTFILE = "index.m3u8"
type ffmpegProcess struct {
cancel context.CancelFunc
cmd *exec.Cmd
}
func (f *ffmpegProcess) Stop() {
c := f.cancel
if c != nil {
c()
}
}
func playffmpeg(loop bool, input string, output string, WhenVideoEnds func(forcequit bool)) (f ffmpegProcess) {
var c context.Context
c, f.cancel = context.WithCancel(context.Background())
if loop {
f.cmd = exec.CommandContext(c, "ffmpeg", "-re", "-stream_loop", "-1", "-i", input, "-hls_flags", "delete_segments+append_list+omit_endlist", "-f", "hls", output)
} else {
f.cmd = exec.CommandContext(c, "ffmpeg", "-re", "-i", input, "-hls_flags", "delete_segments+append_list+omit_endlist", "-f", "hls", output)
}
log.Println("[DEBUG] Starting ffmpeg with flags:", strings.Join(f.cmd.Args, " "))
go func() {
out, err := f.cmd.CombinedOutput()
if err != nil {
log.Println(err.Error()+":", string(out))
}
var forcequit bool
if err != nil && strings.Contains(err.Error(), "signal: killed") {
forcequit = true
}
if WhenVideoEnds != nil {
WhenVideoEnds(forcequit)
}
}()
return
}
func (s *State) playFile(fileName string) (err error) {
s.stopPlaying()
log.Println("Playing", fileName)
s.VideoProcess = playffmpeg(false, fileName, path.Join(s.OutDir, OUTFILE), func(forcequit bool) {
if err := s.playFallback(); err != nil {
log.Fatal(err)
}
})
s.PlayState = PlayingVideo
s.SetNowPlaying(path.Base(fileName))
return
}
func (s *State) playFallback() (err error) {
s.stopPlaying()
log.Println("Playing fallback")
s.VideoProcess = playffmpeg(true, s.FallbackFile, path.Join(s.OutDir, OUTFILE), nil)
s.PlayState = PlayingFallback
s.SetNowPlaying("")
return
}
func (s *State) PlayRandom(autoplay bool) {
s.stopPlaying()
fileName, err := s.getRandomMediaFile()
if err != nil {
return
}
log.Println("Playing", fileName)
s.VideoProcess = playffmpeg(false, fileName, path.Join(s.OutDir, OUTFILE), func(forcequit bool) {
if forcequit {
return
}
if autoplay {
s.PlayRandom(autoplay)
} else {
s.stopPlaying()
}
})
s.PlayState = PlayingVideo
s.SetNowPlaying(path.Base(fileName))
return
}
func (s *State) stopPlaying() {
s.VideoProcess.Stop()
s.PlayState = NotPlaying
switch s.PlayState {
case PlayingVideo:
log.Println("Stopping currently playing video")
case PlayingFallback:
log.Println("Stopping currently playing fallback video")
}
}
func (s *State) SetNowPlaying(p string) {
s.CurrentFile = p
s.Websocket.Broadcast(WebsocketMessage{
Type: WebsocketMessageTypeCurrentlyPlaying,
Message: s.NowPlaying(),
}.Encode())
}

104
static/css/common.css Normal file
View file

@ -0,0 +1,104 @@
@charset "UTF-8";
:root {
--background-color: white;
--text-color: black;
--secondary-text-color: rgb(63, 63, 63);
--disabled-text-color: #9a9a9a;
--interactive-background-color: #eaeaea;
--interactive-border-color: #a3a3a3;
--interactive-focus-border-color: #333333;
--hover-background: #e0e0e0;
--active-button-background-color: #b9b9b9;
--link-color: #3838d2; }
@media (prefers-color-scheme: dark) {
:root {
--background-color: #0f0f0f;
--text-color: white;
--secondary-text-color: rgb(192, 192, 192);
--disabled-text-color: rgb(189, 189, 189);
--interactive-background-color: rgb(31, 31, 31);
--interactive-border-color: #333333;
--interactive-focus-border-color: #a3a3a3;
--hover-background: rgb(56, 56, 56);
--active-button-background-color: rgb(24, 24, 24);
--link-color: orange; } }
html,
body {
background-color: var(--background-color);
color: var(--text-color);
font-family: "Roboto", sans-serif; }
a {
color: var(--link-color);
text-decoration: none; }
a:hover {
cursor: pointer;
text-decoration: underline; }
button:hover,
select:hover {
cursor: pointer;
background-color: var(--hover-background); }
button,
input,
select {
background-color: var(--interactive-background-color);
color: var(--text-color);
padding: 5px;
border: 1px solid var(--interactive-border-color);
border-radius: 5px; }
button:focus,
input:focus,
select:focus {
outline: none;
border: 1px solid var(--interactive-focus-border-color); }
button:disabled,
input:disabled,
select:disabled {
cursor: not-allowed;
color: var(--disabled-text-color); }
button {
padding: 5px 10px 5px 10px; }
button:active:not(:disabled) {
background-color: var(--active-button-background-color); }
input[type=checkbox] {
width: 15px;
height: 15px;
vertical-align: middle;
appearance: none; }
input[type=checkbox]:hover:not(:disabled) {
cursor: pointer;
background-color: var(--hover-background); }
input[type=checkbox]:checked::before {
content: "✓";
position: relative;
top: -9px;
left: -3px; }
.text-center {
text-align: center; }
.hidden {
visibility: hidden; }
.container {
margin-left: 3vw;
margin-right: 3vw; }
.margin-bottom {
margin-bottom: 1vh; }
.margin-top {
margin-top: 1vh; }
.no-select {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none; }
/*# sourceMappingURL=common.css.map */

View file

@ -0,0 +1,7 @@
{
"version": 3,
"mappings": ";AAAA,KAAM;EACJ,kBAAkB,CAAC,MAAM;EACzB,YAAY,CAAC,MAAM;EACnB,sBAAsB,CAAC,gBAAgB;EACvC,qBAAqB,CAAC,QAAQ;EAC9B,8BAA8B,CAAC,QAAQ;EACvC,0BAA0B,CAAC,QAAQ;EACnC,gCAAgC,CAAC,QAAQ;EACzC,kBAAkB,CAAC,QAAQ;EAC3B,gCAAgC,CAAC,QAAQ;EACzC,YAAY,CAAC,QAAQ;;AAGvB,mCAAoC;EAClC,KAAM;IACJ,kBAAkB,CAAC,QAAQ;IAC3B,YAAY,CAAC,MAAM;IACnB,sBAAsB,CAAC,mBAAmB;IAC1C,qBAAqB,CAAC,mBAAmB;IACzC,8BAA8B,CAAC,gBAAgB;IAC/C,0BAA0B,CAAC,QAAQ;IACnC,gCAAgC,CAAC,QAAQ;IACzC,kBAAkB,CAAC,gBAAgB;IACnC,gCAAgC,CAAC,gBAAgB;IACjD,YAAY,CAAC,OAAO;AAIxB;IACK;EACH,gBAAgB,EAAE,uBAAuB;EACzC,KAAK,EAAE,iBAAiB;EACxB,WAAW,EAAE,oBAAoB;;AAGnC,CAAE;EACA,KAAK,EAAE,iBAAiB;EACxB,eAAe,EAAE,IAAI;EAErB,OAAQ;IACN,MAAM,EAAE,OAAO;IACf,eAAe,EAAE,SAAS;;AAM5B;YAAQ;EACN,MAAM,EAAE,OAAO;EACf,gBAAgB,EAAE,uBAAuB;;AAI7C;;MAEO;EACL,gBAAgB,EAAE,mCAAmC;EACrD,KAAK,EAAE,iBAAiB;EACxB,OAAO,EAAE,GAAG;EACZ,MAAM,EAAE,yCAAyC;EACjD,aAAa,EAAE,GAAG;EAElB;;cAAQ;IACN,OAAO,EAAE,IAAI;IACb,MAAM,EAAE,+CAA+C;EAGzD;;iBAAW;IACT,MAAM,EAAE,WAAW;IACnB,KAAK,EAAE,0BAA0B;;AAIrC,MAAO;EACL,OAAO,EAAE,iBAAiB;EAE1B,4BAAwB;IACtB,gBAAgB,EAAE,qCAAqC;;AAI3D,oBAAqB;EACnB,KAAK,EAAE,IAAI;EACX,MAAM,EAAE,IAAI;EACZ,cAAc,EAAE,MAAM;EACtB,UAAU,EAAE,IAAI;EAEhB,yCAAuB;IACrB,MAAM,EAAE,OAAO;IACf,gBAAgB,EAAE,uBAAuB;EAG3C,oCAAkB;IAChB,OAAO,EAAE,GAAG;IACZ,QAAQ,EAAE,QAAQ;IAClB,GAAG,EAAE,IAAI;IACT,IAAI,EAAE,IAAI;;AAId,YAAa;EACX,UAAU,EAAE,MAAM;;AAGpB,OAAQ;EACN,UAAU,EAAE,MAAM;;AAGpB,UAAW;EACT,WAAW,EAAE,GAAG;EAChB,YAAY,EAAE,GAAG;;AAGnB,cAAe;EACb,aAAa,EAAE,GAAG;;AAGpB,WAAY;EACV,UAAU,EAAE,GAAG;;AAGjB,UAAW;EACT,mBAAmB,EAAE,IAAI;EACzB,gBAAgB,EAAE,IAAI;EACtB,eAAe,EAAE,IAAI;EACrB,WAAW,EAAE,IAAI",
"sources": ["common.scss"],
"names": [],
"file": "common.css"
}

44
static/css/loading.css Normal file
View file

@ -0,0 +1,44 @@
#starting {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#please_wait::after{
animation-name: text;
animation-iteration-count: infinite;
animation-duration: 2s;
content: "";
}
@keyframes text {
0% {
content: "";
}
24% {
content: "";
}
25% {
content: ".";
}
49% {
content: ".";
}
50% {
content: "..";
}
74% {
content: "..";
}
75% {
content: "...";
}
100% {
content: "...";
}
}

71
static/css/style.css Normal file
View file

@ -0,0 +1,71 @@
.center-video {
display: flex;
justify-content: center;
}
#video-box {
position: relative;
}
#video-clicker-wrapper, #maximize, #pause {
cursor: pointer;
}
#video {
border: 1px solid var(--text-color);
}
.hidden {
display: none;
}
.video-icon {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(2);
}
.video-icon-corner {
position: absolute;
top: 100%;
left: 100%;
transform: translate(-150%, -150%);
}
#volume-menu {
display: flex;
position: absolute;
top: 100%;
left: 100%;
transform: translate(-110%, -140%);
opacity: 10%;
transition-duration: 0.1s;
}
#muted {
display: flex;
justify-content: center;
align-items: center;
}
#menu {
position: absolute;
top: 100%;
left: 5%;
transform: translate(0%, -150%);
opacity: 10%;
transition-duration: 0.1s;
}
#video-box:hover > #menu, #video-box:hover > #volume-menu {
opacity: 100%
}
#pause svg, #maximize svg {
transition-duration: 0.1s;
}
#pause svg:hover, #maximize svg:hover {
opacity: 50%;
}

10
static/js/loading.js Normal file
View file

@ -0,0 +1,10 @@
async function IsLivestreamReady() {
let resp = await fetch("/api/is_livestream_ready");
return await resp.json()
}
while (!await IsLivestreamReady()) {
await new Promise(r => setTimeout(r, 100));
}
location.reload();

123
static/js/script.js Normal file
View file

@ -0,0 +1,123 @@
const WebsocketMessageTypeViewers = 0;
const WebsocketMessageTypeCurrentlyPlaying = 1;
const playCircle = feather.icons["play-circle"].toSvg()
const pauseCircle = feather.icons["pause-circle"].toSvg()
const viewers = document.getElementById("viewers")
const currently_playing = document.getElementById("currently_playing")
// Video player icons
const loading = document.getElementById("loading");
const paused = document.getElementById("paused");
const muted = document.getElementById("muted");
const volumeslider = document.getElementById("volumeslider");
const video = document.getElementById("video");
const pauseElement = document.getElementById("pause");
function setvolume(volume) {
video.volume = volume
}
video.onseeking = (e) => {
console.log("seeking/loading start")
loading.classList.remove("hidden")
}
video.onseeked = (e) => {
console.log("seeked/load end")
loading.classList.add("hidden")
}
video.onvolumechange = (e) => {
if (video.volume !== volumeslider.volume) {
volumeslider.volume = video.volume
}
if (video.volume == 0) {
muted.classList.remove("hidden")
} else {
muted.classList.add("hidden")
}
}
video.onpause = (e) => {
console.log("paused")
pauseElement.innerHTML = playCircle
paused.classList.remove("hidden")
}
video.onplay = (e) => {
console.log("play/resume")
video.currentTime = video.duration
pauseElement.innerHTML = pauseCircle
paused.classList.add("hidden")
}
function pause() {
if (video.paused) {
video.play()
} else {
video.pause()
}
}
function fullscreen() {
video.requestFullscreen()
}
let wsurl = "";
if (location.protocol === 'https:') {
wsurl = "wss://" + window.location.host + "/ws"
} else {
wsurl = "ws://" + window.location.host + "/ws"
}
let websocket = new WebSocket(wsurl)
websocket.onmessage = (event) => {
let data = JSON.parse(event.data)
switch (data.type) {
case WebsocketMessageTypeViewers:
viewers.innerText = data.message;
break
case WebsocketMessageTypeCurrentlyPlaying:
currently_playing.innerText = data.message
// video.duration is sometimes NaN
if (!isNaN(video.duration)) {
video.currentTime = video.duration
}
break
}
};
let videoSrc = '/media/index.m3u8';
if (Hls.isSupported()) {
let hls = new Hls();
hls.loadSource(videoSrc);
hls.attachMedia(video);
}
// HLS.js is not supported on platforms that do not have Media Source
// Extensions (MSE) enabled.
//
// When the browser has built-in HLS support (check using `canPlayType`),
// we can provide an HLS manifest (i.e. .m3u8 URL) directly to the video
// element through the `src` property. This is using the built-in support
// of the plain video element, without using HLS.js.
//
// Note: it would be more normal to wait on the 'canplay' event below however
// on Safari (where you are most likely to find built-in HLS support) the
// video.src URL must be on the user-driven white-list before a 'canplay'
// event will be emitted; the last video event that can be reliably
// listened-for when the URL is not on the white-list is 'loadedmetadata'.
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = videoSrc;
}
feather.replace()
volumeslider.volume = video.volume

27
utils.go Normal file
View file

@ -0,0 +1,27 @@
package main
import (
"io/fs"
"path"
"path/filepath"
"strings"
)
func listFilesRecursively(findPath string, hide_hidden bool) (filelist []string, err error) {
err = filepath.Walk(findPath, func(currentPath string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
if hide_hidden && strings.HasPrefix(path.Base(currentPath), ".") {
return nil
}
filelist = append(filelist, currentPath)
}
return nil
})
return
}

63
websocket.go Normal file
View file

@ -0,0 +1,63 @@
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/olahol/melody"
)
type WebsocketMessageType = int
const (
WebsocketMessageTypeViewers WebsocketMessageType = iota
WebsocketMessageTypeCurrentlyPlaying
)
type WebsocketMessage struct {
Type WebsocketMessageType `json:"type"`
Message string `json:"message"`
}
func (w WebsocketMessage) Encode() []byte {
m, err := json.Marshal(w)
if err != nil {
log.Fatal(err)
}
return m
}
func (state *State) setupWebsocket() {
state.Websocket = melody.New()
state.Websocket.HandleConnect(func(s *melody.Session) {
viewers, err := state.ViewersAmount()
if err != nil {
log.Fatal(err)
}
state.Websocket.Broadcast(WebsocketMessage{
Type: WebsocketMessageTypeViewers,
Message: fmt.Sprint(viewers + 1),
}.Encode())
s.Write(WebsocketMessage{
Type: WebsocketMessageTypeCurrentlyPlaying,
Message: state.NowPlaying(),
}.Encode())
})
state.Websocket.HandleDisconnect(func(s *melody.Session) {
viewers, err := state.ViewersAmount()
if err != nil {
log.Fatal(err)
}
state.Websocket.BroadcastOthers(WebsocketMessage{
Type: WebsocketMessageTypeViewers,
Message: fmt.Sprint(viewers),
}.Encode(), s)
})
}