Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ Beholder is a Scala 3 HTTP microservice that extracts individual frames from vid
## Requirements

- Java 21+
- [ffmpeg](https://ffmpeg.org/download.html) installed and on `PATH`
- [ffmpeg](https://ffmpeg.org/download.html) **7.1 or newer**, with `ffprobe`, installed and on `PATH`.
Both binaries ship in the same package on Homebrew and Debian/Ubuntu. Without `ffprobe`
captures still succeed, but H.264/HEVC frames keep their codec padding rows (a green band
along the bottom). The Docker image pins and version-checks this for you.
- [sbt](https://www.scala-sbt.org/) (Scala Build Tool)

## API
Expand Down
28 changes: 25 additions & 3 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -29,23 +29,44 @@ Compile / doc / scalacOptions ++= Seq(
"./src/docs/index.md"
)

// Oldest allowed ffmpeg. Container-level clean-aperture (clap) handling landed around 7.1
val minFfmpegMajorVersion = 7

// The apt step, as a single RUN. ffprobe is a hard requirement
val installFfmpegCmd: String =
"""apt-get update \
| && apt-get install -y --no-install-recommends ffmpeg \
| && rm -rf /var/lib/apt/lists/* \
| && command -v ffmpeg \
| && command -v ffprobe \
| && ffmpeg_version="$(ffmpeg -version | head -1 | cut -d' ' -f3)" \
| && ffmpeg_major="$(printf '%s' "$ffmpeg_version" | sed 's/^[nN]//' | cut -d. -f1 | cut -d- -f1)" \
| && echo "ffmpeg version: $ffmpeg_version (major $ffmpeg_major)" \
| && { case "$ffmpeg_major" in ''|*[!0-9]*) echo "ERROR: cannot parse ffmpeg version '$ffmpeg_version'" >&2; exit 1;; esac; } \
| && { [ "$ffmpeg_major" -ge MIN_FFMPEG_MAJOR ] || { echo "ERROR: ffmpeg $ffmpeg_version is older than required major MIN_FFMPEG_MAJOR" >&2; exit 1; }; }"""
.stripMargin('|')
.replace("MIN_FFMPEG_MAJOR", minFfmpegMajorVersion.toString)

// Hack to get the apt-get command in the right place in the docker file
// Inserts apt-get before user is changed to non-root
// Inserts apt-get before user is changed to non-root (apt needs root)
def buildDocker(cmds: Seq[CmdLike]): Seq[CmdLike] =
val idx = cmds.indexWhere(_ match
case Cmd("USER", user) => user != "root"
case _ => false
)
cmds.take(idx) ++
Seq(Cmd("RUN", "apt-get update && apt-get install -y ffmpeg")) ++
Seq(Cmd("RUN", installFfmpegCmd)) ++
cmds.drop(idx)

lazy val root = project
.in(file("."))
.enablePlugins(AutomateHeaderPlugin, GitBranchPrompt, GitVersioning, JavaAppPackaging)
.settings(
name := "beholder",
dockerBaseImage := "eclipse-temurin:25",
// Pinned to the Ubuntu release (26.04 "resolute"); the distro is what
// determines ffmpeg's major series (8.0.x here), Moving to a newer
// Ubuntu/JDK is a deliberate bump; re-check ffmpeg when you make one.
dockerBaseImage := "eclipse-temurin:25-jdk-resolute",
dockerCommands := buildDocker(dockerCommands.value),
dockerEntrypoint := Seq("/opt/docker/bin/beholder", "/opt/beholder/cache"),
dockerExposedPorts := Seq(8080),
Expand All @@ -64,6 +85,7 @@ lazy val root = project
libraryDependencies ++= Seq(
auth0,
auth0jwk,
caffeine,
circeCore,
circeGeneric,
circeParser,
Expand Down
1 change: 1 addition & 0 deletions project/Dependencies.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ object Dependencies:

lazy val auth0 = "com.auth0" % "java-jwt" % "4.6.0"
lazy val auth0jwk = "com.auth0" % "jwks-rsa" % "0.24.1"
lazy val caffeine = "com.github.ben-manes.caffeine" % "caffeine" % "3.2.4"
private val circeVersion = "0.14.16"
lazy val circeCore = "io.circe" %% "circe-core" % circeVersion
lazy val circeGeneric = "io.circe" %% "circe-generic" % circeVersion
Expand Down
4 changes: 3 additions & 1 deletion src/docs/_docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

This is a normal sbt project. You can compile code with `sbt compile`, run it with `sbt run`, and `sbt console` will start a Scala 3 REPL.

Beholder requires that [ffmpeg](https://ffmpeg.org/) is installed to function correctly. The docker build includes ffmpeg.
Beholder requires that [ffmpeg](https://ffmpeg.org/) 7.1 or newer, including `ffprobe`, is installed to function correctly. Both ship in the same package on Homebrew and Debian/Ubuntu. Without `ffprobe` captures still succeed, but H.264/HEVC frames keep their codec padding rows.

The docker build includes ffmpeg: the base image is pinned to an Ubuntu release so the ffmpeg major version cannot drift, and the build fails if ffmpeg is older than the required major or if either binary is missing. See the Docker section of `CLAUDE.md`.

## Useful Commands

Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/org/mbari/beholder/Main.scala
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class MainRunner extends Callable[Int]:
paramLabel = "<rootDirectory>",
description = Array("The location of the image cache")
)
private var cacheRoot: Path = _
private var cacheRoot: Path = scala.compiletime.uninitialized

override def call(): Int =
Main.run(port, cacheRoot, cacheSizeMB, freePct, apiKey)
Expand Down
69 changes: 45 additions & 24 deletions src/main/scala/org/mbari/beholder/etc/ffmpeg/FfmpegUtil.scala
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ object FfmpegUtil:
private val ffmpegExecutable: String =
sys.props.getOrElse("beholder.ffmpeg.path", "ffmpeg")

// Some cameras (e.g. AJA) produce ProRes files where the ProRes bitstream
/** Cached, so repeated captures from the same video only shell out to ffprobe once. */
private val ffprobe: Ffprobe = FfprobeService.default

// Some cameras (e.g. older AJA on i2MAP) produce ProRes files where the ProRes bitstream
// atoms carry no colorspace info, so the decoder reports prim:reserved and
// trc:reserved even though the MOV container correctly says bt709. When
// swscaler sees reserved primaries/TRC it refuses all pixel-format conversions.
Expand All @@ -46,6 +49,34 @@ object FfmpegUtil:
private def isReservedColorspaceError(err: Throwable): Boolean =
ReservedColorspacePattern.findFirstIn(err.getMessage).isDefined

/**
* Build the `-vf` argument shared by every output format.
*
* `-apply_cropping 0` is what stops the decoder honoring a MOV clean aperture (clap) atom, but ffmpeg has only one
* boolean for cropping: it also stops the decoder applying the codec's own crop. That matters for H.264/HEVC in
* MP4, where the coded frame is padded up to the macroblock grid (1080 becomes 1088) and the padding rows decode to
* Y=0,U=0,V=0, i.e. a green band across the bottom of the image. ProRes has no codec level crop, so it never showed
* the problem.
*
* So we suppress cropping in the decoder and reinstate just the codec's crop here, using the size ffprobe reports
* (which ignores the clap). `min()` keeps this safe if the decoded frame is ever smaller than the probe claims: the
* crop clamps instead of failing.
*/
private def buildVideoFilters(videoUri: URI, overrideColorspace: Boolean): Seq[String] =
val cropFilter = ffprobe
.videoSize(videoUri)
.map(size => s"crop=min(iw\\,${size.width}):min(ih\\,${size.height}):0:0")

// colorspace=iall=bt709 is a no-op for YUV→YUV same-csp paths and does
// not update the filter-link prim/trc, so swscaler still sees reserved.
// Route through an rgb24 intermediate: the YUV→RGB conversion forces the
// colorspace filter to run properly and sets prim:bt709 on the link.
val colorspaceFilter = Option.when(overrideColorspace)("colorspace=iall=bt709:all=bt709,format=rgb24")

val filters = (cropFilter ++ colorspaceFilter).toSeq
if filters.isEmpty then Seq.empty
else Seq("-vf", filters.mkString(","))

private def buildPngCommand(
videoUri: URI,
elapsedTime: Duration,
Expand All @@ -56,11 +87,7 @@ object FfmpegUtil:
): Seq[String] =
val time = DurationUtil.toHMS(elapsedTime)

val vfArgs: Seq[String] =
if overrideColorspace then
Seq("-vf", "colorspace=iall=bt709:all=bt709,format=rgb24")
else
Seq.empty
val vfArgs = buildVideoFilters(videoUri, overrideColorspace)

Seq(ffmpegExecutable) ++
Seq("-apply_cropping", "0") ++ // Suppress clap/clean-aperture crop at decoder level; must precede -i
Expand Down Expand Up @@ -90,32 +117,26 @@ object FfmpegUtil:
): Seq[String] =
val time = DurationUtil.toHMS(elapsedTime)

// colorspace=iall=bt709 is a no-op for YUV→YUV same-csp paths and does
// not update the filter-link prim/trc, so swscaler still sees reserved.
// Route through an rgb24 intermediate: the YUV→RGB conversion forces the
// colorspace filter to run properly and sets prim:bt709 on the link.
// The subsequent format=yuv422p (rgb24→YUV) starts from a clean state.
val vfArgs: Seq[String] =
if overrideColorspace then
Seq("-vf", "colorspace=iall=bt709:all=bt709,format=rgb24")
else
Seq.empty
val vfArgs = buildVideoFilters(videoUri, overrideColorspace)

Seq(ffmpegExecutable) ++
Seq("-apply_cropping", "0") ++ // Suppress clap/clean-aperture crop at decoder level; must precede -i
Seq("-ss", time) ++ // Seek. This needs to be first. If it's after -i the capture is MUCH slower
Seq("-apply_cropping", "0") ++ // Suppress clap/clean-aperture crop at decoder level; must precede -i
Seq("-ss", time) ++ // Seek. This needs to be first. If it's after -i the capture is MUCH slower
Option.when(skipNonKeyFrames)(Seq("-skip_frame", "nokey")).getOrElse(Seq.empty) ++
Option.when(!accurate)(Seq("-noaccurate_seek")).getOrElse(Seq.empty) ++
Seq("-i", videoUri.toString) ++ // input file or URL
Seq(
"-map", "0:v:0", // Explicitly select first video stream (avoids ambiguity when audio streams precede video)
"-frames:v", "1") ++
"-map",
"0:v:0", // Explicitly select first video stream (avoids ambiguity when audio streams precede video)
"-frames:v",
"1"
) ++
vfArgs ++
Seq(
"-qmin",
"1", //
"1", //
"-q:v",
"1", //
"1", //
"-hide_banner", // Make quiet
"-loglevel",
"error", // Make quieter
Expand Down Expand Up @@ -206,5 +227,5 @@ object FfmpegUtil:
val fallback = buildCmd(overrideColorspace = true)
log.atDebug.log(() => s"Retrying with colorspace override: ${fallback.mkString(" ")}")
runCommand(fallback).map(_ => target)
case Left(err) => Left(err)
case Right(()) => Right(target)
case Left(err) => Left(err)
case Right(()) => Right(target)
44 changes: 44 additions & 0 deletions src/main/scala/org/mbari/beholder/etc/ffmpeg/Ffprobe.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright 2022 MBARI
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.mbari.beholder.etc.ffmpeg

import java.net.URI

/**
* The size of a video's first video stream, as declared by the codec.
*/
case class VideoSize(width: Int, height: Int)

/**
* Inspects a video before we capture a frame from it.
*/
trait Ffprobe:

/**
* The display size of a video's first video stream.
*
* This is the size the codec declares, and it is deliberately NOT the clean aperture (clap) size: ffprobe reports
* `width`/`height` before any container level cropping is applied, and exposes the clap separately as "Frame
* Cropping" side data. That makes it exactly the size we want to crop to when the decoder has been told to skip
* cropping entirely.
*
* @param videoUri
* The video to inspect
* @return
* The size, or None if the video could not be probed
*/
def videoSize(videoUri: URI): Option[VideoSize]
67 changes: 67 additions & 0 deletions src/main/scala/org/mbari/beholder/etc/ffmpeg/FfprobeService.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright 2022 MBARI
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.mbari.beholder.etc.ffmpeg

import com.github.benmanes.caffeine.cache.{Cache, Caffeine}

import java.net.URI
import java.time.Duration
/**
* An [[Ffprobe]] that memoizes what the underlying probe returns.
*
* Probing a remote video costs an HTTP round trip and the answer never changes for a given URI, so it is worth caching.
* Beholder is long lived, so the cache is bounded by size rather than allowed to grow forever.
*
* @param delegate
* Does the actual probing
* @param maximumSize
* How many videos to remember before Caffeine starts evicting
*/
class FfprobeService(
delegate: Ffprobe = FfprobeUtil,
maximumSize: Long = FfprobeService.DefaultMaximumSize
) extends Ffprobe:

private val cache: Cache[URI, VideoSize] =
Caffeine
.newBuilder()
.maximumSize(maximumSize)
.expireAfterAccess(Duration.ofHours(1))
.build[URI, VideoSize]()

/**
* Caffeine runs the loader at most once per key even under concurrent calls, so several simultaneous captures from
* the same video share a single probe instead of racing.
*
* A failed probe returns null from the loader, which Caffeine declines to store. That is deliberate: a video that
* is briefly unreachable gets probed again next time rather than being remembered as unprobeable.
*/
override def videoSize(videoUri: URI): Option[VideoSize] =
Option(cache.get(videoUri, (uri: URI) => delegate.videoSize(uri).orNull))

/** The number of videos currently remembered. Approximate: Caffeine evicts asynchronously. */
def estimatedSize: Long = cache.estimatedSize()

/** Forget everything. Mostly useful in tests. */
def invalidateAll(): Unit = cache.invalidateAll()

object FfprobeService:

val DefaultMaximumSize: Long = 1000L

/** The instance [[FfmpegUtil]] captures with. */
lazy val default: FfprobeService = FfprobeService()
Loading
Loading