A cross platform Audiobookshelf client for Android and iOS
Dart
Rework the chapter editor and add transcription
Barnabas3e28d4ce750c
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex 9a20b762..9b216708 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -4224,14 +4224,38 @@"chapterFromTracks": "From Tracks","chapterLookup": "Lookup","chapterShowSeconds": "Show seconds",+ "chapterWindowMinutes": "{minutes} min",+ "@chapterWindowMinutes": {+ "placeholders": { "minutes": { "type": "int" } }+ },+ "chapterLoopCut": "Loop the cut",+ "chapterFindStart": "Find the start",+ "chapterFindStartListening": "Listening around the marker",+ "chapterFindStartNone": "Nothing here sounds like a chapter start",+ "chapterFindStartWider": "Search wider",+ "chapterFindStartCeiling": "Searched half an hour around the marker. The start is further off than that, or there's no chapter announcement to hear.",+ "chapterFindStartStrong": "Sounds like this chapter",+ "chapterFindStartMaybe": "Chapter-like words",+ "chapterFindStartGap": "{seconds}s gap",+ "@chapterFindStartGap": {+ "placeholders": { "seconds": { "type": "String" } }+ },+ "chapterFindStartRange": "Searched {from} to {to}",+ "@chapterFindStartRange": {+ "placeholders": { "from": { "type": "String" }, "to": { "type": "String" } }+ },+ "chapterFindStartNeedsModel": "Turn on transcription in Settings and download a model first",+ "chapterFindStartUseThis": "Use this",+ "chapterFindStartTitle": "Title: {title}",+ "@chapterFindStartTitle": {+ "placeholders": { "title": { "type": "String" } }+ },"chapterShiftBySeconds": "Shift by (seconds)","chapterShiftHint": "Shifts every unlocked chapter. Use a negative value to move them earlier.",- "chapterBack1Second": "Back 1 second",- "chapterForward1Second": "Forward 1 second","chapterTitleHint": "Chapter title","chapterStopPreview": "Stop preview","chapterPreviewFromHere": "Preview from here",- "chapterScrubHint": "Scrub to the exact spot, then set",+ "chapterScrubHint": "Drag or nudge to move the start","chapterStartAt": "Start at {time}","@chapterStartAt": {"placeholders": {@@ -4240,8 +4264,6 @@}}},- "chapterSetStartHere": "Set start here",- "chapterMore": "More","chapterUnlock": "Unlock","chapterLock": "Lock","chapterInsertBelow": "Insert below",diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex 9604873e..8080b88c 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -12285,29 +12285,101 @@ abstract class AppLocalizations {/// **'Show seconds'**String get chapterShowSeconds;- /// No description provided for @chapterShiftBySeconds.+ /// No description provided for @chapterWindowMinutes.////// In en, this message translates to:- /// **'Shift by (seconds)'**- String get chapterShiftBySeconds;+ /// **'{minutes} min'**+ String chapterWindowMinutes(int minutes);- /// No description provided for @chapterShiftHint.+ /// No description provided for @chapterLoopCut.////// In en, this message translates to:- /// **'Shifts every unlocked chapter. Use a negative value to move them earlier.'**- String get chapterShiftHint;+ /// **'Loop the cut'**+ String get chapterLoopCut;++ /// No description provided for @chapterFindStart.+ ///+ /// In en, this message translates to:+ /// **'Find the start'**+ String get chapterFindStart;++ /// No description provided for @chapterFindStartListening.+ ///+ /// In en, this message translates to:+ /// **'Listening around the marker'**+ String get chapterFindStartListening;++ /// No description provided for @chapterFindStartNone.+ ///+ /// In en, this message translates to:+ /// **'Nothing here sounds like a chapter start'**+ String get chapterFindStartNone;++ /// No description provided for @chapterFindStartWider.+ ///+ /// In en, this message translates to:+ /// **'Search wider'**+ String get chapterFindStartWider;++ /// No description provided for @chapterFindStartCeiling.+ ///+ /// In en, this message translates to:+ /// **'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.'**+ String get chapterFindStartCeiling;++ /// No description provided for @chapterFindStartStrong.+ ///+ /// In en, this message translates to:+ /// **'Sounds like this chapter'**+ String get chapterFindStartStrong;++ /// No description provided for @chapterFindStartMaybe.+ ///+ /// In en, this message translates to:+ /// **'Chapter-like words'**+ String get chapterFindStartMaybe;- /// No description provided for @chapterBack1Second.+ /// No description provided for @chapterFindStartGap.////// In en, this message translates to:- /// **'Back 1 second'**- String get chapterBack1Second;+ /// **'{seconds}s gap'**+ String chapterFindStartGap(String seconds);- /// No description provided for @chapterForward1Second.+ /// No description provided for @chapterFindStartRange.////// In en, this message translates to:- /// **'Forward 1 second'**- String get chapterForward1Second;+ /// **'Searched {from} to {to}'**+ String chapterFindStartRange(String from, String to);++ /// No description provided for @chapterFindStartNeedsModel.+ ///+ /// In en, this message translates to:+ /// **'Turn on transcription in Settings and download a model first'**+ String get chapterFindStartNeedsModel;++ /// No description provided for @chapterFindStartUseThis.+ ///+ /// In en, this message translates to:+ /// **'Use this'**+ String get chapterFindStartUseThis;++ /// No description provided for @chapterFindStartTitle.+ ///+ /// In en, this message translates to:+ /// **'Title: {title}'**+ String chapterFindStartTitle(String title);++ /// No description provided for @chapterShiftBySeconds.+ ///+ /// In en, this message translates to:+ /// **'Shift by (seconds)'**+ String get chapterShiftBySeconds;++ /// No description provided for @chapterShiftHint.+ ///+ /// In en, this message translates to:+ /// **'Shifts every unlocked chapter. Use a negative value to move them earlier.'**+ String get chapterShiftHint;/// No description provided for @chapterTitleHint.///@@ -12330,7 +12402,7 @@ abstract class AppLocalizations {/// No description provided for @chapterScrubHint.////// In en, this message translates to:- /// **'Scrub to the exact spot, then set'**+ /// **'Drag or nudge to move the start'**String get chapterScrubHint;/// No description provided for @chapterStartAt.@@ -12339,18 +12411,6 @@ abstract class AppLocalizations {/// **'Start at {time}'**String chapterStartAt(String time);- /// No description provided for @chapterSetStartHere.- ///- /// In en, this message translates to:- /// **'Set start here'**- String get chapterSetStartHere;-- /// No description provided for @chapterMore.- ///- /// In en, this message translates to:- /// **'More'**- String get chapterMore;-/// No description provided for @chapterUnlock.////// In en, this message translates to:diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex ca0e24f2..45a0e72c 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -7261,17 +7261,63 @@ class AppLocalizationsDe extends AppLocalizations {String get chapterShowSeconds => 'Sekunden anzeigen';@override- String get chapterShiftBySeconds => 'Verschieben um (Sekunden)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Verschiebt jedes entsperrte Kapitel. Verwende einen negativen Wert, um sie früher zu verschieben.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => '1 Sekunde zurück';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => '1 Sekunde vorwärts';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Verschieben um (Sekunden)';++ @override+ String get chapterShiftHint =>+ 'Verschiebt jedes entsperrte Kapitel. Verwende einen negativen Wert, um sie früher zu verschieben.';@overrideString get chapterTitleHint => 'Kapitelname';@@ -7290,12 +7336,6 @@ class AppLocalizationsDe extends AppLocalizations {return 'Beginne bei $time';}- @override- String get chapterSetStartHere => 'Beginn auf hier festlegen';-- @override- String get chapterMore => 'Mehr';-@overrideString get chapterUnlock => 'Entsperren';diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex d0405f0a..947ec185 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -7154,17 +7154,63 @@ class AppLocalizationsEl extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7176,19 +7222,13 @@ class AppLocalizationsEl extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex e0b35256..48de91bd 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -7154,17 +7154,63 @@ class AppLocalizationsEn extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7176,19 +7222,13 @@ class AppLocalizationsEn extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex b6ee506b..8cec3bdb 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -7156,17 +7156,63 @@ class AppLocalizationsEs extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7178,19 +7224,13 @@ class AppLocalizationsEs extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex f155d1a8..5b60dc75 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -7205,17 +7205,63 @@ class AppLocalizationsFr extends AppLocalizations {String get chapterShowSeconds => 'Afficher les secondes';@override- String get chapterShiftBySeconds => 'Décaler de (secondes)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Retour de 1 seconde';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Avancer de 1 seconde';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Décaler de (secondes)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Titre du chapitre';@@ -7227,19 +7273,13 @@ class AppLocalizationsFr extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Commencer à $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'Plus';-@overrideString get chapterUnlock => 'Déverrouiller';diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex 0819e8a9..e82a7826 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -7154,17 +7154,63 @@ class AppLocalizationsIt extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7176,19 +7222,13 @@ class AppLocalizationsIt extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex a89208f6..ee1a549e 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -7154,17 +7154,63 @@ class AppLocalizationsJa extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7176,19 +7222,13 @@ class AppLocalizationsJa extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex 9dcdd3a8..a6d148f4 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -7154,17 +7154,63 @@ class AppLocalizationsNo extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7176,19 +7222,13 @@ class AppLocalizationsNo extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex 74a8807c..ce8a1a87 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -7154,17 +7154,63 @@ class AppLocalizationsPt extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7176,19 +7222,13 @@ class AppLocalizationsPt extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex 72fe92c3..38d3e705 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -7154,17 +7154,63 @@ class AppLocalizationsRo extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7176,19 +7222,13 @@ class AppLocalizationsRo extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex 46d0e98f..987b31af 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -7158,17 +7158,63 @@ class AppLocalizationsRu extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7180,19 +7226,13 @@ class AppLocalizationsRu extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex 5ba1c1ae..b6bb99aa 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -7062,17 +7062,63 @@ class AppLocalizationsZh extends AppLocalizations {String get chapterShowSeconds => 'Show seconds';@override- String get chapterShiftBySeconds => 'Shift by (seconds)';+ String chapterWindowMinutes(int minutes) {+ return '$minutes min';+ }@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterLoopCut => 'Loop the cut';++ @override+ String get chapterFindStart => 'Find the start';++ @override+ String get chapterFindStartListening => 'Listening around the marker';++ @override+ String get chapterFindStartNone => 'Nothing here sounds like a chapter start';++ @override+ String get chapterFindStartWider => 'Search wider';++ @override+ String get chapterFindStartCeiling =>+ 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@override- String get chapterBack1Second => 'Back 1 second';+ String get chapterFindStartStrong => 'Sounds like this chapter';@override- String get chapterForward1Second => 'Forward 1 second';+ String get chapterFindStartMaybe => 'Chapter-like words';++ @override+ String chapterFindStartGap(String seconds) {+ return '${seconds}s gap';+ }++ @override+ String chapterFindStartRange(String from, String to) {+ return 'Searched $from to $to';+ }++ @override+ String get chapterFindStartNeedsModel =>+ 'Turn on transcription in Settings and download a model first';++ @override+ String get chapterFindStartUseThis => 'Use this';++ @override+ String chapterFindStartTitle(String title) {+ return 'Title: $title';+ }++ @override+ String get chapterShiftBySeconds => 'Shift by (seconds)';++ @override+ String get chapterShiftHint =>+ 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -7084,19 +7130,13 @@ class AppLocalizationsZh extends AppLocalizations {String get chapterPreviewFromHere => 'Preview from here';@override- String get chapterScrubHint => 'Scrub to the exact spot, then set';+ String get chapterScrubHint => 'Drag or nudge to move the start';@overrideString chapterStartAt(String time) {return 'Start at $time';}- @override- String get chapterSetStartHere => 'Set start here';-- @override- String get chapterMore => 'More';-@overrideString get chapterUnlock => 'Unlock';diff --git a/lib/screens/chapter_editor_screen.dart b/lib/screens/chapter_editor_screen.dartindex a0da5661..534b0a18 100644--- a/lib/screens/chapter_editor_screen.dart+++ b/lib/screens/chapter_editor_screen.dart@@ -1,4 +1,5 @@import 'dart:async';+import 'dart:io';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:just_audio/just_audio.dart';@@ -8,6 +9,10 @@ import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';import '../services/api_service.dart';import '../services/audio_player_service.dart';+import '../services/chapter_start_finder.dart';+import '../services/download_service.dart';+import '../services/remote_audio_slice.dart';+import '../services/transcription_service.dart';import '../widgets/overlay_toast.dart';/// Mutable working copy of one chapter. [uid] is a stable identity that@@ -112,6 +117,42 @@ class _ChapterEditBodyState extends State<ChapterEditBody>bool _scrubbing = false;bool? _mainWasPlaying;+ // The scrubber shows a window of the track, not the whole file: on a long+ // book a whole-file slider moves minutes per pixel. Track-local seconds.+ static const List<int> _windowChoices = [2, 5, 10];+ int _windowMinutes = 5;+ double _windowStart = 0;+ // The spot being cut. Loop the cut plays a second before it to two after+ // it on repeat, so a nudge is heard straight away.+ double _cutPos = 0;+ bool _loopCut = false;+ static const double _loopBefore = 1.0;+ static const double _loopAfter = 2.0;+ // Find the start only shows when transcription can actually run here.+ bool _canFind = false;++ Future<void> _checkFindAvailable() async {+ final ok = await TranscriptionService.instance.canTranscribeNow();+ if (mounted && ok != _canFind) setState(() => _canFind = ok);+ }++ double get _windowSeconds => _windowMinutes * 60.0;+ double get _windowEnd => _windowStart + _windowSeconds;++ /// Put the window around [center], keeping it inside the track.+ void _centerWindow(double center) {+ final maxStart = _previewTrackDur > _windowSeconds ? _previewTrackDur - _windowSeconds : 0.0;+ _windowStart = (center - _windowSeconds / 2).clamp(0.0, maxStart);+ }++ void _cycleWindow() {+ final i = _windowChoices.indexOf(_windowMinutes);+ setState(() {+ _windowMinutes = _windowChoices[(i + 1) % _windowChoices.length];+ _centerWindow(_cutPos);+ });+ }+@overridevoid initState() {super.initState();@@ -318,47 +359,34 @@ class _ChapterEditBodyState extends State<ChapterEditBody>// ─── Edits ──────────────────────────────────────────────────+ /// Hours, minutes and seconds drums instead of typing: no keyboard, and no+ /// way to enter a time the book doesn't have.Future<void> _editStart(_Ch c) async {final l = AppLocalizations.of(context)!;- final ctl = TextEditingController(text: _fmtStart(c.start));+ var picked = c.start;+ final maxHours = _duration > 0 ? (_duration / 3600).floor() : 99;final result = await showDialog<double>(context: context,- builder: (dctx) {- String? err;- return StatefulBuilder(builder: (dctx, setLocal) {- return AlertDialog(- title: Text(l.chapterEditStartTitle),- content: TextField(- controller: ctl,- autofocus: true,- keyboardType: const TextInputType.numberWithOptions(decimal: true),- decoration: InputDecoration(- hintText: _showSeconds ? l.chapterTimeHintSeconds : l.chapterTimeHintFull,- errorText: err,- ),- ),- actions: [- TextButton(- onPressed: () => Navigator.pop(dctx),- child: Text(l.cancel),- ),- TextButton(- onPressed: () {- final v = _parseTime(ctl.text);- if (v == null) {- setLocal(() => err = l.chapterInvalidTime);- return;- }- Navigator.pop(dctx, _clampStart(v));- },- child: Text(l.done),- ),- ],- );- });- },+ builder: (dctx) => AlertDialog(+ title: Text(l.chapterEditStartTitle),+ contentPadding: const EdgeInsets.fromLTRB(8, 20, 8, 0),+ content: _TimeDrums(+ seconds: c.start,+ maxHours: maxHours,+ onChanged: (v) => picked = v,+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(dctx),+ child: Text(l.cancel),+ ),+ TextButton(+ onPressed: () => Navigator.pop(dctx, _clampStart(picked)),+ child: Text(l.done),+ ),+ ],+ ),);- ctl.dispose();if (result == null) return;setState(() {c.start = result;@@ -366,16 +394,6 @@ class _ChapterEditBodyState extends State<ChapterEditBody>});}- void _nudge(_Ch c, double delta) {- final next = c.start + delta;- if (next < 0) return;- if (_duration > 0 && next >= _duration) return;- setState(() {- c.start = _clampStart(next);- _check();- });- }-void _toggleLock(_Ch c) {setState(() {if (_locked.contains(c.uid)) {@@ -471,7 +489,7 @@ class _ChapterEditBodyState extends State<ChapterEditBody>if (main.isPlaying) main.pause();}- Future<void> _playChapter(_Ch c) async {+ Future<void> _playChapter(_Ch c, {bool autoplay = true}) async {final l = AppLocalizations.of(context)!;await _stopPreview();@@ -495,13 +513,24 @@ class _ChapterEditBodyState extends State<ChapterEditBody>_previewTrackOffset = startOffset;_previewTrackDur = (track['duration'] as num?)?.toDouble() ?? 0;_previewPosSec = seekSec;+ _cutPos = seekSec;+ _centerWindow(seekSec);});+ unawaited(_checkFindAvailable());try {final player = AudioPlayer();_preview = player;_previewPosSub = player.positionStream.listen((pos) {- if (mounted && !_scrubbing) setState(() => _previewPosSec = pos.inMilliseconds / 1000.0);+ if (!mounted || _scrubbing) return;+ final sec = pos.inMilliseconds / 1000.0;+ if (_loopCut && sec > _cutPos + _loopAfter) {+ _preview?.seek(Duration(milliseconds: ((_cutPos - _loopBefore).clamp(0.0, sec) * 1000).round()));+ return;+ }+ // The window stays on the start; playback running past it just+ // fills the track to the edge.+ setState(() => _previewPosSec = sec);});_previewStateSub = player.playerStateStream.listen((st) {if (!mounted) return;@@ -518,7 +547,7 @@ class _ChapterEditBodyState extends State<ChapterEditBody>Uri.parse(api.buildTrackUrl(contentUrl)),options: mp3ExtractorOptions()));await player.seek(Duration(milliseconds: (seekSec * 1000).round()));- await player.play();+ if (autoplay) await player.play();} catch (e) {debugPrint('[ChapterEditor] preview error: $e');await _stopPreview();@@ -554,33 +583,58 @@ class _ChapterEditBodyState extends State<ChapterEditBody>if (_previewPlaying) {await p.pause();} else {- await p.play();+ // Play always starts from the chapter start, not wherever the pause+ // left the audio: the point of listening is to check the cut.+ _seekPreviewTo(_cutPos);}}- void _seekPreviewBy(double deltaSec) => _seekPreviewTo(_previewPosSec + deltaSec);-- void _seekPreviewTo(double posSec) {+ /// Nudges move the cut, not the playhead: with the loop on the base is the+ /// cut itself, otherwise wherever the audio is.+ void _seekPreviewBy(double deltaSec, {bool play = true}) =>+ _seekPreviewTo(_cutPos + deltaSec, play: play);++ /// Move the chapter's start to [posSec] (seconds into the track) and play+ /// from there, so every nudge and every slider release is heard from the+ /// new start. With the loop on, playback opens a second early and keeps+ /// coming back around it. The panel edits the start itself: there is no+ /// separate "set start" step.+ void _seekPreviewTo(double posSec, {bool play = true}) {final p = _preview;if (p == null) return;var target = posSec;if (target < 0) target = 0;if (_previewTrackDur > 0 && target > _previewTrackDur) target = _previewTrackDur;- p.seek(Duration(milliseconds: (target * 1000).round()));- if (mounted) setState(() => _previewPosSec = target);+ _cutPos = target;+ _Ch? active;+ for (final ch in _chapters) {+ if (ch.uid == _previewUid) {+ active = ch;+ break;+ }+ }+ // A held nudge only moves the start; the audio follows when the finger+ // lifts, so the sound doesn't stutter five times a second.+ if (play) {+ final playFrom = _loopCut ? (target - _loopBefore).clamp(0.0, target) : target;+ p.seek(Duration(milliseconds: (playFrom * 1000).round()));+ if (!_previewPlaying && !_previewLoading) p.play();+ _previewPosSec = playFrom;+ }+ if (mounted) {+ setState(() {+ if (target < _windowStart || target > _windowEnd) _centerWindow(target);+ if (active != null) {+ active.start = _clampStart(_previewTrackOffset + target);+ _check();+ }+ });+ }}- /// Snap the chapter start to the current preview position (the global time- /// the scrubber is sitting on). Works in either direction; keeps previewing- /// so the start can be fine-tuned further.- void _adjustStart(_Ch c) {- final newStart = _clampStart(_previewTrackOffset + _previewPosSec);- setState(() {- c.start = newStart;- _check();- });- HapticFeedback.mediumImpact();- showOverlayToast(context, AppLocalizations.of(context)!.chapterStartSetTo(_clock(newStart)), icon: Icons.check_rounded);+ void _toggleLoopCut() {+ setState(() => _loopCut = !_loopCut);+ if (_loopCut) _seekPreviewTo(_cutPos);}// ─── Bulk add ───────────────────────────────────────────────@@ -898,18 +952,27 @@ class _ChapterEditBodyState extends State<ChapterEditBody>}Widget _buildBody(ColorScheme cs) {+ // Only the save bar and the add field stay put. The toolbar scrolls away+ // with the list, so a small or zoomed screen with the keyboard up still+ // has room to see and reach the chapters instead of a two-row slit.return Column(children: [_saveBar(cs),- _toolbar(cs),- if (_showShift) _shiftPanel(cs),- const Divider(height: 1),Expanded(- child: ListView.builder(+ child: CustomScrollView(controller: _listScroll,- padding: const EdgeInsets.only(bottom: 16),- itemCount: _chapters.length,- itemBuilder: (_, i) => _row(cs, _chapters[i], i),+ slivers: [+ SliverToBoxAdapter(child: _toolbar(cs)),+ // Shifting is lock a few, shift the rest, repeat, so the shift+ // row stays put while the list scrolls under it.+ if (_showShift) PinnedHeaderSliver(child: _shiftPanel(cs)),+ const SliverToBoxAdapter(child: Divider(height: 1)),+ SliverList.builder(+ itemCount: _chapters.length,+ itemBuilder: (_, i) => _row(cs, _chapters[i], i),+ ),+ const SliverPadding(padding: EdgeInsets.only(bottom: 16)),+ ],),),_bulkBar(cs),@@ -1004,7 +1067,8 @@ class _ChapterEditBodyState extends State<ChapterEditBody>Widget _shiftPanel(ColorScheme cs) {final l = AppLocalizations.of(context)!;return Container(- color: cs.surfaceContainerHighest.withValues(alpha: 0.4),+ color: Color.alphaBlend(+ cs.surfaceContainerHighest.withValues(alpha: 0.4), cs.surface),padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),child: Column(crossAxisAlignment: CrossAxisAlignment.start,@@ -1039,7 +1103,6 @@ class _ChapterEditBodyState extends State<ChapterEditBody>Widget _row(ColorScheme cs, _Ch c, int index) {final l = AppLocalizations.of(context)!;- final locked = _locked.contains(c.uid);final hasError = c.error != null;final active = _previewUid == c.uid;return Container(@@ -1068,13 +1131,6 @@ class _ChapterEditBodyState extends State<ChapterEditBody>textAlign: TextAlign.center,style: TextStyle(fontSize: 14, fontWeight: FontWeight.w700, color: cs.onSurfaceVariant)),),- IconButton(- onPressed: () => _nudge(c, -1),- icon: const Icon(Icons.remove_circle_outline_rounded),- iconSize: 24,- color: cs.onSurfaceVariant,- tooltip: l.chapterBack1Second,- ),Expanded(child: InkWell(onTap: () => _editStart(c),@@ -1098,15 +1154,9 @@ class _ChapterEditBodyState extends State<ChapterEditBody>),),),- IconButton(- onPressed: () => _nudge(c, 1),- icon: const Icon(Icons.add_circle_outline_rounded),- iconSize: 24,- color: cs.onSurfaceVariant,- tooltip: l.chapterForward1Second,- ),- _previewButton(cs, c),- _rowMenu(cs, c, locked),+ const SizedBox(width: 2),+ ..._rowActions(cs, c),+ _expandButton(cs, c),],),Padding(@@ -1136,20 +1186,15 @@ class _ChapterEditBodyState extends State<ChapterEditBody>);}- Widget _previewButton(ColorScheme cs, _Ch c) {+ /// Opens the row into its preview panel, where the play button and the+ /// chapter's menu live; opening loads the audio paused.+ Widget _expandButton(ColorScheme cs, _Ch c) {final active = _previewUid == c.uid;- if (active && _previewLoading) {- return const SizedBox(- width: 48,- height: 48,- child: Center(child: SizedBox(width: 22, height: 22, child: CircularProgressIndicator(strokeWidth: 2))),- );- }final l = AppLocalizations.of(context)!;return IconButton(- onPressed: () => active ? _stopPreview() : _playChapter(c),- icon: Icon(active ? Icons.stop_circle_rounded : Icons.play_circle_rounded),- iconSize: 32,+ onPressed: () => active ? _stopPreview() : _playChapter(c, autoplay: false),+ icon: Icon(active ? Icons.expand_less_rounded : Icons.expand_more_rounded),+ iconSize: 28,color: active ? cs.primary : cs.onSurfaceVariant,tooltip: active ? l.chapterStopPreview : l.chapterPreviewFromHere,);@@ -1157,9 +1202,14 @@ class _ChapterEditBodyState extends State<ChapterEditBody>Widget _previewPanel(ColorScheme cs, _Ch c) {final l = AppLocalizations.of(context)!;- final global = _previewTrackOffset + _previewPosSec;- final dur = _previewTrackDur > 0 ? _previewTrackDur : (_previewPosSec > 1 ? _previewPosSec : 1.0);- final val = _previewPosSec.clamp(0.0, dur);+ final global = c.start;+ final trackEnd = _previewTrackDur > 0 ? _previewTrackDur : (_cutPos > 1 ? _cutPos : 1.0);+ final winEnd = _windowEnd < trackEnd ? _windowEnd : trackEnd;+ final winStart = _windowStart < winEnd ? _windowStart : (winEnd - 1).clamp(0.0, winEnd);+ // The thumb is the chapter start. Playback shows as the lighter fill+ // running ahead of it, so the start never drifts off under the audio.+ final val = _cutPos.clamp(winStart, winEnd);+ final playhead = _previewPosSec.clamp(winStart, winEnd);return Container(margin: const EdgeInsets.only(left: 4, right: 4, top: 10),padding: const EdgeInsets.fromLTRB(6, 6, 6, 12),@@ -1189,99 +1239,224 @@ class _ChapterEditBodyState extends State<ChapterEditBody>fontFeatures: const [FontFeature.tabularFigures()])),]),),+ IconButton(+ onPressed: _toggleLoopCut,+ tooltip: l.chapterLoopCut,+ isSelected: _loopCut,+ icon: const Icon(Icons.repeat_rounded),+ selectedIcon: Icon(Icons.repeat_on_rounded, color: cs.primary),+ ),+ if (_canFind)+ IconButton(+ onPressed: () => _showFindStart(c),+ tooltip: l.chapterFindStart,+ icon: const Icon(Icons.hearing_rounded),+ color: cs.primary,+ ),]),- Slider(- value: val,- max: dur,- onChangeStart: (_) => _scrubbing = true,- onChanged: (v) => setState(() => _previewPosSec = v),- onChangeEnd: (v) {- _scrubbing = false;- _seekPreviewTo(v);- },+ Row(children: [+ Expanded(+ child: Slider(+ value: val,+ secondaryTrackValue: playhead > val ? playhead : null,+ min: winStart,+ max: winEnd,+ onChangeStart: (_) => _scrubbing = true,+ onChanged: (v) => _seekPreviewTo(v, play: false),+ onChangeEnd: (v) {+ _scrubbing = false;+ // Let go at an edge and the window slides on by half.+ final edge = _windowSeconds * 0.02;+ if (v <= winStart + edge && winStart > 0) {+ _centerWindow(winStart);+ } else if (v >= winEnd - edge && winEnd < trackEnd) {+ _centerWindow(winEnd);+ }+ _seekPreviewTo(v);+ },+ ),+ ),+ // Tap to cycle the window width: two, five or ten minutes.+ ActionChip(+ visualDensity: VisualDensity.compact,+ label: Text(l.chapterWindowMinutes(_windowMinutes)),+ onPressed: _cycleWindow,+ ),+ const SizedBox(width: 4),+ ]),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12),+ child: Row(children: [+ Text(_clock(_previewTrackOffset + winStart),+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant)),+ const Spacer(),+ Text(_clock(_previewTrackOffset + winEnd),+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant)),+ ]),),+ const SizedBox(height: 6),Row(children: [- _skipBtn('-5s', () => _seekPreviewBy(-5)),+ _skipBtn('-5s', -5),const SizedBox(width: 8),- _skipBtn('-1s', () => _seekPreviewBy(-1)),+ _skipBtn('-1s', -1),const Spacer(),- _skipBtn('+1s', () => _seekPreviewBy(1)),+ _skipBtn('+1s', 1),const SizedBox(width: 8),- _skipBtn('+5s', () => _seekPreviewBy(5)),+ _skipBtn('+5s', 5),]),- const SizedBox(height: 12),- SizedBox(- width: double.infinity,- child: FilledButton.icon(- onPressed: () => _adjustStart(c),- icon: const Icon(Icons.my_location_rounded, size: 18),- label: Text(l.chapterSetStartHere),- ),- ),]),);}- Widget _skipBtn(String label, VoidCallback onTap) {- return OutlinedButton(- onPressed: onTap,- style: OutlinedButton.styleFrom(- minimumSize: const Size(58, 44),- padding: const EdgeInsets.symmetric(horizontal: 10),+ /// A nudge button that keeps nudging while held: the start moves with+ /// each tick, the audio catches up once on release.+ Widget _skipBtn(String label, double delta) {+ Timer? repeat;+ void onTap() => _seekPreviewBy(delta);+ return GestureDetector(+ onLongPressStart: (_) {+ _seekPreviewBy(delta, play: false);+ repeat = Timer.periodic(+ const Duration(milliseconds: 180), (_) => _seekPreviewBy(delta, play: false));+ },+ onLongPressEnd: (_) {+ repeat?.cancel();+ _seekPreviewTo(_cutPos);+ },+ onLongPressCancel: () => repeat?.cancel(),+ child: OutlinedButton(+ onPressed: onTap,+ style: OutlinedButton.styleFrom(+ minimumSize: const Size(58, 44),+ padding: const EdgeInsets.symmetric(horizontal: 10),+ ),+ child: Text(label),),- child: Text(label),);}- Widget _rowMenu(ColorScheme cs, _Ch c, bool locked) {+ /// Listen around the marker for where this chapter really starts and let+ /// the user pick from what was heard.+ Future<void> _showFindStart(_Ch c) async {final l = AppLocalizations.of(context)!;- return PopupMenuButton<String>(- icon: const Icon(Icons.more_vert_rounded),- iconSize: 24,- tooltip: l.chapterMore,- onSelected: (v) {- switch (v) {- case 'lock':- _toggleLock(c);- break;- case 'insert':- _insertBelow(c);- break;- case 'delete':- _remove(c);- break;- }- },- itemBuilder: (_) => [- PopupMenuItem(- value: 'lock',- child: Row(children: [- Icon(locked ? Icons.lock_open_rounded : Icons.lock_rounded,- color: locked ? Colors.orange : cs.onSurfaceVariant),- const SizedBox(width: 12),- Text(locked ? l.chapterUnlock : l.chapterLock),- ]),- ),- PopupMenuItem(- value: 'insert',- child: Row(children: [- Icon(Icons.add_box_outlined, color: cs.onSurfaceVariant),- const SizedBox(width: 12),- Text(l.chapterInsertBelow),- ]),- ),- if (_chapters.length > 1)- PopupMenuItem(- value: 'delete',- child: Row(children: [- Icon(Icons.delete_outline_rounded, color: cs.error),- const SizedBox(width: 12),- Text(l.delete, style: TextStyle(color: cs.error)),- ]),- ),- ],+ if (!await TranscriptionService.instance.canTranscribeNow()) {+ if (mounted) {+ showOverlayToast(context, l.chapterFindStartNeedsModel,+ icon: Icons.record_voice_over_rounded);+ }+ return;+ }+ final localPaths = DownloadService().getLocalPaths(widget.itemId);+ final downloaded = localPaths != null && localPaths.isNotEmpty;+ if (!mounted) return;+ final marker = c.start;+ final track = _trackForTime(marker);+ final api = context.read<AuthProvider>().apiService;+ if (track == null || api == null) return;+ final trackIndex = _tracks.indexOf(track);+ final offset = (track['startOffset'] as num?)?.toDouble() ?? 0;+ final trackDur = (track['duration'] as num?)?.toDouble() ?? 0;+ // Android's decoder opens a stream URL itself. Apple's only reads local+ // files, so on iOS a streamed book gets the window's bytes pulled down+ // and rewrapped first.+ final String source;+ RemoteTrack? remote;+ if (downloaded && trackIndex >= 0 && trackIndex < localPaths.length) {+ source = localPaths[trackIndex];+ } else {+ final contentUrl = track['contentUrl'] as String?;+ if (contentUrl == null) return;+ source = api.buildTrackUrl(contentUrl);+ if (Platform.isIOS) {+ remote = RemoteTrack(+ url: source,+ headers: api.mediaHeaders,+ durationSeconds: trackDur,+ mimeType: track['mimeType'] as String?,+ );+ }+ }+ final index = _chapters.indexOf(c);+ final title = _titleCtl[c.uid]?.text ?? c.title;+ // First pass is the scrubber's own window around the marker.+ final half = _windowSeconds / 2;+ final local = marker - offset;+ await showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ useSafeArea: true,+ backgroundColor: Theme.of(context).colorScheme.surface,+ shape: const RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(20)),+ ),+ builder: (_) => _FindStartSheet(+ source: source,+ remote: remote,+ sourceOffset: offset,+ trackDuration: trackDur,+ centerLocal: local,+ firstHalfWidth: half,+ chapterNumber: index + 1,+ title: title,+ clock: _clock,+ onPlay: (t) {+ if (_previewUid != c.uid) return;+ _seekPreviewTo(t - _previewTrackOffset);+ },+ onPick: (t, suggested) {+ // A heard title replaces an empty or number-only one; a heard+ // name ("Chapter 2: The Storm") is worth taking over anything.+ final current = (_titleCtl[c.uid]?.text ?? c.title).trim();+ final generic = current.isEmpty ||+ RegExp(r'^(chapter|part)?\s*\d+\.?$', caseSensitive: false).hasMatch(current);+ final takeTitle = suggested != null && (suggested.contains(':') || generic);+ setState(() {+ c.start = _clampStart(t);+ if (takeTitle) {+ c.title = suggested;+ _titleCtl[c.uid]?.text = suggested;+ }+ _check();+ });+ if (_previewUid == c.uid) _seekPreviewTo(t - _previewTrackOffset);+ },+ ),);}++ /// Lock, insert and delete sit beside the time now that the row has the+ /// room, instead of behind a menu in the preview panel.+ List<Widget> _rowActions(ColorScheme cs, _Ch c) {+ final l = AppLocalizations.of(context)!;+ final locked = _locked.contains(c.uid);+ return [+ IconButton(+ onPressed: () => _toggleLock(c),+ icon: Icon(locked ? Icons.lock_rounded : Icons.lock_open_rounded),+ iconSize: 22,+ visualDensity: VisualDensity.compact,+ color: locked ? Colors.orange : cs.onSurfaceVariant,+ tooltip: locked ? l.chapterUnlock : l.chapterLock,+ ),+ IconButton(+ onPressed: () => _insertBelow(c),+ icon: const Icon(Icons.add_box_outlined),+ iconSize: 22,+ visualDensity: VisualDensity.compact,+ color: cs.onSurfaceVariant,+ tooltip: l.chapterInsertBelow,+ ),+ if (_chapters.length > 1)+ IconButton(+ onPressed: () => _remove(c),+ icon: const Icon(Icons.delete_outline_rounded),+ iconSize: 22,+ visualDensity: VisualDensity.compact,+ color: cs.error.withValues(alpha: 0.8),+ tooltip: l.delete,+ ),+ ];+ }}class _LookupResult {@@ -1517,3 +1692,351 @@ class _ChapterLookupSheetState extends State<_ChapterLookupSheet> {]);}}++/// Hours, minutes and seconds drums for a chapter start.+class _TimeDrums extends StatefulWidget {+ final double seconds;+ final int maxHours;+ final ValueChanged<double> onChanged;+ const _TimeDrums({required this.seconds, required this.maxHours, required this.onChanged});++ @override+ State<_TimeDrums> createState() => _TimeDrumsState();+}++class _TimeDrumsState extends State<_TimeDrums> {+ late final FixedExtentScrollController _h;+ late final FixedExtentScrollController _m;+ late final FixedExtentScrollController _s;++ @override+ void initState() {+ super.initState();+ final total = widget.seconds.round().clamp(0, 1 << 31);+ _h = FixedExtentScrollController(initialItem: (total ~/ 3600).clamp(0, widget.maxHours));+ _m = FixedExtentScrollController(initialItem: (total % 3600) ~/ 60);+ _s = FixedExtentScrollController(initialItem: total % 60);+ }++ @override+ void dispose() {+ _h.dispose();+ _m.dispose();+ _s.dispose();+ super.dispose();+ }++ void _emit() {+ widget.onChanged(_h.selectedItem * 3600.0 + _m.selectedItem * 60.0 + _s.selectedItem);+ }++ Widget _drum(FixedExtentScrollController c, int count, String unit, ColorScheme cs) {+ return Expanded(+ child: Column(mainAxisSize: MainAxisSize.min, children: [+ SizedBox(+ height: 150,+ child: ListWheelScrollView.useDelegate(+ controller: c,+ itemExtent: 38,+ physics: const FixedExtentScrollPhysics(),+ diameterRatio: 1.6,+ onSelectedItemChanged: (_) => _emit(),+ childDelegate: ListWheelChildBuilderDelegate(+ childCount: count,+ builder: (_, i) => Center(+ child: Text(+ i.toString().padLeft(2, '0'),+ style: TextStyle(+ fontSize: 22,+ fontWeight: FontWeight.w600,+ fontFeatures: const [FontFeature.tabularFigures()],+ color: cs.onSurface,+ ),+ ),+ ),+ ),+ ),+ ),+ Text(unit, style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant)),+ ]),+ );+ }++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ return Row(children: [+ _drum(_h, widget.maxHours + 1, 'h', cs),+ _drum(_m, 60, 'm', cs),+ _drum(_s, 60, 's', cs),+ ]);+ }+}++/// Where a chapter could start, heard from the audio around the marker.+/// Starts on the scrubber's window and can search wider twice, to about+/// half an hour in all, before giving up.+class _FindStartSheet extends StatefulWidget {+ final String source;+ final RemoteTrack? remote;+ final double sourceOffset;+ final double trackDuration;+ final double centerLocal;+ final double firstHalfWidth;+ final int chapterNumber;+ final String title;+ final String Function(double) clock;+ final ValueChanged<double> onPlay;+ final void Function(double time, String? suggestedTitle) onPick;+ const _FindStartSheet({+ required this.source,+ this.remote,+ required this.sourceOffset,+ required this.trackDuration,+ required this.centerLocal,+ required this.firstHalfWidth,+ required this.chapterNumber,+ required this.title,+ required this.clock,+ required this.onPlay,+ required this.onPick,+ });++ @override+ State<_FindStartSheet> createState() => _FindStartSheetState();+}++class _FindStartSheetState extends State<_FindStartSheet> {+ // Each level adds this much on both sides: 5 min, then 15, then 30 in all.+ static const List<double> _growBy = [300, 450];++ final List<ChapterCandidate> _found = [];+ bool _running = true;+ bool _cancelled = false;+ int _level = 0;+ String? _error;+ late double _from = (widget.centerLocal - widget.firstHalfWidth).clamp(0.0, _trackEnd);+ late double _to = (widget.centerLocal + widget.firstHalfWidth).clamp(0.0, _trackEnd);++ double get _trackEnd => widget.trackDuration > 0 ? widget.trackDuration : double.infinity;+ bool get _atCeiling => _level >= _growBy.length;++ @override+ void initState() {+ super.initState();+ _run([(from: _from, to: _to)]);+ }++ @override+ void dispose() {+ _cancelled = true;+ super.dispose();+ }++ Future<void> _run(List<({double from, double to})> ranges) async {+ setState(() {+ _running = true;+ _error = null;+ });+ for (final r in ranges) {+ if (_cancelled) return;+ if (r.to - r.from < 2) continue;+ try {+ await ChapterStartFinder.run(+ source: widget.source,+ remote: widget.remote,+ sourceOffset: widget.sourceOffset,+ startLocal: r.from,+ windowSeconds: r.to - r.from,+ chapterNumber: widget.chapterNumber,+ title: widget.title,+ cancelled: () => _cancelled,+ onCandidate: (c) {+ if (!mounted || _cancelled) return;+ setState(() {+ _found.add(c);+ _found.sort((a, b) => a.time.compareTo(b.time));+ });+ },+ );+ } on TranscriptionException catch (e) {+ if (!mounted) return;+ final l = AppLocalizations.of(context)!;+ setState(() {+ _error = switch (e.kind) {+ TranscriptionError.disabled => l.transcriptionDisabledHint,+ TranscriptionError.modelMissing => l.transcriptionNoModelDownloaded,+ TranscriptionError.busy => l.transcriptionBusyMsg,+ _ => l.transcriptionFailedMsg,+ };+ });+ break;+ } catch (e) {+ debugPrint('[ChapterFind] failed: $e');+ if (!mounted) return;+ setState(() => _error = AppLocalizations.of(context)!.transcriptionFailedMsg);+ break;+ }+ }+ if (mounted) setState(() => _running = false);+ }++ void _wider() {+ if (_running || _atCeiling) return;+ final grow = _growBy[_level];+ final left = (from: (_from - grow).clamp(0.0, _from), to: _from);+ final right = (from: _to, to: (_to + grow).clamp(_to, _trackEnd));+ setState(() {+ _level++;+ _from = left.from;+ _to = right.to;+ });+ _run([left, right]);+ }++ @override+ Widget build(BuildContext context) {+ final l = AppLocalizations.of(context)!;+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final maxH = MediaQuery.of(context).size.height * 0.75;+ return ConstrainedBox(+ constraints: BoxConstraints(maxHeight: maxH),+ child: Column(mainAxisSize: MainAxisSize.min, children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 16, 12, 4),+ child: Row(children: [+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(l.chapterFindStart, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),+ const SizedBox(height: 2),+ Text(+ _running+ ? l.chapterFindStartListening+ : l.chapterFindStartRange(+ widget.clock(widget.sourceOffset + _from),+ widget.clock(widget.sourceOffset + (_to.isFinite ? _to : 0))),+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ ]),+ ),+ if (_running)+ const Padding(+ padding: EdgeInsets.all(8),+ child: SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2)),+ ),+ ]),+ ),+ Flexible(+ child: ListView(+ shrinkWrap: true,+ padding: const EdgeInsets.symmetric(vertical: 4),+ children: [+ for (final c in _found) _candidate(c, l, cs, tt, _isBest(c)),+ if (!_running && _found.isEmpty && _error == null)+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 12),+ child: Text(l.chapterFindStartNone, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),+ ),+ if (_error != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 12),+ child: Text(_error!, style: tt.bodyMedium?.copyWith(color: cs.error)),+ ),+ ],+ ),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 8, 20, 16),+ child: _atCeiling && !_running+ ? Text(l.chapterFindStartCeiling,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant))+ : SizedBox(+ width: double.infinity,+ child: OutlinedButton.icon(+ onPressed: _running || _error != null ? null : _wider,+ icon: const Icon(Icons.unfold_more_rounded, size: 18),+ label: Text(l.chapterFindStartWider),+ ),+ ),+ ),+ ]),+ );+ }++ /// The candidate the finder would pick: the top score, once something was+ /// actually heard that sounds like a chapter.+ bool _isBest(ChapterCandidate c) {+ if (c.score < 2) return false;+ return !_found.any((o) => o.score > c.score);+ }++ Widget _candidate(ChapterCandidate c, AppLocalizations l, ColorScheme cs, TextTheme tt, bool best) {+ final strong = c.score >= 2;+ final maybe = c.score == 1;+ final heard = c.heard.trim();+ final shortHeard = heard.length > 90 ? '${heard.substring(0, 90)}...' : heard;+ final gap = l.chapterFindStartGap(c.silenceSeconds.toStringAsFixed(1));+ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8),+ child: ListTile(+ shape: best+ ? RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(12),+ side: BorderSide(color: cs.primary, width: 1.5))+ : null,+ tileColor: best ? cs.primary.withValues(alpha: 0.06) : null,+ leading: IconButton(+ icon: Icon(Icons.play_circle_outline_rounded, color: cs.primary),+ tooltip: l.preview,+ onPressed: () => widget.onPlay(c.time),+ ),+ title: Row(children: [+ Text(widget.clock(c.time),+ style: tt.titleSmall?.copyWith(+ fontWeight: FontWeight.w700,+ fontFeatures: const [FontFeature.tabularFigures()])),+ const SizedBox(width: 8),+ if (strong || maybe)+ Container(+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),+ decoration: BoxDecoration(+ color: (strong ? cs.primary : cs.onSurface).withValues(alpha: strong ? 0.15 : 0.08),+ borderRadius: BorderRadius.circular(10),+ ),+ child: Text(strong ? l.chapterFindStartStrong : l.chapterFindStartMaybe,+ style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600,+ color: strong ? cs.primary : cs.onSurfaceVariant)),+ ),+ ]),+ subtitle: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(+ heard.isEmpty ? gap : '$gap - $shortHeard',+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ if (c.suggestedTitle != null)+ Text(+ l.chapterFindStartTitle(c.suggestedTitle!),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(color: cs.primary, fontWeight: FontWeight.w600),+ ),+ ]),+ isThreeLine: c.suggestedTitle != null,+ trailing: TextButton(+ onPressed: () {+ widget.onPick(c.time, c.suggestedTitle);+ Navigator.pop(context);+ },+ child: Text(l.chapterFindStartUseThis),+ ),+ onTap: () {+ widget.onPick(c.time, c.suggestedTitle);+ Navigator.pop(context);+ },+ ),+ );+ }+}diff --git a/lib/services/chapter_start_finder.dart b/lib/services/chapter_start_finder.dartnew file mode 100644index 00000000..71776f8d--- /dev/null+++ b/lib/services/chapter_start_finder.dart@@ -0,0 +1,435 @@+import 'dart:io';+import 'dart:math';+import 'dart:typed_data';++import 'package:flutter/foundation.dart';+import 'package:path_provider/path_provider.dart';++import 'remote_audio_slice.dart';+import 'transcription_service.dart';++/// One place in the audio that might be where a chapter starts: the end of a+/// silence, with what was heard right after it and how much that sounded+/// like the chapter being edited.+class ChapterCandidate {+ /// Global book time, seconds.+ final double time;+ final double silenceSeconds;+ final String heard;+ /// 2 = the chapter's own number or title was heard, 1 = some chapter-like+ /// word ("chapter", "part", "prologue"), 0 = just a gap in the audio.+ final int score;+ /// A title read off the narration ("Chapter 2", "Chapter 2: The Storm"),+ /// when the words after the gap announced one.+ final String? suggestedTitle;+ const ChapterCandidate({+ required this.time,+ required this.silenceSeconds,+ required this.heard,+ required this.score,+ this.suggestedTitle,+ });+}++/// Pure helpers, kept apart from the audio plumbing so they can be tested.+class ChapterStartAnalysis {+ /// Runs of quiet in 16-bit mono PCM at [sampleRate], at least [minSeconds]+ /// long. Quiet is judged against the loud parts of the same clip, so a+ /// softly recorded book and a loud one both work.+ static List<({double start, double end})> findSilences(+ Int16List pcm,+ int sampleRate, {+ double minSeconds = 0.8,+ double hopSeconds = 0.05,+ }) {+ if (pcm.isEmpty || sampleRate <= 0) return const [];+ final hop = max(1, (sampleRate * hopSeconds).round());+ final frames = pcm.length ~/ hop;+ if (frames < 4) return const [];+ final rms = Float64List(frames);+ for (var f = 0; f < frames; f++) {+ var acc = 0.0;+ final base = f * hop;+ for (var i = 0; i < hop; i++) {+ final s = pcm[base + i] / 32768.0;+ acc += s * s;+ }+ rms[f] = sqrt(acc / hop);+ }+ final sorted = List<double>.from(rms)..sort();+ final loud = sorted[(sorted.length * 0.9).floor().clamp(0, sorted.length - 1)];+ final threshold = max(loud * 0.12, 0.003);+ final minFrames = max(1, (minSeconds / hopSeconds).round());+ final out = <({double start, double end})>[];+ var runStart = -1;+ for (var f = 0; f <= frames; f++) {+ final quiet = f < frames && rms[f] < threshold;+ if (quiet) {+ if (runStart < 0) runStart = f;+ } else if (runStart >= 0) {+ if (f - runStart >= minFrames) {+ out.add((start: runStart * hopSeconds, end: f * hopSeconds));+ }+ runStart = -1;+ }+ }+ return out;+ }++ /// Cut [from]..[to] seconds out of a 16-bit mono WAV and wrap it in a new+ /// header. Times are clamped to the clip.+ static Uint8List sliceWav(Uint8List wav, int sampleRate, double from, double to) {+ final pcm = pcmOf(wav);+ final a = (from * sampleRate).round().clamp(0, pcm.length);+ final b = (to * sampleRate).round().clamp(a, pcm.length);+ final slice = Int16List.sublistView(pcm, a, b);+ return wavOf(slice, sampleRate);+ }++ /// The samples of a 16-bit mono WAV, header skipped.+ static Int16List pcmOf(Uint8List wav) {+ // The extractor writes a plain 44-byte header; fall back to scanning for+ // the data chunk in case a different writer produced the file.+ var dataStart = 44;+ var dataLen = wav.length - 44;+ for (var i = 12; i + 8 <= wav.length;) {+ final id = String.fromCharCodes(wav.sublist(i, i + 4));+ final len = ByteData.sublistView(wav, i + 4, i + 8).getUint32(0, Endian.little);+ if (id == 'data') {+ dataStart = i + 8;+ dataLen = min(len, wav.length - dataStart);+ break;+ }+ i += 8 + len + (len.isOdd ? 1 : 0);+ }+ final evenLen = dataLen - (dataLen.isOdd ? 1 : 0);+ return Int16List.sublistView(wav, dataStart, dataStart + evenLen);+ }++ static Uint8List wavOf(Int16List pcm, int sampleRate) {+ final dataLen = pcm.lengthInBytes;+ final out = ByteData(44 + dataLen);+ void ascii(int offset, String s) {+ for (var i = 0; i < s.length; i++) {+ out.setUint8(offset + i, s.codeUnitAt(i));+ }+ }+ ascii(0, 'RIFF');+ out.setUint32(4, 36 + dataLen, Endian.little);+ ascii(8, 'WAVE');+ ascii(12, 'fmt ');+ out.setUint32(16, 16, Endian.little);+ out.setUint16(20, 1, Endian.little);+ out.setUint16(22, 1, Endian.little);+ out.setUint32(24, sampleRate, Endian.little);+ out.setUint32(28, sampleRate * 2, Endian.little);+ out.setUint16(32, 2, Endian.little);+ out.setUint16(34, 16, Endian.little);+ ascii(36, 'data');+ out.setUint32(40, dataLen, Endian.little);+ final bytes = out.buffer.asUint8List();+ bytes.setRange(44, 44 + dataLen, pcm.buffer.asUint8List(pcm.offsetInBytes, dataLen));+ return bytes;+ }++ static const _units = {+ 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6,+ 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12,+ 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16,+ 'seventeen': 17, 'eighteen': 18, 'nineteen': 19,+ };+ static const _tens = {+ 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60,+ 'seventy': 70, 'eighty': 80, 'ninety': 90,+ };+ static const _ordinals = {+ 'first': 1, 'second': 2, 'third': 3, 'fourth': 4, 'fifth': 5, 'sixth': 6,+ 'seventh': 7, 'eighth': 8, 'ninth': 9, 'tenth': 10, 'eleventh': 11,+ 'twelfth': 12, 'thirteenth': 13, 'fourteenth': 14, 'fifteenth': 15,+ 'sixteenth': 16, 'seventeenth': 17, 'eighteenth': 18, 'nineteenth': 19,+ 'twentieth': 20, 'thirtieth': 30, 'fortieth': 40, 'fiftieth': 50,+ };+ static const _chapterWords = {+ 'chapter', 'part', 'prologue', 'epilogue', 'interlude', 'book', 'section',+ 'act', 'introduction', 'preface', 'afterword',+ };++ /// Words of [s], lower-cased, with spelled-out numbers turned into digits+ /// ("twenty one" and "twenty-first" both give "21").+ static List<String> words(String s) {+ final raw = s+ .toLowerCase()+ .replaceAll(RegExp(r"[^\p{L}\p{N}' ]+", unicode: true), ' ')+ .split(RegExp(r'\s+'))+ .where((w) => w.isNotEmpty)+ .toList();+ final out = <String>[];+ for (var i = 0; i < raw.length; i++) {+ final w = raw[i];+ final tens = _tens[w];+ if (tens != null) {+ final next = i + 1 < raw.length ? raw[i + 1] : null;+ final unit = next == null ? null : (_units[next] ?? _ordinals[next]);+ if (unit != null && unit < 10) {+ out.add('${tens + unit}');+ i++;+ } else {+ out.add('$tens');+ }+ continue;+ }+ final n = _units[w] ?? _ordinals[w];+ if (n != null) {+ out.add('$n');+ continue;+ }+ if (w == 'hundred' && out.isNotEmpty && int.tryParse(out.last) != null) {+ out[out.length - 1] = '${int.parse(out.last) * 100}';+ continue;+ }+ out.add(w);+ }+ return out;+ }++ /// How much [heard] sounds like the start of chapter [number] titled+ /// [title]: 2 when the number or the title itself is spoken, 1 when any+ /// chapter-like word is, 0 otherwise.+ static int score(String heard, {required int number, required String title}) {+ final h = words(heard);+ if (h.isEmpty) return 0;+ final hasChapterWord = h.any(_chapterWords.contains);+ final numberSpoken = h.contains('$number');+ if (numberSpoken && hasChapterWord) return 2;+ final t = words(title).where((w) => w.length > 2 && !_chapterWords.contains(w)).toList();+ if (t.length >= 2) {+ final hit = t.where(h.contains).length;+ if (hit >= max(2, (t.length * 0.6).ceil())) return 2;+ } else if (t.length == 1 && h.contains(t.first) && t.first.length >= 4) {+ return 2;+ }+ if (numberSpoken && h.indexOf('$number') <= 2) return 2;+ return hasChapterWord ? 1 : 0;+ }++ static const _standaloneHeadings = {+ 'prologue', 'epilogue', 'interlude', 'introduction', 'preface', 'afterword',+ };+ static const _numberedHeadings = {'chapter', 'part', 'book', 'section', 'act'};++ /// A chapter title read off what the narrator said right after the gap.+ /// "Chapter two" gives "Chapter 2"; "Chapter two, the storm. It was..."+ /// gives "Chapter 2: The Storm" when the extra words stop at a sentence+ /// break or a pause. Null when the words don't open with a heading.+ static String? suggestTitle(List<({double start, double end, String text})> segments) {+ if (segments.isEmpty) return null;+ final first = segments.first;+ final toks = words(first.text);+ if (toks.isEmpty) return null;+ final head = toks.first;+ String core;+ int consumed;+ if (_standaloneHeadings.contains(head)) {+ core = _cap(head);+ consumed = 1;+ } else if (_numberedHeadings.contains(head) && toks.length >= 2 && int.tryParse(toks[1]) != null) {+ core = '${_cap(head)} ${toks[1]}';+ consumed = 2;+ } else if (int.tryParse(head) != null && toks.length <= 8) {+ // Some narrators just say the number.+ core = 'Chapter $head';+ consumed = 1;+ } else {+ return null;+ }+ // Whatever else sits in the same breath before a sentence break is the+ // chapter's name. Whisper likes to put a full stop after the number+ // ("Chapter 3. Payback. I think..."), so a short clause right after that+ // stop counts as well, and so does a short second segment that follows+ // without a pause ("Chapter two." "The storm.").+ var rest = _clauseAfter(first.text, consumed);+ if (rest.isEmpty && consumed == 2) {+ final after = _clauseAfter(first.text, consumed, pastHeadingStop: true);+ final n = after.split(RegExp(r'\s+')).where((w) => w.isNotEmpty).length;+ if (n >= 1 && n <= 3) rest = after;+ }+ if (rest.isEmpty && consumed == 2 && segments.length > 1) {+ final next = segments[1];+ if (next.start - first.end < 0.6) {+ final nextWords = words(next.text);+ if (nextWords.isNotEmpty && nextWords.length <= 3 && _endsSentence(next.text)) {+ rest = _clauseAfter(next.text, 0);+ }+ }+ }+ final restWords = rest.split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();+ if (restWords.isEmpty || restWords.length > 6) return core;+ return '$core: ${restWords.map(_cap).join(' ')}';+ }++ static String _cap(String w) {+ if (w.isEmpty) return w;+ final lower = w.toLowerCase();+ return lower[0].toUpperCase() + lower.substring(1);+ }++ static bool _endsSentence(String s) => RegExp(r'[.!?]\s*$').hasMatch(s.trim());++ /// The words of [raw] after its first [skipTokens] spoken tokens, up to the+ /// first sentence break, punctuation dropped. Empty when the heading+ /// itself ended the sentence ("Chapter two." and then narration), unless+ /// [pastHeadingStop] asks for the clause after that stop.+ static String _clauseAfter(String raw, int skipTokens, {bool pastHeadingStop = false}) {+ final rawWords = raw.trim().split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();+ var i = 0;+ var consumed = 0;+ var lastHeadingWord = '';+ while (i < rawWords.length && consumed < skipTokens) {+ // "twenty two" is one token once normalized, so a pair of raw words+ // that collapse together is stepped over as one.+ final mergesWithNext = i + 1 < rawWords.length &&+ words(rawWords[i]).length == 1 &&+ words('${rawWords[i]} ${rawWords[i + 1]}').length == 1;+ if (mergesWithNext) {+ lastHeadingWord = rawWords[i + 1];+ i += 2;+ } else {+ lastHeadingWord = rawWords[i];+ i += 1;+ }+ consumed++;+ }+ if (!pastHeadingStop && skipTokens > 0 && RegExp(r'[.!?]$').hasMatch(lastHeadingWord)) {+ return '';+ }+ final out = <String>[];+ for (; i < rawWords.length; i++) {+ final w = rawWords[i];+ final clean = w.replaceAll(RegExp(r"[^\p{L}\p{N}'-]+", unicode: true), '');+ if (clean.isNotEmpty) out.add(clean);+ if (RegExp(r'[.!?;]$').hasMatch(w)) break;+ }+ return out.join(' ');+ }+}++/// Listens through a stretch of the book around a chapter marker and offers+/// the places a chapter could start: every decent silence, with the first+/// words after it, ranked by whether those words name the chapter.+class ChapterStartFinder {+ static const double afterSilenceSeconds = 6.0;+ static const int maxCandidatesPerWindow = 8;++ /// [source] is a local file or a stream URL the native extractor can open;+ /// [sourceOffset] is where that file starts in global book time and+ /// [startLocal] where the window starts inside it. With [remote] set the+ /// window's bytes are pulled down first and decoded from that slice, for+ /// platforms whose decoder can't read a URL. Candidates arrive through+ /// [onCandidate] as they are heard. Returns how many were found, or throws+ /// a [TranscriptionException] when nothing could be listened to.+ static Future<int> run({+ required String source,+ required double sourceOffset,+ required double startLocal,+ required double windowSeconds,+ required int chapterNumber,+ required String title,+ required void Function(ChapterCandidate) onCandidate,+ bool Function()? cancelled,+ RemoteTrack? remote,+ }) async {+ final svc = TranscriptionService.instance;+ var extractFrom = source;+ var extractStart = startLocal;+ AudioSlice? slice;+ if (remote != null) {+ try {+ slice = await RemoteAudioSlicer.fetch(+ remote,+ startLocal,+ windowSeconds,+ tmpDir: (await getTemporaryDirectory()).path,+ );+ } catch (e) {+ debugPrint('[ChapterFind] slice failed: $e');+ throw TranscriptionException(TranscriptionError.extractFailed, e);+ }+ extractFrom = slice.path;+ extractStart = slice.startWithin;+ }+ final String? wavPath;+ try {+ wavPath = await svc.extractWindowWav(+ source: extractFrom,+ startSeconds: extractStart,+ durationSeconds: windowSeconds,+ );+ } finally {+ if (slice != null) {+ try {+ File(slice.path).deleteSync();+ } catch (_) {}+ }+ }+ if (wavPath == null) throw TranscriptionException(TranscriptionError.extractFailed);+ var found = 0;+ try {+ final wav = await File(wavPath).readAsBytes();+ const rate = 16000;+ final pcm = ChapterStartAnalysis.pcmOf(wav);+ final clipSeconds = pcm.length / rate;+ var silences = ChapterStartAnalysis.findSilences(pcm, rate);+ // A window that opens in the middle of a silence still counts: the+ // speech that follows may be the chapter.+ if (silences.isEmpty || silences.first.start > 0.3) {+ silences = [(start: 0.0, end: 0.0), ...silences];+ }+ // Longest gaps first when there are too many, then back in time order.+ if (silences.length > maxCandidatesPerWindow) {+ silences.sort((a, b) => (b.end - b.start).compareTo(a.end - a.start));+ silences = silences.take(maxCandidatesPerWindow).toList()+ ..sort((a, b) => a.start.compareTo(b.start));+ }+ debugPrint('[ChapterFind] window ${startLocal.toStringAsFixed(1)}s+'+ '${windowSeconds.toStringAsFixed(0)}s: ${silences.length} gaps to listen after');+ for (final s in silences) {+ if (cancelled?.call() == true) break;+ final from = s.end;+ final to = min(clipSeconds, from + afterSilenceSeconds);+ if (to - from < 1.0) continue;+ final piece = ChapterStartAnalysis.sliceWav(wav, rate, from, to);+ final piecePath = '$wavPath.${(from * 10).round()}.wav';+ var heard = '';+ var segments = const <({double start, double end, String text})>[];+ try {+ await File(piecePath).writeAsBytes(piece, flush: true);+ segments = await svc.transcribeWavTimed(piecePath);+ heard = segments.map((s) => s.text).join(' ');+ } on TranscriptionException catch (e) {+ if (e.kind != TranscriptionError.empty) rethrow;+ } finally {+ try {+ File(piecePath).deleteSync();+ } catch (_) {}+ }+ final score = ChapterStartAnalysis.score(heard, number: chapterNumber, title: title);+ final candidate = ChapterCandidate(+ time: sourceOffset + startLocal + from,+ silenceSeconds: s.end - s.start,+ heard: heard,+ score: score,+ suggestedTitle: ChapterStartAnalysis.suggestTitle(segments),+ );+ debugPrint('[ChapterFind] ${candidate.time.toStringAsFixed(1)}s '+ 'gap=${candidate.silenceSeconds.toStringAsFixed(1)}s score=$score "$heard"');+ found++;+ onCandidate(candidate);+ }+ } finally {+ try {+ File(wavPath).deleteSync();+ } catch (_) {}+ }+ return found;+ }+}diff --git a/lib/services/remote_audio_slice.dart b/lib/services/remote_audio_slice.dartnew file mode 100644index 00000000..3c93a0a9--- /dev/null+++ b/lib/services/remote_audio_slice.dart@@ -0,0 +1,527 @@+import 'dart:io';+import 'dart:math';+import 'dart:typed_data';++import 'package:flutter/foundation.dart';+import 'package:http/http.dart' as http;++/// A track of a streamed book: where to fetch it and how long it runs.+class RemoteTrack {+ final String url;+ final Map<String, String> headers;+ final double durationSeconds;+ final String? mimeType;+ const RemoteTrack({+ required this.url,+ required this.headers,+ required this.durationSeconds,+ this.mimeType,+ });+}++/// A local file holding part of a track, and where the wanted moment sits+/// inside it. The caller deletes [path].+class AudioSlice {+ final String path;+ final double startWithin;+ const AudioSlice(this.path, this.startWithin);+}++/// Pulls a stretch of a streamed track down as a small local file the native+/// decoders can open, without fetching the whole book. M4B files are read+/// through their own index so the bytes for the exact samples come down and+/// get rewrapped as a plain AAC stream; MP3 files are cut by byte estimate,+/// which is only as exact as the file's bitrate is steady.+class RemoteAudioSlicer {+ static const int _headBytes = 64 * 1024;+ static const int _mp3MarginBytes = 96 * 1024;+ static final Map<String, Mp4Index> _indexCache = {};++ static Future<AudioSlice> fetch(+ RemoteTrack track,+ double startSeconds,+ double durationSeconds, {+ required String tmpDir,+ }) async {+ final head = await _range(track, 0, _headBytes - 1);+ final kind = _sniff(head.bytes, track.mimeType, track.url);+ final stamp = DateTime.now().microsecondsSinceEpoch;+ if (kind == _Kind.mp4) {+ final index = _indexCache[track.url] ??=+ await _loadIndex(track, head.bytes, head.totalSize);+ final path = '$tmpDir${Platform.pathSeparator}absorb_slice_$stamp.aac';+ return _sliceMp4(track, index, startSeconds, durationSeconds, path);+ }+ if (kind == _Kind.mp3) {+ final path = '$tmpDir${Platform.pathSeparator}absorb_slice_$stamp.mp3';+ return _sliceMp3(track, head.bytes, head.totalSize, startSeconds, durationSeconds, path);+ }+ throw StateError('unsupported track format ${track.mimeType ?? ''}');+ }++ static void forget(String url) => _indexCache.remove(url);++ // MP4++ static Future<Mp4Index> _loadIndex(RemoteTrack track, Uint8List head, int total) async {+ // Walk the top-level atoms until moov turns up. It is usually at the+ // front, but a file that was never "faststarted" keeps it after mdat,+ // which for a 20 hour book is gigabytes away, so hop by atom size.+ var offset = 0;+ var buf = head;+ var bufStart = 0;+ for (var hops = 0; hops < 32; hops++) {+ if (offset + 16 > bufStart + buf.length || offset < bufStart) {+ final r = await _range(track, offset, offset + 15);+ buf = r.bytes;+ bufStart = offset;+ }+ final bd = ByteData.sublistView(buf, offset - bufStart);+ var size = bd.getUint32(0).toDouble();+ final type = String.fromCharCodes(buf.sublist(offset - bufStart + 4, offset - bufStart + 8));+ var headerLen = 8;+ if (size == 1) {+ size = bd.getUint64(8).toDouble();+ headerLen = 16;+ } else if (size == 0) {+ size = (total - offset).toDouble();+ }+ if (type == 'moov') {+ final end = offset + size.toInt() - 1;+ final Uint8List moov;+ if (end < bufStart + buf.length) {+ moov = Uint8List.sublistView(buf, offset - bufStart, end + 1 - bufStart);+ } else {+ moov = (await _range(track, offset, end)).bytes;+ }+ debugPrint('[Slice] moov ${moov.length} bytes at $offset of $total');+ return Mp4Index.parse(moov);+ }+ if (size < headerLen) break;+ offset += size.toInt();+ if (offset >= total) break;+ }+ throw StateError('no moov atom');+ }++ static Future<AudioSlice> _sliceMp4(RemoteTrack track, Mp4Index index,+ double startSeconds, double durationSeconds, String path) async {+ final samples = index.samplesBetween(startSeconds, startSeconds + durationSeconds);+ if (samples.isEmpty) throw StateError('window past the end of the track');+ final firstOffset = index.sampleOffset(samples.first);+ final lastOffset = index.sampleOffset(samples.last) + index.sampleSize(samples.last) - 1;+ final bytes = (await _range(track, firstOffset, lastOffset)).bytes;+ final out = BytesBuilder(copy: false);+ for (final s in samples) {+ final off = index.sampleOffset(s) - firstOffset;+ final size = index.sampleSize(s);+ if (off < 0 || off + size > bytes.length) break;+ out.add(Adts.header(index.config, size));+ out.add(Uint8List.sublistView(bytes, off, off + size));+ }+ await File(path).writeAsBytes(out.takeBytes(), flush: true);+ final startWithin = (startSeconds - index.sampleTime(samples.first)).clamp(0.0, durationSeconds);+ debugPrint('[Slice] mp4 ${samples.length} samples, ${lastOffset - firstOffset + 1} bytes, '+ 'start ${startWithin.toStringAsFixed(2)}s into the slice');+ return AudioSlice(path, startWithin);+ }++ // MP3++ static Future<AudioSlice> _sliceMp3(RemoteTrack track, Uint8List head, int total,+ double startSeconds, double durationSeconds, String path) async {+ final dur = track.durationSeconds > 0 ? track.durationSeconds : 1.0;+ final audioStart = Mp3Probe.audioStart(head);+ final toc = Mp3Probe.xingToc(head, audioStart);+ double fracAt(double t) => (t / dur).clamp(0.0, 1.0);+ int byteAt(double t) {+ final f = fracAt(t);+ if (toc != null) {+ // The Xing table maps 100 points of time to 256ths of the file.+ final i = (f * 100).floor().clamp(0, 99);+ final a = toc[i] / 256.0;+ final b = (i + 1 < 100 ? toc[i + 1] : 256) / 256.0;+ final within = f * 100 - i;+ return (audioStart + (a + (b - a) * within) * (total - audioStart)).round();+ }+ return (audioStart + f * (total - audioStart)).round();+ }+ final from = max(audioStart, byteAt(startSeconds) - _mp3MarginBytes);+ final to = min(total - 1, byteAt(startSeconds + durationSeconds) + _mp3MarginBytes);+ final bytes = (await _range(track, from, to)).bytes;+ // Start on a frame header so the decoder doesn't guess at the first bytes.+ final sync = Mp3Probe.firstFrame(bytes);+ await File(path).writeAsBytes(Uint8List.sublistView(bytes, sync), flush: true);+ // The margin before the estimate is what the decoder should skip. Bytes+ // to seconds uses the average bitrate, which is all a byte estimate has.+ final bytesPerSecond = (total - audioStart) / dur;+ final startWithin = ((byteAt(startSeconds) - (from + sync)) / bytesPerSecond).clamp(0.0, durationSeconds);+ debugPrint('[Slice] mp3 ${to - from + 1} bytes from $from, '+ 'start ${startWithin.toStringAsFixed(2)}s into the slice${toc != null ? ' (xing toc)' : ''}');+ return AudioSlice(path, startWithin);+ }++ // HTTP++ static Future<({Uint8List bytes, int totalSize})> _range(RemoteTrack track, int from, int to) async {+ final resp = await http.get(+ Uri.parse(track.url),+ headers: {...track.headers, 'Range': 'bytes=$from-$to'},+ ).timeout(const Duration(seconds: 60));+ if (resp.statusCode == 206) {+ final cr = resp.headers['content-range'] ?? '';+ final total = int.tryParse(cr.split('/').last) ?? (to + 1);+ return (bytes: resp.bodyBytes, totalSize: total);+ }+ if (resp.statusCode == 200) {+ // A server that ignores Range sends the whole file; take the part asked for.+ final all = resp.bodyBytes;+ final end = min(to + 1, all.length);+ return (bytes: Uint8List.sublistView(all, min(from, all.length), end), totalSize: all.length);+ }+ throw HttpException('range fetch failed: ${resp.statusCode}');+ }++ static _Kind _sniff(Uint8List head, String? mime, String url) {+ if (head.length >= 12) {+ final type = String.fromCharCodes(head.sublist(4, 8));+ if (type == 'ftyp' || type == 'moov' || type == 'mdat' || type == 'free') return _Kind.mp4;+ if (head[0] == 0x49 && head[1] == 0x44 && head[2] == 0x33) return _Kind.mp3;+ if (head[0] == 0xFF && (head[1] & 0xE0) == 0xE0) return _Kind.mp3;+ }+ final m = (mime ?? '').toLowerCase();+ if (m.contains('mp4') || m.contains('m4a') || m.contains('m4b')) return _Kind.mp4;+ if (m.contains('mpeg') || m.contains('mp3')) return _Kind.mp3;+ final lower = url.toLowerCase();+ if (lower.contains('.m4b') || lower.contains('.m4a') || lower.contains('.mp4')) return _Kind.mp4;+ if (lower.contains('.mp3')) return _Kind.mp3;+ return _Kind.unknown;+ }+}++enum _Kind { mp4, mp3, unknown }++/// What the AAC frames need to stand on their own: an ADTS header carries+/// the profile, sample rate and channel count that an MP4 keeps in its+/// index instead.+class AacConfig {+ final int objectType;+ final int sampleRateIndex;+ final int channels;+ const AacConfig(this.objectType, this.sampleRateIndex, this.channels);++ static const sampleRates = [+ 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,+ ];+ int get sampleRate => sampleRateIndex < sampleRates.length ? sampleRates[sampleRateIndex] : 44100;+}++class Adts {+ /// A 7-byte ADTS header for one raw AAC frame of [payload] bytes.+ static Uint8List header(AacConfig c, int payload) {+ final len = payload + 7;+ // HE-AAC signals its object type past what ADTS can carry; LC in the+ // header with implicit SBR is how every decoder expects it.+ final profile = (c.objectType.clamp(1, 4) - 1) & 0x3;+ final h = Uint8List(7);+ h[0] = 0xFF;+ h[1] = 0xF1;+ h[2] = (profile << 6) | ((c.sampleRateIndex & 0xF) << 2) | ((c.channels >> 2) & 0x1);+ h[3] = ((c.channels & 0x3) << 6) | ((len >> 11) & 0x3);+ h[4] = (len >> 3) & 0xFF;+ h[5] = ((len & 0x7) << 5) | 0x1F;+ h[6] = 0xFC;+ return h;+ }+}++/// The audio track's sample tables out of an MP4 moov atom: enough to say+/// which bytes hold any moment of the audio.+class Mp4Index {+ final int timescale;+ final AacConfig config;+ /// Decode time of each sample's start, in timescale units, plus one+ /// trailing entry for the end.+ final Int64List sampleStarts;+ final Uint32List sampleSizes;+ final Int64List sampleOffsets;++ Mp4Index._(this.timescale, this.config, this.sampleStarts, this.sampleSizes, this.sampleOffsets);++ int get sampleCount => sampleSizes.length;+ double sampleTime(int i) => sampleStarts[i] / timescale;+ int sampleSize(int i) => sampleSizes[i];+ int sampleOffset(int i) => sampleOffsets[i];++ /// Sample indexes whose audio falls in [from]..[to] seconds.+ List<int> samplesBetween(double from, double to) {+ final fromT = (from * timescale).floor();+ final toT = (to * timescale).ceil();+ var lo = 0, hi = sampleCount;+ while (lo < hi) {+ final mid = (lo + hi) >> 1;+ if (sampleStarts[mid + 1] <= fromT) {+ lo = mid + 1;+ } else {+ hi = mid;+ }+ }+ final out = <int>[];+ for (var i = lo; i < sampleCount && sampleStarts[i] < toT; i++) {+ out.add(i);+ }+ return out;+ }++ static Mp4Index parse(Uint8List moov) {+ final root = _Atom(moov, 0, moov.length);+ for (final trak in root.children('moov').expand((m) => m.children('trak'))) {+ final mdia = trak.child('mdia');+ if (mdia == null) continue;+ final hdlr = mdia.child('hdlr');+ if (hdlr == null) continue;+ final handler = String.fromCharCodes(moov.sublist(hdlr.body + 8, hdlr.body + 12));+ if (handler != 'soun') continue;+ final mdhd = mdia.child('mdhd');+ final stbl = mdia.child('minf')?.child('stbl');+ if (mdhd == null || stbl == null) continue;+ final mdhdVersion = moov[mdhd.body];+ final timescale = ByteData.sublistView(moov).getUint32(mdhd.body + (mdhdVersion == 1 ? 20 : 12));+ final config = _aacConfig(moov, stbl.child('stsd'));+ if (config == null) throw StateError('audio track is not AAC');+ final stts = _stts(moov, stbl.child('stts'));+ final sizes = _stsz(moov, stbl.child('stsz'));+ final chunkOffsets = _stco(moov, stbl.child('stco') ?? stbl.child('co64'));+ final stsc = _stsc(moov, stbl.child('stsc'));+ final n = sizes.length;+ final starts = Int64List(n + 1);+ var t = 0;+ var si = 0;+ for (final e in stts) {+ for (var k = 0; k < e.count && si < n; k++) {+ starts[si++] = t;+ t += e.delta;+ }+ }+ starts[n] = t;+ final offsets = Int64List(n);+ var sample = 0;+ for (var ci = 0; ci < chunkOffsets.length && sample < n; ci++) {+ final perChunk = _samplesInChunk(stsc, ci + 1);+ var off = chunkOffsets[ci];+ for (var k = 0; k < perChunk && sample < n; k++) {+ offsets[sample] = off;+ off += sizes[sample];+ sample++;+ }+ }+ return Mp4Index._(timescale, config, starts, sizes, offsets);+ }+ throw StateError('no audio track');+ }++ static int _samplesInChunk(List<({int firstChunk, int samples})> stsc, int chunk) {+ var result = stsc.isNotEmpty ? stsc.first.samples : 0;+ for (final e in stsc) {+ if (e.firstChunk <= chunk) result = e.samples;+ }+ return result;+ }++ static List<({int count, int delta})> _stts(Uint8List b, _Atom? a) {+ if (a == null) throw StateError('no stts');+ final bd = ByteData.sublistView(b);+ final n = bd.getUint32(a.body + 4);+ return [+ for (var i = 0; i < n; i++)+ (count: bd.getUint32(a.body + 8 + i * 8), delta: bd.getUint32(a.body + 12 + i * 8)),+ ];+ }++ static Uint32List _stsz(Uint8List b, _Atom? a) {+ if (a == null) throw StateError('no stsz');+ final bd = ByteData.sublistView(b);+ final fixed = bd.getUint32(a.body + 4);+ final n = bd.getUint32(a.body + 8);+ final out = Uint32List(n);+ for (var i = 0; i < n; i++) {+ out[i] = fixed != 0 ? fixed : bd.getUint32(a.body + 12 + i * 4);+ }+ return out;+ }++ static List<int> _stco(Uint8List b, _Atom? a) {+ if (a == null) throw StateError('no stco');+ final bd = ByteData.sublistView(b);+ final n = bd.getUint32(a.body + 4);+ final wide = a.type == 'co64';+ return [+ for (var i = 0; i < n; i++)+ wide ? bd.getUint64(a.body + 8 + i * 8) : bd.getUint32(a.body + 8 + i * 4),+ ];+ }++ static List<({int firstChunk, int samples})> _stsc(Uint8List b, _Atom? a) {+ if (a == null) throw StateError('no stsc');+ final bd = ByteData.sublistView(b);+ final n = bd.getUint32(a.body + 4);+ return [+ for (var i = 0; i < n; i++)+ (firstChunk: bd.getUint32(a.body + 8 + i * 12), samples: bd.getUint32(a.body + 12 + i * 12)),+ ];+ }++ /// The AudioSpecificConfig out of stsd > mp4a > esds.+ static AacConfig? _aacConfig(Uint8List b, _Atom? stsd) {+ if (stsd == null) return null;+ // stsd: version/flags (4) + entry count (4), then sample entries.+ final entry = _Atom(b, stsd.body + 8, stsd.end);+ if (entry.type != 'mp4a') return null;+ // mp4a: 6 reserved + 2 data ref index + 8 reserved + channels (2) ++ // sample size (2) + 4 reserved + sample rate (4) = 28 bytes of fields.+ final bd = ByteData.sublistView(b);+ final channels = bd.getUint16(entry.body + 16);+ final esds = _Atom(b, entry.body + 28, entry.end).siblingsUntil(entry.end).firstWhere(+ (x) => x.type == 'esds',+ orElse: () => throw StateError('no esds'),+ );+ // esds: version/flags then ES_Descriptor (0x03) > DecoderConfig (0x04)+ // > DecoderSpecificInfo (0x05) which holds the AudioSpecificConfig.+ var p = esds.body + 4;+ int readLen() {+ var len = 0;+ for (var i = 0; i < 4; i++) {+ final v = b[p++];+ len = (len << 7) | (v & 0x7F);+ if (v & 0x80 == 0) break;+ }+ return len;+ }+ if (b[p] != 0x03) return null;+ p++;+ readLen();+ p += 2; // ES_ID+ final esFlags = b[p++];+ if (esFlags & 0x80 != 0) p += 2; // dependsOn_ES_ID+ if (esFlags & 0x40 != 0) p += 1 + b[p]; // URL string+ if (esFlags & 0x20 != 0) p += 2; // OCR_ES_ID+ if (b[p] != 0x04) return null;+ p++;+ readLen();+ p += 13;+ if (b[p] != 0x05) return null;+ p++;+ final dsiLen = readLen();+ if (dsiLen < 2) return null;+ final asc = (b[p] << 8) | b[p + 1];+ final objectType = asc >> 11;+ final rateIndex = (asc >> 7) & 0xF;+ final chanConfig = (asc >> 3) & 0xF;+ return AacConfig(objectType, rateIndex, chanConfig != 0 ? chanConfig : channels);+ }+}++/// One box of an MP4 file.+class _Atom {+ final Uint8List bytes;+ final int start;+ final int end;+ late final int size;+ late final String type;+ late final int body;++ _Atom(this.bytes, this.start, int limit) : end = limit {+ if (start + 8 > limit) {+ size = 0;+ type = '';+ body = start;+ return;+ }+ final bd = ByteData.sublistView(bytes);+ var s = bd.getUint32(start);+ type = String.fromCharCodes(bytes.sublist(start + 4, start + 8));+ var header = 8;+ if (s == 1 && start + 16 <= limit) {+ s = bd.getUint64(start + 8);+ header = 16;+ } else if (s == 0) {+ s = limit - start;+ }+ size = min(s, limit - start);+ body = start + header;+ }++ int get next => start + size;++ /// The boxes laid out directly inside this one.+ List<_Atom> children(String ofType) {+ // The root pseudo-atom is the whole buffer: its own header is the first+ // real atom, so walk from start rather than body.+ final from = start == 0 && end == bytes.length && type == ofType ? start : body;+ return _Atom(bytes, from, end).siblingsUntil(end).where((a) => a.type == ofType).toList();+ }++ _Atom? child(String ofType) {+ for (final a in _Atom(bytes, body, end).siblingsUntil(end)) {+ if (a.type == ofType) return a;+ }+ return null;+ }++ /// This box and the ones after it up to [limit].+ List<_Atom> siblingsUntil(int limit) {+ final out = <_Atom>[];+ var a = this;+ while (a.start + 8 <= limit && a.size >= 8) {+ out.add(a);+ if (a.next >= limit) break;+ a = _Atom(bytes, a.next, limit);+ }+ return out;+ }+}++/// Just enough MP3 knowledge to cut a file by byte position.+class Mp3Probe {+ /// Where the audio frames begin: after an ID3v2 tag if there is one.+ static int audioStart(Uint8List head) {+ if (head.length >= 10 && head[0] == 0x49 && head[1] == 0x44 && head[2] == 0x33) {+ final size = ((head[6] & 0x7F) << 21) | ((head[7] & 0x7F) << 14) | ((head[8] & 0x7F) << 7) | (head[9] & 0x7F);+ return 10 + size + ((head[5] & 0x10) != 0 ? 10 : 0);+ }+ return 0;+ }++ /// The first byte of a frame header at or after [from].+ static int firstFrame(Uint8List bytes, [int from = 0]) {+ for (var i = from; i + 4 <= bytes.length; i++) {+ if (bytes[i] == 0xFF && (bytes[i + 1] & 0xE0) == 0xE0 && ((bytes[i + 1] >> 1) & 0x3) != 0 && ((bytes[i + 2] >> 4) & 0xF) != 0xF) {+ return i;+ }+ }+ return 0;+ }++ /// The 100-entry seek table of a VBR file's Xing header, or null.+ static List<int>? xingToc(Uint8List head, int audioStart) {+ final frame = firstFrame(head, audioStart);+ // The Xing tag sits after the side information, whose size depends on+ // the MPEG version and channel mode.+ if (frame + 4 > head.length) return null;+ final versionBits = (head[frame + 1] >> 3) & 0x3;+ final mono = ((head[frame + 3] >> 6) & 0x3) == 3;+ final mpeg1 = versionBits == 3;+ final side = mpeg1 ? (mono ? 17 : 32) : (mono ? 9 : 17);+ final p = frame + 4 + side;+ if (p + 8 > head.length) return null;+ final tag = String.fromCharCodes(head.sublist(p, p + 4));+ if (tag != 'Xing' && tag != 'Info') return null;+ final flags = ByteData.sublistView(head).getUint32(p + 4);+ var q = p + 8;+ if (flags & 0x1 != 0) q += 4;+ if (flags & 0x2 != 0) q += 4;+ if (flags & 0x4 == 0) return null;+ if (q + 100 > head.length) return null;+ return List<int>.generate(100, (i) => head[q + i]);+ }+}diff --git a/lib/services/transcription_service.dart b/lib/services/transcription_service.dartindex c0f76791..74a87130 100644--- a/lib/services/transcription_service.dart+++ b/lib/services/transcription_service.dart@@ -514,6 +514,129 @@ class TranscriptionService {}}+ /// Transcription is switched on and a model for [feature] is on the device,+ /// regardless of any particular book.+ Future<bool> canTranscribeNow({+ TranscriptionFeature feature = TranscriptionFeature.readAlong,+ }) async {+ if (!await PlayerSettings.getTranscriptionEnabled()) return false;+ final info = await _modelFor(null, feature);+ return isModelDownloaded(info.size);+ }++ /// Decode [durationSeconds] of [source] from [startSeconds] (seconds into+ /// that file, not the book) into a 16kHz mono WAV and hand back its path.+ /// [source] is a local file, a content:// URI or a stream URL; the caller+ /// owns the file. For callers that want the audio itself rather than a+ /// transcript, like the chapter start finder.+ Future<String?> extractWindowWav({+ required String source,+ required double startSeconds,+ required double durationSeconds,+ }) =>+ _extractWav(+ sourcePath: source,+ startSeconds: startSeconds,+ durationSeconds: durationSeconds,+ );++ /// Whisper over one ready-made 16kHz mono WAV. Same guards as+ /// [transcribeAt]; the file is left alone.+ Future<String> transcribeWav(+ String wavPath, {+ String? itemId,+ bool? preferAccuracy,+ TranscriptionFeature feature = TranscriptionFeature.readAlong,+ }) async {+ if (!await PlayerSettings.getTranscriptionEnabled()) {+ throw TranscriptionException(TranscriptionError.disabled);+ }+ if (_busy) throw TranscriptionException(TranscriptionError.busy);+ final info = await _modelFor(preferAccuracy, feature);+ if (!await isModelDownloaded(info.size)) {+ throw TranscriptionException(TranscriptionError.modelMissing);+ }+ lastModelUsed = info.size;+ _busy = true;+ final watch = Stopwatch()..start();+ try {+ final lang = itemId == null ? 'auto' : (_bookLang[itemId] ?? 'auto');+ final String text;+ try {+ final result = await _whisper.transcribe(+ model: info.whisperModel,+ audioPath: wavPath,+ lang: lang,+ convert: false,+ withTimestamps: false,+ vadMode: WhisperVadMode.disabled,+ threads: _threads(),+ );+ text = (result?.transcription.text ?? '').trim();+ if (itemId != null) _cacheLanguage(itemId, result?.language, text.isNotEmpty);+ } catch (e) {+ if (e is TranscriptionException) rethrow;+ throw TranscriptionException(TranscriptionError.transcribeFailed, e);+ }+ debugPrint('[Transcribe] wav model=${info.fileName} lang=$lang '+ 'whisper=${watch.elapsedMilliseconds}ms chars=${text.length}');+ if (text.isEmpty) throw TranscriptionException(TranscriptionError.empty);+ return text;+ } finally {+ _busy = false;+ }+ }++ /// Like [transcribeWav] but keeps Whisper's segments and their timing, for+ /// callers that care where the pauses fall.+ Future<List<({double start, double end, String text})>> transcribeWavTimed(+ String wavPath, {+ String? itemId,+ TranscriptionFeature feature = TranscriptionFeature.readAlong,+ }) async {+ if (!await PlayerSettings.getTranscriptionEnabled()) {+ throw TranscriptionException(TranscriptionError.disabled);+ }+ if (_busy) throw TranscriptionException(TranscriptionError.busy);+ final info = await _modelFor(null, feature);+ if (!await isModelDownloaded(info.size)) {+ throw TranscriptionException(TranscriptionError.modelMissing);+ }+ lastModelUsed = info.size;+ _busy = true;+ try {+ final lang = itemId == null ? 'auto' : (_bookLang[itemId] ?? 'auto');+ final List<({double start, double end, String text})> segments;+ try {+ final result = await _whisper.transcribe(+ model: info.whisperModel,+ audioPath: wavPath,+ lang: lang,+ convert: false,+ withTimestamps: true,+ vadMode: WhisperVadMode.disabled,+ threads: _threads(),+ );+ segments = (result?.transcription.segments ?? const [])+ .map((s) => (+ start: s.fromTs.inMilliseconds / 1000.0,+ end: s.toTs.inMilliseconds / 1000.0,+ text: s.text.trim(),+ ))+ .where((s) => s.text.isNotEmpty)+ .toList();+ if (itemId != null) _cacheLanguage(itemId, result?.language, segments.isNotEmpty);+ } catch (e) {+ if (e is TranscriptionException) rethrow;+ throw TranscriptionException(TranscriptionError.transcribeFailed, e);+ }+ if (segments.isEmpty) throw TranscriptionException(TranscriptionError.empty);+ return segments;+ } finally {+ _busy = false;+ }+ }+// Internals// Capped at 4, not core count: whisper barriers its threads at every layer,