Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add M4B encode tab to edit server details sheet

Barnabas7ce0da95456f
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 72ab5ccc..3ca99cec 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -609,6 +609,23 @@
"clearLocalMetadata": "Clear Local Metadata",
"searchOnGoodreads": "Search on Goodreads",
"editServerDetails": "Edit Server Details",
+ "encodeTab": "Encode",
+ "codec": "Codec",
+ "bitrate": "Bitrate",
+ "channels": "Channels",
+ "mono": "Mono",
+ "stereo": "Stereo",
+ "startM4bEncode": "Start M4B Encode",
+ "encodeStarted": "M4B encode started",
+ "encodeFailed": "Failed to start encode",
+ "encodeFinished": "M4B encode finished",
+ "currentlyLabel": "Currently:",
+ "encodeOutputPathNote": "Finished M4B will be put into your audiobook folder at: {path}/",
+ "@encodeOutputPathNote": { "placeholders": { "path": { "type": "String" } } },
+ "encodeBackupNote": "A backup of your original audio files will be stored in: /metadata/cache/items/{itemId}/. Make sure to periodically purge items cache.",
+ "@encodeBackupNote": { "placeholders": { "itemId": { "type": "String" } } },
+ "encodeTimeNote": "Encoding can take up to 30 minutes.",
+ "encodeRescanNote": "If you have the watcher disabled you will need to re-scan this audiobook afterwards.",
"aboutSection": "About",
"chaptersCount": "Chapters ({count})",
"@chaptersCount": { "placeholders": { "count": { "type": "int" } } },
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 84c08bd5..899e43c5 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -3292,6 +3292,96 @@ abstract class AppLocalizations {
/// **'Edit Server Details'**
String get editServerDetails;
+ /// No description provided for @encodeTab.
+ ///
+ /// In en, this message translates to:
+ /// **'Encode'**
+ String get encodeTab;
+
+ /// No description provided for @codec.
+ ///
+ /// In en, this message translates to:
+ /// **'Codec'**
+ String get codec;
+
+ /// No description provided for @bitrate.
+ ///
+ /// In en, this message translates to:
+ /// **'Bitrate'**
+ String get bitrate;
+
+ /// No description provided for @channels.
+ ///
+ /// In en, this message translates to:
+ /// **'Channels'**
+ String get channels;
+
+ /// No description provided for @mono.
+ ///
+ /// In en, this message translates to:
+ /// **'Mono'**
+ String get mono;
+
+ /// No description provided for @stereo.
+ ///
+ /// In en, this message translates to:
+ /// **'Stereo'**
+ String get stereo;
+
+ /// No description provided for @startM4bEncode.
+ ///
+ /// In en, this message translates to:
+ /// **'Start M4B Encode'**
+ String get startM4bEncode;
+
+ /// No description provided for @encodeStarted.
+ ///
+ /// In en, this message translates to:
+ /// **'M4B encode started'**
+ String get encodeStarted;
+
+ /// No description provided for @encodeFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Failed to start encode'**
+ String get encodeFailed;
+
+ /// No description provided for @encodeFinished.
+ ///
+ /// In en, this message translates to:
+ /// **'M4B encode finished'**
+ String get encodeFinished;
+
+ /// No description provided for @currentlyLabel.
+ ///
+ /// In en, this message translates to:
+ /// **'Currently:'**
+ String get currentlyLabel;
+
+ /// No description provided for @encodeOutputPathNote.
+ ///
+ /// In en, this message translates to:
+ /// **'Finished M4B will be put into your audiobook folder at: {path}/'**
+ String encodeOutputPathNote(String path);
+
+ /// No description provided for @encodeBackupNote.
+ ///
+ /// In en, this message translates to:
+ /// **'A backup of your original audio files will be stored in: /metadata/cache/items/{itemId}/. Make sure to periodically purge items cache.'**
+ String encodeBackupNote(String itemId);
+
+ /// No description provided for @encodeTimeNote.
+ ///
+ /// In en, this message translates to:
+ /// **'Encoding can take up to 30 minutes.'**
+ String get encodeTimeNote;
+
+ /// No description provided for @encodeRescanNote.
+ ///
+ /// In en, this message translates to:
+ /// **'If you have the watcher disabled you will need to re-scan this audiobook afterwards.'**
+ String get encodeRescanNote;
+
/// No description provided for @aboutSection.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index f1683c68..8c0e2536 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -1799,6 +1799,56 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get editServerDetails => 'Server-Details bearbeiten';
+ @override
+ String get encodeTab => 'Encode';
+
+ @override
+ String get codec => 'Codec';
+
+ @override
+ String get bitrate => 'Bitrate';
+
+ @override
+ String get channels => 'Channels';
+
+ @override
+ String get mono => 'Mono';
+
+ @override
+ String get stereo => 'Stereo';
+
+ @override
+ String get startM4bEncode => 'Start M4B Encode';
+
+ @override
+ String get encodeStarted => 'M4B encode started';
+
+ @override
+ String get encodeFailed => 'Failed to start encode';
+
+ @override
+ String get encodeFinished => 'M4B encode finished';
+
+ @override
+ String get currentlyLabel => 'Currently:';
+
+ @override
+ String encodeOutputPathNote(String path) {
+ return 'Finished M4B will be put into your audiobook folder at: $path/';
+ }
+
+ @override
+ String encodeBackupNote(String itemId) {
+ return 'A backup of your original audio files will be stored in: /metadata/cache/items/$itemId/. Make sure to periodically purge items cache.';
+ }
+
+ @override
+ String get encodeTimeNote => 'Encoding can take up to 30 minutes.';
+
+ @override
+ String get encodeRescanNote =>
+ 'If you have the watcher disabled you will need to re-scan this audiobook afterwards.';
+
@override
String get aboutSection => 'Info';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index a2ba4463..01d05e7b 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -1780,6 +1780,56 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get editServerDetails => 'Edit Server Details';
+ @override
+ String get encodeTab => 'Encode';
+
+ @override
+ String get codec => 'Codec';
+
+ @override
+ String get bitrate => 'Bitrate';
+
+ @override
+ String get channels => 'Channels';
+
+ @override
+ String get mono => 'Mono';
+
+ @override
+ String get stereo => 'Stereo';
+
+ @override
+ String get startM4bEncode => 'Start M4B Encode';
+
+ @override
+ String get encodeStarted => 'M4B encode started';
+
+ @override
+ String get encodeFailed => 'Failed to start encode';
+
+ @override
+ String get encodeFinished => 'M4B encode finished';
+
+ @override
+ String get currentlyLabel => 'Currently:';
+
+ @override
+ String encodeOutputPathNote(String path) {
+ return 'Finished M4B will be put into your audiobook folder at: $path/';
+ }
+
+ @override
+ String encodeBackupNote(String itemId) {
+ return 'A backup of your original audio files will be stored in: /metadata/cache/items/$itemId/. Make sure to periodically purge items cache.';
+ }
+
+ @override
+ String get encodeTimeNote => 'Encoding can take up to 30 minutes.';
+
+ @override
+ String get encodeRescanNote =>
+ 'If you have the watcher disabled you will need to re-scan this audiobook afterwards.';
+
@override
String get aboutSection => 'About';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index b0d13ce9..90fba31e 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -1717,6 +1717,56 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get editServerDetails => '编辑服务器详情';
+ @override
+ String get encodeTab => 'Encode';
+
+ @override
+ String get codec => 'Codec';
+
+ @override
+ String get bitrate => 'Bitrate';
+
+ @override
+ String get channels => 'Channels';
+
+ @override
+ String get mono => 'Mono';
+
+ @override
+ String get stereo => 'Stereo';
+
+ @override
+ String get startM4bEncode => 'Start M4B Encode';
+
+ @override
+ String get encodeStarted => 'M4B encode started';
+
+ @override
+ String get encodeFailed => 'Failed to start encode';
+
+ @override
+ String get encodeFinished => 'M4B encode finished';
+
+ @override
+ String get currentlyLabel => 'Currently:';
+
+ @override
+ String encodeOutputPathNote(String path) {
+ return 'Finished M4B will be put into your audiobook folder at: $path/';
+ }
+
+ @override
+ String encodeBackupNote(String itemId) {
+ return 'A backup of your original audio files will be stored in: /metadata/cache/items/$itemId/. Make sure to periodically purge items cache.';
+ }
+
+ @override
+ String get encodeTimeNote => 'Encoding can take up to 30 minutes.';
+
+ @override
+ String get encodeRescanNote =>
+ 'If you have the watcher disabled you will need to re-scan this audiobook afterwards.';
+
@override
String get aboutSection => '关于';
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 27e2d012..59f6151a 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -912,6 +912,16 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
_goOffline();
}
+ void _onEncodeFinished(Map<String, dynamic> data) {
+ final messenger = scaffoldMessengerKey.currentState;
+ if (messenger == null) return;
+ final ctx = messenger.context;
+ final l = AppLocalizations.of(ctx);
+ messenger
+ ..clearSnackBars()
+ ..showSnackBar(SnackBar(content: Text(l?.encodeFinished ?? 'M4B encode finished')));
+ }
+
void _goOffline() {
if (_networkOffline) return;
debugPrint('[Library] Network error — going offline');
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 0d54519f..8d883b02 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -166,6 +166,7 @@ class LibraryProvider extends ChangeNotifier
socket.onCollectionUpdated = _onRemoteCollectionUpdated;
socket.onUserUpdated = _onRemoteUserUpdated;
socket.onReconnectFailed = _onSocketReconnectFailed;
+ socket.onEncodeFinished = _onEncodeFinished;
socket.connect(auth.serverUrl!, auth.token!, customHeaders: auth.customHeaders);
}
debugPrint('[Library] Calling loadLibraries()');
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 84e146da..a6b26a8c 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -2047,6 +2047,29 @@ class ApiService {
return null;
}
+ /// Start an M4B encode task on the server.
+ /// POST /api/tools/item/:id/encode-m4b?codec=&bitrate=&channels=
+ Future<bool> startM4bEncode(
+ String itemId, {
+ required String codec,
+ required String bitrate,
+ required int channels,
+ }) async {
+ try {
+ final uri = Uri.parse('$_cleanBaseUrl/api/tools/item/$itemId/encode-m4b')
+ .replace(queryParameters: {
+ 'codec': codec,
+ 'bitrate': bitrate,
+ 'channels': '$channels',
+ });
+ final r = await _authPost(uri);
+ return r.statusCode == 200;
+ } catch (e) {
+ debugPrint('startM4bEncode error: $e');
+ }
+ return false;
+ }
+
/// Update podcast media settings (auto-download, etc.)
/// PATCH /api/items/:id/media body: mediaUpdates at the media level
Future<bool> updatePodcastMedia(String itemId, Map<String, dynamic> mediaUpdates) async {
diff --git a/lib/services/socket_service.dart b/lib/services/socket_service.dart
index aa9945c8..d0266a73 100644
--- a/lib/services/socket_service.dart
+++ b/lib/services/socket_service.dart
@@ -52,6 +52,10 @@ class SocketService {
/// Called when socket.io exhausts all reconnection attempts.
VoidCallback? onReconnectFailed;
+ /// Called when an M4B encode task finishes on the server.
+ /// Payload: serialized Task object including action and data.libraryItemId.
+ void Function(Map<String, dynamic> data)? onEncodeFinished;
+
/// Update the stored token (e.g. after a JWT refresh) and re-auth if connected.
void updateToken(String newToken) {
_token = newToken;
@@ -145,6 +149,14 @@ class SocketService {
if (data is Map<String, dynamic>) onUserUpdated?.call(data);
});
+ // M4B encode task finished (fires once for the whole task, not per track)
+ _socket!.on('task_finished', (data) {
+ if (data is Map<String, dynamic> && data['action'] == 'encode-m4b') {
+ debugPrint('[Socket] Encode finished');
+ onEncodeFinished?.call(data);
+ }
+ });
+
_socket!.onDisconnect((reason) {
final duration = _connectedAt != null
? DateTime.now().difference(_connectedAt!).inSeconds
@@ -184,6 +196,7 @@ class SocketService {
onCollectionUpdated = null;
onUserUpdated = null;
onReconnectFailed = null;
+ onEncodeFinished = null;
}
/// Disconnect the socket but keep callbacks and credentials so we can
@@ -263,6 +276,12 @@ class SocketService {
if (data is Map<String, dynamic>) onUserUpdated?.call(data);
});
+ _socket!.on('task_finished', (data) {
+ if (data is Map<String, dynamic> && data['action'] == 'encode-m4b') {
+ onEncodeFinished?.call(data);
+ }
+ });
+
_socket!.onDisconnect((reason) {
final duration = _connectedAt != null
? DateTime.now().difference(_connectedAt!).inSeconds
diff --git a/lib/widgets/edit_metadata_sheet.dart b/lib/widgets/edit_metadata_sheet.dart
index 7528fb64..40ed26e0 100644
--- a/lib/widgets/edit_metadata_sheet.dart
+++ b/lib/widgets/edit_metadata_sheet.dart
@@ -13,6 +13,8 @@ void showEditMetadataSheet(
required String itemId,
required Map<String, dynamic> metadata,
List<String> tags = const [],
+ List<dynamic> audioFiles = const [],
+ String relPath = '',
}) {
showModalBottomSheet(
context: context,
@@ -29,6 +31,8 @@ void showEditMetadataSheet(
itemId: itemId,
metadata: metadata,
tags: tags,
+ audioFiles: audioFiles,
+ relPath: relPath,
scrollController: sc,
),
),
@@ -39,12 +43,16 @@ class _EditMetadataContent extends StatefulWidget {
final String itemId;
final Map<String, dynamic> metadata;
final List<String> tags;
+ final List<dynamic> audioFiles;
+ final String relPath;
final ScrollController scrollController;
const _EditMetadataContent({
required this.itemId,
required this.metadata,
this.tags = const [],
+ this.audioFiles = const [],
+ this.relPath = '',
required this.scrollController,
});
@@ -93,10 +101,16 @@ class _EditMetadataContentState extends State<_EditMetadataContent>
String? _coverFilePath;
bool _saving = false;
+ // Encode tab
+ String _encodeCodec = 'aac';
+ String _encodeBitrate = '128k';
+ int _encodeChannels = 2;
+ bool _encoding = false;
+
@override
void initState() {
super.initState();
- _tabCtrl = TabController(length: 2, vsync: this);
+ _tabCtrl = TabController(length: 3, vsync: this);
final m = widget.metadata;
_titleCtrl = TextEditingController(text: m['title'] as String? ?? '');
_subtitleCtrl = TextEditingController(text: m['subtitle'] as String? ?? '');
@@ -400,6 +414,193 @@ class _EditMetadataContentState extends State<_EditMetadataContent>
return value.toString();
}
+ // ─── Encode Tab ─────────────────────────────────────────────
+
+ Map<String, dynamic>? get _firstAudioFile {
+ if (widget.audioFiles.isEmpty) return null;
+ final f = widget.audioFiles.first;
+ return f is Map<String, dynamic> ? f : null;
+ }
+
+ String? get _currentCodec {
+ final c = _firstAudioFile?['codec'] as String?;
+ if (c == null || c.isEmpty) return null;
+ return c.toUpperCase();
+ }
+
+ int? get _currentBitrateKbps {
+ final b = (_firstAudioFile?['bitRate'] as num?)?.toInt();
+ if (b == null || b <= 0) return null;
+ return (b / 1000).round();
+ }
+
+ String? _currentChannelText(AppLocalizations l) {
+ final ch = (_firstAudioFile?['channels'] as num?)?.toInt();
+ if (ch == null) return null;
+ final layout = (_firstAudioFile?['channelLayout'] as String?)?.trim();
+ final name = layout != null && layout.isNotEmpty
+ ? layout
+ : (ch == 1 ? l.mono : l.stereo);
+ return '$ch ($name)';
+ }
+
+ Widget _buildEncodeTab(ColorScheme cs, TextTheme tt, AppLocalizations l) {
+ final codecText = _currentCodec;
+ final bitrateText = _currentBitrateKbps;
+ final channelText = _currentChannelText(l);
+
+ return SingleChildScrollView(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(20, 20, 20, 24 + MediaQuery.of(context).viewPadding.bottom),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ _encodeLabel(l.codec, tt, cs),
+ _encodeToggleRow<String>(
+ values: const ['copy', 'aac', 'opus'],
+ labels: const ['Copy', 'AAC', 'OPUS'],
+ selected: _encodeCodec,
+ onTap: (v) => setState(() => _encodeCodec = v),
+ cs: cs, tt: tt,
+ ),
+ if (codecText != null) _currentLine(codecText, cs, tt, l),
+ const SizedBox(height: 20),
+ _encodeLabel(l.bitrate, tt, cs),
+ _encodeToggleRow<String>(
+ values: const ['32k', '64k', '128k', '192k'],
+ labels: const ['32k', '64k', '128k', '192k'],
+ selected: _encodeBitrate,
+ onTap: (v) => setState(() => _encodeBitrate = v),
+ cs: cs, tt: tt,
+ ),
+ if (bitrateText != null) _currentLine(l.kbpsValue(bitrateText), cs, tt, l),
+ const SizedBox(height: 20),
+ _encodeLabel(l.channels, tt, cs),
+ _encodeToggleRow<int>(
+ values: const [1, 2],
+ labels: [l.mono, l.stereo],
+ selected: _encodeChannels,
+ onTap: (v) => setState(() => _encodeChannels = v),
+ cs: cs, tt: tt,
+ ),
+ if (channelText != null) _currentLine(channelText, cs, tt, l),
+ const SizedBox(height: 24),
+ if (widget.relPath.isNotEmpty)
+ _encodeNote(l.encodeOutputPathNote('.../${widget.relPath}'), cs, tt),
+ _encodeNote(l.encodeBackupNote(widget.itemId), cs, tt),
+ _encodeNote(l.encodeTimeNote, cs, tt),
+ _encodeNote(l.encodeRescanNote, cs, tt),
+ const SizedBox(height: 20),
+ SizedBox(
+ width: double.infinity,
+ height: 44,
+ child: FilledButton.icon(
+ onPressed: _encoding ? null : _startEncode,
+ icon: _encoding
+ ? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.onPrimary))
+ : const Icon(Icons.transform_rounded, size: 18),
+ label: Text(l.startM4bEncode),
+ style: FilledButton.styleFrom(
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ),
+ ),
+ ),
+ ]),
+ );
+ }
+
+ Widget _encodeNote(String text, ColorScheme cs, TextTheme tt) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 10),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: Icon(Icons.star_rounded, size: 14, color: cs.tertiary),
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ text,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, height: 1.35),
+ ),
+ ),
+ ]),
+ );
+ }
+
+ Widget _encodeLabel(String text, TextTheme tt, ColorScheme cs) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 10),
+ child: Text(text, style: tt.labelLarge?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
+ );
+ }
+
+ Widget _currentLine(String value, ColorScheme cs, TextTheme tt, AppLocalizations l) {
+ return Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Text.rich(
+ TextSpan(
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.7)),
+ children: [
+ TextSpan(text: '${l.currentlyLabel} '),
+ TextSpan(text: value, style: TextStyle(color: cs.onSurface, fontWeight: FontWeight.w600)),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _encodeToggleRow<T>({
+ required List<T> values,
+ required List<String> labels,
+ required T selected,
+ required void Function(T) onTap,
+ required ColorScheme cs,
+ required TextTheme tt,
+ }) {
+ return Wrap(spacing: 8, runSpacing: 8, children: List.generate(values.length, (i) {
+ final isSel = values[i] == selected;
+ return InkWell(
+ onTap: () => onTap(values[i]),
+ borderRadius: BorderRadius.circular(10),
+ child: Container(
+ height: 36,
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: isSel ? cs.primaryContainer : cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(10),
+ border: Border.all(color: isSel ? cs.primary : cs.onSurface.withValues(alpha: 0.1)),
+ ),
+ child: Text(
+ labels[i],
+ style: tt.bodyMedium?.copyWith(
+ color: isSel ? cs.onPrimaryContainer : cs.onSurfaceVariant,
+ fontWeight: isSel ? FontWeight.w600 : FontWeight.w500,
+ ),
+ ),
+ ),
+ );
+ }));
+ }
+
+ Future<void> _startEncode() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ setState(() => _encoding = true);
+ final ok = await api.startM4bEncode(
+ widget.itemId,
+ codec: _encodeCodec,
+ bitrate: _encodeBitrate,
+ channels: _encodeChannels,
+ );
+ if (!mounted) return;
+ setState(() => _encoding = false);
+ final l = AppLocalizations.of(context)!;
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text(ok ? l.encodeStarted : l.encodeFailed)),
+ );
+ if (ok) Navigator.pop(context);
+ }
+
// ─── Build ──────────────────────────────────────────────────
@override
@@ -437,6 +638,7 @@ class _EditMetadataContentState extends State<_EditMetadataContent>
tabs: [
Tab(text: l.quickMatch),
Tab(text: l.custom),
+ Tab(text: l.encodeTab),
],
),
@@ -447,6 +649,7 @@ class _EditMetadataContentState extends State<_EditMetadataContent>
children: [
_buildQuickMatchTab(cs, tt, l),
_buildCustomTab(cs, tt, l),
+ _buildEncodeTab(cs, tt, l),
],
),
),