Skip to main content

mp3rgain/
lib.rs

1//! # mp3rgain
2//!
3//! Lossless MP3 volume adjustment library - a modern mp3gain replacement.
4//!
5//! This library provides lossless MP3 volume adjustment by modifying
6//! the `global_gain` field in each frame's side information.
7//!
8//! ## Features
9//!
10//! - **Lossless**: No re-encoding, preserves audio quality
11//! - **Fast**: Direct binary manipulation, no audio decoding
12//! - **Compatible**: Works with all MP3 files (MPEG1/2/2.5 Layer III)
13//! - **Reversible**: Changes can be undone by applying negative gain
14//!
15//! ## Optional Features
16//!
17//! - **replaygain**: Enable ReplayGain analysis (requires symphonia)
18//!   - Track gain calculation (`-r` flag)
19//!   - Album gain calculation (`-a` flag)
20//!
21//! ## Example
22//!
23//! ```no_run
24//! use mp3rgain::{apply_gain, apply_gain_db, analyze, GainOptions, Channel};
25//! use std::path::Path;
26//!
27//! // Simple gain adjustment: +2 steps (+3.0 dB)
28//! let frames = apply_gain(Path::new("song.mp3"), 2).unwrap();
29//! println!("Modified {} frames", frames);
30//!
31//! // Or specify gain in dB directly
32//! let frames = apply_gain_db(Path::new("song.mp3"), 4.5).unwrap();
33//!
34//! // Builder pattern for advanced options
35//! GainOptions::new(5)
36//!     .wrap(true)
37//!     .undo(true)
38//!     .apply(Path::new("song.mp3")).unwrap();
39//!
40//! // Channel-specific gain with undo support
41//! GainOptions::new(3)
42//!     .channel(Channel::Left)
43//!     .undo(true)
44//!     .apply(Path::new("song.mp3")).unwrap();
45//! ```
46//!
47//! ## Modules
48//!
49//! - [`analysis`] - MP3 file analysis and amplitude detection
50//! - [`gain`] - Gain adjustment operations and the [`GainOptions`] builder
51//! - [`ape`] - APEv2 tag reading, writing, and management
52//! - [`replaygain`] - ReplayGain loudness analysis
53//! - [`mp4meta`] - MP4/M4A metadata handling
54//! - [`aac`] - AAC bitstream parsing (feature-gated)
55//!
56//! ## Technical Details
57//!
58//! Each gain step equals 1.5 dB (fixed by MP3 specification).
59//! The global_gain field is 8 bits, allowing values 0-255.
60
61#[cfg(feature = "aac")]
62pub mod aac;
63#[cfg(feature = "aac")]
64mod aac_codebooks;
65
66pub mod analysis;
67pub mod ape;
68pub mod apply;
69pub mod error;
70mod frame;
71pub mod gain;
72pub mod id3v2;
73pub mod mp4meta;
74pub mod replaygain;
75
76pub use analysis::{
77    analyze, analyze_data, find_max_amplitude, is_mono, ChannelMode, MaxAmplitudeResult,
78    Mp3Analysis, MpegVersion,
79};
80pub use ape::{
81    delete_ape_tag, read_ape_tag, read_ape_tag_from_file, write_ape_album_minmax, write_ape_tag,
82    ApeItem, ApeTag, TAG_MP3GAIN_ALBUM_MINMAX, TAG_MP3GAIN_MINMAX, TAG_MP3GAIN_UNDO,
83    TAG_REPLAYGAIN_ALBUM_GAIN, TAG_REPLAYGAIN_ALBUM_PEAK, TAG_REPLAYGAIN_TRACK_GAIN,
84    TAG_REPLAYGAIN_TRACK_PEAK,
85};
86pub use apply::{
87    apply_with_options, predict_apply, write_album_minmax, AacAlbumInfo, ApplyOptions, ApplyReport,
88    ClippingDetection,
89};
90pub use error::{Error, Result};
91pub use gain::{
92    apply_gain, apply_gain_db, apply_gain_to_peak, db_to_linear, db_to_steps, peak_to_headroom_db,
93    peak_to_pcm_sample, steps_to_db, undo_gain, would_clip, Channel, GainOptions, GAIN_STEP_DB,
94    MAX_GAIN, MIN_GAIN,
95};
96pub use id3v2::{
97    delete_id3v2_replaygain, read_id3v2_replaygain, undo_gain_id3v2, write_id3v2_replaygain,
98    write_id3v2_undo, Id3v2ReplayGain,
99};
100
101use std::path::{Path, PathBuf};
102
103/// File extensions mp3rgain can process.
104pub const SUPPORTED_EXTENSIONS: &[&str] = &["mp3", "m4a", "aac", "mp4"];
105
106/// Returns true if `path` is a regular audio file mp3rgain can process.
107/// Filters out macOS resource fork files (`._*`) and unsupported extensions.
108pub fn is_supported_audio_path(path: &Path) -> bool {
109    if path
110        .file_name()
111        .and_then(|n| n.to_str())
112        .is_some_and(|n| n.starts_with("._"))
113    {
114        return false;
115    }
116    path.extension()
117        .and_then(|e| e.to_str())
118        .is_some_and(|ext| {
119            SUPPORTED_EXTENSIONS
120                .iter()
121                .any(|s| ext.eq_ignore_ascii_case(s))
122        })
123}
124
125/// Collect supported audio file paths from a directory.
126///
127/// When `recursive` is true, descends into subdirectories. Files are filtered
128/// by [`is_supported_audio_path`]. The returned paths are not sorted.
129pub fn collect_audio_files(dir: &Path, recursive: bool) -> Result<Vec<PathBuf>> {
130    let mut result = Vec::new();
131    collect_audio_files_into(dir, recursive, &mut result)?;
132    Ok(result)
133}
134
135/// Apply gain in dB, auto-dispatching by file format.
136///
137/// Detects MP4/AAC files via [`mp4meta::is_aac_file`] and routes them through
138/// the AAC pipeline (which rewrites only the AAC `global_gain` bitfields inside
139/// `mdat`). All other files fall back to the MP3 pipeline.
140///
141/// Calling [`gain::apply_gain_db`] directly on an M4A file would scan the raw
142/// bytes for MP3 sync words and overwrite the byte following any match,
143/// corrupting the MP4 container — see issue #149.
144pub fn apply_gain_db_auto(file_path: &Path, gain_db: f64) -> Result<usize> {
145    #[cfg(feature = "aac")]
146    {
147        if mp4meta::is_aac_file(file_path) {
148            return aac::apply_aac_gain_to_path(file_path, file_path, gain::db_to_steps(gain_db));
149        }
150    }
151    gain::apply_gain_db(file_path, gain_db)
152}
153
154/// Undo previously-applied gain, auto-dispatching by file format and tag mode.
155///
156/// AAC files go through the AAC undo path. For MP3, `use_id3v2 = true` routes
157/// to ID3v2; otherwise the default APE undo is used.
158pub fn undo_gain_auto(file_path: &Path, use_id3v2: bool) -> Result<usize> {
159    #[cfg(feature = "aac")]
160    {
161        if mp4meta::is_aac_file(file_path) {
162            return aac::undo_aac_gain(file_path);
163        }
164    }
165    if use_id3v2 {
166        id3v2::undo_gain_id3v2(file_path)
167    } else {
168        gain::undo_gain(file_path)
169    }
170}
171
172/// Delete ReplayGain / undo tags, auto-dispatching by file format and tag mode.
173///
174/// For AAC, deletes both the ReplayGain and undo freeform tags. For MP3,
175/// `use_id3v2 = true` removes the ID3v2 frames; otherwise the APE tag is
176/// removed.
177pub fn delete_gain_tags_auto(file_path: &Path, use_id3v2: bool) -> Result<()> {
178    #[cfg(feature = "aac")]
179    {
180        if mp4meta::is_aac_file(file_path) {
181            mp4meta::delete_replaygain_tags(file_path)?;
182            return mp4meta::delete_undo_tags(file_path);
183        }
184    }
185    if use_id3v2 {
186        id3v2::delete_id3v2_replaygain(file_path)
187    } else {
188        ape::delete_ape_tag(file_path)
189    }
190}
191
192/// Read the left-channel undo step count without modifying the file.
193///
194/// Mirrors [`undo_gain_auto`]'s dispatch so the returned value matches what
195/// `undo_gain_auto` would roll back. Returns `None` if the tag is absent or
196/// unreadable.
197pub fn read_undo_steps(file_path: &Path, use_id3v2: bool) -> Option<i32> {
198    #[cfg(feature = "aac")]
199    {
200        if mp4meta::is_aac_file(file_path) {
201            let undo_tags = mp4meta::read_undo_tags(file_path).ok()?;
202            return Some(ape::parse_undo_values(undo_tags.undo()).0);
203        }
204    }
205    if use_id3v2 {
206        let rg = id3v2::read_id3v2_replaygain(file_path).ok()?;
207        return Some(ape::parse_undo_values(rg.undo.as_deref()).0);
208    }
209    let tag = ape::read_ape_tag_from_file(file_path).ok()??;
210    tag.get_undo_gain()
211}
212
213fn collect_audio_files_into(dir: &Path, recursive: bool, result: &mut Vec<PathBuf>) -> Result<()> {
214    let entries = std::fs::read_dir(dir).map_err(|e| Error::io_read(dir, e))?;
215    for entry in entries {
216        let entry = entry.map_err(|e| Error::io_read(dir, e))?;
217        let file_type = entry.file_type().map_err(|e| Error::io_read(dir, e))?;
218        let path = entry.path();
219        if file_type.is_dir() {
220            if recursive {
221                collect_audio_files_into(&path, recursive, result)?;
222            }
223        } else if is_supported_audio_path(&path) {
224            result.push(path);
225        }
226    }
227    Ok(())
228}
229
230#[cfg(all(test, feature = "aac"))]
231mod auto_dispatch_tests {
232    use super::*;
233    use std::io::Write;
234
235    /// Regression for issue #149: applying gain to an MP4 file via the
236    /// auto-dispatcher must NOT run the MP3 sync-word scanner, which would
237    /// overwrite bytes inside MP4 atoms whenever they happen to look like a
238    /// valid MPEG L3 frame header and corrupt the container.
239    ///
240    /// The crafted MP4 below embeds a 72-byte MPEG2.5 L3 8kbps frame header
241    /// immediately after the ftyp box. The buggy MP3 path would treat byte 27
242    /// (the `global_gain` location inside the side info) as a writable gain
243    /// slot and rewrite it. The dispatch must hand the file to the AAC path
244    /// (which rejects it cleanly because there's no `mdat`) and leave the
245    /// bytes untouched.
246    #[test]
247    fn auto_dispatch_does_not_corrupt_mp4_when_payload_mimics_mp3_frame() {
248        let dir = std::env::temp_dir().join("mp3rgain_issue_149");
249        let _ = std::fs::create_dir_all(&dir);
250        let path = dir.join("fake.m4a");
251
252        // ftyp box (20 bytes) + two back-to-back MPEG2.5 L3 8kbps/11025Hz stereo
253        // "frames" (52 bytes each). The MP3 scanner validates a frame by looking
254        // for another sync word at next_pos or by next_pos == audio_end — so two
255        // chained frames make the first one parse as valid.
256        let mut bytes = vec![
257            0x00, 0x00, 0x00, 0x14, b'f', b't', b'y', b'p', b'M', b'4', b'A', b' ', 0x00, 0x00,
258            0x00, 0x00, b'M', b'4', b'A', b' ', // ftyp box (20 bytes, accepted brand)
259        ];
260        let frame_header = [0xFFu8, 0xE3, 0x10, 0x00];
261        bytes.extend_from_slice(&frame_header);
262        bytes.resize(20 + 52, 0x55); // pad first frame to 52 bytes
263        bytes.extend_from_slice(&frame_header);
264        bytes.resize(20 + 52 + 52, 0x55); // pad second frame to 52 bytes
265        let original = bytes.clone();
266
267        std::fs::File::create(&path)
268            .unwrap()
269            .write_all(&bytes)
270            .unwrap();
271
272        let _ = apply_gain_db_auto(&path, 3.0);
273
274        let after = std::fs::read(&path).unwrap();
275        assert_eq!(
276            after, original,
277            "MP4 bytes must be untouched by auto dispatch"
278        );
279
280        let _ = std::fs::remove_dir_all(&dir);
281    }
282}