BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
506 lines · 31.2 KB · download this file
package BlowfishCMS;
# Video: the video library. Videos are uploaded as exported (MP4: H.264, AV1
# or VP9 video with AAC or Opus audio), in pieces like every library upload
# (Library.pm), so a 2 GB file needs no single long request and an interrupted
# upload can resume. Each finished
# upload is checked by reading its MP4 structure (mp4_info) and then stored
# unchanged under the media folder's video/, where httpd serves it with range
# requests for streaming. Optional poster images go through the image pipeline.
# Every BlowfishCMS/*.pm file adds subs to the one BlowfishCMS package; request state
# is shared through the package variables below and reset by BlowfishCMS::handle_request.
use v5.36;
use utf8;
use JSON::PP qw(encode_json decode_json);
use Digest::SHA qw(hmac_sha256_hex sha256_hex);
use Encode qw(decode encode FB_CROAK);
use Fcntl qw(:flock :DEFAULT);
use Unicode::Normalize qw(NFKC);
use POSIX qw(strftime);
use File::Basename qw(basename);
our ($base,$data,$store,$cdata,$root,$db,$q,$route,$admin,$contact,$comments_route,$method,$cookie_header,$csrf);
sub video_max_bytes { 2*1024*1024*1024 } # largest video accepted
sub video_dir { "$store/video" }
# Free space (bytes) on the filesystem holding $dir, from df(1).
# How much space is free where $dir is, in bytes: it runs `df -k` and reads
# the "available" column (the fourth) of its last line. undef if unknown.
sub free_bytes ($dir) {
open my $df,'-|','/bin/df','-k',$dir or return undef;
my @lines=<$df>;close $df;
my @f=split ' ',$lines[-1]//'';
return @f>=4 && $f[3] =~ /\A\d+\z/ ? $f[3]*1024 : undef;
}
# Seconds as "4:05" or "1:02:03".
sub duration_text ($seconds) {
my $s=int(($seconds//0)+.5);
return $s>=3600 ? sprintf('%d:%02d:%02d',$s/3600,($s/60)%60,$s%60) : sprintf('%d:%02d',$s/60,$s%60);
}
# ---- MP4 inspection ---------------------------------------------------------
# Reads the box structure of an MP4 file without decoding any video: the codecs,
# picture size, frame rate and duration, and whether the index (moov) comes
# before the media data, which lets playback start before the whole index
# has been downloaded ("fast start"). Dies with a message for files browsers
# can't play.
# An MP4 file is a tree of "boxes" (also called atoms): each starts with its
# length (4 bytes) and a 4-letter type, and may contain more boxes. This
# lists the boxes found directly in a piece of data, as [type, contents].
# A length of 1 means a 64-bit length follows; 0 means "to the end".
sub mp4_boxes ($buf) {
my @boxes;my $pos=0;my $n=length $buf;
while ($pos+8<=$n) {
my ($len,$type)=unpack('Na4',substr($buf,$pos,8));my $hdr=8;
if ($len==1) {last if $pos+16>$n;$len=unpack('Q>',substr($buf,$pos+8,8));$hdr=16}
elsif ($len==0) {$len=$n-$pos}
last if $len<$hdr || $pos+$len>$n;
push @boxes,[$type,substr($buf,$pos+$hdr,$len-$hdr)];
$pos+=$len;
}
return @boxes;
}
# Finds a box by its path, one level at a time: mp4_child($moov,'mdia',
# 'minf') is moov's mdia's minf. undef if it isn't there.
sub mp4_child ($buf,@path) {
for my $want (@path) {my ($box)=grep {$_->[0] eq $want} mp4_boxes($buf);return undef unless $box;$buf=$box->[1]}
return $buf;
}
# Checks an uploaded video before it's accepted, by reading its structure
# (never decoding the picture). It walks the top-level boxes on disk (the
# media data can be gigabytes, so only box headers are read), needs ftyp,
# moov (the index) and mdat (the media), then reads moov into memory and
# finds:
# - the duration (mvhd: a length in "time units" and units per second)
# - for the first video track: its codec (from stsd), its size (tkhd stores
# it as 16.16 fixed-point numbers, hence the /65536) and its frame rate
# (frames counted in stts, divided by the track's duration from mdhd)
# - for the first sound track: its codec
# - fast_start: whether the index comes before the media, which lets
# playback begin before the whole file has downloaded
# Then it refuses what browsers can't play, with a message saying how to
# export instead: HEVC, encrypted video, unknown codecs, Dolby sound, or
# pictures larger than 4096 px.
sub mp4_info ($path) {
open my $fh,'<:raw',$path or die "The upload could not be read.\n";
my $size=-s $path;my ($pos,%top)=(0);
while ($pos+8<=$size) {
seek($fh,$pos,0);read($fh,my $h,16);
my ($len,$type)=unpack('Na4',$h);my $hdr=8;
if ($len==1) {$len=unpack('Q>',substr($h,8,8));$hdr=16}
elsif ($len==0) {$len=$size-$pos}
die "This isn't a complete MP4 file. Export it again as MP4.\n" if $len<$hdr || $pos+$len>$size || $type !~ /\A[\x20-\x7e]{4}\z/;
$top{$type} //= [$pos,$len,$hdr];
$pos+=$len;
}
die "Use an MP4 video (exported as H.264, AV1 or VP9 in an .mp4 file).\n" unless $top{ftyp} && $top{moov};
die "This MP4 has no video data. Export it again.\n" unless $top{mdat};
my ($moov_pos,$moov_len,$moov_hdr)=@{$top{moov}};
die "This MP4's index is unusually large (over 64 MB); export it again with standard settings.\n" if $moov_len>64*1048576;
seek($fh,$moov_pos+$moov_hdr,0);read($fh,my $moov,$moov_len-$moov_hdr);close $fh;
my %info=(fast_start=>($moov_pos<$top{mdat}[0]) ? 1 : 0);
if (defined(my $mvhd=mp4_child($moov,'mvhd'))) {
my ($scale,$dur)=ord($mvhd)==1 ? (unpack('N',substr($mvhd,20,4)),unpack('Q>',substr($mvhd,24,8))) : unpack('NN',substr($mvhd,12,8));
$info{duration}=$scale ? $dur/$scale : 0;
}
for my $trak (map {$_->[1]} grep {$_->[0] eq 'trak'} mp4_boxes($moov)) {
my $hdlr=mp4_child($trak,'mdia','hdlr') // next;my $handler=substr($hdlr,8,4);
my $stsd=mp4_child($trak,'mdia','minf','stbl','stsd') // next;
my $codec=length($stsd)>=16 ? substr($stsd,12,4) : '';
if ($handler eq 'vide' && !$info{video}) {
$info{video}=$codec;
my $tkhd=mp4_child($trak,'tkhd') // '';
($info{width},$info{height})=map {int($_/65536)} unpack('NN',substr($tkhd,-8)) if length($tkhd)>=8;
# Frame rate: samples in the track divided by its duration.
my $mdhd=mp4_child($trak,'mdia','mdhd') // '';my $stts=mp4_child($trak,'mdia','minf','stbl','stts') // '';
my ($scale,$dur)=ord($mdhd)==1 ? (unpack('N',substr($mdhd,20,4)),unpack('Q>',substr($mdhd,24,8))) : length($mdhd)>=20 ? unpack('NN',substr($mdhd,12,8)) : (0,0);
if ($scale && $dur && length($stts)>=8) {
my $n=unpack('N',substr($stts,4,4));my $frames=0;
$frames+=unpack('N',substr($stts,8+8*$_,4)) for grep {8+8*$_+8<=length $stts} 0..$n-1;
$info{fps}=$frames/($dur/$scale) if $frames;
}
} elsif ($handler eq 'soun' && !$info{audio}) {
$info{audio}=$codec;
}
}
my $v=$info{video} // die "This file has no video track.\n";
die "This video is HEVC (H.265), which most browsers can't play. Export it as H.264 (AVC) instead.\n" if $v =~ /\A(?:hvc1|hev1|dvh1|dvhe)\z/;
die "This video is encrypted (DRM) and can't be played on the site.\n" if $v eq 'encv' || ($info{audio}//'') eq 'enca';
die "This video uses the '".($v =~ s/[^\x20-\x7e]/?/gr)."' format, which browsers can't play. Export it as H.264 (AVC) in an MP4 file.\n" unless $v =~ /\A(?:avc1|avc3|av01|vp09)\z/;
if (defined(my $a=$info{audio})) {
die "The sound is Dolby (AC-3/E-AC-3), which most browsers can't play. Export the audio as AAC.\n" if $a =~ /\A(?:ac-3|ec-3)\z/;
die "The sound uses the '".($a =~ s/[^\x20-\x7e]/?/gr)."' format, which browsers can't play. Export the audio as AAC.\n" unless $a =~ /\A(?:mp4a|Opus|fLaC)\z/;
}
die "The picture is larger than 4096 pixels; export at 1080p or 4K.\n" if ($info{width}//0)>4096 || ($info{height}//0)>4096;
return \%info;
}
# "1920×1080 · 29.97 fps · 4:05" for an item.
sub video_summary ($item) {
return join ' · ',grep {length} ($item->{width} && $item->{height} ? "$item->{width}×$item->{height}" : ''),
(defined $item->{fps} ? sprintf('%g fps',int($item->{fps}*100+.5)/100) : ''),($item->{duration} ? duration_text($item->{duration}) : '');
}
# Publishes a finished upload (Library.pm receives it in pieces): checks the
# MP4, stores it unchanged with its optional poster, and returns a message.
# Turns a finished upload into a library video: checks it (mp4_info), stores
# an optional poster picture, moves the file into the video folder under a
# random name, and adds the catalogue entry at the top of the library. If the
# entry can't be added, the file and poster are removed again.
sub video_publish ($part,$meta) {
my $info=mp4_info($part);
my $poster=$q->upload('poster') ? save_image($q->upload('poster'),'video') : undef;
my $vid=random_id();my $file="$vid.mp4";my $dest=video_dir()."/$file";
require File::Copy;
unless (File::Copy::move($part,$dest)) {my $e=$!;remove_image('video',$poster->{filename}) if $poster;die "The video could not be stored ($e).\n"}
chmod 0644,$dest;
my $title=upload_title($meta->{name});
attempt {
$db->do('INSERT INTO uploads (id,kind,title,description,collection,filename,thumbnail,mime,bytes,width,height,duration,fps,created_at,artwork,sort_order) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,(SELECT COALESCE(MIN(sort_order),0)-1 FROM uploads WHERE kind=?))',undef,
$vid,'video',$title,$meta->{description},$meta->{collection},$file,$poster?$poster->{filename}:'','video/mp4',$meta->{size},$info->{width},$info->{height},$info->{duration},$info->{fps},now(),'','video');
1;
} or do {my $e=$@;unlink $dest;remove_image('video',$poster->{filename}) if $poster;die $e};
my $note=$info->{fast_start} ? '' : ' It wasn’t exported with “fast start” (web optimised), so playback may take a moment longer to begin; it still plays normally.';
return "“$title” published (".video_summary({%$info}).").$note";
}
# Replace or remove a video's poster image (from the library).
# Replaces or removes a video's poster picture (the picture shown before it
# plays).
sub video_poster ($item) {
my $poster=param('remove_poster',1) eq '1' ? undef : save_image($q->upload('poster'),'video');
attempt {$db->do('UPDATE uploads SET thumbnail=? WHERE id=?',undef,$poster?$poster->{filename}:'',$item->{id});1}
or do {my $e=$@;remove_image('video',$poster->{filename}) if $poster;die $e};
remove_image('video',$item->{thumbnail}) if $item->{thumbnail};
return $poster ? 'Poster updated.' : 'Poster removed; the first frame is shown instead.';
}
# ---- Public list (the videos block) ------------------------------------------
# Videos, each linking to its item page with its likes and comments (%o page
# and tag_buttons, as for music).
# Draws a list of videos for the video gallery block. With a poster nothing
# is downloaded until play (preload="none"); without one, the browser fetches
# just enough to show a frame, and "#t=0.1" makes that the frame at 0.1 s
# rather than a possibly black first frame. controlslist="nodownload" hides
# the browser's download button.
sub video_list_html ($list,$show_filter=1,%o) {
my $pages=$o{page}//1;my ($likes,$talk)=$pages ? talk_counts('video') : ({},{});my $stats=$pages && talk_library_on('video') && comments_enabled();
return '<p class="empty-media">No videos yet. Check back soon.</p>' unless @$list;
my $tmap=$o{tag_buttons} ? item_tags_map('video') : undef;
my $html=($show_filter ? collection_filter_html($list) : '').tag_buttons_html($tmap,$list).'<div class="video-list">';
for my $item (@$list) {
my $title=h($item->{title});my $url=h(media_url($item));
# With a poster nothing loads until play; without one, the first frame is shown.
my $poster=$item->{thumbnail} ? ' poster="'.h(media_url($item,1)).'" preload="none"' : ' preload="metadata"';
$html.='<article class="video-card" data-collection="'.h($item->{collection}).'"'.tags_data_attr($tmap,$item->{id}).'>'
.'<video controls playsinline controlslist="nodownload" disableremoteplayback'.$poster.' src="'.$url.($item->{thumbnail}?'':'#t=0.1').'" aria-label="'.$title.'"></video>'
.'<div class="video-info"><h2>'.($pages ? '<a href="/video/'.$item->{id}.'/">'.$title.'</a>' : $title).'</h2>'.($stats && !$item->{talk_off} ? talk_stats_html($likes->{$item->{id}},$talk->{$item->{id}}) : '').'<p class="media-label">'.h(join ' · ',grep {length} $item->{collection},($item->{duration} ? duration_text($item->{duration}) : '')).'</p>'
.(length $item->{description} ? '<p>'.h($item->{description}).'</p>' : '').'</div></article>';
}
return $html.'</div>';
}
# ---- Livestreams into the library ------------------------------------------------
# A livestream arrives as a "fragmented" MP4: its index (moov) lists no
# samples, and each 2-second piece brings its own small index (moof) before
# its media (mdat). Browsers play that while it's live, but as a file it has
# no length and can't be seeked, and mp4_info refuses it. mp4_unfragment
# writes the same picture and sound as an ordinary MP4: one index at the
# front (fast start) listing every sample, then the media, copied unchanged.
# Nothing is decoded, so it takes about as long as copying the file.
#
# It reads each moof's track fragments (traf): tfhd (the track and its
# defaults; trex in the moov has the defaults' defaults), tfdt (when the
# fragment starts, in the track's time units) and trun (the samples: size,
# duration, flags, composition offset, and where their data is). A gap
# before a fragment (a piece that never arrived) lengthens the sample before
# it, so sound and picture stay together; a fragment that goes back in time
# is a repeat and is skipped; a piece cut short at the end (the recording
# stopped mid-write) is left out.
#
# The edit list (edts/elst) says where each track starts on screen: the
# encoder's delays (B-frames, sound priming) are in the stream's own edit
# list, and the tracks may also start at different moments of the stream.
# Both are kept, measured from the track that starts first.
# A box: its length, type and contents (a 64-bit length when it's 4 GB or more).
sub mp4_box ($type,$body) {
my $n=length($body)+8;
return $n<=0xffffffff ? pack('Na4',$n,$type).$body : pack('Na4Q>',1,$type,$n+8).$body;
}
# A "full box": a version and flags before the contents.
sub mp4_fullbox ($type,$version,$flags,$body) { return mp4_box($type,pack('N',($version<<24)|$flags).$body) }
# Run-length entries from packed 32-bit numbers: how many, and the entries
# packed as (count, value) pairs. Read four bytes at a time, so a long
# stream's million samples never become a million Perl values at once (a
# 3-hour stream would otherwise take hundreds of MB while it's joined).
sub mp4_runs ($packed,$fmt='N') {
my ($out,$n,$count,$prev)=('',0,0,undef);
for (my $i=0;$i<length $packed;$i+=4) {
my $v=unpack($fmt,substr($packed,$i,4));
if (defined $prev && $v==$prev) {$count++;next}
if (defined $prev) {$out.=pack("N$fmt",$count,$prev);$n++}
($prev,$count)=($v,1);
}
if (defined $prev) {$out.=pack("N$fmt",$count,$prev);$n++}
return ($n,$out);
}
# A header box (mvhd, tkhd, mdhd) with a new duration. A 32-bit duration
# that no longer fits is written as version 1, with 64-bit times.
sub mp4_set_duration ($type,$body,$dur) {
my $v=ord $body;
# Where the duration is, after the version, the times and (tkhd) the track number.
my %at=(mvhd=>[16,24],mdhd=>[16,24],tkhd=>[20,28]);
my ($at0,$at1)=@{$at{$type}};
if ($v==1) {substr($body,$at1,8)=pack('Q>',$dur);return $body}
if ($dur<=0xffffffff) {substr($body,$at0,4)=pack('N',$dur);return $body}
# Version 0 to 1: the two times and the duration become 64-bit.
my ($ct,$mt)=unpack('NN',substr($body,4,8));
my $mid=$type eq 'tkhd' ? substr($body,12,8) : substr($body,12,4); # track number and reserved, or the time scale
return pack('N',(1<<24)|(unpack('N',$body)&0xffffff)).pack('Q>Q>',$ct,$mt).$mid.pack('Q>',$dur).substr($body,$at0+4);
}
# Whether an MP4 is fragmented: it has a moof (a piece's own index) at the top level.
sub mp4_fragmented ($path) {
open my $fh,'<:raw',$path or return 0;my $size=-s $path;my $pos=0;
while ($pos+8<=$size) {
seek($fh,$pos,0);read($fh,my $h,16);my ($len,$type)=unpack('Na4',$h);
if ($len==1) {$len=unpack('Q>',substr($h,8,8))} elsif ($len==0) {last}
last if $len<8;
return 1 if $type eq 'moof';
$pos+=$len;
}
return 0;
}
sub mp4_unfragment ($in,$out) {
open my $fh,'<:raw',$in or die "The recording could not be read.\n";
my $size=-s $in;my ($pos,$moov,%t,@ids,@chunks)=(0);my $rel=0;
my $stop=0; # set once a piece is cut short: nothing after it is used
while (!$stop && $pos+8<=$size) {
seek($fh,$pos,0);read($fh,my $h,16);
my ($len,$type)=unpack('Na4',$h);my $hdr=8;
if ($len==1) {$len=unpack('Q>',substr($h,8,8));$hdr=16} elsif ($len==0) {$len=$size-$pos}
last if $len<$hdr || $pos+$len>$size;
if ($type eq 'moov' || $type eq 'moof') {
die "This recording's index is unusually large.\n" if $len>64*1048576;
seek($fh,$pos+$hdr,0);read($fh,my $body,$len-$hdr);
if ($type eq 'moov') {
die "This recording has two beginnings.\n" if $moov;
$moov=$body;
my %trex;
for my $x (map {$_->[1]} grep {$_->[0] eq 'trex'} mp4_boxes(mp4_child($body,'mvex') // '')) {my ($id,@d)=unpack('x4NNNNN',$x);$trex{$id}=\@d}
for my $trak (map {$_->[1]} grep {$_->[0] eq 'trak'} mp4_boxes($body)) {
my $tkhd=mp4_child($trak,'tkhd') // next;my $id=unpack('N',substr($tkhd,ord($tkhd)==1 ? 20 : 12,4));
my $mdhd=mp4_child($trak,'mdia','mdhd') // next;
my $ts=unpack('N',substr($mdhd,ord($mdhd)==1 ? 20 : 12,4)) or next;
my $hdlr=mp4_child($trak,'mdia','hdlr') // '';
# The stream's own edit list: its empty edits (in the movie's
# units) and the media time the first real edit starts at.
my ($empty,$mtime)=(0,0);
if (defined(my $elst=mp4_child($trak,'edts','elst'))) {
my ($vf,$n)=unpack('NN',$elst);my $w=($vf>>24)==1 ? 20 : 12;
for my $i (0..$n-1) {
last if 8+($i+1)*$w>length $elst;
my ($d,$m)=$w==20 ? unpack('Q>q>',substr($elst,8+$i*$w,16)) : unpack('Nl>',substr($elst,8+$i*$w,8));
if ($m<0) {$empty+=$d} else {$mtime=$m;last}
}
}
$t{$id}={trak=>$trak,ts=>$ts,video=>substr($hdlr,8,4) eq 'vide',empty=>$empty,mtime=>$mtime,trex=>$trex{$id}//[1,0,0,0],
sizes=>'',durs=>'',ctos=>'',sync=>'',n=>0,chunks=>[],neg=>0,cto=>0};
push @ids,$id;
}
die "This recording has no tracks.\n" unless @ids;
} else {
die "This recording doesn't start with its index.\n" unless $moov;
# Every track's samples in this piece are read first, and kept
# only if the whole piece is there: picture and sound end together.
my @plan;
for my $traf (map {$_->[1]} grep {$_->[0] eq 'traf'} mp4_boxes($body)) {
my $tfhd=mp4_child($traf,'tfhd') // next;
my ($vf,$id)=unpack('NN',$tfhd);my $tr=$t{$id} or next;
my $o=8;my $base=$pos;
if ($vf&0x1) {$base=unpack('Q>',substr($tfhd,$o,8));$o+=8}
$o+=4 if $vf&0x2;
my $ddur=$tr->{trex}[1];my $dsize=$tr->{trex}[2];my $dflags=$tr->{trex}[3];
if ($vf&0x8) {$ddur=unpack('N',substr($tfhd,$o,4));$o+=4}
if ($vf&0x10) {$dsize=unpack('N',substr($tfhd,$o,4));$o+=4}
if ($vf&0x20) {$dflags=unpack('N',substr($tfhd,$o,4));$o+=4}
next if $vf&0x10000; # "duration is empty": no samples
my $tfdt=mp4_child($traf,'tfdt');
my $start=defined $tfdt ? (ord($tfdt)==1 ? unpack('Q>',substr($tfdt,4,8)) : unpack('N',substr($tfdt,4,4))) : $tr->{next};
my (@runs,$data);
for my $trun (map {$_->[1]} grep {$_->[0] eq 'trun'} mp4_boxes($traf)) {
my ($tvf,$n)=unpack('NN',$trun);my $ver=$tvf>>24;my $f=$tvf&0xffffff;my $p=8;
if ($f&0x1) {$data=$base+unpack('l>',substr($trun,$p,4));$p+=4}
$data//=$base;
my $first;if ($f&0x4) {$first=unpack('N',substr($trun,$p,4));$p+=4}
my $per=4*(!!($f&0x100)+!!($f&0x200)+!!($f&0x400)+!!($f&0x800));
die "This recording's index is damaged.\n" if $p+$n*$per>length $trun;
my (@s,$bytes);$bytes=0;
for my $i (0..$n-1) {
my ($d,$sz,$fl,$c)=($ddur,$dsize,$dflags,0);
if ($f&0x100) {$d=unpack('N',substr($trun,$p,4));$p+=4}
if ($f&0x200) {$sz=unpack('N',substr($trun,$p,4));$p+=4}
if ($f&0x400) {$fl=unpack('N',substr($trun,$p,4));$p+=4} elsif ($i==0 && defined $first) {$fl=$first}
if ($f&0x800) {$c=$ver ? unpack('l>',substr($trun,$p,4)) : unpack('N',substr($trun,$p,4));$p+=4}
push @s,[$d,$sz,$fl,$c];$bytes+=$sz;
}
if ($data+$bytes>$size) {$stop=1;last}
push @runs,[$data,$bytes,\@s];$data+=$bytes;
}
last if $stop;
push @plan,[$tr,$start,\@runs] if @runs;
}
for my $pl ($stop ? () : @plan) {
my ($tr,$start,$runs)=@$pl;
# Where it starts against where the track had got to.
if (defined $tr->{next}) {
my $gap=$start-$tr->{next};
my $last=$tr->{n} ? unpack('N',substr($tr->{durs},-4)) : 0;
if ($gap<0 && -$gap>=$last) {next} # a repeat
substr($tr->{durs},-4)=pack('N',$last+$gap) if $gap && $tr->{n};
$tr->{next}+=$gap;
} else {
$tr->{t0}=$tr->{next}=$start;
}
my $dts=$tr->{next};
for my $run (@$runs) {
my ($from,$bytes,$s)=@$run;
for my $x (@$s) {
my ($d,$sz,$fl,$c)=@$x;
$tr->{n}++;
$tr->{sizes}.=pack('N',$sz);$tr->{durs}.=pack('N',$d);$tr->{ctos}.=pack('l>',$c);
$tr->{cto}=1 if $c;$tr->{neg}=1 if $c<0;
# A sync sample (one playback can start at) doesn't have "is non-sync" (bit 16).
$tr->{sync}.=pack('N',$tr->{n}) unless $fl&0x10000;
# Where the first picture shows: the earliest composition time.
$tr->{first}=$dts+$c if !defined $tr->{first} || $dts+$c<$tr->{first};
$dts+=$d;
}
push @{$tr->{chunks}},[$rel,scalar @$s];push @chunks,[$from,$bytes];$rel+=$bytes;
}
$tr->{next}=$dts;
}
}
}
$pos+=$len;
}
@ids=grep {$t{$_}{n}} @ids;
die "This recording has no video or sound in it.\n" unless @ids && $moov;
my $mvhd=mp4_child($moov,'mvhd') // die "This recording's index is damaged.\n";
my $mts=unpack('N',substr($mvhd,ord($mvhd)==1 ? 20 : 12,4)) || 1000;
# When each track starts on screen, in seconds: the stream's own empty
# edits, plus how far its first picture or sound is past its edit's start.
for my $tr (map {$t{$_}} @ids) {
my $from=$tr->{first}>$tr->{mtime} ? $tr->{first} : $tr->{mtime};
$from=$tr->{t0} if $from<$tr->{t0};
$tr->{from}=$from;
$tr->{shows}=$tr->{empty}/$mts+($from-$tr->{mtime})/$tr->{ts};
}
my ($origin)=sort {$a<=>$b} map {$t{$_}{shows}} @ids;
my $mdat_bytes=$rel;my $long=$mdat_bytes+8>0xffffffff;
my $co64=$mdat_bytes+64*1048576>0xffffffff;
my $build=sub ($base) {
my ($movie_dur,$traks)=(0,'');
for my $tr (map {$t{$_}} @ids) {
my $total=$tr->{next}-$tr->{t0};
my $wait=int(($tr->{shows}-$origin)*$mts+.5);
my $plays=int(($tr->{t0}+$total-$tr->{from})/$tr->{ts}*$mts+.5);$plays=0 if $plays<0;
$movie_dur=$wait+$plays if $wait+$plays>$movie_dur;
my $elst=($wait ? pack('Nl>nn',$wait,-1,1,0) : '').pack('Nl>nn',$plays,$tr->{from}-$tr->{t0},1,0);
my $stbl=mp4_box('stsd',mp4_child($tr->{trak},'mdia','minf','stbl','stsd'));
my ($sn,$stts)=mp4_runs($tr->{durs});
$stbl.=mp4_fullbox('stts',0,0,pack('N',$sn).$stts);
if ($tr->{cto}) {my ($cn,$ctts)=mp4_runs($tr->{ctos},'l>');$stbl.=mp4_fullbox('ctts',$tr->{neg} ? 1 : 0,0,pack('N',$cn).$ctts)}
my $nsync=length($tr->{sync})/4;
$stbl.=mp4_fullbox('stss',0,0,pack('N',$nsync).$tr->{sync}) if $tr->{video} && $nsync<$tr->{n};
my (@stsc,$k);
for my $c (@{$tr->{chunks}}) {$k++;push @stsc,[$k,$c->[1]] unless @stsc && $stsc[-1][1]==$c->[1]}
$stbl.=mp4_fullbox('stsc',0,0,pack('N',scalar @stsc).join('',map {pack('NNN',@$_,1)} @stsc));
$stbl.=mp4_fullbox('stsz',0,0,pack('NN',0,$tr->{n}).$tr->{sizes});
$stbl.=$co64 ? mp4_fullbox('co64',0,0,pack('N',scalar @{$tr->{chunks}}).join('',map {pack('Q>',$base+$_->[0])} @{$tr->{chunks}}))
: mp4_fullbox('stco',0,0,pack('N',scalar @{$tr->{chunks}}).join('',map {pack('N',$base+$_->[0])} @{$tr->{chunks}}));
my $minf=join('',map {mp4_box(@$_)} grep {$_->[0] ne 'stbl'} mp4_boxes(mp4_child($tr->{trak},'mdia','minf'))).mp4_box('stbl',$stbl);
my $mdia=join('',map {$_->[0] eq 'mdhd' ? mp4_box('mdhd',mp4_set_duration('mdhd',$_->[1],$total)) : $_->[0] eq 'minf' ? mp4_box('minf',$minf) : mp4_box(@$_)} mp4_boxes(mp4_child($tr->{trak},'mdia')));
$traks.=mp4_box('trak',mp4_box('tkhd',mp4_set_duration('tkhd',mp4_child($tr->{trak},'tkhd'),$wait+$plays))
.mp4_box('edts',mp4_fullbox('elst',0,0,pack('N',$wait ? 2 : 1).$elst)).mp4_box('mdia',$mdia));
}
return mp4_box('moov',mp4_box('mvhd',mp4_set_duration('mvhd',$mvhd,$movie_dur)).$traks);
};
my $ftyp=mp4_box('ftyp','isom'.pack('N',512).'isomiso2avc1mp41');
my $head=$ftyp.$build->(0);
$head=$ftyp.$build->(length($head)+($long ? 16 : 8));
open my $oh,'>:raw',$out or die "The video could not be written.\n";
print {$oh} $head,($long ? pack('Na4Q>',1,'mdat',$mdat_bytes+16) : pack('Na4',$mdat_bytes+8,'mdat'));
for my $c (@chunks) {
my ($from,$left)=@$c;seek($fh,$from,0);
while ($left>0) {
my $got=read($fh,my $buf,$left>4194304 ? 4194304 : $left) or die "The recording could not be read.\n";
print {$oh} $buf or die "The video could not be written (is the disk full?).\n";$left-=$got;
}
}
close $oh or die "The video could not be written (is the disk full?).\n";
close $fh;
return 1;
}
# Videos handed to the library by add-ons (Live's saved streams), each a
# NAME.mp4 with a NAME.json saying its title, description and tags. An
# add-on writes them in its own data folder's videos/; every minute root's
# `blowfishctl requests` moves them here (only files that are the add-on's
# own) and runs `site.pl --import-videos` as the admin's account.
sub videos_in_dir { "$data/videos-in" }
# site.pl --import-videos: adds each waiting video to the library, at the top,
# as a fragmented recording joined into an ordinary MP4 (or as it is when it
# already is one), checked like an upload. Without room for the copy it
# waits (it's tried again next minute); a video that can't be added goes to
# failed/ with a note of why, which the Overview shows until it's cleared.
sub videos_import_cli {
# What it says goes to blowfishcms-videos.log, titles and all.
binmode STDOUT,':encoding(UTF-8)';binmode STDERR,':encoding(UTF-8)';
my $dir=videos_in_dir();
opendir(my $dh,$dir) or return 0;
my @names=sort grep {/\A[a-z0-9][a-z0-9_-]{0,80}\.mp4\z/ && -f "$dir/$_" && !-l "$dir/$_"} readdir $dh;closedir $dh;
my $status=0;
for my $name (@names) {
my $stem=$name =~ s/\.mp4\z//r;my $src="$dir/$name";
my $meta=read_json_file("$dir/$stem.json");$meta={} unless ref $meta eq 'HASH';
my $bytes=-s $src;my $free=free_bytes(video_dir());
if (defined $free && $free<$bytes+256*1048576) {say STDERR "$name: waiting for disk space (".int($bytes/1048576)." MB needed)";$status=1;next}
my $vid=random_id();my $dest=video_dir()."/$vid.mp4";
my $fragmented=mp4_fragmented($src);
my $ok=attempt {
my $info;
if ($fragmented) {mp4_unfragment($src,"$dest.part");$info=mp4_info("$dest.part");rename "$dest.part",$dest or die "The video could not be stored.\n"}
else {$info=mp4_info($src);require File::Copy;File::Copy::move($src,$dest) or die "The video could not be stored ($!).\n"}
chmod 0644,$dest;
my $clean=sub ($v,$max) {$v=decode('UTF-8',$v//'',sub {''}) unless utf8::is_utf8($v//'');$v =~ s/[\x00-\x1f\x7f]+/ /g;$v =~ s/\A\s+|\s+\z//g;return substr($v,0,$max)};
my $title=$clean->($meta->{title},200);$title=upload_title($name) unless length $title;
$db->begin_work;
$db->do('INSERT INTO uploads (id,kind,title,description,collection,filename,thumbnail,mime,bytes,width,height,duration,fps,created_at,artwork,sort_order) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,(SELECT COALESCE(MIN(sort_order),0)-1 FROM uploads WHERE kind=?))',undef,
$vid,'video',$title,$clean->($meta->{description},4000),$clean->($meta->{collection},80),"$vid.mp4",'','video/mp4',-s $dest,$info->{width},$info->{height},$info->{duration},$info->{fps},now(),'','video');
item_tags_set('video',$vid,$clean->($meta->{tags},400));
$db->commit;
say "$name: added to Videos as “$title” (".video_summary({%$info}).')';
1;
};
if ($ok) {unlink $src,"$dir/$stem.json";next}
my $e=clean_error($@);attempt {$db->rollback} if $db->{BegunWork};
# An ordinary MP4 already moved goes back; a joined copy is removed.
if (!$fragmented && -e $dest && !-e $src) {rename $dest,$src} else {unlink $dest}
unlink "$dest.part";
mkdir "$dir/failed",0700;
if (rename $src,"$dir/failed/$name") {
rename "$dir/$stem.json","$dir/failed/$stem.json";
if (open my $fh,'>:raw',"$dir/failed/$stem.why") {print {$fh} encode('UTF-8',$e);close $fh}
}
say STDERR "$name: $e";$status=1;
}
return $status;
}
# Videos an add-on handed over that couldn't be added: [file, why], for the
# Overview. They stay in videos-in/failed/ (on the server) until removed.
sub videos_failed {
my $dir=videos_in_dir().'/failed';opendir(my $dh,$dir) or return ();
my @f=sort grep {/\A[a-z0-9][a-z0-9_-]{0,80}\.mp4\z/} readdir $dh;closedir $dh;
return map {my $stem=s/\.mp4\z//r;my $why='';if (open my $fh,'<:raw',"$dir/$stem.why") {local $/;$why=decode('UTF-8',<$fh>//'',sub {''});close $fh}[$_,$why]} @f;
}
1;