`<cacheDir>/conversions/` is shared by the convert tab, the join tab and `ConcatEngine`, and
until now none of the three named a file that belonged to one job. A conversion derived its name
from the input's display name, so two `holiday.mp4` from different folders wrote the same file.
A join used the constant `joined.<ext>`, so any two joins of one format did. The list file was
the constant `concat_list.txt`, so any two joins at all did, and one of them would read the
other's input list.
The naming half is not a hypothesis. Two independent conversions on a Pixel each computed
`cache/conversions/input_converted.mp4`, the second silently overwrote the first, and a tag query
in a fresh process then returned **two SUCCEEDED `WorkInfo`s naming that one file** with one file
on disk. That is the collision reaching the point where it makes a *fix* ambiguous rather than
just a file: `Reattachment` can offer the bytes, because they are the user's either way, but it
cannot say which job produced them.
`StagingNames` keys the name on the WorkManager request id. That id is what stays still across a
retry -- `WorkerWrapper` builds `WorkerParameters` from the `WorkSpec` id and only increments
`runAttemptCount` -- which matters more here than uniqueness does, and matters more since the
previous commit made retries routine. A failed attempt deletes its staged file on the way out,
and that only collects the partial the *previous* attempt left when the name has not moved.
Opaque rather than sanitised, deliberately. The staged name is never shown to anyone: `save()`
recomputes a suggested name and the user picks the real one in the SAF dialog. So there was
nothing to lose by dropping the display name, and something to gain -- a provider-supplied
display name can contain a separator, be empty, or be four kilobytes long, and `File(stagingDir,
"../escape_converted.mp4")` resolves to a path outside staging. That was reachable before this
commit and is now unreachable by construction rather than by a sanitiser that has to be right
about every case. There is a test for exactly that name.
The extension stays, and is not decoration: `FFmpegConcatCommand` names no output muxer, so
FFmpeg infers it from the output path. A fully opaque name would quietly produce the wrong
container.
`ConcatEngine`'s list file is derived from the output it belongs to rather than taking another
parameter, so the two cannot drift apart, a directory listing shows which list belongs to which
join, and the sweep ages them together.
Three neighbouring comments claimed things that are no longer true, and are corrected rather than
left to mislead the next reader:
- `Reattachment.Ambiguous` said it "resolves on its own once each job stages under a name of
its own". It now does -- for work enqueued from here on. The case is **kept**, because the
queue outlives the change: WorkManager holds finished work for about a week, and the jobs
likeliest to be sitting in it when this code first runs are the ones named the old way.
Behaviour is unchanged and `ReattachmentTest` is untouched.
- `OutputPublisher.sweepStaging` justified its age rule partly on there being "no per-job
namespacing". There is now, and the rule still stands on its own: per-job names stop two jobs
from sharing a file, and say nothing about whether a file's job is still running, which is the
question a sweep actually asks. Same for `StagingSweep` and the note in
`LibreMediaConverterApp`.
- Both ViewModels' `reattach()` explained aliasing as something nothing prevented. Narrowed to
what is still true of work already in the queue.
`ConcatEngineTest` asks `StagingNames` for the list file's name instead of spelling out
`concat_list.txt`. That is the difference between a test and a tautology: a literal there would
have gone on passing after the rename while asserting that a file nothing creates does not exist.
The same trap was live in the two worker tests from the previous commits, whose staged-file
assertions computed a path of their own -- they now assert on the staging directory being empty,
which cannot go vacuous when a name moves.
`PerJobStagingTest` drives the real worker, because the naming function was never the part that
was wrong: what was wrong was which name the worker asked for. Two jobs converting one file must
leave two files; a second attempt at one job must not leave a second; and a display name that
climbs out of staging must not. The first and third fail before the change with "each job must
have staged its own file, found [input_converted.mp4] expected:<2> but was:<1>" and "the output
belongs in staging expected:<1> but was:<0>" -- the latter because the file had landed in
`cacheDir` instead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
88 lines
3.5 KiB
Kotlin
88 lines
3.5 KiB
Kotlin
package org.libremediaconverter.ffmpeg
|
|
|
|
import android.content.Context
|
|
import android.net.Uri
|
|
import android.util.Log
|
|
import com.arthenica.ffmpegkit.FFmpegKit
|
|
import com.arthenica.ffmpegkit.FFmpegKitConfig
|
|
import com.arthenica.ffmpegkit.ReturnCode
|
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
|
import org.libremediaconverter.convert.MediaProbe
|
|
import org.libremediaconverter.convert.StagingNames
|
|
import org.libremediaconverter.model.ConcatPlanner
|
|
import org.libremediaconverter.model.ConcatStrategy
|
|
import org.libremediaconverter.model.OutputFormat
|
|
import java.io.File
|
|
import kotlin.coroutines.resume
|
|
import kotlin.coroutines.resumeWithException
|
|
|
|
/**
|
|
* Joins several inputs into one file.
|
|
*
|
|
* Picks between a stream copy and a full re-encode by inspecting the inputs, because
|
|
* the `concat` demuxer requires matching codec, resolution and timebase and does not
|
|
* reliably fail when they differ — it can emit a file whose later segments are
|
|
* garbled. See [ConcatPlanner].
|
|
*/
|
|
class ConcatEngine(private val context: Context) {
|
|
|
|
data class Result(val strategy: ConcatStrategy, val output: File)
|
|
|
|
suspend fun join(inputs: List<Uri>, output: File, format: OutputFormat = OutputFormat.MP4_H264): Result {
|
|
require(inputs.size >= 2) { "Joining needs at least two files." }
|
|
|
|
val paths = inputs.map { uri ->
|
|
if (uri.scheme == "content") {
|
|
FFmpegKitConfig.getSafParameterForRead(context, uri)
|
|
} else {
|
|
uri.path
|
|
} ?: error("Could not open one of the input files.")
|
|
}
|
|
|
|
val strategy = ConcatPlanner.plan(inputs.map { MediaProbe.probeForConcat(context, it) })
|
|
Log.i(TAG, "Joining ${inputs.size} files using $strategy")
|
|
|
|
// The demuxer reads its input list from a file, which must live somewhere
|
|
// FFmpeg can read; app cache is a real path, so it just works.
|
|
//
|
|
// Named after the output rather than by the constant "concat_list.txt" it used to use.
|
|
// The constant meant any two joins running at once shared one list file, so one of them
|
|
// read the other's inputs -- and it is why a blanket sweep of the staging directory was
|
|
// never safe. See StagingNames.
|
|
val listFile = File(output.parentFile, StagingNames.concatListFor(output.name)).apply {
|
|
writeText(FFmpegConcatCommand.listFileContents(paths))
|
|
}
|
|
|
|
val args = FFmpegConcatCommand.build(strategy, paths, listFile, output, format)
|
|
try {
|
|
execute(args)
|
|
} finally {
|
|
listFile.delete()
|
|
}
|
|
return Result(strategy, output)
|
|
}
|
|
|
|
private suspend fun execute(args: List<String>) = suspendCancellableCoroutine { cont ->
|
|
Log.i(TAG, "ffmpeg ${args.joinToString(" ")}")
|
|
val session = FFmpegKit.executeWithArgumentsAsync(args.toTypedArray()) { completed ->
|
|
val rc = completed.getReturnCode()
|
|
when {
|
|
ReturnCode.isSuccess(rc) -> cont.resume(Unit)
|
|
ReturnCode.isCancel(rc) -> cont.cancel()
|
|
else -> cont.resumeWithException(
|
|
FFmpegEngine.FFmpegException(
|
|
"Joining failed (${rc?.value}): " +
|
|
completed.getAllLogsAsString(LOG_TAIL_LIMIT).orEmpty(),
|
|
),
|
|
)
|
|
}
|
|
}
|
|
cont.invokeOnCancellation { FFmpegKit.cancel(session.getSessionId()) }
|
|
}
|
|
|
|
private companion object {
|
|
const val TAG = "ConcatEngine"
|
|
const val LOG_TAIL_LIMIT = 40
|
|
}
|
|
}
|