audiobook-forge 2.10.0

CLI tool for converting audiobook directories to M4B format with chapters and metadata
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Single book processor

use crate::audio::{
    generate_chapters_from_files, inject_chapters_mp4box, inject_metadata_atomicparsley,
    parse_cue_file, write_mp4box_chapters, AacEncoder, FFmpeg,
};
use crate::models::{BookFolder, ProcessingResult};
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::Semaphore;

/// Processor for converting a single audiobook
pub struct Processor {
    ffmpeg: FFmpeg,
    keep_temp: bool,
    encoder: AacEncoder,
    enable_parallel_encoding: bool,
    max_concurrent_files: usize,
    quality_preset: Option<String>,
}

impl Processor {
    /// Create a new processor
    pub fn new() -> Result<Self> {
        Ok(Self {
            ffmpeg: FFmpeg::new()?,
            keep_temp: false,
            encoder: crate::audio::get_encoder(),
            enable_parallel_encoding: true,
            max_concurrent_files: 8,
            quality_preset: None,
        })
    }

    /// Create processor with options
    pub fn with_options(
        keep_temp: bool,
        encoder: AacEncoder,
        enable_parallel_encoding: bool,
        max_concurrent_files: usize,
        quality_preset: Option<String>,
    ) -> Result<Self> {
        Ok(Self {
            ffmpeg: FFmpeg::new()?,
            keep_temp,
            encoder,
            enable_parallel_encoding,
            max_concurrent_files: max_concurrent_files.clamp(1, 32),
            quality_preset,
        })
    }

