A cross platform Audiobookshelf client for Android and iOS
Dart
Export a bookmark as a trimmed audio clip to your files
Barnabas2cc615fe9521
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/AudioClipExporter.kt b/android/app/src/main/kotlin/com/barnabas/absorb/AudioClipExporter.ktnew file mode 100644index 00000000..6199e6ed--- /dev/null+++ b/android/app/src/main/kotlin/com/barnabas/absorb/AudioClipExporter.kt@@ -0,0 +1,284 @@+package com.barnabas.absorb++import android.content.Context+import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaExtractor+import android.media.MediaFormat+import android.media.MediaMuxer+import android.net.Uri+import android.util.Log+import java.io.ByteArrayOutputStream+import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder++/**+ * Extracts a time window of an audiobook file and writes it as an AAC .m4a clip,+ * using only the platform MediaCodec/MediaMuxer stack (no ffmpeg). Decodes the+ * window to PCM, then re-encodes to AAC and muxes into an mp4/m4a container.+ *+ * Source can be a local file path, an Android SAF content:// URI, or an http(s)+ * URL (streamed books) - MediaExtractor range-requests just the window in the+ * streamed case, so we never download the whole track. Mono and stereo pass+ * through; anything with more channels is downmixed to mono. Runs off the main+ * thread (the caller spawns a worker).+ */+object AudioClipExporter {+ private const val TAG = "AbsorbClip"+ private const val TIMEOUT_US = 10_000L+ private const val BIT_RATE = 128_000+ private const val AAC_MIME = "audio/mp4a-latm"++ fun exportM4a(+ context: Context,+ source: String,+ isLocal: Boolean,+ headers: Map<String, String>?,+ startSeconds: Double,+ durationSeconds: Double,+ outPath: String,+ ): Boolean {+ return try {+ val decoded = decodeWindow(context, source, isLocal, headers, startSeconds, durationSeconds)+ if (decoded == null || decoded.pcm.isEmpty()) {+ Log.e(TAG, "no PCM decoded from clip window")+ return false+ }+ encodeM4a(outPath, decoded.pcm, decoded.sampleRate, decoded.channels)+ Log.d(TAG, "clip ok: ${decoded.pcm.size} PCM bytes @${decoded.sampleRate}Hz/${decoded.channels}ch -> $outPath")+ true+ } catch (e: Exception) {+ Log.e(TAG, "exportM4a failed: ${e.message}", e)+ try { File(outPath).delete() } catch (_: Exception) {}+ false+ }+ }++ private class Decoded(val pcm: ByteArray, val sampleRate: Int, val channels: Int)++ private fun decodeWindow(+ context: Context,+ source: String,+ isLocal: Boolean,+ headers: Map<String, String>?,+ startSeconds: Double,+ durationSeconds: Double,+ ): Decoded? {+ val extractor = MediaExtractor()+ var codec: MediaCodec? = null+ try {+ when {+ isLocal && source.startsWith("content://") ->+ extractor.setDataSource(context, Uri.parse(source), null)+ !isLocal ->+ extractor.setDataSource(source, headers ?: emptyMap())+ else ->+ extractor.setDataSource(source)+ }++ val trackIndex = selectAudioTrack(extractor)+ if (trackIndex < 0) {+ Log.e(TAG, "no audio track in $source")+ return null+ }+ extractor.selectTrack(trackIndex)+ val inFormat = extractor.getTrackFormat(trackIndex)+ val mime = inFormat.getString(MediaFormat.KEY_MIME) ?: return null+ val srcChannels = if (inFormat.containsKey(MediaFormat.KEY_CHANNEL_COUNT))+ inFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT) else 1+ // Preserve mono/stereo; downmix anything wider to mono (matches how+ // the rest of the app collapses multichannel output).+ val target = if (srcChannels in 1..2) srcChannels else 1++ val startUs = (startSeconds * 1_000_000L).toLong()+ val durationUs = (durationSeconds * 1_000_000L).toLong()+ extractor.seekTo(startUs, MediaExtractor.SEEK_TO_CLOSEST_SYNC)++ codec = MediaCodec.createDecoderByType(mime)+ codec.configure(inFormat, null, null, 0)+ codec.start()++ val info = MediaCodec.BufferInfo()+ var sawInputEOS = false+ var sawOutputEOS = false+ var outRate = if (inFormat.containsKey(MediaFormat.KEY_SAMPLE_RATE))+ inFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE) else 44100+ var outChannels = srcChannels+ // AudioFormat.ENCODING_PCM_16BIT == 2, ENCODING_PCM_FLOAT == 4+ var pcmEncoding = if (inFormat.containsKey(MediaFormat.KEY_PCM_ENCODING))+ inFormat.getInteger(MediaFormat.KEY_PCM_ENCODING) else 2++ val out = ByteArrayOutputStream()+ var firstSampleUs = -1L+ var collectedUs = 0L++ while (!sawOutputEOS) {+ if (!sawInputEOS) {+ val inIndex = codec.dequeueInputBuffer(TIMEOUT_US)+ if (inIndex >= 0) {+ val inBuf = codec.getInputBuffer(inIndex)!!+ val sampleSize = extractor.readSampleData(inBuf, 0)+ if (sampleSize < 0) {+ codec.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM)+ sawInputEOS = true+ } else {+ codec.queueInputBuffer(inIndex, 0, sampleSize, extractor.sampleTime, 0)+ extractor.advance()+ }+ }+ }++ val outIndex = codec.dequeueOutputBuffer(info, TIMEOUT_US)+ if (outIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {+ val of = codec.outputFormat+ if (of.containsKey(MediaFormat.KEY_SAMPLE_RATE)) outRate = of.getInteger(MediaFormat.KEY_SAMPLE_RATE)+ if (of.containsKey(MediaFormat.KEY_CHANNEL_COUNT)) outChannels = of.getInteger(MediaFormat.KEY_CHANNEL_COUNT)+ if (of.containsKey(MediaFormat.KEY_PCM_ENCODING)) pcmEncoding = of.getInteger(MediaFormat.KEY_PCM_ENCODING)+ } else if (outIndex >= 0) {+ val outBuf = codec.getOutputBuffer(outIndex)+ if (outBuf != null && info.size > 0) {+ if (firstSampleUs < 0) firstSampleUs = info.presentationTimeUs+ appendInterleaved(outBuf, info, outChannels, target, pcmEncoding, out)+ collectedUs = info.presentationTimeUs - firstSampleUs+ }+ codec.releaseOutputBuffer(outIndex, false)+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) sawOutputEOS = true+ if (durationUs > 0 && collectedUs >= durationUs) sawOutputEOS = true+ }+ }+ return Decoded(out.toByteArray(), outRate, target)+ } finally {+ try { codec?.stop() } catch (_: Exception) {}+ try { codec?.release() } catch (_: Exception) {}+ try { extractor.release() } catch (_: Exception) {}+ }+ }++ /** Append decoded frames as 16-bit little-endian PCM with [target] channels. */+ private fun appendInterleaved(+ buf: ByteBuffer,+ info: MediaCodec.BufferInfo,+ channels: Int,+ target: Int,+ pcmEncoding: Int,+ out: ByteArrayOutputStream,+ ) {+ buf.position(info.offset)+ buf.limit(info.offset + info.size)+ val ch = if (channels <= 0) 1 else channels+ if (pcmEncoding == 4) { // ENCODING_PCM_FLOAT+ val fb = buf.order(ByteOrder.nativeOrder()).asFloatBuffer()+ val frames = fb.remaining() / ch+ val frame = FloatArray(ch)+ for (f in 0 until frames) {+ for (c in 0 until ch) frame[c] = fb.get()+ writeFrame16(out, frame, ch, target)+ }+ } else { // 16-bit PCM+ val sb = buf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()+ val frames = sb.remaining() / ch+ val frame = FloatArray(ch)+ for (f in 0 until frames) {+ for (c in 0 until ch) frame[c] = sb.get() / 32768f+ writeFrame16(out, frame, ch, target)+ }+ }+ }++ private fun writeFrame16(out: ByteArrayOutputStream, frame: FloatArray, ch: Int, target: Int) {+ if (target == 1) {+ var sum = 0f+ for (c in 0 until ch) sum += frame[c]+ putShort(out, sum / ch)+ } else { // stereo+ putShort(out, frame[0])+ putShort(out, if (ch >= 2) frame[1] else frame[0])+ }+ }++ private fun putShort(out: ByteArrayOutputStream, sample: Float) {+ val clamped = if (sample > 1f) 1f else if (sample < -1f) -1f else sample+ val v = (clamped * 32767f).toInt()+ out.write(v and 0xFF)+ out.write((v shr 8) and 0xFF)+ }++ private fun encodeM4a(outPath: String, pcm: ByteArray, sampleRate: Int, channels: Int) {+ File(outPath).parentFile?.mkdirs()+ val encoder = MediaCodec.createEncoderByType(AAC_MIME)+ val muxer = MediaMuxer(outPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)+ var muxerTrack = -1+ var muxerStarted = false+ try {+ val format = MediaFormat.createAudioFormat(AAC_MIME, sampleRate, channels).apply {+ setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)+ setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE)+ setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 64 * 1024)+ }+ encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ encoder.start()++ val info = MediaCodec.BufferInfo()+ val bytesPerFrame = channels * 2+ val totalFrames = pcm.size / bytesPerFrame+ var inFrame = 0+ var sawInputEOS = false+ var sawOutputEOS = false++ while (!sawOutputEOS) {+ if (!sawInputEOS) {+ val inIndex = encoder.dequeueInputBuffer(TIMEOUT_US)+ if (inIndex >= 0) {+ val inBuf = encoder.getInputBuffer(inIndex)!!+ inBuf.clear()+ val maxFrames = inBuf.remaining() / bytesPerFrame+ val framesThis = minOf(maxFrames, totalFrames - inFrame)+ if (framesThis <= 0) {+ val ptsUs = (inFrame.toLong() * 1_000_000L) / sampleRate+ encoder.queueInputBuffer(inIndex, 0, 0, ptsUs, MediaCodec.BUFFER_FLAG_END_OF_STREAM)+ sawInputEOS = true+ } else {+ val byteLen = framesThis * bytesPerFrame+ inBuf.put(pcm, inFrame * bytesPerFrame, byteLen)+ val ptsUs = (inFrame.toLong() * 1_000_000L) / sampleRate+ encoder.queueInputBuffer(inIndex, 0, byteLen, ptsUs, 0)+ inFrame += framesThis+ }+ }+ }++ val outIndex = encoder.dequeueOutputBuffer(info, TIMEOUT_US)+ if (outIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {+ muxerTrack = muxer.addTrack(encoder.outputFormat)+ muxer.start()+ muxerStarted = true+ } else if (outIndex >= 0) {+ val outBuf = encoder.getOutputBuffer(outIndex)+ // Codec-config bytes go to the muxer via addTrack's format, not as a sample.+ if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) info.size = 0+ if (info.size > 0 && muxerStarted && outBuf != null) {+ outBuf.position(info.offset)+ outBuf.limit(info.offset + info.size)+ muxer.writeSampleData(muxerTrack, outBuf, info)+ }+ encoder.releaseOutputBuffer(outIndex, false)+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) sawOutputEOS = true+ }+ }+ } finally {+ try { encoder.stop() } catch (_: Exception) {}+ try { encoder.release() } catch (_: Exception) {}+ try { if (muxerStarted) muxer.stop() } catch (_: Exception) {}+ try { muxer.release() } catch (_: Exception) {}+ }+ }++ private fun selectAudioTrack(extractor: MediaExtractor): Int {+ for (i in 0 until extractor.trackCount) {+ val mime = extractor.getTrackFormat(i).getString(MediaFormat.KEY_MIME) ?: continue+ if (mime.startsWith("audio/")) return i+ }+ return -1+ }+}diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.ktindex fe847216..8c845045 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt@@ -110,6 +110,14 @@ class MainActivity : AudioServiceActivity() {}}+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.absorb.clip")+ .setMethodCallHandler { call, result ->+ when (call.method) {+ "exportClip" -> handleExportClip(call, result)+ else -> result.notImplemented()+ }+ }+// GMS-backed channels (cast foreground service, wear bridges).// Resolves to the real impl in github/playstore, no-op in fdroid.PlatformIntegration.registerChannels(this, flutterEngine)@@ -170,6 +178,29 @@ class MainActivity : AudioServiceActivity() {}.start()}+ // Extract a short audio window starting at a bookmark and write it as an+ // AAC .m4a clip (bookmark clip export). Runs off the main thread.+ private fun handleExportClip(call: MethodCall, result: MethodChannel.Result) {+ val source = call.argument<String>("source")+ val isLocal = call.argument<Boolean>("isLocal") ?: true+ val headers = call.argument<Map<String, String>>("headers")+ val startSeconds = call.argument<Double>("startSeconds") ?: 0.0+ val durationSeconds = call.argument<Double>("durationSeconds") ?: 60.0+ val outPath = call.argument<String>("outPath")+ if (source == null || outPath == null) {+ result.error("CLIP_ARGS", "Missing source or outPath", null)+ return+ }+ Thread {+ val ok = AudioClipExporter.exportM4a(+ applicationContext, source, isLocal, headers, startSeconds, durationSeconds, outPath)+ runOnUiThread {+ if (ok) result.success(true)+ else result.error("CLIP_FAILED", "Could not export clip", null)+ }+ }.start()+ }+private fun handleInit(result: MethodChannel.Result) {try {val tempEq = Equalizer(0, 0)diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swiftindex c46c8c0f..70522acb 100644--- a/ios/Runner/AppDelegate.swift+++ b/ios/Runner/AppDelegate.swift@@ -306,6 +306,35 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl}}+ // Bookmark clip export: extract a time window of a book and write a .m4a.+ let clipChannel = FlutterMethodChannel(name: "com.absorb.clip",+ binaryMessenger: messenger)+ clipChannel.setMethodCallHandler { (call, result) in+ guard call.method == "exportClip" else { result(FlutterMethodNotImplemented); return }+ let args = call.arguments as? [String: Any]+ guard let source = args?["source"] as? String,+ let outPath = args?["outPath"] as? String else {+ result(FlutterError(code: "CLIP_ARGS", message: "Missing source or outPath", details: nil))+ return+ }+ let isLocal = args?["isLocal"] as? Bool ?? true+ let headers = args?["headers"] as? [String: String]+ let start = args?["startSeconds"] as? Double ?? 0+ let duration = args?["durationSeconds"] as? Double ?? 60+ AudioClipExporter.exportM4a(+ source: source, isLocal: isLocal, headers: headers,+ startSeconds: start, durationSeconds: duration, outPath: outPath+ ) { ok, errMessage in+ DispatchQueue.main.async {+ if ok {+ result(true)+ } else {+ result(FlutterError(code: "CLIP_FAILED", message: errMessage ?? "export failed", details: nil))+ }+ }+ }+ }+let widgetChannel = FlutterMethodChannel(name: "com.absorb.widget",binaryMessenger: messenger)self.widgetChannel = widgetChannel@@ -473,3 +502,64 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl}}++/// Extracts a time window of an audiobook and exports it as an AAC .m4a clip+/// via AVAssetExportSession (bookmark clip export). Local files always work;+/// streamed URLs carry the access token in the URL and pass any custom headers+/// best-effort - a server that needs custom headers AVFoundation can't send+/// (some reverse proxies) may fail to export while streaming, which the UI+/// surfaces as a normal export failure.+enum AudioClipExporter {+ static func exportM4a(+ source: String,+ isLocal: Bool,+ headers: [String: String]?,+ startSeconds: Double,+ durationSeconds: Double,+ outPath: String,+ completion: @escaping (Bool, String?) -> Void+ ) {+ let asset: AVURLAsset+ if isLocal {+ asset = AVURLAsset(url: URL(fileURLWithPath: source))+ } else {+ guard let url = URL(string: source) else {+ completion(false, "bad url")+ return+ }+ var options: [String: Any] = [:]+ if let headers = headers, !headers.isEmpty {+ options["AVURLAssetHTTPHeaderFieldsKey"] = headers+ }+ asset = AVURLAsset(url: url, options: options)+ }++ let outURL = URL(fileURLWithPath: outPath)+ try? FileManager.default.createDirectory(+ at: outURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ // AVAssetExportSession refuses to overwrite an existing file.+ try? FileManager.default.removeItem(at: outURL)++ guard let export = AVAssetExportSession(+ asset: asset, presetName: AVAssetExportPresetAppleM4A) else {+ completion(false, "could not create export session")+ return+ }+ export.outputURL = outURL+ export.outputFileType = .m4a+ let start = CMTime(seconds: max(0, startSeconds), preferredTimescale: 600)+ let duration = CMTime(seconds: max(1, durationSeconds), preferredTimescale: 600)+ export.timeRange = CMTimeRange(start: start, duration: duration)++ export.exportAsynchronously {+ switch export.status {+ case .completed:+ completion(true, nil)+ default:+ let message = export.error?.localizedDescription ?? "status \(export.status.rawValue)"+ try? FileManager.default.removeItem(at: outURL)+ completion(false, message)+ }+ }+ }+}diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex 93d39abc..fdf23cec 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -3667,6 +3667,25 @@"bookmarkPause": "Pause","bookmarkPreviewFailed": "Couldn't play this spot.",+ "clipExport": "Export clip",+ "clipJumpToStart": "Jump to start",+ "clipJumpToEnd": "Jump to end",+ "clipSetStart": "Set start",+ "clipSetEnd": "Set end",+ "clipInLabel": "In",+ "clipOutLabel": "Out",+ "clipSave": "Save clip",+ "clipExportSaved": "Saved {filename}",+ "@clipExportSaved": {+ "placeholders": {+ "filename": {+ "type": "String"+ }+ }+ },+ "clipExportClamped": "Clip saved, shortened to the end of this track",+ "clipExportFailed": "Couldn't export the clip.",+"fsPickerTitle": "Select folder","fsServerRoot": "Server root","fsEmptyFolder": "No subfolders here",diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex 8f2e0155..3ab69e79 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -10704,6 +10704,72 @@ abstract class AppLocalizations {/// **'Couldn\'t play this spot.'**String get bookmarkPreviewFailed;+ /// No description provided for @clipExport.+ ///+ /// In en, this message translates to:+ /// **'Export clip'**+ String get clipExport;++ /// No description provided for @clipJumpToStart.+ ///+ /// In en, this message translates to:+ /// **'Jump to start'**+ String get clipJumpToStart;++ /// No description provided for @clipJumpToEnd.+ ///+ /// In en, this message translates to:+ /// **'Jump to end'**+ String get clipJumpToEnd;++ /// No description provided for @clipSetStart.+ ///+ /// In en, this message translates to:+ /// **'Set start'**+ String get clipSetStart;++ /// No description provided for @clipSetEnd.+ ///+ /// In en, this message translates to:+ /// **'Set end'**+ String get clipSetEnd;++ /// No description provided for @clipInLabel.+ ///+ /// In en, this message translates to:+ /// **'In'**+ String get clipInLabel;++ /// No description provided for @clipOutLabel.+ ///+ /// In en, this message translates to:+ /// **'Out'**+ String get clipOutLabel;++ /// No description provided for @clipSave.+ ///+ /// In en, this message translates to:+ /// **'Save clip'**+ String get clipSave;++ /// No description provided for @clipExportSaved.+ ///+ /// In en, this message translates to:+ /// **'Saved {filename}'**+ String clipExportSaved(String filename);++ /// No description provided for @clipExportClamped.+ ///+ /// In en, this message translates to:+ /// **'Clip saved, shortened to the end of this track'**+ String get clipExportClamped;++ /// No description provided for @clipExportFailed.+ ///+ /// In en, this message translates to:+ /// **'Couldn\'t export the clip.'**+ String get clipExportFailed;+/// No description provided for @fsPickerTitle.////// In en, this message translates to:diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex f5e15117..8f3c778e 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -6198,6 +6198,42 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex 5bad1f13..498b1c20 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -6131,6 +6131,42 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex 0b65e2b9..d08facb2 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -6131,6 +6131,42 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex 80c48236..10e80b53 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -6131,6 +6131,42 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex e3094d8f..e0a5efd5 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -6133,6 +6133,42 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex 79ed31bf..51ac5ba8 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -6131,6 +6131,42 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex 64e01e5a..5503fb6c 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -6131,6 +6131,42 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex feeb22e0..e413849d 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -6131,6 +6131,42 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex 7520bb80..778c0851 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -6131,6 +6131,42 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex 81ef045b..c12e5734 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -6131,6 +6131,42 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex 48cf1125..e27c10a7 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -6134,6 +6134,42 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex cb26dc3e..931e9168 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -6054,6 +6054,42 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get bookmarkPreviewFailed => 'Couldn\'t play this spot.';+ @override+ String get clipExport => 'Export clip';++ @override+ String get clipJumpToStart => 'Jump to start';++ @override+ String get clipJumpToEnd => 'Jump to end';++ @override+ String get clipSetStart => 'Set start';++ @override+ String get clipSetEnd => 'Set end';++ @override+ String get clipInLabel => 'In';++ @override+ String get clipOutLabel => 'Out';++ @override+ String get clipSave => 'Save clip';++ @override+ String clipExportSaved(String filename) {+ return 'Saved $filename';+ }++ @override+ String get clipExportClamped =>+ 'Clip saved, shortened to the end of this track';++ @override+ String get clipExportFailed => 'Couldn\'t export the clip.';+@overrideString get fsPickerTitle => 'Select folder';diff --git a/lib/screens/bookmarks_screen.dart b/lib/screens/bookmarks_screen.dartindex 3f3b4e12..846a307c 100644--- a/lib/screens/bookmarks_screen.dart+++ b/lib/screens/bookmarks_screen.dart@@ -264,9 +264,15 @@ class _BookmarksScreenState extends State<BookmarksScreen> {Future<void> _jumpToBookmark(String itemId, Bookmark bookmark, String bookTitle) async {final l = AppLocalizations.of(context)!;final api = context.read<AuthProvider>().apiService;- final result = await showDialog<BookmarkDetailResult>(+ final result = await showModalBottomSheet<BookmarkDetailResult>(context: context,- builder: (ctx) => BookmarkDetailDialog(+ isScrollControlled: true,+ showDragHandle: true,+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,+ shape: const RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),+ ),+ builder: (ctx) => BookmarkDetailSheet(itemId: itemId,bookmark: bookmark,api: api,diff --git a/lib/services/book_track_resolver.dart b/lib/services/book_track_resolver.dartnew file mode 100644index 00000000..55548725--- /dev/null+++ b/lib/services/book_track_resolver.dart@@ -0,0 +1,82 @@+import 'dart:convert';++import 'api_service.dart';+import 'download_service.dart';++/// One playable track of a book: a local file path / SAF content URI, or a+/// streamed per-file URL, plus its duration in seconds.+typedef BookTrack = ({String source, double duration, bool local});++/// A global book position resolved to the track that contains it.+typedef TrackHit = ({int index, double localOffset, BookTrack track});++/// Resolves a book's audio tracks the same way for everything that needs to+/// reach into the raw files (bookmark preview, clip export): downloaded books+/// use the local files + cached track durations; streamed books build per-file+/// URLs from the library item. Kept in one place so the preview player and the+/// exporter can't drift apart on multi-file mapping.+class BookTrackResolver {+ static Future<List<BookTrack>?> resolve(String itemId, ApiService? api) async {+ // Downloaded book: local files + cached track durations.+ final localPaths = DownloadService().getLocalPaths(itemId);+ final sessionRaw = DownloadService().getCachedSessionData(itemId);+ if (localPaths != null && localPaths.isNotEmpty && sessionRaw != null) {+ try {+ final session = jsonDecode(sessionRaw) as Map<String, dynamic>;+ final audioTracks = session['audioTracks'] as List<dynamic>?;+ if (audioTracks != null && audioTracks.length == localPaths.length) {+ return [+ for (var i = 0; i < localPaths.length; i++)+ (+ source: localPaths[i],+ duration: ((audioTracks[i] as Map<String, dynamic>)['duration']+ as num?)+ ?.toDouble() ??+ 0,+ local: true,+ ),+ ];+ }+ } catch (_) {}+ }++ // Streamed book: build per-file URLs from the library item.+ if (api == null) return null;+ final item = await api.getLibraryItem(itemId);+ if (item == null) return null;+ final media = item['media'] as Map<String, dynamic>? ?? {};+ final audioFiles = ((media['audioFiles'] as List<dynamic>?) ?? const [])+ .whereType<Map<String, dynamic>>()+ .toList()+ ..sort((a, b) =>+ ((a['index'] as num?) ?? 0).compareTo((b['index'] as num?) ?? 0));+ if (audioFiles.isEmpty) return null;+ return [+ for (final af in audioFiles)+ (+ source: api.buildFileUrl(itemId, af['ino']?.toString() ?? ''),+ duration: (af['duration'] as num?)?.toDouble() ?? 0,+ local: false,+ ),+ ];+ }++ /// Map a global position (seconds from book start) to a track + local offset+ /// within it. Falls back to the last track when the position runs past the+ /// summed durations (e.g. unknown per-track durations).+ static TrackHit mapGlobal(List<BookTrack> tracks, double globalSeconds) {+ var acc = 0.0;+ var idx = tracks.length - 1;+ var local = globalSeconds;+ for (var i = 0; i < tracks.length; i++) {+ if (globalSeconds < acc + tracks[i].duration || i == tracks.length - 1) {+ idx = i;+ final upper = tracks[i].duration > 0 ? tracks[i].duration : globalSeconds;+ local = (globalSeconds - acc).clamp(0.0, upper);+ break;+ }+ acc += tracks[i].duration;+ }+ return (index: idx, localOffset: local, track: tracks[idx]);+ }+}diff --git a/lib/services/bookmark_preview_player.dart b/lib/services/bookmark_preview_player.dartindex f2a42e8e..e828869b 100644--- a/lib/services/bookmark_preview_player.dart+++ b/lib/services/bookmark_preview_player.dart@@ -1,12 +1,11 @@import 'dart:async';-import 'dart:convert';import 'package:flutter/foundation.dart';import 'package:just_audio/just_audio.dart';import 'api_service.dart';import 'audio_player_service.dart';-import 'download_service.dart';+import 'book_track_resolver.dart';import 'offline_source.dart';/// Auditions a book at a given position WITHOUT moving the user's real playback@@ -27,13 +26,18 @@ class BookmarkPreviewPlayer extends ChangeNotifier {bool? _mainWasPlaying;Timer? _autoStop;+ // Track-local position (ms) the current audition started at, so pausing then+ // hitting Listen again restarts the clip from the top instead of resuming+ // mid-clip - makes it easy to re-judge the in-point while trimming.+ int? _lastSeekMs;+/// The audition auto-stops after this long so a single tap never plays the- /// rest of the book (a single-file m4b would otherwise run for hours). Plenty- /// for a bookmark preview; easy to bump or wire to a setting.- static const Duration _autoStopAfter = Duration(seconds: 60);+ /// rest of the book (a single-file m4b would otherwise run for hours). The+ /// bookmark dialog keeps this in sync with the chosen clip length, so what you+ /// preview is exactly what an export would produce.+ Duration clipLength = const Duration(seconds: 60);- // (source path/url, track duration seconds, isLocal) resolved once per book.- List<({String source, double duration, bool local})>? _tracks;+ List<BookTrack>? _tracks;bool get isLoading => _loading;bool get isPlaying => _playing;@@ -49,6 +53,11 @@ class BookmarkPreviewPlayer extends ChangeNotifier {await p.pause();} else {_pauseMain();+ // Restart from the clip start so every replay auditions the beginning+ // of the selection (also recovers from the auto-stop at the clip end).+ if (_lastSeekMs != null) {+ await p.seek(Duration(milliseconds: _lastSeekMs!));+ }_startAutoStop();await p.play();}@@ -71,22 +80,11 @@ class BookmarkPreviewPlayer extends ChangeNotifier {throw StateError('no audio for $itemId');}- // Map the global position to a track + local offset.- var acc = 0.0;- var idx = tracks.length - 1;- var local = globalSeconds;- for (var i = 0; i < tracks.length; i++) {- if (globalSeconds < acc + tracks[i].duration || i == tracks.length - 1) {- idx = i;- final upper = tracks[i].duration > 0 ? tracks[i].duration : globalSeconds;- local = (globalSeconds - acc).clamp(0.0, upper);- break;- }- acc += tracks[i].duration;- }- final track = tracks[idx];+ final hit = BookTrackResolver.mapGlobal(tracks, globalSeconds);+ final track = hit.track;+ final local = hit.localOffset;debugPrint('[BookmarkPreview] $itemId: play ${globalSeconds.toStringAsFixed(1)}s -> '- 'track[$idx] ${track.local ? "local" : "stream"} @${local.toStringAsFixed(1)}s');+ 'track[${hit.index}] ${track.local ? "local" : "stream"} @${local.toStringAsFixed(1)}s');try {await _disposePlayer();@@ -111,10 +109,11 @@ class BookmarkPreviewPlayer extends ChangeNotifier {await player.setAudioSource(AudioSource.uri(Uri.parse(track.source), headers: api?.mediaHeaders));}- await player.seek(Duration(milliseconds: (local * 1000).round()));+ _lastSeekMs = (local * 1000).round();+ await player.seek(Duration(milliseconds: _lastSeekMs!));// Start the auto-stop BEFORE awaiting play(): just_audio's play() future// doesn't complete until playback ends, so a timer after it never armed -- // that's why the 60s cap wasn't firing.+ // that's why the cap wasn't firing._startAutoStop();await player.play();} catch (e) {@@ -125,59 +124,8 @@ class BookmarkPreviewPlayer extends ChangeNotifier {}}- Future<List<({String source, double duration, bool local})>?> _resolveTracks() async {- if (_tracks != null) return _tracks;-- // Downloaded book: local files + cached track durations.- final localPaths = DownloadService().getLocalPaths(itemId);- final sessionRaw = DownloadService().getCachedSessionData(itemId);- if (localPaths != null && localPaths.isNotEmpty && sessionRaw != null) {- try {- final session = jsonDecode(sessionRaw) as Map<String, dynamic>;- final audioTracks = session['audioTracks'] as List<dynamic>?;- if (audioTracks != null && audioTracks.length == localPaths.length) {- _tracks = [- for (var i = 0; i < localPaths.length; i++)- (- source: localPaths[i],- duration: ((audioTracks[i] as Map<String, dynamic>)['duration'] as num?)?.toDouble() ?? 0,- local: true,- ),- ];- debugPrint('[BookmarkPreview] $itemId: ${_tracks!.length} local track(s)');- return _tracks;- }- } catch (_) {}- }-- // Streamed book: build per-file URLs from the library item.- if (api == null) {- debugPrint('[BookmarkPreview] $itemId: no api (not downloaded, not logged in?)');- return null;- }- final item = await api!.getLibraryItem(itemId);- if (item == null) {- debugPrint('[BookmarkPreview] $itemId: getLibraryItem returned null');- return null;- }- final media = item['media'] as Map<String, dynamic>? ?? {};- final audioFiles = ((media['audioFiles'] as List<dynamic>?) ?? const [])- .whereType<Map<String, dynamic>>()- .toList()- ..sort((a, b) => ((a['index'] as num?) ?? 0).compareTo((b['index'] as num?) ?? 0));- if (audioFiles.isEmpty) {- debugPrint('[BookmarkPreview] $itemId: library item has no audioFiles');- return null;- }- _tracks = [- for (final af in audioFiles)- (- source: api!.buildFileUrl(itemId, af['ino']?.toString() ?? ''),- duration: (af['duration'] as num?)?.toDouble() ?? 0,- local: false,- ),- ];- debugPrint('[BookmarkPreview] $itemId: ${_tracks!.length} streamed track(s)');+ Future<List<BookTrack>?> _resolveTracks() async {+ _tracks ??= await BookTrackResolver.resolve(itemId, api);return _tracks;}@@ -189,8 +137,8 @@ class BookmarkPreviewPlayer extends ChangeNotifier {void _startAutoStop() {_autoStop?.cancel();- _autoStop = Timer(_autoStopAfter, () {- debugPrint('[BookmarkPreview] auto-stop after ${_autoStopAfter.inSeconds}s');+ _autoStop = Timer(clipLength, () {+ debugPrint('[BookmarkPreview] auto-stop after ${clipLength.inSeconds}s');_player?.pause();});}@@ -198,6 +146,7 @@ class BookmarkPreviewPlayer extends ChangeNotifier {Future<void> _disposePlayer() async {_autoStop?.cancel();_autoStop = null;+ _lastSeekMs = null;await _stateSub?.cancel();_stateSub = null;final p = _player;diff --git a/lib/services/clip_editor_controller.dart b/lib/services/clip_editor_controller.dartnew file mode 100644index 00000000..f0b76d02--- /dev/null+++ b/lib/services/clip_editor_controller.dart@@ -0,0 +1,185 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:just_audio/just_audio.dart';++import 'api_service.dart';+import 'audio_player_service.dart';+import 'book_track_resolver.dart';+import 'offline_source.dart';++/// Drives the play-and-mark clip editor: loads the track the bookmark lives in,+/// plays a navigable window around it, reports a playhead, and tracks the+/// in/out points the user marks by ear. Pauses the main player while open and+/// restores it on dispose. All positions are GLOBAL book seconds (so they line+/// up with bookmark times and feed [ClipExportService] directly); internally we+/// translate to the loaded track's local time.+class ClipEditorController extends ChangeNotifier {+ ClipEditorController({+ required this.itemId,+ required this.bookmarkSeconds,+ this.api,+ });++ final String itemId;+ final double bookmarkSeconds;+ final ApiService? api;++ // Shortest allowed clip, and how far before/after the bookmark the editor+ // window reaches (clamped to the track) so the scrub bar stays navigable+ // instead of spanning a whole single-file book.+ static const double minClip = 1;+ static const double _leadIn = 30;+ static const double _leadOut = 330;++ AudioPlayer? _player;+ StreamSubscription<Duration>? _posSub;+ StreamSubscription<PlayerState>? _stateSub;+ bool _disposed = false;+ bool? _mainWasPlaying;++ bool _ready = false;+ bool _loading = true;+ bool _playing = false;+ double _trackBase = 0; // global seconds at the loaded track's start+ double _winStart = 0;+ double _winEnd = 0;+ double _position = 0; // global playhead+ double _inPoint = 0; // global+ double _outPoint = 0; // global++ bool get isReady => _ready;+ bool get isLoading => _loading;+ bool get isPlaying => _playing;+ double get windowStart => _winStart;+ double get windowEnd => _winEnd;+ double get position => _position.clamp(_winStart, _winEnd);+ double get inPoint => _inPoint;+ double get outPoint => _outPoint;+ double get clipDuration => _outPoint - _inPoint;++ Future<void> init() async {+ _pauseMain();+ final tracks = await BookTrackResolver.resolve(itemId, api);+ if (_disposed) return;+ if (tracks == null || tracks.isEmpty) {+ _loading = false;+ notifyListeners();+ throw StateError('no audio for $itemId');+ }+ final hit = BookTrackResolver.mapGlobal(tracks, bookmarkSeconds);+ var base = 0.0;+ for (var i = 0; i < hit.index; i++) {+ base += tracks[i].duration;+ }+ _trackBase = base;+ final trackDur = hit.track.duration > 0+ ? hit.track.duration+ : (bookmarkSeconds - base + _leadOut + _leadIn);+ final trackEnd = base + trackDur;+ _winStart = (bookmarkSeconds - _leadIn).clamp(base, trackEnd);+ _winEnd = (bookmarkSeconds + _leadOut).clamp(_winStart + minClip, trackEnd);+ _inPoint = bookmarkSeconds.clamp(_winStart, _winEnd - minClip);+ _outPoint = (bookmarkSeconds + 60).clamp(_inPoint + minClip, _winEnd);+ _position = _inPoint;++ try {+ final track = hit.track;+ final player = AudioPlayer(useProxyForRequestHeaders: false);+ _player = player;+ if (track.local) {+ await player.setAudioSource(localAudioSource(track.source));+ } else {+ await player.setAudioSource(+ AudioSource.uri(Uri.parse(track.source), headers: api?.mediaHeaders));+ }+ await player.seek(Duration(milliseconds: ((_position - _trackBase) * 1000).round()));+ _posSub = player.positionStream.listen((d) {+ if (_disposed) return;+ _position = _trackBase + d.inMilliseconds / 1000.0;+ // Free-play to the window end (not the out point) so the user can hear+ // past where they think the clip ends and place the out mark by ear.+ if (_playing && _position >= _winEnd) {+ player.pause();+ player.seek(Duration(milliseconds: ((_winEnd - _trackBase) * 1000).round()));+ }+ notifyListeners();+ });+ _stateSub = player.playerStateStream.listen((s) {+ if (_disposed) return;+ final done = s.processingState == ProcessingState.completed;+ _loading = s.processingState == ProcessingState.loading ||+ s.processingState == ProcessingState.buffering;+ _playing = s.playing && !done;+ notifyListeners();+ });+ _ready = true;+ _loading = false;+ notifyListeners();+ } catch (e) {+ debugPrint('[ClipEditor] load failed: $e');+ _loading = false;+ notifyListeners();+ rethrow;+ }+ }++ Future<void> togglePlay() async {+ final p = _player;+ if (p == null) return;+ if (p.playing) {+ await p.pause();+ } else {+ // Replaying from the window end restarts at the in point.+ if (_position >= _winEnd - 0.1) await seekToGlobal(_inPoint);+ await p.play();+ }+ }++ Future<void> seekToGlobal(double global) async {+ final p = _player;+ if (p == null) return;+ final clamped = global.clamp(_winStart, _winEnd);+ _position = clamped;+ notifyListeners();+ await p.seek(Duration(milliseconds: ((clamped - _trackBase) * 1000).round()));+ }++ Future<void> skip(double delta) => seekToGlobal(_position + delta);++ void setStart() {+ _inPoint = _position.clamp(_winStart, _outPoint - minClip);+ notifyListeners();+ }++ void setEnd() {+ _outPoint = _position.clamp(_inPoint + minClip, _winEnd);+ notifyListeners();+ }++ void nudgeStart(double delta) {+ _inPoint = (_inPoint + delta).clamp(_winStart, _outPoint - minClip);+ notifyListeners();+ }++ void nudgeEnd(double delta) {+ _outPoint = (_outPoint + delta).clamp(_inPoint + minClip, _winEnd);+ notifyListeners();+ }++ void _pauseMain() {+ final main = AudioPlayerService();+ _mainWasPlaying ??= main.isPlaying;+ if (main.isPlaying) main.pause();+ }++ @override+ void dispose() {+ _disposed = true;+ _posSub?.cancel();+ _stateSub?.cancel();+ _player?.dispose();+ if (_mainWasPlaying == true) AudioPlayerService().play();+ super.dispose();+ }+}diff --git a/lib/services/clip_export_service.dart b/lib/services/clip_export_service.dartnew file mode 100644index 00000000..26bf4510--- /dev/null+++ b/lib/services/clip_export_service.dart@@ -0,0 +1,93 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:path_provider/path_provider.dart';++import 'api_service.dart';+import 'book_track_resolver.dart';++/// Outcome of a clip export. [tempPath] is a freshly written .m4a in the temp+/// dir that the caller should hand to a save/share sheet and then delete.+/// [clamped] is true when the requested length ran past the end of the track+/// the bookmark sits in and we shortened it (cross-file stitching isn't done).+class ClipExportResult {+ ClipExportResult({+ required this.tempPath,+ required this.durationSeconds,+ required this.clamped,+ });+ final String tempPath;+ final double durationSeconds;+ final bool clamped;+}++class ClipExportException implements Exception {+ ClipExportException(this.message);+ final String message;+ @override+ String toString() => 'ClipExportException: $message';+}++/// Extracts a short audio clip starting at a bookmark and encodes it to .m4a+/// (AAC) via native code - Android MediaCodec + MediaMuxer, iOS+/// AVAssetExportSession. Works on downloaded files and streamed URLs (the+/// native side range-requests just the needed window with the auth headers).+class ClipExportService {+ static const _channel = MethodChannel('com.absorb.clip');++ /// Build a clip for [itemId] starting at [startSeconds] (global book+ /// position) running [requestedDuration] seconds. Throws+ /// [ClipExportException] on any failure so the UI can show one message.+ Future<ClipExportResult> exportClip({+ required String itemId,+ required double startSeconds,+ required double requestedDuration,+ ApiService? api,+ }) async {+ final tracks = await BookTrackResolver.resolve(itemId, api);+ if (tracks == null || tracks.isEmpty) {+ throw ClipExportException('no audio resolved for $itemId');+ }+ final hit = BookTrackResolver.mapGlobal(tracks, startSeconds);+ final track = hit.track;++ // Don't run past the end of this track - cross-file stitching is a v1+ // limitation, so shorten and tell the user.+ var duration = requestedDuration;+ var clamped = false;+ if (track.duration > 0) {+ final available = track.duration - hit.localOffset;+ if (available > 1 && duration > available) {+ duration = available;+ clamped = true;+ }+ }+ if (duration < 1) duration = requestedDuration;++ final tmp = await getTemporaryDirectory();+ final outPath =+ '${tmp.path}/absorb_clip_${DateTime.now().millisecondsSinceEpoch}.m4a';++ bool ok;+ try {+ ok = await _channel.invokeMethod<bool>('exportClip', {+ 'source': track.source,+ 'isLocal': track.local,+ 'headers': track.local ? null : api?.mediaHeaders,+ 'startSeconds': hit.localOffset,+ 'durationSeconds': duration,+ 'outPath': outPath,+ }) ??+ false;+ } on PlatformException catch (e) {+ debugPrint('[ClipExport] native error: ${e.code} ${e.message}');+ throw ClipExportException(e.message ?? e.code);+ }+ if (!ok) throw ClipExportException('native export returned false');++ return ClipExportResult(+ tempPath: outPath,+ durationSeconds: duration,+ clamped: clamped,+ );+ }+}diff --git a/lib/widgets/bookmark_detail_dialog.dart b/lib/widgets/bookmark_detail_dialog.dartindex 5f80775f..0ed8dab8 100644--- a/lib/widgets/bookmark_detail_dialog.dart+++ b/lib/widgets/bookmark_detail_dialog.dart@@ -4,22 +4,23 @@ import '../l10n/app_localizations.dart';import '../services/api_service.dart';import '../services/bookmark_service.dart';import '../services/bookmark_preview_player.dart';+import 'clip_editor_sheet.dart';-/// Result of [BookmarkDetailDialog]. [action] is 'jump' (caller should seek+/// Result of [BookmarkDetailSheet]. [action] is 'jump' (caller should seek/// there) or 'saved' (stay put, refresh). [position] is the possibly-nudged-/// bookmark time in seconds. The dialog returns null when closed without saving.+/// bookmark time in seconds. The sheet returns null when closed without saving.typedef BookmarkDetailResult = ({String action, double position});-/// Rich bookmark detail editor shared by the standalone Bookmarks screen and the-/// in-player bookmark sheet: roomy title/note, a -5/-1/+1/+5 fine time nudge-/// (synced to the server), and inline preview playback that auditions the spot-/// without moving the user's real position. Persists on Save/Jump, then pops a-/// [BookmarkDetailResult].-class BookmarkDetailDialog extends StatefulWidget {+/// Bookmark editor shown as a bottom sheet, shared by the standalone Bookmarks+/// screen and the in-player bookmark sheet: roomy title/note, a -5/-1/+1/+5 fine+/// time nudge (synced to the server), inline preview that auditions the spot+/// without moving the user's real position, and an Export clip action that opens+/// the [ClipEditorSheet]. Persists on Save/Jump, then pops a [BookmarkDetailResult].+class BookmarkDetailSheet extends StatefulWidget {final String itemId;final Bookmark bookmark;final ApiService? api;- const BookmarkDetailDialog({+ const BookmarkDetailSheet({super.key,required this.itemId,required this.bookmark,@@ -27,10 +28,10 @@ class BookmarkDetailDialog extends StatefulWidget {});@override- State<BookmarkDetailDialog> createState() => _BookmarkDetailDialogState();+ State<BookmarkDetailSheet> createState() => _BookmarkDetailSheetState();}-class _BookmarkDetailDialogState extends State<BookmarkDetailDialog> {+class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {late final TextEditingController _titleC;late final TextEditingController _noteC;late double _seconds;@@ -46,6 +47,7 @@ class _BookmarkDetailDialogState extends State<BookmarkDetailDialog> {// self-heals to 0 if the user saves._seconds = widget.bookmark.positionSeconds < 0 ? 0.0 : widget.bookmark.positionSeconds;_preview = BookmarkPreviewPlayer(itemId: widget.itemId, api: widget.api)+ ..clipLength = const Duration(seconds: 60)..addListener(_onPreview);}@@ -91,18 +93,41 @@ class _BookmarkDetailDialogState extends State<BookmarkDetailDialog> {}}+ Future<void> _openClipEditor() async {+ await _preview.stop();+ if (!mounted) return;+ await showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ showDragHandle: true,+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,+ shape: const RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),+ ),+ builder: (_) => ClipEditorSheet(+ itemId: widget.itemId,+ bookmarkSeconds: _seconds,+ bookmarkTitle:+ _titleC.text.trim().isEmpty ? widget.bookmark.title : _titleC.text.trim(),+ api: widget.api,+ ),+ );+ }+Future<void> _persist() async {setState(() => _saving = true);await _preview.stop();final newTitle =_titleC.text.trim().isEmpty ? widget.bookmark.title : _titleC.text.trim();+ // Pass the trimmed text as-is (even empty) so clearing the note actually+ // clears it - updateBookmark treats empty as "clear", null as "leave".final newNote = _noteC.text.trim();final svc = BookmarkService();await svc.updateBookmark(itemId: widget.itemId,bookmarkId: widget.bookmark.id,title: newTitle,- note: newNote.isEmpty ? null : newNote,+ note: newNote,api: widget.api,);if ((_seconds - widget.bookmark.positionSeconds).abs() >= 0.05) {@@ -119,15 +144,34 @@ class _BookmarkDetailDialogState extends State<BookmarkDetailDialog> {Widget build(BuildContext context) {final l = AppLocalizations.of(context)!;final tt = Theme.of(context).textTheme;- return AlertDialog(- scrollable: true,- title: Text(l.editBookmark),- content: SizedBox(- width: double.maxFinite,+ final cs = Theme.of(context).colorScheme;+ return Padding(+ padding: EdgeInsets.only(+ left: 20,+ right: 20,+ top: 4,+ bottom: 20 + MediaQuery.of(context).viewInsets.bottom,+ ),+ child: SingleChildScrollView(child: Column(mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.start,children: [+ Row(+ children: [+ Text(l.editBookmark, style: tt.titleLarge),+ const Spacer(),+ Text(+ _fmt(_seconds),+ style: tt.titleMedium?.copyWith(+ color: cs.primary,+ fontWeight: FontWeight.w600,+ fontFeatures: [const FontFeature.tabularFigures()],+ ),+ ),+ ],+ ),+ const SizedBox(height: 16),TextField(controller: _titleC,decoration: InputDecoration(@@ -136,8 +180,8 @@ class _BookmarkDetailDialogState extends State<BookmarkDetailDialog> {const SizedBox(height: 12),TextField(controller: _noteC,- minLines: 4,- maxLines: 10,+ minLines: 3,+ maxLines: 8,keyboardType: TextInputType.multiline,textCapitalization: TextCapitalization.sentences,decoration: InputDecoration(@@ -148,8 +192,8 @@ class _BookmarkDetailDialogState extends State<BookmarkDetailDialog> {),const SizedBox(height: 16),Row(children: [- _nudgeBtn('-5', () => _nudge(-5)),- _nudgeBtn('-1', () => _nudge(-1)),+ _nudgeBtn('-5', _saving ? null : () => _nudge(-5)),+ _nudgeBtn('-1', _saving ? null : () => _nudge(-1)),Expanded(child: Center(child: Text(@@ -161,8 +205,8 @@ class _BookmarkDetailDialogState extends State<BookmarkDetailDialog> {),),),- _nudgeBtn('+1', () => _nudge(1)),- _nudgeBtn('+5', () => _nudge(5)),+ _nudgeBtn('+1', _saving ? null : () => _nudge(1)),+ _nudgeBtn('+5', _saving ? null : () => _nudge(5)),]),const SizedBox(height: 4),Center(@@ -178,46 +222,61 @@ class _BookmarkDetailDialogState extends State<BookmarkDetailDialog> {onPressed: _preview.isLoading ? null : _togglePreview,),),+ const SizedBox(height: 8),+ SizedBox(+ width: double.infinity,+ child: OutlinedButton.icon(+ icon: const Icon(Icons.content_cut_rounded, size: 18),+ label: Text(l.clipExport),+ onPressed: _saving ? null : _openClipEditor,+ ),+ ),+ const SizedBox(height: 16),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ TextButton(+ onPressed: _saving+ ? null+ : () async {+ await _preview.stop();+ if (mounted) Navigator.pop(context);+ },+ child: Text(l.bookmarksScreenClose),+ ),+ const SizedBox(width: 8),+ TextButton(+ onPressed: _saving+ ? null+ : () async {+ await _persist();+ if (mounted) {+ Navigator.pop(context, (action: 'saved', position: _seconds));+ }+ },+ child: Text(l.save),+ ),+ const SizedBox(width: 8),+ FilledButton(+ onPressed: _saving+ ? null+ : () async {+ await _persist();+ if (mounted) {+ Navigator.pop(context, (action: 'jump', position: _seconds));+ }+ },+ child: Text(l.bookmarksJump),+ ),+ ],+ ),],),),- actions: [- TextButton(- onPressed: _saving- ? null- : () async {- await _preview.stop();- if (mounted) Navigator.pop(context);- },- child: Text(l.bookmarksScreenClose),- ),- TextButton(- onPressed: _saving- ? null- : () async {- await _persist();- if (mounted) {- Navigator.pop(context, (action: 'saved', position: _seconds));- }- },- child: Text(l.save),- ),- FilledButton(- onPressed: _saving- ? null- : () async {- await _persist();- if (mounted) {- Navigator.pop(context, (action: 'jump', position: _seconds));- }- },- child: Text(l.bookmarksJump),- ),- ],);}- Widget _nudgeBtn(String label, VoidCallback onTap) {+ Widget _nudgeBtn(String label, VoidCallback? onTap) {return Padding(padding: const EdgeInsets.symmetric(horizontal: 2),child: OutlinedButton(diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dartindex aecb3377..587bb321 100644--- a/lib/widgets/card_buttons.dart+++ b/lib/widgets/card_buttons.dart@@ -850,9 +850,17 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {final hasNote = bm.note != null && bm.note!.isNotEmpty;return InkWell(onTap: () async {- final result = await showDialog<BookmarkDetailResult>(+ final result = await showModalBottomSheet<BookmarkDetailResult>(context: ctx,- builder: (_) => BookmarkDetailDialog(+ isScrollControlled: true,+ showDragHandle: true,+ backgroundColor:+ Theme.of(ctx).bottomSheetTheme.backgroundColor,+ shape: const RoundedRectangleBorder(+ borderRadius:+ BorderRadius.vertical(top: Radius.circular(24)),+ ),+ builder: (_) => BookmarkDetailSheet(itemId: widget.itemId,bookmark: bm,api: context.read<AuthProvider>().apiService,diff --git a/lib/widgets/clip_editor_sheet.dart b/lib/widgets/clip_editor_sheet.dartnew file mode 100644index 00000000..f2504e1b--- /dev/null+++ b/lib/widgets/clip_editor_sheet.dart@@ -0,0 +1,416 @@+import 'dart:io';+import 'dart:typed_data';++import 'package:file_picker/file_picker.dart';+import 'package:flutter/material.dart';++import '../l10n/app_localizations.dart';+import '../services/api_service.dart';+import '../services/clip_editor_controller.dart';+import '../services/clip_export_service.dart';++/// Play-and-mark clip editor. Opened from the bookmark sheet's "Export clip".+/// Plays a navigable window around the bookmark; the user marks in/out by ear+/// (Set start / Set end at the playhead), fine-tunes with -1/+1, then saves an+/// .m4a to Files.+class ClipEditorSheet extends StatefulWidget {+ final String itemId;+ final double bookmarkSeconds;+ final String bookmarkTitle;+ final ApiService? api;+ const ClipEditorSheet({+ super.key,+ required this.itemId,+ required this.bookmarkSeconds,+ required this.bookmarkTitle,+ this.api,+ });++ @override+ State<ClipEditorSheet> createState() => _ClipEditorSheetState();+}++class _ClipEditorSheetState extends State<ClipEditorSheet> {+ late final ClipEditorController _c;+ bool _saving = false;+ bool _failed = false;++ @override+ void initState() {+ super.initState();+ _c = ClipEditorController(+ itemId: widget.itemId,+ bookmarkSeconds: widget.bookmarkSeconds,+ api: widget.api,+ )..addListener(_onChange);+ _c.init().catchError((_) {+ if (mounted) setState(() => _failed = true);+ });+ }++ void _onChange() {+ if (mounted) setState(() {});+ }++ @override+ void dispose() {+ _c.removeListener(_onChange);+ _c.dispose();+ super.dispose();+ }++ String _fmt(double s) {+ final v = s < 0 ? 0 : s.toInt();+ final h = v ~/ 3600;+ final m = (v % 3600) ~/ 60;+ final sec = v % 60;+ if (h > 0) {+ return '$h:${m.toString().padLeft(2, '0')}:${sec.toString().padLeft(2, '0')}';+ }+ return '$m:${sec.toString().padLeft(2, '0')}';+ }++ String _fileName() {+ final t = widget.bookmarkTitle.trim();+ final stamp = _fmt(_c.inPoint).replaceAll(':', '-');+ final safe =+ '${t.isEmpty ? 'Clip' : t} $stamp'.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_').trim();+ return '${safe.isEmpty ? 'clip' : safe}.m4a';+ }++ Future<void> _save() async {+ final l = AppLocalizations.of(context)!;+ final messenger = ScaffoldMessenger.of(context);+ final navigator = Navigator.of(context);+ setState(() => _saving = true);+ try {+ final res = await ClipExportService().exportClip(+ itemId: widget.itemId,+ startSeconds: _c.inPoint,+ requestedDuration: _c.clipDuration,+ api: widget.api,+ );+ final bytes = await File(res.tempPath).readAsBytes();+ final name = _fileName();+ final saved = await FilePicker.platform.saveFile(+ dialogTitle: l.clipExport,+ fileName: name,+ bytes: Uint8List.fromList(bytes),+ );+ try {+ await File(res.tempPath).delete();+ } catch (_) {}+ if (!mounted) return;+ if (saved == null) {+ setState(() => _saving = false);+ return; // user cancelled the save dialog+ }+ navigator.pop();+ messenger.showSnackBar(SnackBar(+ content: Text(res.clamped ? l.clipExportClamped : l.clipExportSaved(name)),+ behavior: SnackBarBehavior.floating,+ ));+ } catch (e) {+ debugPrint('[ClipEditor] save failed: $e');+ if (!mounted) return;+ setState(() => _saving = false);+ messenger.showSnackBar(SnackBar(+ content: Text(l.clipExportFailed),+ behavior: SnackBarBehavior.floating,+ ));+ }+ }++ @override+ Widget build(BuildContext context) {+ final l = AppLocalizations.of(context)!;+ final tt = Theme.of(context).textTheme;+ final cs = Theme.of(context).colorScheme;+ return Padding(+ padding: EdgeInsets.only(+ left: 20,+ right: 20,+ top: 4,+ bottom: 20 + MediaQuery.of(context).viewInsets.bottom,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Text(l.clipExport, style: tt.titleLarge),+ const Spacer(),+ if (_c.isReady)+ Text(+ _fmt(_c.clipDuration),+ style: tt.titleMedium?.copyWith(+ color: cs.primary,+ fontWeight: FontWeight.w600,+ fontFeatures: [const FontFeature.tabularFigures()],+ ),+ ),+ ],+ ),+ const SizedBox(height: 16),+ if (_failed)+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 32),+ child: Center(child: Text(l.bookmarkPreviewFailed)),+ )+ else if (!_c.isReady)+ const Padding(+ padding: EdgeInsets.symmetric(vertical: 40),+ child: Center(child: CircularProgressIndicator()),+ )+ else+ ..._editor(l, tt, cs),+ ],+ ),+ );+ }++ List<Widget> _editor(AppLocalizations l, TextTheme tt, ColorScheme cs) {+ final busy = _saving;+ return [+ _ClipScrubBar(+ windowStart: _c.windowStart,+ windowEnd: _c.windowEnd,+ inPoint: _c.inPoint,+ outPoint: _c.outPoint,+ position: _c.position,+ trackColor: cs.surfaceContainerHighest,+ selectionColor: cs.primary.withValues(alpha: 0.35),+ playheadColor: cs.primary,+ onSeek: busy ? null : _c.seekToGlobal,+ ),+ const SizedBox(height: 4),+ Row(+ mainAxisAlignment: MainAxisAlignment.spaceBetween,+ children: [+ Text(_fmt(_c.windowStart), style: tt.bodySmall),+ Text(_fmt(_c.position),+ style: tt.bodySmall?.copyWith(+ fontFeatures: [const FontFeature.tabularFigures()],+ )),+ Text(_fmt(_c.windowEnd), style: tt.bodySmall),+ ],+ ),+ const SizedBox(height: 12),+ Row(+ mainAxisAlignment: MainAxisAlignment.spaceEvenly,+ children: [+ IconButton(+ iconSize: 26,+ icon: const Icon(Icons.skip_previous_rounded),+ tooltip: l.clipJumpToStart,+ onPressed: busy ? null : () => _c.seekToGlobal(_c.inPoint),+ ),+ IconButton(+ iconSize: 28,+ icon: const Icon(Icons.replay_5_rounded),+ onPressed: busy ? null : () => _c.skip(-5),+ ),+ IconButton.filled(+ iconSize: 38,+ icon: Icon(_c.isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded),+ onPressed: busy ? null : _c.togglePlay,+ ),+ IconButton(+ iconSize: 28,+ icon: const Icon(Icons.forward_5_rounded),+ onPressed: busy ? null : () => _c.skip(5),+ ),+ IconButton(+ iconSize: 26,+ icon: const Icon(Icons.skip_next_rounded),+ tooltip: l.clipJumpToEnd,+ onPressed: busy ? null : () => _c.seekToGlobal(_c.outPoint),+ ),+ ],+ ),+ const SizedBox(height: 20),+ Row(+ children: [+ Expanded(+ child: OutlinedButton.icon(+ icon: const Icon(Icons.first_page_rounded, size: 18),+ label: Text(l.clipSetStart),+ onPressed: busy ? null : () => setState(_c.setStart),+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: OutlinedButton.icon(+ icon: const Icon(Icons.last_page_rounded, size: 18),+ label: Text(l.clipSetEnd),+ onPressed: busy ? null : () => setState(_c.setEnd),+ ),+ ),+ ],+ ),+ const SizedBox(height: 20),+ _markStepper(l.clipInLabel, _fmt(_c.inPoint), busy,+ () => _c.nudgeStart(-1), () => _c.nudgeStart(1)),+ const SizedBox(height: 12),+ _markStepper(l.clipOutLabel, _fmt(_c.outPoint), busy,+ () => _c.nudgeEnd(-1), () => _c.nudgeEnd(1)),+ const SizedBox(height: 24),+ SizedBox(+ width: double.infinity,+ child: FilledButton.icon(+ icon: _saving+ ? const SizedBox(+ width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))+ : const Icon(Icons.save_alt_rounded),+ label: Text(l.clipSave),+ onPressed: (_saving || _c.clipDuration < ClipEditorController.minClip)+ ? null+ : _save,+ ),+ ),+ ];+ }++ // A spaced stepper for one clip end: label on the left, then -1 / time / +1+ // as icon buttons matching the transport controls.+ Widget _markStepper(String label, String value, bool busy,+ VoidCallback onMinus, VoidCallback onPlus) {+ final tt = Theme.of(context).textTheme;+ return Row(+ children: [+ Text(label, style: tt.titleMedium),+ const Spacer(),+ IconButton(+ iconSize: 28,+ icon: const Icon(Icons.remove_circle_outline_rounded),+ onPressed: busy ? null : onMinus,+ ),+ SizedBox(+ width: 88,+ child: Text(+ value,+ textAlign: TextAlign.center,+ style: tt.titleMedium?.copyWith(+ fontWeight: FontWeight.w600,+ fontFeatures: [const FontFeature.tabularFigures()],+ ),+ ),+ ),+ IconButton(+ iconSize: 28,+ icon: const Icon(Icons.add_circle_outline_rounded),+ onPressed: busy ? null : onPlus,+ ),+ ],+ );+ }+}++/// A flat scrub bar: a track, a highlighted selection between in/out, and a+/// playhead. Tap or drag to move the playhead.+class _ClipScrubBar extends StatelessWidget {+ const _ClipScrubBar({+ required this.windowStart,+ required this.windowEnd,+ required this.inPoint,+ required this.outPoint,+ required this.position,+ required this.trackColor,+ required this.selectionColor,+ required this.playheadColor,+ required this.onSeek,+ });++ final double windowStart;+ final double windowEnd;+ final double inPoint;+ final double outPoint;+ final double position;+ final Color trackColor;+ final Color selectionColor;+ final Color playheadColor;+ final ValueChanged<double>? onSeek;++ double get _span => (windowEnd - windowStart).clamp(0.001, double.infinity);+ double _frac(double v) => ((v - windowStart) / _span).clamp(0.0, 1.0);++ @override+ Widget build(BuildContext context) {+ return LayoutBuilder(builder: (context, constraints) {+ final width = constraints.maxWidth;+ void seekAt(double dx) {+ if (onSeek == null) return;+ final frac = (dx / width).clamp(0.0, 1.0);+ onSeek!(windowStart + frac * _span);+ }++ return GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTapDown: (d) => seekAt(d.localPosition.dx),+ onHorizontalDragUpdate: (d) => seekAt(d.localPosition.dx),+ child: SizedBox(+ height: 36,+ width: double.infinity,+ child: CustomPaint(+ painter: _ScrubPainter(+ startFrac: _frac(inPoint),+ endFrac: _frac(outPoint),+ posFrac: _frac(position),+ trackColor: trackColor,+ selectionColor: selectionColor,+ playheadColor: playheadColor,+ ),+ ),+ ),+ );+ });+ }+}++class _ScrubPainter extends CustomPainter {+ _ScrubPainter({+ required this.startFrac,+ required this.endFrac,+ required this.posFrac,+ required this.trackColor,+ required this.selectionColor,+ required this.playheadColor,+ });++ final double startFrac;+ final double endFrac;+ final double posFrac;+ final Color trackColor;+ final Color selectionColor;+ final Color playheadColor;++ @override+ void paint(Canvas canvas, Size size) {+ final cy = size.height / 2;+ final track = Paint()..color = trackColor;+ canvas.drawRRect(+ RRect.fromLTRBR(0, cy - 3, size.width, cy + 3, const Radius.circular(3)),+ track,+ );+ final x1 = startFrac * size.width;+ final x2 = endFrac * size.width;+ canvas.drawRRect(+ RRect.fromLTRBR(x1, cy - 6, x2, cy + 6, const Radius.circular(4)),+ Paint()..color = selectionColor,+ );+ final px = (posFrac * size.width).clamp(0.0, size.width);+ final head = Paint()+ ..color = playheadColor+ ..strokeWidth = 2;+ canvas.drawLine(Offset(px, cy - 12), Offset(px, cy + 12), head);+ canvas.drawCircle(Offset(px, cy), 6, Paint()..color = playheadColor);+ }++ @override+ bool shouldRepaint(_ScrubPainter old) =>+ old.startFrac != startFrac ||+ old.endFrac != endFrac ||+ old.posFrac != posFrac ||+ old.selectionColor != selectionColor;+}