提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
+150
View File
@@ -0,0 +1,150 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "sh.haven.core.ffmpeg"
compileSdk = 37
defaultConfig {
minSdk = 26
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
dependencies {
implementation(libs.coroutines.core)
implementation(libs.coroutines.android)
implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
testImplementation(libs.junit)
}
// Build FFmpeg (and its 12 codec/font dependencies) from pinned source and
// place the three binaries in jniLibs, instead of shipping committed copies
// (#493). F-Droid already did this — their recipe `scandelete`s
// core/ffmpeg/src/main/jniLibs and runs build-ffmpeg/build.sh — so it was
// *our* release workflow that was the odd one out, shipping 172 MB of blobs
// nothing rebuilt.
//
// Cost, measured rather than assumed: a clean build of the whole chain
// (x264, x265, vpx, lame, opus, ogg, vorbis, freetype, fribidi, harfbuzz,
// libass, mbedtls, then FFmpeg n8.0) is 2m42s on a 12-core desktop. The
// issue estimated ~1h per ABI; that was wrong by about twentyfold, and the
// estimate is what had kept these committed.
//
// One ABI per invocation. Each release matrix job builds only the ABI it
// packages, so the wall-clock cost is one build per job, in parallel — not
// three.
val ffmpegAbis = mapOf(
"arm64" to "arm64-v8a",
"x64" to "x86_64",
"armv7" to "armeabi-v7a",
)
val ffmpegScript = rootProject.file("build-ffmpeg/build.sh")
val pinnedNdk = "29.0.14206865"
val ndkDir: String = run {
val sdk = System.getenv("ANDROID_SDK_ROOT")
?: System.getenv("ANDROID_HOME")
?: rootProject.file("local.properties").takeIf { it.exists() }
?.readLines()
?.firstOrNull { it.startsWith("sdk.dir=") }
?.substringAfter("sdk.dir=")
?: File(System.getProperty("user.home"), "Android/Sdk").absolutePath
File(sdk, "ndk/$pinnedNdk").absolutePath
}
val buildFfmpegNatives by tasks.registering {
val targetAbi = providers.gradleProperty("targetAbi").orNull
// No -PtargetAbi (a plain local build) means every ABI, because there is
// no flavour to infer one from and shipping an APK missing ffmpeg is worse
// than a slow build.
val abis = targetAbi?.let { listOfNotNull(ffmpegAbis[it]) } ?: ffmpegAbis.values.toList()
// build.sh carries every source pin — 9 tarball sha256s and 4 commit SHAs —
// so hashing it captures everything that decides the output.
inputs.file(ffmpegScript)
inputs.property("abis", abis)
inputs.property("ndk", pinnedNdk)
outputs.dirs(abis.map { file("src/main/jniLibs/$it") })
onlyIf {
val skipped = providers.gradleProperty("skipFfmpegNatives").orNull == "true"
if (skipped) logger.lifecycle("[ffmpeg] -PskipFfmpegNatives — not building")
!skipped && abis.isNotEmpty() && ffmpegScript.exists()
}
doLast {
require(File(ndkDir).isDirectory) {
"NDK $pinnedNdk not found at $ndkDir — sdkmanager \"ndk;$pinnedNdk\""
}
abis.forEach { abi ->
logger.lifecycle("[ffmpeg] building $abi (a few minutes)")
val proc = ProcessBuilder("bash", ffmpegScript.absolutePath)
.directory(rootProject.projectDir)
.redirectErrorStream(true)
.apply {
environment()["ABI"] = abi
// Same reason as core/wayland: the runner image presets
// ANDROID_NDK_HOME to its own older NDK, and the script
// prefers the environment over the newest available.
environment()["ANDROID_NDK_HOME"] = ndkDir
}
.start()
val tail = ArrayDeque<String>()
proc.inputStream.bufferedReader().forEachLine {
logger.info(it)
tail.addLast(it)
if (tail.size > 40) tail.removeFirst()
}
val code = proc.waitFor()
if (code != 0) {
logger.error("--- build.sh ($abi) last ${tail.size} lines ---")
tail.forEach { logger.error(it) }
}
require(code == 0) { "build-ffmpeg/build.sh failed for $abi with exit code $code" }
val out = file("src/main/jniLibs/$abi")
// Everything the script leaves in bin/: the two executables, the
// shared libav*/libsw* libraries they link against, and
// libc++_shared.so. Copied by pattern rather than by name so a
// library FFmpeg adds or renames travels with the build instead of
// being silently dropped and failing at exec time on the device.
out.deleteRecursively()
copy {
from(rootProject.file("build-ffmpeg/build-$abi/install/bin")) {
include("lib*.so")
}
into(out)
}
val produced = out.listFiles()?.map { it.name }?.sorted().orEmpty()
val expected = listOf("libffmpeg.so", "libffprobe.so", "libc++_shared.so")
val missing = expected.filterNot { it in produced }
require(missing.isEmpty()) { "ffmpeg build produced no $missing in $out" }
// The executables are dynamically linked against these now, so an
// empty set means the shared build silently reverted to static and
// the APK would be ~11 MB larger for no reason.
require(produced.any { it.startsWith("libav") }) {
"ffmpeg build produced no shared libav* libraries in $out (got $produced)"
}
logger.lifecycle("[ffmpeg] $abi: ${produced.size} binaries into $out — $produced")
}
}
}
tasks.named("preBuild") {
dependsOn(buildFfmpegNatives)
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
@@ -0,0 +1,70 @@
package sh.haven.core.ffmpeg
import android.content.Context
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.File
import javax.inject.Inject
import javax.inject.Singleton
/**
* Runs FFmpeg and FFprobe binaries bundled in the APK's nativeLibraryDir.
*
* The binaries are cross-compiled ELF executables renamed to lib*.so so
* Android's package installer extracts them to a directory where execve
* is permitted (the W^X workaround shared with PRoot).
*/
@Singleton
class FfmpegExecutor @Inject constructor(
@ApplicationContext private val context: Context,
) {
private val nativeLibDir: String
get() = context.applicationInfo.nativeLibraryDir
private val ffmpegBinary: File
get() = File(nativeLibDir, "libffmpeg.so")
private val ffprobeBinary: File
get() = File(nativeLibDir, "libffprobe.so")
/** True if both ffmpeg and ffprobe binaries exist and are executable. */
fun isAvailable(): Boolean =
ffmpegBinary.canExecute() && ffprobeBinary.canExecute()
/**
* Run ffmpeg with the given arguments. Blocks until completion.
*
* @param args FFmpeg arguments (e.g. ["-i", "input.mp4", "-c:v", "libx264", "output.mp4"])
* @param onStderr Line-by-line callback for progress/diagnostic output
* @return Result with exit code, captured output, and timing
*/
fun execute(args: List<String>, onStderr: (String) -> Unit = {}): FfmpegResult {
return startJob(args, onStderr).await()
}
/**
* Run ffprobe with the given arguments. Blocks until completion.
*
* @param args FFprobe arguments (e.g. ["-show_format", "-of", "json", "input.mp4"])
* @param onStderr Line-by-line callback for diagnostic output
* @return Result with exit code, captured output, and timing
*/
fun probe(args: List<String>, onStderr: (String) -> Unit = {}): FfmpegResult {
return startProbeJob(args, onStderr).await()
}
/**
* Start a non-blocking ffmpeg job that can be cancelled.
*/
fun startJob(args: List<String>, onStderr: (String) -> Unit = {}): FfmpegJob {
check(ffmpegBinary.canExecute()) { "libffmpeg.so not found or not executable" }
return FfmpegJob.start(ffmpegBinary, args, nativeLibDir, onStderr = onStderr)
}
/**
* Start a non-blocking ffprobe job that can be cancelled.
*/
fun startProbeJob(args: List<String>, onStderr: (String) -> Unit = {}): FfmpegJob {
check(ffprobeBinary.canExecute()) { "libffprobe.so not found or not executable" }
return FfmpegJob.start(ffprobeBinary, args, nativeLibDir, onStderr = onStderr)
}
}
@@ -0,0 +1,127 @@
package sh.haven.core.ffmpeg
import java.io.File
import java.util.concurrent.TimeUnit
/**
* A running FFmpeg process with cancel and progress semantics.
*
* Stderr is streamed line-by-line on a daemon thread to [onStderr]
* (FFmpeg writes progress like "frame= 120 fps=..." to stderr).
* Stdout is captured in full for commands like ffprobe -show_format.
*/
class FfmpegJob internal constructor(
private val process: Process,
private val startTimeMs: Long,
onStderr: (String) -> Unit,
) {
@Volatile
private var cancelled = false
private val stderrLines = mutableListOf<String>()
private val stdoutBuilder = StringBuilder()
private val stderrThread = Thread({
// FFmpeg writes progress using \r (carriage return) to overwrite the
// same line, not \n. BufferedReader.readLine() only splits on \n, so
// progress updates would accumulate into one giant line that only
// appears when ffmpeg finishes. Read char-by-char and split on both.
try {
val reader = process.errorStream.bufferedReader()
val buf = StringBuilder()
var ch: Int
while (reader.read().also { ch = it } != -1) {
if (ch == '\r'.code || ch == '\n'.code) {
if (buf.isNotEmpty()) {
val line = buf.toString()
buf.clear()
synchronized(stderrLines) { stderrLines.add(line) }
onStderr(line)
}
} else {
buf.append(ch.toChar())
}
}
if (buf.isNotEmpty()) {
val line = buf.toString()
synchronized(stderrLines) { stderrLines.add(line) }
onStderr(line)
}
} catch (_: java.io.IOException) {
// Normal when cancel()/destroyForcibly() closes the stream from
// another thread, or when Android kills the ffmpeg PhantomProcess
// mid-transcode. Either way, we're done reading and the job
// status is already reflected via process.exitValue(). Without
// this catch the uncaught InterruptedIOException crashes the
// whole app with a FATAL EXCEPTION.
}
}, "ffmpeg-stderr").apply { isDaemon = true; start() }
private val stdoutThread = Thread({
try {
stdoutBuilder.append(process.inputStream.bufferedReader().readText())
} catch (_: java.io.IOException) {
// Same rationale as stderrThread above.
}
}, "ffmpeg-stdout").apply { isDaemon = true; start() }
val isRunning: Boolean get() = process.isAlive
/**
* Send SIGTERM, wait up to 3s for graceful exit, then SIGKILL.
* FFmpeg respects SIGTERM and flushes its output file.
*/
fun cancel() {
cancelled = true
process.destroy()
if (!process.waitFor(3, TimeUnit.SECONDS)) {
process.destroyForcibly()
}
}
/**
* Block until the process exits and return the result.
*/
fun await(): FfmpegResult {
process.waitFor()
stderrThread.join(2000)
stdoutThread.join(2000)
return FfmpegResult(
exitCode = process.exitValue(),
stdout = stdoutBuilder.toString(),
stderr = synchronized(stderrLines) { stderrLines.joinToString("\n") },
cancelled = cancelled,
elapsedMs = System.currentTimeMillis() - startTimeMs,
)
}
companion object {
/**
* Start a new FFmpeg/FFprobe process.
*
* @param binary Path to libffmpeg.so or libffprobe.so
* @param args Command-line arguments (without the binary path)
* @param nativeLibDir Directory containing the shared libraries the
* executables link against — libavcodec.so and friends, plus
* libc++_shared.so. Both binaries are dynamically linked, so this
* reaching LD_LIBRARY_PATH is what makes them runnable at all.
* @param workDir Working directory for the process
* @param onStderr Line-by-line callback for stderr output
*/
internal fun start(
binary: File,
args: List<String>,
nativeLibDir: String,
workDir: File? = null,
onStderr: (String) -> Unit = {},
): FfmpegJob {
val cmd = listOf(binary.absolutePath) + args
val pb = ProcessBuilder(cmd).apply {
environment()["LD_LIBRARY_PATH"] = nativeLibDir
workDir?.let { directory(it) }
}
val process = pb.start()
return FfmpegJob(process, System.currentTimeMillis(), onStderr)
}
}
}
@@ -0,0 +1,49 @@
package sh.haven.core.ffmpeg
/**
* Parsed progress from FFmpeg's stderr output.
*
* FFmpeg writes lines like:
* frame= 120 fps= 30 q=28.0 size= 256kB time=00:00:04.00 bitrate= 524.3kbits/s speed=1.50x
*/
data class FfmpegProgress(
val frame: Long = 0,
val fps: Double = 0.0,
val size: String = "",
val timeSeconds: Double = 0.0,
val bitrate: String = "",
val speed: String = "",
) {
companion object {
private val FRAME_RE = Regex("""frame=\s*(\d+)""")
private val FPS_RE = Regex("""fps=\s*([\d.]+)""")
private val SIZE_RE = Regex("""size=\s*(\S+)""")
private val TIME_RE = Regex("""time=\s*(\d+):(\d+):(\d+(?:\.\d+)?)""")
private val BITRATE_RE = Regex("""bitrate=\s*(\S+)""")
private val SPEED_RE = Regex("""speed=\s*(\S+)""")
/**
* Parse a single stderr line from FFmpeg. Returns null if the line
* is not a progress line (e.g. it's a header, warning, or error).
*/
fun parse(line: String): FfmpegProgress? {
// Progress lines always contain "time=" and "bitrate="
if ("time=" !in line || "bitrate=" !in line) return null
val hours = TIME_RE.find(line)?.let { m ->
m.groupValues[1].toDouble() * 3600 +
m.groupValues[2].toDouble() * 60 +
m.groupValues[3].toDouble()
} ?: return null
return FfmpegProgress(
frame = FRAME_RE.find(line)?.groupValues?.get(1)?.toLongOrNull() ?: 0,
fps = FPS_RE.find(line)?.groupValues?.get(1)?.toDoubleOrNull() ?: 0.0,
size = SIZE_RE.find(line)?.groupValues?.get(1) ?: "",
timeSeconds = hours,
bitrate = BITRATE_RE.find(line)?.groupValues?.get(1) ?: "",
speed = SPEED_RE.find(line)?.groupValues?.get(1) ?: "",
)
}
}
}
@@ -0,0 +1,14 @@
package sh.haven.core.ffmpeg
/**
* Result of an FFmpeg or FFprobe invocation.
*/
data class FfmpegResult(
val exitCode: Int,
val stdout: String,
val stderr: String,
val cancelled: Boolean,
val elapsedMs: Long,
) {
val success: Boolean get() = exitCode == 0 && !cancelled
}
@@ -0,0 +1,41 @@
package sh.haven.core.ffmpeg
/**
* One-tap filter presets for common operations.
* Each preset maps to a list of VideoFilter and/or AudioFilter instances.
*/
object FilterPresets {
data class Preset(
val key: String,
val label: String,
val videoFilters: List<VideoFilter> = emptyList(),
val audioFilters: List<AudioFilter> = emptyList(),
)
val STABILIZE = Preset(
key = "stabilize",
label = "Stabilize",
videoFilters = listOf(VideoFilter.Stabilize()),
)
val FIX_COLORS = Preset(
key = "fix_colors",
label = "Fix Colors",
videoFilters = listOf(VideoFilter.AutoColor),
)
val ENHANCE = Preset(
key = "enhance",
label = "Enhance",
videoFilters = listOf(VideoFilter.AutoColor, VideoFilter.Sharpen(0.5f)),
)
val NORMALIZE_AUDIO = Preset(
key = "normalize_audio",
label = "Normalize Audio",
audioFilters = listOf(AudioFilter.Normalize),
)
val all = listOf(STABILIZE, FIX_COLORS, ENHANCE, NORMALIZE_AUDIO)
}
@@ -0,0 +1,575 @@
package sh.haven.core.ffmpeg
import android.content.Context
import android.util.Log
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.Closeable
import java.io.File
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.concurrent.thread
private const val TAG = "HlsStreamServer"
/**
* Streams media via HLS (HTTP Live Streaming).
*
* Pipeline: input → ffmpeg (HLS muxer) → .m3u8 + .ts segments → HTTP server
*
* Any device on the local network can play the stream by opening
* `http://<phone-ip>:<port>/` in a browser (serves an HTML5 player)
* or pointing a media player at `http://<phone-ip>:<port>/stream.m3u8`.
*/
@Singleton
class HlsStreamServer @Inject constructor(
@ApplicationContext private val context: Context,
private val ffmpegExecutor: FfmpegExecutor,
) : Closeable {
/** One entry in a folder-as-playlist stream. */
data class PlaylistItem(val title: String, val input: String)
private var serverSocket: ServerSocket? = null
private var serverThread: Thread? = null
private var ffmpegJob: FfmpegJob? = null
private var hlsDir: File? = null
/** Non-empty when streaming a folder playlist. */
@Volatile
private var playlist: List<PlaylistItem> = emptyList()
@Volatile
private var currentIndex: Int = 0
@Volatile
var port: Int = 0
private set
@Volatile
var isRunning: Boolean = false
private set
@Volatile
private var localOnly: Boolean = false
/**
* Optional observer for ffmpeg stderr lines. Lets callers capture the
* transcoder output into their own verbose-log buffer (Haven's audit
* log) alongside the normal Log.w broadcast to logcat.
*/
@Volatile
var onStderr: ((String) -> Unit)? = null
/**
* Start streaming a media file.
*
* @param inputPath Absolute path to the input file
* @param preferredPort Port to listen on (0 = auto)
* @return The port the server is listening on
*/
/**
* @param localOnly when true, bind to 127.0.0.1 (loopback only — not
* reachable from other devices on the network). Use
* for on-device playback in Chrome.
*/
fun startFile(inputPath: String, preferredPort: Int = 8080, localOnly: Boolean = false): Int {
stop()
this.localOnly = localOnly
val dir = prepareHlsDir()
playlist = emptyList()
currentIndex = 0
startFfmpegForInput(inputPath, dir)
startHttpServer(preferredPort, dir, localOnly)
return port
}
/**
* Start streaming a folder playlist. The first item begins playing
* immediately; the browser UI lets the viewer skip to any other item.
* Each switch restarts ffmpeg with fresh segments.
*
* @param items list of media files to stream, already resolved to local
* paths or HTTP loopback URLs
*/
fun startPlaylist(items: List<PlaylistItem>, preferredPort: Int = 8080, localOnly: Boolean = false): Int {
require(items.isNotEmpty()) { "playlist must not be empty" }
stop()
this.localOnly = localOnly
val dir = prepareHlsDir()
playlist = items
currentIndex = 0
startFfmpegForInput(items[0].input, dir)
startHttpServer(preferredPort, dir, localOnly)
return port
}
/** Switch a running playlist stream to a different item. */
@Synchronized
fun switchTo(index: Int) {
val items = playlist
if (items.isEmpty() || index !in items.indices) return
val dir = hlsDir ?: return
ffmpegJob?.cancel()
ffmpegJob = null
// Wipe old segments so the player doesn't splice frames together.
dir.listFiles()?.forEach { if (it.name.startsWith("seg") || it.name.endsWith(".m3u8")) it.delete() }
currentIndex = index
startFfmpegForInput(items[index].input, dir)
}
private fun prepareHlsDir(): File {
val dir = File(context.cacheDir, "hls_stream").apply { mkdirs() }
dir.listFiles()?.forEach { it.delete() }
hlsDir = dir
return dir
}
private fun startFfmpegForInput(inputPath: String, dir: File) {
val playlistPath = File(dir, "stream.m3u8").absolutePath
// Probe input for video + audio streams (excluding attached pictures like album art)
val probeResult = ffmpegExecutor.probe(listOf(
"-v", "error",
"-show_entries", "stream=codec_type:stream_disposition=attached_pic",
"-of", "flat", inputPath,
))
val probeOut = probeResult.stdout
val hasVideoStream = probeOut.contains("codec_type=\"video\"")
val isAttachedPic = probeOut.contains("attached_pic=1")
val hasRealVideo = hasVideoStream && !isAttachedPic
val hasAudio = probeOut.contains("codec_type=\"audio\"")
Log.w(TAG, "Probe: hasRealVideo=$hasRealVideo hasAudio=$hasAudio stdout=${probeOut.take(300)}")
// Start ffmpeg: transcode to HLS segments.
// For video inputs, force H.264 Main profile, level 4.0, max 30fps
// and max 1920x1080 dimensions so the output works with Android
// Chrome's MediaCodec (it rejects non-standard resolutions and
// framerates — e.g. portrait 1344x2992 at 55fps from screen
// recordings would fail with MEDIA_ERR_SRC_NOT_SUPPORTED).
val args = buildList {
add("-y")
add("-i"); add(inputPath)
if (hasRealVideo) {
add("-map"); add("0:v:0")
if (hasAudio) {
add("-map"); add("0:a:0?")
add("-c:a"); add("aac"); add("-b:a"); add("128k")
} else {
add("-an")
}
add("-c:v"); add("libx264")
// `ultrafast` disables CABAC + 8x8dct + weight_p and makes
// libx264 write "Constrained Baseline" into the SPS regardless
// of `-profile:v main`. Chrome's MSE rejects Constrained
// Baseline > 720p, so 1080p inputs silently fail with
// MEDIA_ERR_SRC_NOT_SUPPORTED. `veryfast` is the cheapest
// preset that actually honours Main profile. The `zerolatency`
// tune is dropped because it's a live-streaming knob with no
// benefit in a VOD pipeline and it bloats output ~2.7x.
add("-preset"); add("veryfast")
add("-profile:v"); add("main")
add("-level"); add("4.0")
add("-pix_fmt"); add("yuv420p")
// Scale to fit within 1920x1080 (or the other way for portrait),
// preserving aspect ratio. Even dimensions required by libx264.
add("-vf"); add("scale='min(1920,iw)':'min(1080,ih)':force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2")
// Cap framerate at 30fps — screen recordings at 54.80fps
// trip MediaCodec on some Android devices
add("-r"); add("30")
} else {
// Audio-only: map only audio stream to avoid decoding
// attached pictures (album art) that lack a decoder
add("-map"); add("0:a:0?")
add("-c:a"); add("aac"); add("-b:a"); add("128k")
}
add("-f"); add("hls")
add("-hls_time"); add("2")
add("-hls_list_size"); add("0") // 0 = keep all segments
add("-hls_playlist_type"); add("event") // growing playlist — hls.js plays segments as they appear
add("-hls_flags"); add("independent_segments")
add("-hls_segment_filename"); add(File(dir, "seg%03d.ts").absolutePath)
add(playlistPath)
}
Log.w(TAG, "Starting ffmpeg HLS: ${args.joinToString(" ")}")
onStderr?.invoke("cmd=ffmpeg ${args.joinToString(" ")}")
val job = ffmpegExecutor.startJob(args) { line ->
Log.w(TAG, "ffmpeg: $line")
onStderr?.invoke(line)
}
ffmpegJob = job
// Monitor ffmpeg in a background thread — log if it exits early
Thread({
val result = job.await()
Log.w(TAG, "ffmpeg exited: code=${result.exitCode} stderr=${result.stderr.take(500)}")
}, "hls-ffmpeg-monitor").apply { isDaemon = true }.start()
}
private fun startHttpServer(preferredPort: Int, dir: File, @Suppress("UNUSED_PARAMETER") localOnly: Boolean = false) {
// Always bind 0.0.0.0 — Chrome on Android runs in a separate
// process and can't reach a server bound to 127.0.0.1 in Haven's
// process on some devices/Android versions. The caller controls
// the advertised URL (127.0.0.1 vs LAN IP) to limit exposure.
val ss = ServerSocket(preferredPort, 10, InetAddress.getByName("0.0.0.0"))
serverSocket = ss
port = ss.localPort
isRunning = true
serverThread = thread(name = "hls-http", isDaemon = true) {
Log.i(TAG, "HLS server listening on port $port")
while (isRunning) {
try {
val client = ss.accept()
thread(name = "hls-client", isDaemon = true) {
handleClient(client, dir)
}
} catch (_: Exception) {
break
}
}
}
}
/**
* Start streaming from a camera or microphone pipe.
*
* @param ffmpegArgs Full ffmpeg args (caller provides -i pipe: or device input)
* @param preferredPort Port to listen on
* @return The port the server is listening on
*/
fun startCustom(ffmpegArgs: List<String>, preferredPort: Int = 8080): Int {
stop()
val dir = prepareHlsDir()
playlist = emptyList()
currentIndex = 0
ffmpegJob = ffmpegExecutor.startJob(ffmpegArgs) { line ->
Log.d(TAG, "ffmpeg: $line")
}
startHttpServer(preferredPort, dir)
return port
}
override fun close() = stop()
fun stop() {
isRunning = false
ffmpegJob?.cancel()
ffmpegJob = null
try { serverSocket?.close() } catch (_: Exception) {}
serverSocket = null
serverThread = null
port = 0
hlsDir?.listFiles()?.forEach { it.delete() }
hlsDir = null
playlist = emptyList()
currentIndex = 0
localOnly = false
}
private fun handleClient(socket: Socket, hlsDir: File) {
try {
socket.use { s ->
// In local-only mode, reject connections from non-loopback
// peers so LAN devices can't reach the stream even though
// the socket is bound to 0.0.0.0.
if (localOnly && !s.inetAddress.isLoopbackAddress) {
Log.w(TAG, "Rejected non-local connection from ${s.inetAddress}")
s.getOutputStream().write("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n".toByteArray())
return
}
val reader = s.getInputStream().bufferedReader()
val requestLine = reader.readLine() ?: return
Log.d(TAG, "HTTP ${s.inetAddress}: $requestLine")
// Consume headers
while (reader.readLine().let { it != null && it.isNotEmpty() }) { /* skip */ }
val parts = requestLine.split(" ")
if (parts.size < 2) return
val path = parts[1].substringBefore('?') // strip query params
val out = s.getOutputStream()
when {
path == "/" || path == "/index.html" -> {
servePlayerPage(out)
}
path == "/playlist.json" -> {
servePlaylistJson(out)
}
path.startsWith("/switch") -> {
val idx = path.substringAfter("i=", "").substringBefore('&')
.toIntOrNull()
if (idx != null && idx in playlist.indices) {
switchTo(idx)
val body = "{\"ok\":true,\"index\":$idx}"
val bytes = body.toByteArray()
out.write(("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${bytes.size}\r\nAccess-Control-Allow-Origin: *\r\n\r\n").toByteArray())
out.write(bytes)
} else {
out.write("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n".toByteArray())
}
}
path.endsWith(".m3u8") -> {
serveFile(out, File(hlsDir, "stream.m3u8"), "application/vnd.apple.mpegurl")
}
path.endsWith(".ts") -> {
val name = path.substringAfterLast('/')
serveFile(out, File(hlsDir, name), "video/MP2T")
}
else -> {
val response = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"
out.write(response.toByteArray())
}
}
out.flush()
}
} catch (_: Exception) {
// Client disconnected
}
}
private fun serveFile(out: java.io.OutputStream, file: File, contentType: String) {
if (!file.exists()) {
val response = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"
out.write(response.toByteArray())
return
}
val bytes = file.readBytes()
val header = buildString {
append("HTTP/1.1 200 OK\r\n")
append("Content-Type: $contentType\r\n")
append("Content-Length: ${bytes.size}\r\n")
append("Access-Control-Allow-Origin: *\r\n")
append("Cache-Control: no-cache\r\n")
append("\r\n")
}
out.write(header.toByteArray())
out.write(bytes)
}
private fun servePlaylistJson(out: java.io.OutputStream) {
val items = playlist
val json = buildString {
append("{\"current\":").append(currentIndex).append(",\"items\":[")
items.forEachIndexed { i, it ->
if (i > 0) append(',')
append('"').append(jsonEscape(it.title)).append('"')
}
append("]}")
}
val bytes = json.toByteArray()
out.write(("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${bytes.size}\r\nAccess-Control-Allow-Origin: *\r\nCache-Control: no-cache\r\n\r\n").toByteArray())
out.write(bytes)
}
private fun jsonEscape(s: String): String = buildString(s.length) {
for (c in s) when (c) {
'\\' -> append("\\\\")
'"' -> append("\\\"")
'\n' -> append("\\n")
'\r' -> append("\\r")
'\t' -> append("\\t")
else -> if (c < ' ') append(String.format("\\u%04x", c.code)) else append(c)
}
}
private fun servePlayerPage(out: java.io.OutputStream) {
val html = """
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Haven Stream</title>
<style>
body { margin: 0; background: #000; display: flex; align-items: center;
justify-content: center; min-height: 100vh; font-family: sans-serif; color: #fff; }
video { max-width: 100%; max-height: 100vh; }
.info { position: fixed; top: 8px; left: 8px; color: #888; font-size: 12px; pointer-events: none; }
/* Playlist sidebar — hidden when playlist is empty (single-file mode). */
#playlist {
position: fixed; top: 0; right: 0; bottom: 0; width: 280px;
background: rgba(20, 20, 20, 0.92); color: #eee; overflow-y: auto;
padding: 12px 0; font-size: 13px;
transform: translateX(100%); transition: transform 0.2s;
z-index: 10;
}
#playlist.visible { transform: translateX(0); }
#playlist .head { padding: 4px 16px 12px; color: #aaa; font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em; }
#playlist .item { padding: 10px 16px; cursor: pointer; border-left: 3px solid transparent; word-break: break-word; }
#playlist .item:hover { background: rgba(255,255,255,0.05); }
#playlist .item.current { background: rgba(255,255,255,0.08); border-left-color: #4ea1ff; color: #fff; }
#playlist-toggle {
position: fixed; top: 16px; right: 16px;
background: rgba(0,0,0,0.7); color: #fff;
padding: 8px 12px; border-radius: 20px;
font-size: 13px; cursor: pointer; user-select: none;
border: 1px solid rgba(255,255,255,0.3);
display: none; z-index: 11;
}
#playlist-toggle.visible { display: block; }
/* Overlay shown while the video is muted — tap to unmute and keep playing. */
#unmute {
position: fixed; top: 16px; right: 16px;
background: rgba(0, 0, 0, 0.7); color: #fff;
padding: 8px 14px; border-radius: 20px;
font-size: 14px; cursor: pointer; user-select: none;
border: 1px solid rgba(255, 255, 255, 0.3);
display: none;
}
#unmute.visible { display: block; }
/* Error / status banner */
#status {
position: fixed; bottom: 16px; left: 50%; transform: translateX(-50%);
background: rgba(0, 0, 0, 0.8); color: #fff;
padding: 10px 16px; border-radius: 6px;
font-size: 13px; max-width: 80%; text-align: center;
display: none;
}
#status.visible { display: block; }
#status.error { background: rgba(180, 0, 0, 0.9); }
</style>
</head><body>
<div class="info">Haven Stream</div>
<video id="v" controls autoplay muted playsinline></video>
<div id="unmute">🔇 Tap to unmute</div>
<div id="playlist-toggle">☰ Playlist</div>
<div id="playlist"><div class="head">Playlist</div><div id="playlist-items"></div></div>
<div id="status"></div>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
const video = document.getElementById('v');
const unmuteBtn = document.getElementById('unmute');
const statusEl = document.getElementById('status');
const src = '/stream.m3u8';
function showStatus(msg, isError) {
statusEl.textContent = msg;
statusEl.className = 'visible' + (isError ? ' error' : '');
}
function hideStatus() { statusEl.className = ''; }
function showUnmute() { unmuteBtn.classList.add('visible'); }
function hideUnmute() { unmuteBtn.classList.remove('visible'); }
unmuteBtn.addEventListener('click', () => {
video.muted = false;
video.play().catch(() => {});
hideUnmute();
});
video.addEventListener('volumechange', () => {
if (!video.muted) hideUnmute();
});
video.addEventListener('playing', () => {
hideStatus();
// If we're playing muted, surface the unmute hint
if (video.muted) showUnmute();
});
video.addEventListener('error', () => {
const err = video.error;
showStatus('Video error: ' + (err ? 'code ' + err.code : 'unknown'), true);
});
function tryPlay() {
// Start muted so Chrome allows autoplay, then show the unmute hint.
video.muted = true;
video.play().catch(e => {
console.warn('autoplay failed:', e);
showStatus('Tap the play button to start', false);
});
}
// HLS loader — prefer hls.js (handles growing EVENT playlists reliably)
// over native HLS (Chrome reports support but chokes on incomplete manifests).
// Fall back to native only when hls.js isn't available (Safari/iOS).
let hls = null;
const nativeHls = !window.Hls?.isSupported?.() && video.canPlayType('application/vnd.apple.mpegurl');
function loadSource() {
if (nativeHls) {
video.src = src + '?t=' + Date.now();
video.addEventListener('loadedmetadata', tryPlay, { once: true });
} else if (window.Hls && Hls.isSupported()) {
if (hls) { try { hls.destroy(); } catch(e) {} }
hls = new Hls();
hls.on(Hls.Events.ERROR, (_, data) => {
console.warn('hls.js error:', data);
if (data.fatal) showStatus('Stream error: ' + data.details, true);
});
hls.on(Hls.Events.MANIFEST_PARSED, tryPlay);
hls.loadSource(src);
hls.attachMedia(video);
} else {
showStatus('HLS is not supported in this browser', true);
}
}
loadSource();
// Playlist UI — only visible when /playlist.json has entries.
const playlistEl = document.getElementById('playlist');
const itemsEl = document.getElementById('playlist-items');
const toggleBtn = document.getElementById('playlist-toggle');
toggleBtn.addEventListener('click', () => playlistEl.classList.toggle('visible'));
function renderPlaylist(data) {
itemsEl.innerHTML = '';
if (!data.items || data.items.length === 0) return;
toggleBtn.classList.add('visible');
playlistEl.classList.add('visible');
data.items.forEach((title, i) => {
const row = document.createElement('div');
row.className = 'item' + (i === data.current ? ' current' : '');
row.textContent = (i + 1) + '. ' + title;
row.addEventListener('click', () => switchTo(i));
itemsEl.appendChild(row);
});
}
async function switchTo(i) {
try {
showStatus('Loading item ' + (i + 1) + '…', false);
await fetch('/switch?i=' + i);
// Wait for ffmpeg to produce the first segment before reloading the
// source. Poll the playlist file for ~6 s.
for (let attempt = 0; attempt < 30; attempt++) {
await new Promise(r => setTimeout(r, 200));
const r = await fetch('/stream.m3u8?t=' + Date.now(), { cache: 'no-store' });
if (r.ok) {
const text = await r.text();
if (text.indexOf('seg') !== -1) break;
}
}
loadSource();
refreshPlaylist();
} catch (e) {
showStatus('Switch failed: ' + e, true);
}
}
async function refreshPlaylist() {
try {
const r = await fetch('/playlist.json', { cache: 'no-store' });
if (r.ok) renderPlaylist(await r.json());
} catch (e) { /* ignore */ }
}
refreshPlaylist();
</script>
</body></html>
""".trimIndent()
val bytes = html.toByteArray()
val header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: ${bytes.size}\r\n\r\n"
out.write(header.toByteArray())
out.write(bytes)
}
}
@@ -0,0 +1,54 @@
package sh.haven.core.ffmpeg
/**
* Parsed ffprobe output. Only the fields Haven's UI actually uses are
* represented — raw JSON stays in [rawJson] for callers that need more.
*/
data class MediaInfo(
val formatName: String?,
val durationSeconds: Double?,
val bitrateBps: Long?,
val sizeBytes: Long?,
val videoStreams: List<VideoStream>,
val audioStreams: List<AudioStream>,
val subtitleStreams: List<SubtitleStream>,
val chapters: List<Chapter>,
val rawJson: String,
) {
val hasVideo: Boolean get() = videoStreams.any { !it.isAttachedPic }
val hasAudio: Boolean get() = audioStreams.isNotEmpty()
data class VideoStream(
val index: Int,
val codec: String?,
val width: Int?,
val height: Int?,
val pixelFormat: String?,
val frameRate: Double?,
val bitrateBps: Long?,
val isAttachedPic: Boolean,
)
data class AudioStream(
val index: Int,
val codec: String?,
val channels: Int?,
val channelLayout: String?,
val sampleRate: Int?,
val bitrateBps: Long?,
val language: String?,
)
data class SubtitleStream(
val index: Int,
val codec: String?,
val language: String?,
val title: String?,
)
data class Chapter(
val startSeconds: Double,
val endSeconds: Double,
val title: String?,
)
}
@@ -0,0 +1,124 @@
package sh.haven.core.ffmpeg
import org.json.JSONArray
import org.json.JSONObject
/**
* Builds ffprobe argument lists and parses the resulting JSON into a
* [MediaInfo]. Uses Android's built-in `org.json`, no extra dependencies.
*/
object ProbeCommand {
/** Full probe: format + streams + chapters as JSON on stdout. */
fun fullInfo(input: String): List<String> = listOf(
"-v", "quiet",
"-print_format", "json",
"-show_format",
"-show_streams",
"-show_chapters",
input,
)
/** Duration-only probe — cheap and used by preview logic. */
fun durationOnly(input: String): List<String> = listOf(
"-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
input,
)
fun parse(json: String): MediaInfo {
val root = runCatching { JSONObject(json) }.getOrElse { JSONObject() }
val format = root.optJSONObject("format")
val streams = root.optJSONArray("streams") ?: JSONArray()
val chaptersJson = root.optJSONArray("chapters") ?: JSONArray()
val videos = mutableListOf<MediaInfo.VideoStream>()
val audios = mutableListOf<MediaInfo.AudioStream>()
val subs = mutableListOf<MediaInfo.SubtitleStream>()
for (i in 0 until streams.length()) {
val s = streams.optJSONObject(i) ?: continue
when (s.optString("codec_type")) {
"video" -> videos += parseVideo(s)
"audio" -> audios += parseAudio(s)
"subtitle" -> subs += parseSubtitle(s)
}
}
val chapters = mutableListOf<MediaInfo.Chapter>()
for (i in 0 until chaptersJson.length()) {
val c = chaptersJson.optJSONObject(i) ?: continue
chapters += MediaInfo.Chapter(
startSeconds = c.optString("start_time").toDoubleOrNull() ?: 0.0,
endSeconds = c.optString("end_time").toDoubleOrNull() ?: 0.0,
title = c.optJSONObject("tags")?.optString("title")?.takeIf { it.isNotEmpty() },
)
}
return MediaInfo(
formatName = format?.optString("format_long_name")?.takeIf { it.isNotEmpty() }
?: format?.optString("format_name")?.takeIf { it.isNotEmpty() },
durationSeconds = format?.optString("duration")?.toDoubleOrNull(),
bitrateBps = format?.optString("bit_rate")?.toLongOrNull(),
sizeBytes = format?.optString("size")?.toLongOrNull(),
videoStreams = videos,
audioStreams = audios,
subtitleStreams = subs,
chapters = chapters,
rawJson = json,
)
}
private fun parseVideo(s: JSONObject): MediaInfo.VideoStream {
val disp = s.optJSONObject("disposition")
return MediaInfo.VideoStream(
index = s.optInt("index"),
codec = s.optString("codec_name").takeIf { it.isNotEmpty() },
width = s.optInt("width").takeIf { it > 0 },
height = s.optInt("height").takeIf { it > 0 },
pixelFormat = s.optString("pix_fmt").takeIf { it.isNotEmpty() },
frameRate = parseRational(s.optString("avg_frame_rate"))
?: parseRational(s.optString("r_frame_rate")),
bitrateBps = s.optString("bit_rate").toLongOrNull(),
isAttachedPic = disp?.optInt("attached_pic") == 1,
)
}
private fun parseAudio(s: JSONObject): MediaInfo.AudioStream {
val tags = s.optJSONObject("tags")
return MediaInfo.AudioStream(
index = s.optInt("index"),
codec = s.optString("codec_name").takeIf { it.isNotEmpty() },
channels = s.optInt("channels").takeIf { it > 0 },
channelLayout = s.optString("channel_layout").takeIf { it.isNotEmpty() },
sampleRate = s.optString("sample_rate").toIntOrNull(),
bitrateBps = s.optString("bit_rate").toLongOrNull(),
language = tags?.optString("language")?.takeIf { it.isNotEmpty() },
)
}
private fun parseSubtitle(s: JSONObject): MediaInfo.SubtitleStream {
val tags = s.optJSONObject("tags")
return MediaInfo.SubtitleStream(
index = s.optInt("index"),
codec = s.optString("codec_name").takeIf { it.isNotEmpty() },
language = tags?.optString("language")?.takeIf { it.isNotEmpty() },
title = tags?.optString("title")?.takeIf { it.isNotEmpty() },
)
}
private fun parseRational(v: String?): Double? {
if (v.isNullOrEmpty() || v == "0/0") return null
val parts = v.split("/")
return when (parts.size) {
1 -> parts[0].toDoubleOrNull()
2 -> {
val num = parts[0].toDoubleOrNull() ?: return null
val den = parts[1].toDoubleOrNull() ?: return null
if (den == 0.0) null else num / den
}
else -> null
}
}
}
@@ -0,0 +1,214 @@
package sh.haven.core.ffmpeg
/**
* Builds FFmpeg transcode command-line arguments.
*
* Usage:
* val args = TranscodeCommand(input = "/path/in.mkv", output = "/path/out.mp4")
* .videoCodec("libx264")
* .audioCodec("aac")
* .build()
* executor.execute(args)
*/
class TranscodeCommand(
private val input: String,
private val output: String,
) {
private var vCodec: String? = null
private var aCodec: String? = null
private var vBitrate: String? = null
private var aBitrate: String? = null
private var crf: Int? = null
private var preset: String? = null
private var scale: String? = null
private val vFilters = mutableListOf<VideoFilter>()
private val aFilters = mutableListOf<AudioFilter>()
private var extraArgs = mutableListOf<String>()
private var overwrite = true
private var seekSeconds: Double? = null
private var durationSeconds: Double? = null
private var toSeconds: Double? = null
private var framesLimit: Int? = null
fun videoCodec(codec: String) = apply { vCodec = codec }
fun audioCodec(codec: String) = apply { aCodec = codec }
fun videoBitrate(bitrate: String) = apply { vBitrate = bitrate }
fun audioBitrate(bitrate: String) = apply { aBitrate = bitrate }
fun crf(value: Int) = apply { crf = value }
fun preset(value: String) = apply { preset = value }
fun scale(widthxheight: String) = apply { scale = widthxheight }
fun videoFilter(filter: VideoFilter) = apply { vFilters.add(filter) }
fun videoFilters(filters: List<VideoFilter>) = apply { vFilters.addAll(filters) }
fun audioFilter(filter: AudioFilter) = apply { aFilters.add(filter) }
fun audioFilters(filters: List<AudioFilter>) = apply { aFilters.addAll(filters) }
fun overwrite(value: Boolean) = apply { overwrite = value }
fun extra(vararg args: String) = apply { extraArgs.addAll(args) }
/** Seek to a position before decoding. Emitted before -i for fast keyframe seek. */
fun seekTo(seconds: Double) = apply { seekSeconds = seconds }
/** Limit output duration in seconds (-t flag). */
fun duration(seconds: Double) = apply { durationSeconds = seconds }
/**
* Stop writing output when the input timestamp reaches [seconds] (-to flag,
* absolute end time). Mutually exclusive with [duration]; if both are set,
* whichever ffmpeg sees first wins — but note that -to is relative to the
* seek point when -ss is used before -i.
*/
fun to(seconds: Double) = apply { toSeconds = seconds }
/** Limit output to N video frames (-frames:v flag). */
fun frames(count: Int) = apply { framesLimit = count }
/** Copy video and audio streams without re-encoding. */
fun copy() = apply { vCodec = "copy"; aCodec = "copy" }
fun build(): List<String> = buildList {
if (overwrite) add("-y")
// -ss before -i = fast keyframe seek (input seeking)
seekSeconds?.let { add("-ss"); add(String.format(java.util.Locale.US, "%.3f", it)) }
add("-i"); add(input)
// -t after -i = limit output duration
durationSeconds?.let { add("-t"); add(String.format(java.util.Locale.US, "%.3f", it)) }
toSeconds?.let { add("-to"); add(String.format(java.util.Locale.US, "%.3f", it)) }
vCodec?.let { add("-c:v"); add(it) }
aCodec?.let { add("-c:a"); add(it) }
vBitrate?.let { add("-b:v"); add(it) }
aBitrate?.let { add("-b:a"); add(it) }
crf?.let { add("-crf"); add(it.toString()) }
preset?.let { add("-preset"); add(it) }
// Build -vf chain: combine explicit scale + VideoFilter list
val allVf = buildList {
scale?.let { add("scale=$it") }
if (vFilters.isNotEmpty()) add(VideoFilter.chain(vFilters))
}
if (allVf.isNotEmpty()) {
add("-vf"); add(allVf.joinToString(","))
}
// Build -af chain from AudioFilter list
if (aFilters.isNotEmpty()) {
add("-af"); add(AudioFilter.chain(aFilters))
}
framesLimit?.let { add("-frames:v"); add(it.toString()) }
addAll(extraArgs)
add(output)
}
companion object {
/** Quick H.264 + AAC transcode with sensible defaults. */
fun h264(input: String, output: String, crf: Int = 23) =
TranscodeCommand(input, output)
.videoCodec("libx264")
.audioCodec("aac")
.crf(crf)
.preset("medium")
/** Quick H.265 + AAC transcode. */
fun h265(input: String, output: String, crf: Int = 28) =
TranscodeCommand(input, output)
.videoCodec("libx265")
.audioCodec("aac")
.crf(crf)
.preset("medium")
/** VP9 + Opus for WebM. */
fun vp9(input: String, output: String, crf: Int = 31) =
TranscodeCommand(input, output)
.videoCodec("libvpx-vp9")
.audioCodec("libopus")
.crf(crf)
.extra("-b:v", "0")
/** Audio-only MP3 extraction. */
fun mp3(input: String, output: String, bitrate: String = "192k") =
TranscodeCommand(input, output)
.extra("-vn")
.audioCodec("libmp3lame")
.audioBitrate(bitrate)
/**
* Lossless trim: fast seek to [startSec], then stream-copy for
* `endSec - startSec` seconds. Uses -t (duration) rather than -to
* (absolute end) so the semantics are unambiguous regardless of how
* ffmpeg interprets output timestamps after -ss.
*/
fun trim(input: String, output: String, startSec: Double, endSec: Double) =
TranscodeCommand(input, output)
.seekTo(startSec)
.duration((endSec - startSec).coerceAtLeast(0.0))
.copy()
/**
* Audio-only extraction in the requested codec.
*
* @param codec one of "libmp3lame", "aac", "libopus", "flac", or "copy"
* (copy keeps the source audio stream bit-exact)
* @param bitrate e.g. "192k"; ignored for "copy" and "flac"
*/
fun extractAudio(
input: String,
output: String,
codec: String = "libmp3lame",
bitrate: String = "192k",
): TranscodeCommand {
val cmd = TranscodeCommand(input, output)
.extra("-vn")
.audioCodec(codec)
if (codec != "copy" && codec != "flac") cmd.audioBitrate(bitrate)
return cmd
}
/**
* Contact sheet: sample one frame every [sampleEverySec] seconds,
* scale each sample to [tileWidth]x[tileHeight], and tile the
* resulting frames into a [cols]x[rows] grid. Output is a
* single-frame MP4 (same trick as [frameAt]) so the bundled ffmpeg
* doesn't need mjpeg/image2 muxers; the caller decodes to a Bitmap
* via MediaMetadataRetriever and saves as PNG.
*/
fun contactSheet(
input: String,
output: String,
sampleEverySec: Double,
cols: Int,
rows: Int,
tileWidth: Int,
tileHeight: Int,
): TranscodeCommand {
val fps = if (sampleEverySec <= 0.0) 1.0 else 1.0 / sampleEverySec
val vf = "fps=${String.format(java.util.Locale.US, "%.6f", fps)}," +
"scale=${tileWidth}:${tileHeight}:force_original_aspect_ratio=decrease," +
"pad=${tileWidth}:${tileHeight}:(ow-iw)/2:(oh-ih)/2," +
"tile=${cols}x${rows}"
return TranscodeCommand(input, output)
.videoCodec("libx264")
.preset("ultrafast")
.crf(18)
.frames(1)
// Force MP4 muxer so a caller-chosen output name with e.g. .png
// doesn't trip ffmpeg's image2 auto-detection. The caller is
// expected to use a .mp4 intermediate and decode to Bitmap.
.extra("-an", "-vf", vf, "-f", "mp4", "-pix_fmt", "yuv420p")
}
/**
* Extract a single frame as a 1-frame MP4 at the given seek position.
* Uses libx264 ultrafast because the bundled ffmpeg may not include
* the mjpeg encoder or image2 muxer. The caller decodes the MP4 to
* a Bitmap via Android's MediaMetadataRetriever.
*/
fun frameAt(input: String, output: String, seekSeconds: Double = 0.0) =
TranscodeCommand(input, output)
.seekTo(seekSeconds)
.videoCodec("libx264")
.preset("ultrafast")
.crf(18)
.frames(1)
.extra("-an")
}
}
@@ -0,0 +1,187 @@
package sh.haven.core.ffmpeg
import java.util.Locale
/**
* Video filters that can be chained in an FFmpeg `-vf` argument.
*
* Each subclass maps to a single ffmpeg filter expression. Multiple
* filters are comma-joined: `-vf "deshake,eq=brightness=0.1,unsharp=5:5:1.0"`
*
* Parameters use ffmpeg's native ranges and defaults so the UI can
* expose sliders with meaningful bounds.
*/
sealed class VideoFilter {
abstract fun toFfmpeg(): String
// --- Color / histogram ---
/** Adjust brightness. Range: -1.0 (black) to 1.0 (white). Default: 0.0 */
data class Brightness(val value: Float = 0f) : VideoFilter() {
override fun toFfmpeg() = "eq=brightness=${fmt(value)}"
}
/** Adjust contrast. Range: 0.0 to 3.0. Default: 1.0 (unchanged) */
data class Contrast(val value: Float = 1f) : VideoFilter() {
override fun toFfmpeg() = "eq=contrast=${fmt(value)}"
}
/** Adjust saturation. Range: 0.0 (grayscale) to 3.0. Default: 1.0 */
data class Saturation(val value: Float = 1f) : VideoFilter() {
override fun toFfmpeg() = "eq=saturation=${fmt(value)}"
}
/** Adjust gamma. Range: 0.1 to 10.0. Default: 1.0. Values <1 brighten shadows, >1 darken. */
data class Gamma(val value: Float = 1f) : VideoFilter() {
override fun toFfmpeg() = "eq=gamma=${fmt(value)}"
}
/** Auto-normalize histogram (stretch levels to full range). */
data object AutoColor : VideoFilter() {
override fun toFfmpeg() = "normalize"
}
/**
* RGB color balance for shadows/midtones/highlights.
* Each value ranges from -1.0 to 1.0. Default: 0.0 (no shift).
*/
data class ColorBalance(
val rs: Float = 0f, val gs: Float = 0f, val bs: Float = 0f,
val rm: Float = 0f, val gm: Float = 0f, val bm: Float = 0f,
val rh: Float = 0f, val gh: Float = 0f, val bh: Float = 0f,
) : VideoFilter() {
override fun toFfmpeg() = buildString {
append("colorbalance=")
append("rs=${fmt(rs)}:gs=${fmt(gs)}:bs=${fmt(bs)}")
append(":rm=${fmt(rm)}:gm=${fmt(gm)}:bm=${fmt(bm)}")
append(":rh=${fmt(rh)}:gh=${fmt(gh)}:bh=${fmt(bh)}")
}
}
// --- Stabilization / sharpness ---
/** Stabilize shaky video. Built-in deshake filter (no external lib). */
data class Stabilize(val rx: Int = 16, val ry: Int = 16) : VideoFilter() {
override fun toFfmpeg() = "deshake=rx=$rx:ry=$ry"
}
/** Sharpen (positive) or blur (negative). Range: -1.5 to 3.0. Default: 1.0 */
data class Sharpen(val amount: Float = 1f) : VideoFilter() {
override fun toFfmpeg() = "unsharp=5:5:${fmt(amount)}:5:5:${fmt(amount)}"
}
/** Denoise using non-local means. Strength 1-20. Default: 5 */
data class Denoise(val strength: Int = 5) : VideoFilter() {
override fun toFfmpeg() = "nlmeans=$strength"
}
// --- Geometry ---
/** Scale to width x height. Use -1 or -2 to preserve aspect ratio. */
data class Scale(val w: Int, val h: Int = -2) : VideoFilter() {
override fun toFfmpeg() = "scale=$w:$h"
}
/** Crop to w x h starting at (x, y). */
data class Crop(val w: Int, val h: Int, val x: Int = 0, val y: Int = 0) : VideoFilter() {
override fun toFfmpeg() = "crop=$w:$h:$x:$y"
}
/** Rotate by arbitrary angle in degrees. */
data class Rotate(val degrees: Float) : VideoFilter() {
override fun toFfmpeg() = "rotate=${fmt(degrees)}*PI/180"
}
/** 90/180/270 rotation and flip. dir: 0=90CCW, 1=90CW, 2=90CCW+flip, 3=90CW+flip */
data class Transpose(val dir: Int) : VideoFilter() {
override fun toFfmpeg() = "transpose=$dir"
}
/**
* Perspective (projective) transform.
* Coordinates are pixel positions in the source image for each corner.
* Maps the quadrilateral defined by these 4 corners onto the full output rectangle.
*/
data class Perspective(
val x0: Float, val y0: Float,
val x1: Float, val y1: Float,
val x2: Float, val y2: Float,
val x3: Float, val y3: Float,
) : VideoFilter() {
override fun toFfmpeg() =
"perspective=" +
"x0=${fmt(x0)}:y0=${fmt(y0)}:" +
"x1=${fmt(x1)}:y1=${fmt(y1)}:" +
"x2=${fmt(x2)}:y2=${fmt(y2)}:" +
"x3=${fmt(x3)}:y3=${fmt(y3)}:" +
"interpolation=linear"
}
// --- Time / speed ---
/** Fade in from black. Duration in seconds. */
data class FadeIn(val duration: Float = 1f) : VideoFilter() {
override fun toFfmpeg() = "fade=in:d=${fmt(duration)}"
}
/** Fade out to black. Requires start time or uses end of video. */
data class FadeOut(val duration: Float = 1f) : VideoFilter() {
override fun toFfmpeg() = "fade=out:d=${fmt(duration)}:st=0"
}
/** Change playback speed. 2.0 = 2x faster, 0.5 = half speed. */
data class Speed(val factor: Float = 1f) : VideoFilter() {
override fun toFfmpeg() = "setpts=PTS/${fmt(factor)}"
}
/** Change frame rate. */
data class Fps(val rate: Int) : VideoFilter() {
override fun toFfmpeg() = "fps=$rate"
}
companion object {
/** Build the `-vf` argument string from a list of filters. */
fun chain(filters: List<VideoFilter>): String =
filters.joinToString(",") { it.toFfmpeg() }
}
}
/**
* Audio filters for the FFmpeg `-af` argument.
*/
sealed class AudioFilter {
abstract fun toFfmpeg(): String
/** Adjust volume in dB. Positive = louder, negative = quieter. */
data class Volume(val db: Float = 0f) : AudioFilter() {
override fun toFfmpeg() = "volume=${fmt(db)}dB"
}
/** EBU R128 loudness normalization. */
data object Normalize : AudioFilter() {
override fun toFfmpeg() = "loudnorm"
}
/** Audio fade in. Duration in seconds. */
data class FadeIn(val duration: Float = 1f) : AudioFilter() {
override fun toFfmpeg() = "afade=t=in:d=${fmt(duration)}"
}
/** Audio fade out. Duration in seconds. */
data class FadeOut(val duration: Float = 1f) : AudioFilter() {
override fun toFfmpeg() = "afade=t=out:d=${fmt(duration)}"
}
/** Change audio speed. Range: 0.5 to 100.0 (atempo limitation). */
data class Speed(val factor: Float = 1f) : AudioFilter() {
override fun toFfmpeg() = "atempo=${fmt(factor)}"
}
companion object {
fun chain(filters: List<AudioFilter>): String =
filters.joinToString(",") { it.toFfmpeg() }
}
}
/** Format a float without trailing zeros, always using '.' as decimal separator. */
private fun fmt(v: Float): String = String.format(Locale.US, "%.2f", v).trimEnd('0').trimEnd('.')
@@ -0,0 +1,63 @@
package sh.haven.core.ffmpeg
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
class FfmpegProgressTest {
@Test
fun `parse typical progress line`() {
val line = "frame= 120 fps= 30 q=28.0 size= 256kB time=00:00:04.00 bitrate= 524.3kbits/s speed=1.50x"
val p = FfmpegProgress.parse(line)
assertNotNull(p)
assertEquals(120L, p!!.frame)
assertEquals(30.0, p.fps, 0.01)
assertEquals("256kB", p.size)
assertEquals(4.0, p.timeSeconds, 0.01)
assertEquals("524.3kbits/s", p.bitrate)
assertEquals("1.50x", p.speed)
}
@Test
fun `parse progress with hours`() {
val line = "frame= 5400 fps=60.0 q=23.0 size= 10240kB time=01:30:00.00 bitrate= 200.0kbits/s speed=2.00x"
val p = FfmpegProgress.parse(line)
assertNotNull(p)
assertEquals(5400.0, p!!.timeSeconds, 0.01) // 1h30m = 5400s
assertEquals(5400L, p.frame)
}
@Test
fun `parse progress with sub-second time`() {
val line = "frame= 10 fps=0.0 q=0.0 size= 0kB time=00:00:00.40 bitrate= 0.0kbits/s speed=N/A"
val p = FfmpegProgress.parse(line)
assertNotNull(p)
assertEquals(0.4, p!!.timeSeconds, 0.001)
assertEquals("N/A", p.speed)
}
@Test
fun `returns null for non-progress line`() {
assertNull(FfmpegProgress.parse("ffmpeg version 7.1.1 Copyright (c) 2000-2024"))
assertNull(FfmpegProgress.parse(" built with gcc 14"))
assertNull(FfmpegProgress.parse("Input #0, mov,mp4,m4a,3gp, from 'input.mp4':"))
assertNull(FfmpegProgress.parse(""))
}
@Test
fun `returns null for incomplete progress line`() {
// Has time= but no bitrate=
assertNull(FfmpegProgress.parse("time=00:00:01.00 speed=1x"))
}
@Test
fun `parse compact progress format`() {
val line = "frame=1 fps=0 q=0.0 size=0kB time=00:00:00.04 bitrate=0.0kbits/s speed=0.8x"
val p = FfmpegProgress.parse(line)
assertNotNull(p)
assertEquals(1L, p!!.frame)
assertEquals(0.04, p.timeSeconds, 0.001)
}
}
@@ -0,0 +1,52 @@
package sh.haven.core.ffmpeg
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class FfmpegResultTest {
@Test
fun `success is true when exit code is 0 and not cancelled`() {
val result = FfmpegResult(
exitCode = 0,
stdout = "ffmpeg version 7.1.1",
stderr = "",
cancelled = false,
elapsedMs = 50,
)
assertTrue(result.success)
}
@Test
fun `success is false when exit code is non-zero`() {
val result = FfmpegResult(
exitCode = 1,
stdout = "",
stderr = "Error opening input",
cancelled = false,
elapsedMs = 100,
)
assertFalse(result.success)
}
@Test
fun `success is false when cancelled even if exit code is 0`() {
val result = FfmpegResult(
exitCode = 0,
stdout = "",
stderr = "",
cancelled = true,
elapsedMs = 3000,
)
assertFalse(result.success)
}
@Test
fun `data class equality works`() {
val a = FfmpegResult(0, "out", "err", false, 100)
val b = FfmpegResult(0, "out", "err", false, 100)
assertEquals(a, b)
}
}
@@ -0,0 +1,134 @@
package sh.haven.core.ffmpeg
import org.junit.Assert.assertEquals
import org.junit.Test
class TranscodeCommandTest {
@Test
fun `h264 preset builds correct args`() {
val args = TranscodeCommand.h264("/in.mkv", "/out.mp4").build()
assertEquals(
listOf("-y", "-i", "/in.mkv", "-c:v", "libx264", "-c:a", "aac", "-crf", "23", "-preset", "medium", "/out.mp4"),
args,
)
}
@Test
fun `h265 with custom crf`() {
val args = TranscodeCommand.h265("/in.avi", "/out.mp4", crf = 20).build()
assert(args.contains("libx265"))
assert(args.contains("20"))
}
@Test
fun `vp9 includes zero bitrate flag`() {
val args = TranscodeCommand.vp9("/in.mp4", "/out.webm").build()
val bvIndex = args.indexOf("-b:v")
assertEquals("0", args[bvIndex + 1])
}
@Test
fun `mp3 extraction drops video`() {
val args = TranscodeCommand.mp3("/in.mp4", "/out.mp3").build()
assert("-vn" in args)
assert("libmp3lame" in args)
assert("192k" in args)
}
@Test
fun `copy mode`() {
val args = TranscodeCommand("/in.mkv", "/out.mp4").copy().build()
assertEquals(listOf("-y", "-i", "/in.mkv", "-c:v", "copy", "-c:a", "copy", "/out.mp4"), args)
}
@Test
fun `custom builder chain`() {
val args = TranscodeCommand("/in.mov", "/out.mp4")
.videoCodec("libx264")
.audioCodec("aac")
.videoBitrate("2M")
.audioBitrate("128k")
.scale("1280:-1")
.extra("-movflags", "+faststart")
.build()
assert("-b:v" in args && args[args.indexOf("-b:v") + 1] == "2M")
assert("-vf" in args && args[args.indexOf("-vf") + 1] == "scale=1280:-1")
assert("-movflags" in args)
}
@Test
fun `no overwrite flag`() {
val args = TranscodeCommand("/in.mp4", "/out.mp4").overwrite(false).build()
assert("-y" !in args)
}
@Test
fun `seekTo emits -ss before -i`() {
val args = TranscodeCommand("/in.mp4", "/out.mp4")
.videoCodec("libx264")
.seekTo(12.5)
.build()
val ssIndex = args.indexOf("-ss")
val iIndex = args.indexOf("-i")
assert(ssIndex >= 0) { "-ss not found" }
assert(ssIndex < iIndex) { "-ss should come before -i" }
assertEquals("12.500", args[ssIndex + 1])
}
@Test
fun `duration emits -t after -i`() {
val args = TranscodeCommand("/in.mp4", "/out.mp4")
.videoCodec("libx264")
.duration(5.0)
.build()
val tIndex = args.indexOf("-t")
val iIndex = args.indexOf("-i")
assert(tIndex >= 0) { "-t not found" }
assert(tIndex > iIndex) { "-t should come after -i" }
assertEquals("5.000", args[tIndex + 1])
}
@Test
fun `frames emits -frames_v`() {
val args = TranscodeCommand("/in.mp4", "/out.jpg")
.frames(1)
.build()
val framesIndex = args.indexOf("-frames:v")
assert(framesIndex >= 0) { "-frames:v not found" }
assertEquals("1", args[framesIndex + 1])
}
@Test
fun `frameAt builds single-frame extraction command`() {
val args = TranscodeCommand.frameAt("/in.mp4", "/out.mp4", seekSeconds = 10.0).build()
// -ss before -i
val ssIndex = args.indexOf("-ss")
val iIndex = args.indexOf("-i")
assert(ssIndex >= 0 && ssIndex < iIndex)
assertEquals("10.000", args[ssIndex + 1])
// -frames:v 1
val framesIndex = args.indexOf("-frames:v")
assert(framesIndex >= 0)
assertEquals("1", args[framesIndex + 1])
// Uses libx264 ultrafast for the 1-frame MP4
assert("libx264" in args)
assert("ultrafast" in args)
// No audio
assert("-an" in args)
}
@Test
fun `seekTo and duration together`() {
val args = TranscodeCommand.h264("/in.mp4", "/out.mp4")
.seekTo(30.0)
.duration(5.0)
.build()
val ssIndex = args.indexOf("-ss")
val iIndex = args.indexOf("-i")
val tIndex = args.indexOf("-t")
assert(ssIndex < iIndex) { "-ss before -i" }
assert(tIndex > iIndex) { "-t after -i" }
}
}
@@ -0,0 +1,130 @@
package sh.haven.core.ffmpeg
import org.junit.Assert.assertEquals
import org.junit.Test
class VideoFilterTest {
@Test
fun `brightness serializes correctly`() {
assertEquals("eq=brightness=0.5", VideoFilter.Brightness(0.5f).toFfmpeg())
assertEquals("eq=brightness=-0.3", VideoFilter.Brightness(-0.3f).toFfmpeg())
assertEquals("eq=brightness=0", VideoFilter.Brightness(0f).toFfmpeg())
}
@Test
fun `contrast serializes correctly`() {
assertEquals("eq=contrast=1.5", VideoFilter.Contrast(1.5f).toFfmpeg())
}
@Test
fun `saturation zero produces grayscale`() {
assertEquals("eq=saturation=0", VideoFilter.Saturation(0f).toFfmpeg())
}
@Test
fun `gamma serializes correctly`() {
assertEquals("eq=gamma=2.2", VideoFilter.Gamma(2.2f).toFfmpeg())
}
@Test
fun `auto color is normalize`() {
assertEquals("normalize", VideoFilter.AutoColor.toFfmpeg())
}
@Test
fun `stabilize defaults`() {
assertEquals("deshake=rx=16:ry=16", VideoFilter.Stabilize().toFfmpeg())
}
@Test
fun `sharpen serializes correctly`() {
assertEquals("unsharp=5:5:1:5:5:1", VideoFilter.Sharpen(1f).toFfmpeg())
}
@Test
fun `denoise serializes correctly`() {
assertEquals("nlmeans=10", VideoFilter.Denoise(10).toFfmpeg())
}
@Test
fun `scale with aspect ratio preservation`() {
assertEquals("scale=1280:-2", VideoFilter.Scale(1280).toFfmpeg())
assertEquals("scale=720:480", VideoFilter.Scale(720, 480).toFfmpeg())
}
@Test
fun `crop serializes correctly`() {
assertEquals("crop=640:480:100:50", VideoFilter.Crop(640, 480, 100, 50).toFfmpeg())
}
@Test
fun `transpose 90 CW`() {
assertEquals("transpose=1", VideoFilter.Transpose(1).toFfmpeg())
}
@Test
fun `speed 2x`() {
assertEquals("setpts=PTS/2", VideoFilter.Speed(2f).toFfmpeg())
}
@Test
fun `fade in`() {
assertEquals("fade=in:d=1.5", VideoFilter.FadeIn(1.5f).toFfmpeg())
}
@Test
fun `chain combines multiple filters`() {
val chain = VideoFilter.chain(listOf(
VideoFilter.Stabilize(),
VideoFilter.Brightness(0.1f),
VideoFilter.AutoColor,
))
assertEquals("deshake=rx=16:ry=16,eq=brightness=0.1,normalize", chain)
}
@Test
fun `empty chain produces empty string`() {
assertEquals("", VideoFilter.chain(emptyList()))
}
// --- Audio filters ---
@Test
fun `volume in dB`() {
assertEquals("volume=3dB", AudioFilter.Volume(3f).toFfmpeg())
assertEquals("volume=-6dB", AudioFilter.Volume(-6f).toFfmpeg())
}
@Test
fun `normalize is loudnorm`() {
assertEquals("loudnorm", AudioFilter.Normalize.toFfmpeg())
}
@Test
fun `audio speed`() {
assertEquals("atempo=1.5", AudioFilter.Speed(1.5f).toFfmpeg())
}
@Test
fun `audio chain`() {
val chain = AudioFilter.chain(listOf(
AudioFilter.Normalize,
AudioFilter.Volume(3f),
))
assertEquals("loudnorm,volume=3dB", chain)
}
@Test
fun `color balance serializes all 9 params`() {
val cb = VideoFilter.ColorBalance(
rs = 0.1f, gs = -0.1f, bs = 0f,
rm = 0f, gm = 0.2f, bm = 0f,
rh = 0f, gh = 0f, bh = -0.3f,
)
assertEquals(
"colorbalance=rs=0.1:gs=-0.1:bs=0:rm=0:gm=0.2:bm=0:rh=0:gh=0:bh=-0.3",
cb.toFfmpeg(),
)
}
}