repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

343 lines · 22.1 KB · download this file

package BlowfishCMS::Addon::Live;
# Live: video from OBS on the site, as HLS. OBS streams as usual (Start
# Streaming) to live-upload on the same computer (PowerShell or sh, in
# public/), whose FFmpeg takes the RTMP stream, cuts it into fMP4 pieces
# without re-encoding, and live-upload sends each piece here with the stream
# key in an X-Stream-Key header. They come as plain uploads, not chunked ones:
# OpenBSD httpd can't pass a chunked request body to FastCGI, and FFmpeg's
# own HTTP output always sends them chunked.
#
# Addresses (the add-on's own service): PUT /x/live/in/NAME (a piece: live.m3u8,
# or an .mp4 or .m4s it names; DELETE in/live.m3u8 ends the stream), and
# /x/live/status (JSON: live or not, for the player). The pieces are written to
# addon_files_dir("live"), which httpd serves as they are at /x/live/files/.
# A piece not in the playlist for a minute is removed, and when a stream ends
# (live-upload's DELETE, or nothing new for a minute) every piece goes. The
# pieces never fill more than CAP: past it, a piece is refused.
#
# Keeps: the stream key's sha256 in the secrets folder (key.sha256, 0400; the
# key itself is shown once, when it's made), and status.json in the data
# folder (when the stream started and the last piece came, and the recording).
# Since 1.1.0 each stream is also recorded (rec/) and handed to the Videos
# library when it ends (videos/); see "Saving streams" below. Block:
# live_player (the player, or a picture and note while off). Admin: the
# Stream screen (/admin/x/live/, the service): the key, how the stream stands,
# saving streams on or off, and setting up OBS.
use v5.36;
use utf8;
use JSON::PP ();
use Digest::SHA qw(sha256_hex);
use Fcntl qw(O_WRONLY O_CREAT O_TRUNC :flock);
use POSIX qw(strftime);
BEGIN {
    no strict 'refs';
    *{$_}=\&{"BlowfishCMS::$_"} for qw(h param site_url window window_html admin_page end_page fields redirect header attempt failed_action random_id render_markdown addon_data_dir addon_secret_dir addon_files_dir eq_safe free_bytes switch_field);
}

