Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
20 changes: 20 additions & 0 deletions src/main/resources/reference.conf
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
beholder {
api.key = "foo"
api.key = ${?BEHOLDER_API_KEY}
capture {
# How many ffmpeg processes may run at once. ffmpeg is itself multi-threaded, so this is
# deliberately well below the CPU count. 0 = auto (a quarter of the processors, at least 2).
threads = 0
threads = ${?BEHOLDER_CAPTURE_THREADS}
# How many requests may wait for a worker before the service starts answering 503.
# 0 = auto (8 per thread).
queuesize = 0
queuesize = ${?BEHOLDER_CAPTURE_QUEUESIZE}
# How long a request may wait for a worker before it is discarded instead of run. Nothing
# cancels a queued capture, so without this a client that gave up still costs a full ffmpeg
# run when its turn comes, while live requests wait behind it. Keep it under the timeout your
# clients use. 0 = no deadline (queued work always runs, however long it waited).
maxwait = 15s
maxwait = ${?BEHOLDER_CAPTURE_MAXWAIT}
}
cache {
size = 500
size = ${?BEHOLDER_CACHE_SIZE} # size in MB
Expand All @@ -10,6 +26,8 @@ beholder {
ffmpeg {
path = "ffmpeg"
path = ${?BEHOLDER_FFMPEG_PATH}
timeout = 60s # a capture that runs longer than this is killed
timeout = ${?BEHOLDER_FFMPEG_TIMEOUT}
}
ffprobe {
cache {
Expand All @@ -20,6 +38,8 @@ beholder {
}
path = "ffprobe"
path = ${?BEHOLDER_FFPROBE_PATH}
timeout = 30s # a probe that runs longer than this is killed
timeout = ${?BEHOLDER_FFPROBE_TIMEOUT}
}
http {
port = 8080
Expand Down
31 changes: 28 additions & 3 deletions src/main/scala/org/mbari/beholder/AppConfig.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,39 @@ object AppConfig:
object Api:
val Key: String = Config.getString("beholder.api.key")

/**
* Sizing for the pool that runs ffmpeg. Both settings accept 0, meaning "work it out from the machine". Deriving
* threads from the CPU count has to survive a small container: a quarter of one processor rounds to zero, and a
* pool of zero threads is refused, so the floor is what keeps the service startable.
*/
object Capture:
val Threads: Int =
Config.getInt("beholder.capture.threads") match
case configured if configured > 0 => configured
case _ => math.max(2, Runtime.getRuntime.availableProcessors / 4)

val QueueSize: Int =
Config.getInt("beholder.capture.queuesize") match
case configured if configured > 0 => configured
case _ => Threads * 8

/**
* How long a request may wait for a worker before it is discarded rather than run. Unlike the two above, 0 is
* not "work it out" but "no deadline" — there is nothing about the machine to derive it from. The right value
* comes from how long the callers wait, which only the operator knows.
*/
val MaxWait: Duration = Config.getDuration("beholder.capture.maxwait")

object Ffmpeg:
val Path: String = Config.getString("beholder.ffmpeg.path")
val Path: String = Config.getString("beholder.ffmpeg.path")
val Timeout: Duration = Config.getDuration("beholder.ffmpeg.timeout")

object Ffprobe:
object Cache:
val MaxCount: Int = Config.getInt("beholder.ffprobe.cache.maxcount")
val MaxCount: Int = Config.getInt("beholder.ffprobe.cache.maxcount")
val Expire: Duration = Config.getDuration("beholder.ffprobe.cache.expire")
val Path: String = Config.getString("beholder.ffprobe.path")
val Path: String = Config.getString("beholder.ffprobe.path")
val Timeout: Duration = Config.getDuration("beholder.ffprobe.timeout")

object Http:
val Port: Int = Config.getInt("beholder.http.port")
Expand Down
4 changes: 2 additions & 2 deletions src/main/scala/org/mbari/beholder/ImageCacheImpl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ import org.mbari.beholder.util.NumberUtil
import scala.jdk.CollectionConverters.*

/**
* Disk-backed image frame cache. Frames are indexed by (videoUri, elapsedTime) for O(1) lookups and evicted oldest-first
* when total on-disk size exceeds `maxCacheSizeMB`.
* Disk-backed image frame cache. Frames are indexed by (videoUri, elapsedTime) for O(1) lookups and evicted
* oldest-first when total on-disk size exceeds `maxCacheSizeMB`.
*
* Improvements over JpegCache:
* - O(1) lookup via nested ConcurrentHashMap (URI → elapsedMs → Jpeg) instead of O(n) TreeSet.find
Expand Down
124 changes: 91 additions & 33 deletions src/main/scala/org/mbari/beholder/ImageCapture.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ import org.mbari.beholder.etc.ffmpeg.FfmpegUtil
import org.mbari.beholder.etc.jdk.Logging.given
import org.mbari.beholder.etc.jdk.DurationUtil

import java.nio.file.Files
import java.nio.file.{Files, Path}
import java.util.concurrent.{CompletableFuture, ConcurrentHashMap}
import org.mbari.beholder.etc.jdk.PathUtil
import org.mbari.beholder.api.ErrorMsg
import org.mbari.beholder.api.StatusMsg
Expand All @@ -32,10 +33,27 @@ import scala.util.Try
import scala.util.Failure
import scala.util.Success

class ImageCapture(cache: ImageCache):
/**
* How a single frame is pulled out of a video: `(videoUri, elapsedTime, target, accurate, skipNonKeyFrames)`.
*
* Injectable so that [[ImageCapture]] can be exercised without paying for a real ffmpeg run, in the same spirit as
* `FfprobeService` taking its delegate.
*/
type FrameGrabber = (URI, Duration, Path, Boolean, Boolean) => Either[Throwable, Path]

class ImageCapture(cache: ImageCache, grabFrameFrom: FrameGrabber = FfmpegUtil.frameCapture(_, _, _, _, _)):

private val log = System.getLogger(getClass.getName)

/**
* Captures currently running, keyed by the file each one is producing.
*
* Without this, a burst of requests for the same frame all miss the cache and all shell out, so the same frame is
* decoded N times — and, because the target path is derived from the request rather than made unique, N ffmpeg
* processes write the same file at once and a caller can be handed a half-written frame.
*/
private val inFlight = ConcurrentHashMap[Path, CompletableFuture[Either[ErrorMsg, CachedImage]]]()

/**
* Capture a frame from the video at the specified elapsed time. If the frame is not already in the cache, it will
* be captured using ffmpeg and stored in the cache.
Expand Down Expand Up @@ -65,43 +83,83 @@ class ImageCapture(cache: ImageCache):
): Either[ErrorMsg, CachedImage] =
cache.get(videoUri, elapsedTime, imageType) match
case Some(cachedImage) => Right(cachedImage)
case None => grabFrame(videoUri, elapsedTime, accurate, skipNonKeyFrames, imageType)
case None =>
val cachedImage = CachedImage.toPath(cache.root, videoUri, elapsedTime, imageType = imageType)
if !PathUtil.isChild(cache.root, cachedImage.path) then
Left(ServerError("An invalid cache path was calculated"))
else
coalesced(cachedImage):
grabFrame(videoUri, elapsedTime, accurate, skipNonKeyFrames, imageType, cachedImage)

/**
* Runs `work` for `target`, or — if a capture of the same frame is already running — waits for that one and returns
* its result.
*
* `accurate` and `skipNonKeyFrames` are deliberately not part of the key. The cache is not keyed on them either, so
* a request that differs only in those flags already gets whichever frame was cached first; coalescing on the same
* identity as the cache keeps the two consistent.
*
* Note that `work` runs outside the map, not inside `computeIfAbsent`: that method holds a bin lock for the
* duration of its mapping function, which would stall unrelated captures that happen to hash to the same bin for as
* long as an ffmpeg run takes.
*/
private def coalesced(
cachedImage: CachedImage
)(work: => Either[ErrorMsg, CachedImage]): Either[ErrorMsg, CachedImage] =
val target = cachedImage.path
val mine = CompletableFuture[Either[ErrorMsg, CachedImage]]()
val existing = inFlight.putIfAbsent(target, mine)

if existing != null then
log.atDebug.log(() => s"Joining an in-flight capture of $target")
existing.join()
else
try
// The previous leader for this frame may have finished and cached it between our
// cache lookup and our claim here, which would make this a needless second run.
val result = cache.get(cachedImage) match
case Some(alreadyCached) => Right(alreadyCached)
case None => work
mine.complete(result)
result
finally
// A no-op if the try block already completed it. It matters when `work` throws:
// without it, everyone waiting on this frame would wait forever.
mine.complete(Left(ServerError("The capture failed unexpectedly")))
inFlight.remove(target, mine)

private def grabFrame(
videoUri: URI,
elapsedTime: Duration,
accurate: Boolean,
skipNonKeyFrames: Boolean,
imageType: ImageType = ImageType.Jpeg
imageType: ImageType,
cachedImage: CachedImage
): Either[ErrorMsg, CachedImage] =
val cachedImage = CachedImage.toPath(cache.root, videoUri, elapsedTime, imageType = imageType)
if PathUtil.isChild(cache.root, cachedImage.path) then
val parent = cachedImage.path.getParent()
if !Files.exists(parent) then Files.createDirectories(parent)
FfmpegUtil.frameCapture(videoUri, elapsedTime, cachedImage.path, accurate, skipNonKeyFrames) match
case Left(e) =>
log
.withCause(e)
.atDebug
.log(() => s"Failed to capture image at ${DurationUtil.toHMS(elapsedTime)} from $videoUri")
Left(StatusMsg(s"Failed to capture frame from $videoUri at $elapsedTime", 500))
case Right(path) =>
Try:
val sizeBytes = Files.size(path)
val theImage = cachedImage.copy(path = path, sizeBytes = Some(sizeBytes))
cache.put(theImage)
log.atDebug.log(() =>
val parent = cachedImage.path.getParent()
if !Files.exists(parent) then Files.createDirectories(parent)
grabFrameFrom(videoUri, elapsedTime, cachedImage.path, accurate, skipNonKeyFrames) match
case Left(e) =>
log
.withCause(e)
.atDebug
.log(() => s"Failed to capture image at ${DurationUtil.toHMS(elapsedTime)} from $videoUri")
Left(StatusMsg(s"Failed to capture frame from $videoUri at $elapsedTime", 500))
case Right(path) =>
Try:
val sizeBytes = Files.size(path)
val theImage = cachedImage.copy(path = path, sizeBytes = Some(sizeBytes))
cache.put(theImage)
log.atDebug
.log(() =>
s"Captured image (${imageType.mediaType}) at ${DurationUtil.toHMS(elapsedTime)} from $videoUri"
)
theImage
match
case Failure(exception) =>
log
.withCause(exception)
.atError
.log(() =>
s"Failed to capture image at ${DurationUtil.toHMS(elapsedTime)} from $videoUri"
)
Left(StatusMsg(s"Failed to capture frame from $videoUri at $elapsedTime", 500))
case Success(value) => Right(value)
else Left(ServerError("An invalid cache path was calculated"))
theImage
match
case Failure(exception) =>
log
.withCause(exception)
.atError
.log(() => s"Failed to capture image at ${DurationUtil.toHMS(elapsedTime)} from $videoUri")
Left(StatusMsg(s"Failed to capture frame from $videoUri at $elapsedTime", 500))
case Success(value) => Right(value)
9 changes: 6 additions & 3 deletions src/main/scala/org/mbari/beholder/ImageType.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@ import java.nio.file.Path

/**
* The image type. Used to determine the image type of a cached image.
* @param extension The extension for the image type (e.g. ".jpg", ".png")
* @param mediaType The media type (e.g. "image/jpeg", "image/png")
* @param evictionOrder The order in which the image type is evicted from the cache. Lower values are evicted first.
* @param extension
* The extension for the image type (e.g. ".jpg", ".png")
* @param mediaType
* The media type (e.g. "image/jpeg", "image/png")
* @param evictionOrder
* The order in which the image type is evicted from the cache. Lower values are evicted first.
*/
enum ImageType(val extension: String, val mediaType: String, val evictionOrder: Int):
case Jpeg extends ImageType(".jpg", "image/jpeg", 2)
Expand Down
50 changes: 30 additions & 20 deletions src/main/scala/org/mbari/beholder/Main.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,17 @@ import io.vertx.core.Vertx
import io.vertx.core.http.HttpServerOptions
import io.vertx.ext.web.Router
import io.vertx.ext.web.handler.CorsHandler
import org.mbari.beholder.api.{
CaptureEndpoints,
HealthEndpoints,
SwaggerEndpoints
}
import org.mbari.beholder.api.{CaptureEndpoints, HealthEndpoints, SwaggerEndpoints}
import org.mbari.beholder.etc.jdk.Logging.given
import picocli.CommandLine
import picocli.CommandLine.{Command, Option as Opt, Parameters}
import sttp.tapir.server.vertx.VertxFutureServerInterpreter
import sttp.tapir.server.vertx.VertxFutureServerInterpreter.*

import java.nio.file.{
Files,
Path
}
import java.nio.file.{Files, Path}
import java.util.concurrent.Callable
import scala.concurrent.duration.Duration
import scala.concurrent.{
Await,
ExecutionContext,
ExecutionContextExecutor
}
import scala.concurrent.{Await, ExecutionContext, ExecutionContextExecutor}

@Command(
description = Array("Start the server"),
Expand Down Expand Up @@ -143,11 +132,11 @@ object Main:
val status = if ctx.statusCode() > 0 then ctx.statusCode() else 500
val cause = ctx.failure()
if cause != null then log.atWarn.withCause(cause).log(s"Route failure: status=$status")
if !ctx.response().ended() then
ctx.response().setStatusCode(status).end()
if !ctx.response().ended() then ctx.response().setStatusCode(status).end()

// Add CORS
val corsHandler = CorsHandler.create()
val corsHandler = CorsHandler
.create()
.allowedMethod(io.vertx.core.http.HttpMethod.GET)
.allowedMethod(io.vertx.core.http.HttpMethod.POST)
.allowedHeader("X-Requested-With")
Expand All @@ -161,9 +150,30 @@ object Main:
log.atInfo.log(() => s"Creating cache directory: $cacheRoot")
Files.createDirectories(cacheRoot)

val jpegCache = ImageCacheImpl(cacheRoot, cacheSizeMb, freePct)
val jpegCapture = ImageCapture(jpegCache)
val captureEndpoints = CaptureEndpoints(jpegCapture, apiKey)
val jpegCache = ImageCacheImpl(cacheRoot, cacheSizeMb, freePct)
val jpegCapture = ImageCapture(jpegCache)

// Captures run here, not on the global ExecutionContext: an ffmpeg process holds its
// thread for the whole capture, so the pool is what caps how many run at once, and
// anything past its queue is refused with a 503 instead of queued indefinitely.
val captureExecutor = CaptureEndpoints.defaultExecutor

// Spelled out rather than logged as a raw duration: zero means the deadline is off, and a
// literal "0s" in the log reads like the exact opposite — that everything is dropped at once.
val maxWait = AppConfig.Capture.MaxWait
val waitPolicy =
if maxWait.isZero || maxWait.isNegative then "no wait deadline"
else if maxWait.toSeconds > 0 then s"dropped after ${maxWait.toSeconds}s waiting"
else s"dropped after ${maxWait.toMillis}ms waiting"

log.atInfo
.log(
s"Captures limited to ${AppConfig.Capture.Threads} concurrent ffmpeg processes " +
s"(${AppConfig.Capture.QueueSize} may queue, $waitPolicy, " +
s"killed after ${AppConfig.Ffmpeg.Timeout.toSeconds}s)"
)

val captureEndpoints = CaptureEndpoints(jpegCapture, apiKey, captureExecutor)
val healthEndpoints = HealthEndpoints()
val swaggerEndpoints = SwaggerEndpoints(captureEndpoints, healthEndpoints)
val allEndpointImpls =
Expand Down
Loading
Loading