    /// Process a single book folder
    pub async fn process_book(
        &self,
        book_folder: &BookFolder,
        output_dir: &Path,
        chapter_source: &str,
    ) -> Result<ProcessingResult> {
        let start_time = Instant::now();
        let result = ProcessingResult::new(book_folder.name.clone());

        tracing::info!("=== Starting book processing: {} ===", book_folder.name);

        // Create output directory if it doesn't exist
        if !output_dir.exists() {
            std::fs::create_dir_all(output_dir)
                .context("Failed to create output directory")?;
        }

        // Determine output file path
        let output_filename = book_folder.get_output_filename();
        let output_path = output_dir.join(&output_filename);

        // Create temp directory
        let temp_dir = self.create_temp_dir(&book_folder.name)?;

        // Check if we can use copy mode
        let use_copy = book_folder.can_use_concat_copy();

        tracing::info!(
            "Processing {} - {} tracks, copy_mode={}",
            book_folder.name,
            book_folder.tracks.len(),
            use_copy
        );

        // Get quality profile (auto-detected from source)
        let mut quality = book_folder
            .get_best_quality_profile(true)
            .context("No tracks found")?
            .clone();

        // Apply quality preset override if specified
        if let Some(ref preset) = self.quality_preset {
            quality = quality.apply_preset(Some(preset.as_str()));
            tracing::info!("Applying quality preset '{}': {}", preset, quality);
        }

        if book_folder.tracks.len() == 1 {
            // Single file - just convert
            self.ffmpeg
                .convert_single_file(
                    &book_folder.tracks[0].file_path,
                    &output_path,
                    &quality,
                    use_copy,
                    self.encoder,
                )
                .await
                .context("Failed to convert audio file")?;
        } else if use_copy {
            // Copy mode - can concatenate directly
            let concat_file = temp_dir.join("concat.txt");
            let file_refs: Vec<&Path> = book_folder
                .tracks
                .iter()
                .map(|t| t.file_path.as_path())
                .collect();
            FFmpeg::create_concat_file(&file_refs, &concat_file)?;

            self.ffmpeg
                .concat_audio_files(
                    &concat_file,
                    &output_path,
                    &quality,
                    use_copy,
                    self.encoder,
                )
                .await
                .context("Failed to concatenate audio files")?;
        } else if self.enable_parallel_encoding && book_folder.tracks.len() > 1 {
            // Transcode mode - encode files in parallel with throttling
            let effective_limit = self.max_concurrent_files.min(book_folder.tracks.len());

            tracing::info!(
                "Using parallel encoding: {} files with max {} concurrent",
                book_folder.tracks.len(),
                effective_limit
            );

            // Create semaphore to limit concurrent file encodings
            let semaphore = Arc::new(Semaphore::new(effective_limit));

            // Step 1: Encode all files to AAC/M4A in parallel (with throttling)
            let mut encoded_files = Vec::new();
            let mut tasks = Vec::new();

            for (i, track) in book_folder.tracks.iter().enumerate() {
                let temp_output = temp_dir.join(format!("encoded_{:04}.m4a", i));
                encoded_files.push(temp_output.clone());

                tracing::info!(
                    "[{}/{}] Encoding: {} ({:.1} min)",
                    i + 1,
                    book_folder.tracks.len(),
                    track.file_path.file_name().unwrap().to_string_lossy(),
                    track.quality.duration / 60.0
                );

                let ffmpeg = self.ffmpeg.clone();
                let input = track.file_path.clone();
                let output = temp_output;
                let quality = quality.clone();
                let encoder = self.encoder;
                let sem = Arc::clone(&semaphore);

                // Spawn parallel encoding task with semaphore
                let task = tokio::spawn(async move {
                    // Acquire permit before encoding (blocks if limit reached)
                    let _permit = sem.acquire().await.unwrap();

                    ffmpeg
                        .convert_single_file(&input, &output, &quality, false, encoder)
                        .await
                    // Permit automatically released when _permit drops
                });

                tasks.push(task);
            }

            // Wait for all encoding tasks to complete
            for (i, task) in tasks.into_iter().enumerate() {
                match task.await {
                    Ok(Ok(())) => continue,
                    Ok(Err(e)) => {
                        return Err(e).context(format!("Track {} encoding failed", i));
                    }
                    Err(e) => {
                        return Err(anyhow::anyhow!("Task {} panicked: {}", i, e));
                    }
                }
            }

            tracing::info!("All {} files encoded, now concatenating...", encoded_files.len());

            // Step 2: Concatenate the encoded files (fast, no re-encoding)
            let concat_file = temp_dir.join("concat.txt");
            let file_refs: Vec<&Path> = encoded_files.iter().map(|p| p.as_path()).collect();
            FFmpeg::create_concat_file(&file_refs, &concat_file)?;

            self.ffmpeg
                .concat_audio_files(
                    &concat_file,
                    &output_path,
                    &quality,
                    true, // use copy mode for concatenation
                    self.encoder,
                )
                .await
                .context("Failed to concatenate encoded files")?;
        } else {
            // Serial mode - concatenate and encode in one FFmpeg call (traditional method)
            tracing::info!("Using serial encoding (parallel encoding disabled in config)");

            let concat_file = temp_dir.join("concat.txt");
            let file_refs: Vec<&Path> = book_folder
                .tracks
                .iter()
                .map(|t| t.file_path.as_path())
                .collect();
            FFmpeg::create_concat_file(&file_refs, &concat_file)?;

            self.ffmpeg
                .concat_audio_files(
                    &concat_file,
                    &output_path,
                    &quality,
                    false, // transcode mode
                    self.encoder,
                )
                .await
                .context("Failed to concatenate audio files")?;
        }

        tracing::info!("Audio processing complete: {}", output_path.display());

        // Step 3: Generate and inject chapters
        let chapters = self.generate_chapters(book_folder, chapter_source)?;

        if !chapters.is_empty() {
            tracing::info!("Injecting {} chapters using MP4Box", chapters.len());

            let chapters_file = temp_dir.join("chapters.txt");
            write_mp4box_chapters(&chapters, &chapters_file)
                .context("Failed to write chapter file")?;

            inject_chapters_mp4box(&output_path, &chapters_file)
                .await
                .context("Failed to inject chapters")?;

            tracing::info!("✓ Chapter injection complete");
        }

        // Step 4: Inject metadata
        let title = book_folder.get_album_title();
        let artist = book_folder.get_album_artist();
        let year = book_folder.get_year();
        let genre = book_folder.get_genre();
        let comment = book_folder.get_comment();
        let composer = book_folder.get_composer();

        tracing::info!("Injecting metadata using AtomicParsley");
        tracing::debug!(
            "Metadata: title={:?}, artist={:?}",
            title,
            artist
        );

        inject_metadata_atomicparsley(
            &output_path,
            title.as_deref(),
            artist.as_deref(),
            title.as_deref(), // Use title as album
            artist.as_deref(), // Album artist
            year,
            genre.as_deref(),
            composer.as_deref(),
            comment.as_deref(),
            book_folder.cover_file.as_deref(),
        )
        .await
        .context("Failed to inject metadata")?;

        tracing::info!("✓ Metadata injection complete");

        // Clean up extracted cover file if it was auto-extracted
        if let Some(cover_path) = &book_folder.cover_file {
            if cover_path.file_name().and_then(|n| n.to_str()) == Some(".extracted_cover.jpg") {
                if let Err(e) = std::fs::remove_file(cover_path) {
                    tracing::debug!("Failed to remove extracted cover file: {}", e);
                } else {
                    tracing::debug!("Cleaned up extracted cover file");
                }
            }
        }

        // Clean up temp directory
        if !self.keep_temp {
            if let Err(e) = std::fs::remove_dir_all(&temp_dir) {
                tracing::warn!("Failed to remove temp directory: {}", e);
            }
        }

        // Calculate processing time
        let processing_time = start_time.elapsed().as_secs_f64();

        tracing::info!(
            "=== Completed: {} in {:.1}s ===",
            book_folder.name,
            processing_time
        );

        // Return success result
        Ok(result.success(output_path, processing_time, use_copy))
    }