# A stream is live while its playlist is newer than this many seconds.
sub FRESH () { 15 }
# The most the stream's pieces may fill on the server (a 2-second piece at 6 Mbps is 1.5 MB).
sub CAP () { 64*1048576 }
sub files () { addon_files_dir('live') }
sub key_file () { addon_secret_dir('live').'/key.sha256' }
sub key_hash () { open my $fh,'<',key_file() or return '';my $v=do {local $/;<$fh>};close $fh;$v//='';$v =~ s/\s+//g;return $v }
sub status () { open my $fh,'<:raw',addon_data_dir('live').'/status.json' or return {};my $s=eval {JSON::PP::decode_json(do {local $/;<$fh>})};close $fh;return ref $s eq 'HASH' ? $s : {} }
sub status_save ($s) {
    my $file=addon_data_dir('live').'/status.json';
    open my $fh,'>:raw',"$file.tmp" or return;print {$fh} JSON::PP->new->canonical->encode($s);close $fh;rename "$file.tmp",$file;
}
sub live_since () {
    my $at=(stat files().'/live.m3u8')[9] or return undef;
    return time-$at<=FRESH ? (status()->{started}//$at) : undef;
}
# ---- Counting viewers ----------------------------------------------------------------------------
# A player that's playing sends w=ID (16 random hex digits, made by the page)
# with each status check, every 10 seconds. Each ID is an empty file in the
# data folder's viewers/, touched at each check: whoever checked in the last
# 30 seconds is watching. Files a minute old are removed, and all of them
# when the stream ends, so nothing about a visitor is kept. The most at once
# during a stream is its peak (in status.json), shown on the Stream screen.
# At most 5,000 at once are counted, so made-up IDs can't fill the disk.
sub viewers_dir () { addon_data_dir('live').'/viewers' }
sub viewer_seen ($id) {
    my $dir=viewers_dir();mkdir $dir,0700 unless -d $dir;
    my $f="$dir/$id";
    if (-e $f) {utime undef,undef,$f;return}
    return if viewers_now()>=5000;
    if (open my $fh,'>',$f) {close $fh}
}
sub viewers_now () {
    my $dir=viewers_dir();opendir(my $dh,$dir) or return 0;my ($n,$now)=(0,time);
    for (grep {/\A[a-f0-9]{16}\z/} readdir $dh) {
        my $age=$now-((stat "$dir/$_")[9]//0);
        if ($age<=30) {$n++} elsif ($age>60) {unlink "$dir/$_"}
    }
    closedir $dh;return $n;
}
sub viewers_clear () { my $dir=viewers_dir();opendir(my $dh,$dir) or return;unlink map {"$dir/$_"} grep {/\A[a-f0-9]{16}\z/} readdir $dh;closedir $dh }

# Every piece and the playlist: when a stream ends, nothing of it is kept.
sub clear_all () {
    opendir(my $dh,files()) or return;
    unlink map {files()."/$_"} grep {/\A[a-z0-9][a-z0-9_.-]*\.(?:mp4|m4s|m3u8)\z/} readdir $dh;
    closedir $dh;
}
sub pieces_bytes () {
    opendir(my $dh,files()) or return 0;my $n=0;
    $n+=(-s files()."/$_")//0 for grep {/\A[a-z0-9][a-z0-9_.-]*\.(?:mp4|m4s)\z/} readdir $dh;
    closedir $dh;return $n;
}
sub write_file ($file,$data,$mode=0640) {
    sysopen(my $fh,"$file.tmp",O_WRONLY|O_CREAT|O_TRUNC,$mode) or die "The piece couldn’t be saved: the add-on’s folders aren’t set up (doas blowfishctl addon enable live).\n";
    binmode $fh;print {$fh} $data;close $fh or die "The piece couldn’t be saved (is the disk full?).\n";
    rename "$file.tmp",$file or do {unlink "$file.tmp";die "The piece couldn’t be saved.\n"};
}

# ---- Saving streams ----------------------------------------------------------------------------
# While a stream is on, its pieces are also appended, in order, to one file
# in the data folder: rec/NAME.mp4 holds the stream's beginning (init.mp4)
# and then each numbered piece once, in order, with a note beside it
# (NAME.json: the video's title and its tag, pastlivestreams). When the
# stream ends, both move to videos/. Every minute root's runner
# (`blowfishctl requests`) takes them from there to the admin, which joins
# the pieces into an ordinary MP4 and adds it to the Videos library, at the
# top, with that tag. Owners turn this off on the Stream screen (save.off).
#
# A recording stops growing (the stream doesn't) when the disk would be left
# with less than 1 GB beyond a second copy of it, since joining it makes one.
# A stream that ends without saying so is handed over by whichever comes
# first: the next stream, the status check visitors' players make, the
# Stream screen, or (after 15 minutes) the runner itself.
sub SPARE () { 1024*1048576 }
sub rec_dir () { addon_data_dir('live').'/rec' }
sub out_dir () { addon_data_dir('live').'/videos' }
sub saving () { return !-e addon_data_dir('live').'/save.off' }
# One request at a time changes the recording (pieces, and the checks that end it).
sub rec_locked ($code) {
    open my $lock,'>>',addon_data_dir('live').'/rec.lock' or return $code->();
    flock($lock,LOCK_EX);my @r=$code->();close $lock;
    return wantarray ? @r : $r[0];
}
# A new stream's beginning: ends any recording before it and starts one.
sub rec_start ($init) {
    rec_finish();
    return unless saving();
    my $dir=rec_dir();mkdir $dir,0700 unless -d $dir;
    # When it started, and a little randomness so two in the same second don't meet.
    my $name=strftime('%Y%m%d-%H%M%S',localtime).'-'.substr(random_id(),0,4);
    write_file("$dir/$name.init",$init,0600);
    write_file("$dir/$name.mp4",$init,0600);
    my $title='Livestream, '.(strftime('%e %B %Y, %H:%M',localtime) =~ s/\A\s+//r);
    write_file("$dir/$name.json",JSON::PP->new->canonical->encode({title=>$title,tags=>'pastlivestreams',started=>time}),0600);
    my $s=status();$s->{rec}={name=>$name,seq=>-1,bytes=>length $init,at=>time,init=>sha256_hex($init)};status_save($s);
}
# A numbered piece: appended once, after the ones before it. Numbers that
# start again from 0 are a new stream from the same live-upload.
sub rec_add ($seq,$data) {
    my $s=status();my $r=$s->{rec} or return;
    my $dir=rec_dir();
    if ($seq<=$r->{seq} || !-f "$dir/$r->{name}.mp4") {
        return unless $seq==0 || !-f "$dir/$r->{name}.mp4";
        open my $fh,'<:raw',"$dir/$r->{name}.init" or return;my $init=do {local $/;<$fh>};close $fh;
        rec_start($init);$s=status();$r=$s->{rec} or return;
    }
    return if $r->{full};
    # How much room is left, checked every half minute (df is a process of its own).
    if (time-($r->{checked}//0)>=30) {
        $r->{checked}=time;my $free=free_bytes($dir);
        $r->{full}=1 if defined $free && $free<$r->{bytes}+length($data)+SPARE;
    }
    unless ($r->{full}) {
        if (open my $fh,'>>:raw',"$dir/$r->{name}.mp4") {print {$fh} $data;close $fh or $r->{full}=1}
        else {$r->{full}=1}
        unless ($r->{full}) {$r->{seq}=$seq;$r->{bytes}+=length $data;$r->{at}=time}
    }
    status_save($s);
}
# The stream has ended: its recording goes to videos/ for the runner (with
# when it ended in its note), or, with no pieces in it, is thrown away.
sub rec_finish () {
    my $s=status();my $r=delete $s->{rec};status_save($s);
    return unless $r;
    my $dir=rec_dir();my $name=$r->{name};
    unlink "$dir/$name.init";
    if ($r->{seq}<0 || !-f "$dir/$name.mp4") {unlink "$dir/$name.mp4","$dir/$name.json";return}
    my $out=out_dir();mkdir $out,0700 unless -d $out;
    my $meta=eval {open my $fh,'<:raw',"$dir/$name.json" or die;my $m=JSON::PP::decode_json(do {local $/;<$fh>});close $fh;$m};
    $meta={title=>'Livestream',tags=>'pastlivestreams'} unless ref $meta eq 'HASH';
    $meta->{ended}=$r->{at};$meta->{seconds}=$r->{at}-($meta->{started}//$r->{at});
    attempt {write_file("$out/$name.json",JSON::PP->new->canonical->encode($meta),0600);1};
    unlink "$dir/$name.json";
    # The note first: the runner takes a video only with its note beside it.
    rename "$dir/$name.mp4","$out/$name.mp4";
}
# A recording whose stream has gone quiet for a minute is finished.
sub rec_check () {
    my $r=status()->{rec} or return;
    rec_finish() if time-($r->{at}//0)>60;
}

# ---- Receiving the stream ----------------------------------------------------------------------
sub reply ($status,$text) { header($status,'text/plain; charset=UTF-8',"Cache-Control: no-store\r\n");print "$text\n";return 1 }
sub route ($rest) {
    if ($rest eq 'status') {
        my $since=live_since();my $n=0;
        if (defined $since) {
            # A player that's playing counts itself; the count goes back to every page.
            my $w=param('w',16);viewer_seen($w) if $w =~ /\A[a-f0-9]{16}\z/;
            $n=viewers_now();
            rec_locked(sub {my $s=status();if ($n>($s->{peak}//0)) {$s->{peak}=$n;status_save($s)}}) if $n>(status()->{peak}//0);
        }
        # A stream that stopped without saying so (live-upload closed, the computer asleep): cleared after a minute.
        elsif (do {my $at=(stat files().'/live.m3u8')[9];!$at || time-$at>60}) {clear_all();viewers_clear();attempt {rec_locked(\&rec_check);1}}
        header(200,'application/json; charset=UTF-8',"Cache-Control: no-store\r\n");
        print JSON::PP->new->canonical->encode({live=>defined $since ? JSON::PP::true : JSON::PP::false,since=>$since,viewers=>$n});
        return 1;
    }
    my ($name)=$rest =~ m{\Ain/([a-z0-9][a-z0-9_.-]{0,99})\z} or return 0;
    my $method=$BlowfishCMS::method;
    return reply(405,'Send pieces with PUT.') unless $method eq 'PUT' || $method eq 'POST' || $method eq 'DELETE';
    my $want=key_hash();
    return reply(403,'Live has no stream key yet: make one on its Stream screen.') unless length $want;
    my $key=$ENV{HTTP_X_STREAM_KEY}//'';$key =~ s/\s+//g;
    return reply(403,'That stream key isn’t right.') unless length $key && eq_safe(sha256_hex($key),$want);
    my $playlist=$name eq 'live.m3u8';
    return reply(400,'Only live.m3u8 and the .mp4 and .m4s pieces it names are taken.') unless $playlist || $name =~ /\.(?:mp4|m4s)\z/;
    if ($method eq 'DELETE') {
        if ($playlist) {clear_all();viewers_clear();rec_locked(sub {my $s=status();delete $s->{started};status_save($s);attempt {rec_finish();1}})}
        else {unlink files()."/$name"}
        return reply(200,'Removed.');
    }
    my $q=$BlowfishCMS::q;
    my $data=$q->param('PUTDATA') // $q->param('POSTDATA');
    return reply(411,'Send each piece whole, with its length (not chunked).') unless defined $data && length $data;
    if ($playlist) {
        return reply(400,'That isn’t an HLS playlist.') unless $data =~ /\A#EXTM3U/ && length $data<=65536;
        write_file(files().'/live.m3u8',$data);
        prune($data);
    }
    else {
        # Never more than CAP on the server: first drop what the playlist no longer names, however new.
        if (pieces_bytes()+length($data)>CAP) {
            if (open my $fh,'<:raw',files().'/live.m3u8') {local $/;prune(scalar <$fh>,0);close $fh}
            return reply(507,'The stream’s pieces fill more than 64 MB on the server: lower OBS’s bitrate, or check that the pieces are about 2 seconds long (keyframe interval 2).') if pieces_bytes()+length($data)>CAP;
        }
        write_file(files()."/$name",$data);
    }
    rec_locked(sub {
        # The recording, which never gets in the way of the stream: a beginning
        # (init.mp4) that's new, or comes after a quiet spell, starts one.
        attempt {
            if ($name =~ /\.mp4\z/) {
                my $r=status()->{rec};
                rec_start($data) if !$r || time-($r->{at}//0)>FRESH || ($r->{init}//'') ne sha256_hex($data);
            }
            elsif ($name =~ /(\d+)\.m4s\z/) {rec_add($1,$data)}
            1;
        };
        my $s=status();my $now=time;
        # A new stream: its own start, and its own peak of viewers.
        if (!$s->{started} || $now-($s->{last}//0)>FRESH) {$s->{started}=$now;$s->{peak}=0}
        $s->{last}=$now;status_save($s);
    });
    return reply(200,'Saved.');
}
# Pieces the playlist no longer names go once they're a minute old (a viewer
# may still be fetching the one before).
sub prune ($playlist,$age=60) {
    my %keep=map {($_=>1)} ($playlist =~ m{^([a-z0-9][a-z0-9_.-]*\.(?:mp4|m4s))\s*$}mg),($playlist =~ m{URI="([a-z0-9][a-z0-9_.-]*\.mp4)"}g);
    opendir(my $dh,files()) or return;
    for my $f (readdir $dh) {
        next unless $f =~ /\A[a-z0-9][a-z0-9_.-]*\.(?:mp4|m4s)\z/ && !$keep{$f};
        unlink files()."/$f" if time-((stat files()."/$f")[9]//time)>=$age;
    }
    closedir $dh;
}

# ---- On the site -----------------------------------------------------------------------------
sub blocks {
    return {live_player=>{label=>'Live player',group=>'addons',about=>'Your live stream from OBS, or a picture and note while you’re not live.',
        fields=>[['title','Panel title','text',120],['picture','Picture while not live','picture'],['note','Note while not live','markdown',4000,'Markdown, such as when you’re next live']],
        render=>\&render_player}};
}
sub render_player ($b,%o) {
    my $d=$b->{data}//{};my $pic='';
    if (length($d->{picture}//'') && (my $p=BlowfishCMS::picture_by_id($d->{picture}))) {
        $pic='<img class="live__picture" src="'.h(BlowfishCMS::picture_url($p)).'" alt="'.h($p->{description}//'').'" loading="lazy">';
    }
    my $note=length($d->{note}//'') ? render_markdown($d->{note}) : '<p>Not live right now.</p>';
    my $html='<div class="live" data-live="/x/live/">'
        .'<div class="live__screen" data-live-on hidden><video class="live__video" controls playsinline preload="none"></video>'
        .'<button class="live__watch buttonlike is-primary" type="button" data-live-watch>▶ watch live</button><span class="live__badges"><span class="live__badge">live</span><span class="live__viewers" data-live-viewers hidden></span></span></div>'
        .'<div class="live__off" data-live-off>'.$pic.'<div class="live__note page-copy">'.$note.'</div></div>'
        .'<p class="live__problem panel-note" data-live-problem hidden></p></div>';
    return window_html($d->{title},'',$html,%o);
}

# ---- The Stream screen (the add-on's service) ---------------------------------------------------
sub service_admin ($rest) {
    return 0 unless $rest eq '';
    my $message=param('notice',2000);my $made='';
    if ($BlowfishCMS::method eq 'POST') {
        attempt {
            my $action=param('action',30);
            if ($action eq 'key_make') {
                # Shown once, on this page (never in an address), then only its sha256 is kept.
                $made=random_id().random_id();
                write_file(key_file(),sha256_hex($made)."\n",0400);
                $message='A new stream key is below. Copy it into live-upload now: it isn’t shown again, and the old key stops working.';
                1;
            }
            elsif ($action eq 'key_remove') {
                unlink key_file();
                redirect('/admin/x/live/?notice='.CGI::escape('Stream key removed. Nothing can be streamed until a new one is made.'));
            }
            elsif ($action eq 'save_streams') {
                my $off=addon_data_dir('live').'/save.off';
                if (param('save',1) eq '1') {unlink $off} else {write_file($off,"off\n",0600)}
                redirect('/admin/x/live/?notice='.CGI::escape(saving() ? 'Each stream will be saved to the Videos library, tagged #pastlivestreams.' : 'Streams won’t be saved. One being recorded now is still saved when it ends.').'#saving');
            }
            else {die "Choose an action.\n"}
        } or $message=failed_action($@);
    }
    admin_page('Stream',section=>'x-live-service',notice=>$message,
        intro=>'Stream from OBS to your own site: OBS streams to <strong>live-upload</strong> on your computer, which sends the stream here piece by piece. Visitors watch it on the Live page, or in a Live player block on any page.');
    attempt {rec_locked(\&rec_check);1};
    my $since=live_since();my $s=status();my $r=$s->{rec};
    my $waiting=0;
    if (opendir my $dh,out_dir()) {$waiting=grep {/\.mp4\z/} readdir $dh;closedir $dh}
    my $rec=$r && $r->{full} ? ['warn','stopped at '.mb($r->{bytes}).': the server’s disk is nearly full (the stream goes on)']
        : $r ? ['ok','recording, '.mb($r->{bytes}).' so far'] : saving() ? ['ok','on: each stream goes to the Videos library, tagged #pastlivestreams'] : ['warn','off'];
    my @rows=(['Now',defined $since ? ['ok','live since '.ago($since)] : ['warn',$s->{last} ? 'not live (last piece '.ago($s->{last}).')' : 'not live (nothing received yet)']],
        ['Stream key',length key_hash() ? ['ok','made (only its fingerprint is kept)'] : ['warn','none yet: make one below']],
        (defined $since ? (['Watching',['ok',viewers_now().' now · at most '.($s->{peak}//0).' at once this stream']])
            : $s->{peak} ? (['Watching',['ok','at most '.$s->{peak}.' at once, the last stream']]) : ()),
        ['Saving streams',$rec],
        ($waiting ? (['Waiting for Videos',['ok',$waiting==1 ? '1 stream, added within a minute or two' : "$waiting streams, added within a minute or two"]]) : ()),
        ['Upload address',['ok',site_url().'/x/live/in/']]);
    my $st='<table class="seo-table mail-status"><tbody>'.join('',map {'<tr><th>'.h($_->[0]).'</th><td class="is-'.$_->[1][0].'">'.h($_->[1][1]).'</td></tr>'} @rows).'</tbody></table>';
    my $k=length $made ? '<p class="live-key"><label>Your stream key<input type="text" readonly value="'.h($made).'" spellcheck="false" autocomplete="off"></label></p>' : '';
    $k.='<form method="post" action="/admin/x/live/" class="admin-form'.(length key_hash() ? ' delete-form" data-confirm="Make a new stream key? The one live-upload uses now stops working.' : '').'">'.fields('key_make','x-live')
        .'<button class="buttonlike" type="submit">'.(length key_hash() ? 'make a new stream key' : 'make a stream key').'</button></form>';
    $k.='<form method="post" action="/admin/x/live/" class="delete-form" data-confirm="Remove the stream key? Nothing can be streamed until a new one is made.">'.fields('key_remove','x-live').'<button class="text-button danger">remove the stream key</button></form>' if length key_hash();
    my $site=site_url();
    my $setup='<ol class="mail-steps">'
        .'<li><strong>FFmpeg</strong>, once, on the streaming computer: on Windows, in PowerShell, <code>winget install Gyan.FFmpeg</code>; on a Mac, <code>brew install ffmpeg</code>.</li>'
        .'<li><strong>live-upload</strong>: save <a href="/addons/live/live-upload.ps1" download>live-upload.ps1</a> (Windows) or <a href="/addons/live/live-upload.sh" download>live-upload.sh</a> (Mac, Linux) and start it:<br><code>powershell -ExecutionPolicy Bypass -File live-upload.ps1 -Site '.h($site).'</code><br>or <code>sh live-upload.sh '.h($site).'</code>. It asks for the stream key, keeps it only while it runs, and waits for OBS. Leave it running.</li>'
        .'<li><strong>OBS</strong>, once: Settings → <em>Stream</em>, Service <em>Custom…</em>, Server <code>rtmp://127.0.0.1:1935/live</code>, Stream Key anything (it stays on your computer). Settings → <em>Output</em>: a keyframe interval of <strong>2</strong> seconds, H.264 video (x264 or your graphics card’s), AAC audio, and a bitrate your upload can carry (3000–6000 Kbps for 1080p).</li>'
        .'<li><strong>Start Streaming</strong> in OBS. live-upload says <em>Live.</em>, this screen says <em>live</em>, and the Live page plays the stream about 10 seconds behind. <strong>Stop Streaming</strong> takes it off the site; live-upload waits for the next time (Ctrl+C stops it).</li></ol>';
    my $save='<form method="post" action="/admin/x/live/" class="admin-form">'.fields('save_streams','x-live')
        .switch_field('save','Save each stream to the Videos library, tagged <a href="/tags/pastlivestreams/">#pastlivestreams</a>',saving(),html=>1)
        .'<span class="optional">When you stop streaming, the stream is added to Videos within a minute or two, ready to watch (and to rename or delete there). While it’s recording it takes as much room on the server as the stream so far; it stops recording, not streaming, before the disk gets too full.</span>'
        .'<button class="buttonlike" type="submit">save</button></form>';
    window('stream',$st.'<div class="box-part"><h3>Stream key</h3>'.$k.'</div><div class="box-part" id="saving"><h3>Saving streams</h3>'.$save.'</div><details class="box-part mail-setup"'.(length key_hash() ? '' : ' open').'><summary>Setting up OBS</summary>'.$setup.'</details>');
    end_page();
    return 1;
}
sub mb ($bytes) { return $bytes>=1073741824 ? sprintf('%.1f GB',$bytes/1073741824) : sprintf('%d MB',$bytes/1048576) }
sub ago ($t) {
    my $s=time-$t;
    return $s<60 ? 'just now' : $s<3600 ? int($s/60).' min ago' : $s<86400 ? int($s/3600).' h ago' : int($s/86400).' days ago';
}

1;