    /// Generate chapters for the book
    fn generate_chapters(
        &self,
        book_folder: &BookFolder,
        chapter_source: &str,
    ) -> Result<Vec<crate::audio::Chapter>> {
        match chapter_source {
            "cue" => {
                // Use CUE file if available
                if let Some(ref cue_file) = book_folder.cue_file {
                    tracing::info!("Using CUE file for chapters: {}", cue_file.display());
                    return parse_cue_file(cue_file);
                }
                Ok(Vec::new())
            }
            "files" | "auto" => {
                // Generate chapters from files
                if book_folder.tracks.len() > 1 {
                    let files: Vec<&Path> = book_folder
                        .tracks
                        .iter()
                        .map(|t| t.file_path.as_path())
                        .collect();
                    let durations: Vec<f64> = book_folder
                        .tracks
                        .iter()
                        .map(|t| t.quality.duration)
                        .collect();

                    tracing::info!(
                        "Generating {} chapters from files",
                        book_folder.tracks.len()
                    );
                    Ok(generate_chapters_from_files(&files, &durations))
                } else {
                    // Single file - check for CUE
                    if let Some(ref cue_file) = book_folder.cue_file {
                        tracing::info!("Using CUE file for single-file book");
                        parse_cue_file(cue_file)
                    } else {
                        Ok(Vec::new())
                    }
                }
            }
            "none" => Ok(Vec::new()),
            _ => {
                tracing::warn!("Unknown chapter source: {}, using auto", chapter_source);
                self.generate_chapters(book_folder, "auto")
            }
        }
    }

    /// Create temporary directory for processing
    fn create_temp_dir(&self, book_name: &str) -> Result<PathBuf> {
        let temp_base = std::env::temp_dir();
        let sanitized_name = sanitize_filename::sanitize(book_name);
        let temp_dir = temp_base.join(format!("audiobook-forge-{}", sanitized_name));

        if temp_dir.exists() {
            std::fs::remove_dir_all(&temp_dir).ok();
        }

        std::fs::create_dir_all(&temp_dir).context("Failed to create temp directory")?;

        Ok(temp_dir)
    }
}

impl Default for Processor {
    fn default() -> Self {
        Self::new().expect("Failed to create processor")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_processor_creation() {
        let processor = Processor::new();
        assert!(processor.is_ok());
    }

    #[test]
    fn test_processor_with_options() {
        let processor = Processor::with_options(true, AacEncoder::AppleSilicon, true, 8, None).unwrap();
        assert!(processor.keep_temp);
        assert_eq!(processor.encoder, AacEncoder::AppleSilicon);
        assert_eq!(processor.max_concurrent_files, 8);
        assert_eq!(processor.quality_preset, None);

        let processor_with_preset = Processor::with_options(false, AacEncoder::Native, true, 4, Some("high".to_string())).unwrap();
        assert_eq!(processor_with_preset.quality_preset, Some("high".to_string()));
    }

    #[test]
    fn test_create_temp_dir() {
        let processor = Processor::new().unwrap();
        let temp_dir = processor.create_temp_dir("Test Book").unwrap();

        assert!(temp_dir.exists());
        assert!(temp_dir.to_string_lossy().contains("audiobook-forge"));

        // Clean up
        std::fs::remove_dir_all(temp_dir).ok();
    }
}