feat(synth): Enhance 8-bit synthesizer with anti-aliasing and progress tracking
Browse filesThis commit introduces a major overhaul of the 8-bit synthesizer to significantly improve its audio quality and provide better user feedback during rendering.
The primary motivations were to reduce sonic harshness caused by digital aliasing and to offer real-time progress updates for a better user experience, especially on long tracks.
1. Advanced Anti-Aliasing and Audio Quality Engine:
Implemented a suite of optional, high-quality DSP features to produce a cleaner, less harsh sound. These are controlled by a new "Audio Quality & Anti-Aliasing" section in the UI.
**Additive Synthesis:** Added a high-quality (but CPU-intensive) band-limited waveform generator to eliminate aliasing at its source.
**Waveform Edge Smoothing:** A low-cost alternative that applies a configurable sub-millisecond smoothing filter to the edges of standard waveforms.
**Dynamic Harmonic Filtering:** A new frequency-dependent lowpass filter is applied to each note, intelligently removing excessive high-frequency harmonics while preserving the note's fundamental character.
**Improved Distortion and Noise:** The distortion algorithm is now a smoother soft-clipping function, and the noise generator includes a lowpass filter to soften its texture.
**Final Limiter:** A final gain stage with a soft limiter (`tanh`) is applied to prevent digital clipping and manage dynamics.
2. Note-Level Rendering Progress Bar:
The `synthesize_8bit_style` function has been refactored to provide detailed, real-time progress feedback.
The progress bar (`tqdm`) is now applied to the inner **note-processing loop** instead of the outer instrument loop.
This provides a smooth, granular progress update that accurately reflects the CPU workload, which is especially useful for MIDI files with thousands of notes but few instrument tracks.
The progress tracking system has been made robust to work seamlessly in both single-file and batch-processing modes.
165 unmodified lines16616716816917017117217317417517617780 unmodified lines2582592602612622632641 unmodified line2662672682692702715 unmodified lines2772782792802812822839 unmodified lines293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510411 unmodified lines922923924925926927928223 unmodified lines1152115311541155115611571158490 unmodified lines164916501651165216531654165595 unmodified lines17511752175317541755175625 unmodified lines1782178317841785178617871788178917901791179217931794179517961797179817991800757 unmodified lines2558255925602561256225632564227 unmodified lines27922793279427952796279718 unmodified lines281628172818281928202821108 unmodified lines293029312932293329342935165 unmodified liness8bit_echo_rate_hz: float = 5.0s8bit_echo_decay_factor: float = 0.6s8bit_echo_trigger_threshold: float = 2.5# =================================================================================================# === Helper Functions ===# =================================================================================================def prepare_soundfonts():"""Ensures a default set of SoundFonts are downloaded, then scans the 'src/sf2'80 unmodified lines# =================================================================================================# === 8-bit Style Synthesizer (Stereo Enabled) ===# =================================================================================================def synthesize_8bit_style(*, midi_data: pretty_midi.PrettyMIDI, fs: int, params: AppParameters):"""Synthesizes an 8-bit style audio waveform from a PrettyMIDI object.This function generates waveforms manually instead of using a synthesizer like FluidSynth.1 unmodified lineInstruments are panned based on their order in the MIDI file.Instrument 1 -> Left, Instrument 2 -> Right.Now supports graded levels for smoothing and vibrato continuity."""total_duration = midi_data.get_end_time()# Initialize a stereo waveform buffer (2 channels: Left, Right)5 unmodified linesosc_phase = {}# Vibrato phase trackingvibrato_phase = 0.0for i, instrument in enumerate(midi_data.instruments):# --- Panning Logic ---# Default to center-panned mono9 unmodified lineselif i == 1: # Rightpan_l, pan_r = 0.0, 1.0# Other instruments remain centeredosc_phase[i] = 0.0 # Independent phase tracking for each instrumentfor note in instrument.notes:freq = pretty_midi.note_number_to_hz(note.pitch)note_duration = note.end - note.startnum_samples = int(note_duration * fs)if num_samples <= 0:continuet = np.arange(num_samples) / fs# --- Graded Continuous Vibrato ---# This now interpolates between a fully reset vibrato and a fully continuous one.# Use accumulated phase to avoid vibrato reset per notevib_phase_inc = 2 * np.pi * params.s8bit_vibrato_rate / fsper_note_vib_phase = 2 * np.pi * params.s8bit_vibrato_rate * tcontinuous_vib_phase = vibrato_phase + np.arange(num_samples) * vib_phase_inc# Weighted average of the two phase typesfinal_vib_phase = (per_note_vib_phase * (1 - params.s8bit_continuous_vibrato_level) +continuous_vib_phase * params.s8bit_continuous_vibrato_level)vibrato_lfo = params.s8bit_vibrato_depth * np.sin(final_vib_phase)# Update the global vibrato phase for the next noteif num_samples > 0:vibrato_phase = (continuous_vib_phase[-1] + vib_phase_inc) % (2 * np.pi)# --- Waveform Generation with FM ---fm_lfo = params.s8bit_fm_modulation_depth * np.sin(2 * np.pi * params.s8bit_fm_modulation_rate * t)modulated_freq = freq * (1 + fm_lfo)# --- Waveform Generation (Main Oscillator with phase continuity) ---phase_inc = 2 * np.pi * (modulated_freq + vibrato_lfo) / fsphase = osc_phase[i] + np.cumsum(phase_inc)if num_samples > 0:osc_phase[i] = phase[-1] % (2 * np.pi) # Store last phaseif params.s8bit_waveform_type == 'Square':note_waveform = signal.square(phase, duty=params.s8bit_pulse_width)elif params.s8bit_waveform_type == 'Sawtooth':note_waveform = signal.sawtooth(phase)else: # Trianglenote_waveform = signal.sawtooth(phase, width=0.5)# --- Bass Boost (Sub-Octave Oscillator) ---if params.s8bit_bass_boost_level > 0:bass_freq = freq / 2.0# Only add bass if the frequency is reasonably audibleif bass_freq > 20:# Bass uses a simple square wave, no vibrato, for stabilitybass_phase_inc = 2 * np.pi * bass_freq / fsbass_phase = np.cumsum(np.full(num_samples, bass_phase_inc))bass_sub_waveform = signal.square(bass_phase, duty=0.5)# Mix the main and bass waveforms.# As bass level increases, slightly decrease main waveform volume to prevent clipping.main_level = 1.0 - (0.5 * params.s8bit_bass_boost_level)note_waveform = (note_waveform * main_level) + (bass_sub_waveform * params.s8bit_bass_boost_level)# --- Noise & Distortion Simulation (White Noise) ---if params.s8bit_noise_level > 0:note_waveform += np.random.uniform(-1, 1, num_samples) * params.s8bit_noise_level# --- Distortion (Wave Shaping) ---if params.s8bit_distortion_level > 0:# Using a tanh function for a smoother, "warmer" distortionnote_waveform = np.tanh(note_waveform * (1 + params.s8bit_distortion_level * 5))# --- ADSR Envelope ---start_amp = note.velocity / 127.0envelope = np.zeros(num_samples)if params.s8bit_envelope_type == 'Plucky (AD Envelope)':attack_samples = min(int(0.005 * fs), num_samples)# --- Adaptive Decay Logic ---# This ensures short staccato notes have the same initial decay rate# as long notes, fixing the perceived low volume issue.if params.s8bit_adaptive_decay:# 1. Calculate the "ideal" number of decay samples based on the user's setting.ideal_decay_samples = int(params.s8bit_decay_time_s * fs)if ideal_decay_samples <= 0:ideal_decay_samples = 1 # Avoid division by zero.# 2. Create the full, "ideal" decay curve from peak to zero.ideal_decay_curve = np.linspace(start_amp, 0, ideal_decay_samples)# 3. Determine how many decay samples can actually fit in this note's duration.actual_decay_samples = num_samples - attack_samplesif actual_decay_samples > 0:# 4. Take the initial part of the ideal curve, sized to fit the note.num_samples_to_take = min(len(ideal_decay_curve), actual_decay_samples)# Apply the attack portion.envelope[:attack_samples] = np.linspace(0, start_amp, attack_samples)# Apply the truncated decay curve.envelope[attack_samples : attack_samples + num_samples_to_take] = ideal_decay_curve[:num_samples_to_take]# --- Original Decay Logic (Fallback) ---else:decay_samples = min(int(params.s8bit_decay_time_s * fs), num_samples - attack_samples)envelope[:attack_samples] = np.linspace(0, start_amp, attack_samples)if decay_samples > 0:envelope[attack_samples:attack_samples+decay_samples] = np.linspace(start_amp, 0, decay_samples)else: # Sustainedenvelope = np.linspace(start_amp, 0, num_samples)# --- Hybrid Note Smoothing (Proportional with an Absolute Cap) ---# This improved logic calculates the fade duration as a percentage of the note's# length but caps it at a fixed maximum duration. This provides the best of both worlds:# it preserves volume on short notes while ensuring long notes have a crisp attack.if params.s8bit_smooth_notes_level > 0 and num_samples > 10:# 1. Define the maximum allowable fade time in seconds (e.g., 30ms).# This prevents fades from becoming too long on sustained notes.max_fade_duration_s = 0.03# 2. Calculate the proportional fade length based on the note's duration.# At level 1.0, this is 10% of the note's start and 10% of its end.fade_percentage = 0.1 * params.s8bit_smooth_notes_levelproportional_fade_samples = int(num_samples * fade_percentage)# 3. Calculate the absolute maximum fade length in samples.absolute_max_fade_samples = int(fs * max_fade_duration_s)# 4. The final fade_samples is the SMALLEST of the three constraints:# a) The proportional length.# b) The absolute maximum length.# c) Half the note's total length (to prevent overlap).fade_samples = min(proportional_fade_samples, absolute_max_fade_samples, num_samples // 2)if fade_samples > 0:# Apply a fade-in to the attack portion of the envelope.envelope[:fade_samples] *= np.linspace(0.5, 1.0, fade_samples)# Apply a fade-out to the tail portion of the envelope.envelope[-fade_samples:] *= np.linspace(1.0, 0.0, fade_samples)# Apply envelope to the (potentially combined) waveformnote_waveform *= envelope# =========================================================================# === Echo Sustain Logic for Long Plucky Notes (Now works correctly) ===# =========================================================================# This feature fills the silent tail of long notes with decaying echoes.# It is applied only for Plucky envelopes and after the main envelope has been applied.if params.s8bit_envelope_type == 'Plucky (AD Envelope)' and params.s8bit_echo_sustain and num_samples > 0:# The duration of the initial pluck is determined by its decay time.initial_pluck_duration_s = params.s8bit_decay_time_sinitial_pluck_samples = int(initial_pluck_duration_s * fs)# Check if the note is long enough to even need echoes.if num_samples > initial_pluck_samples * params.s8bit_echo_trigger_threshold: # Only trigger if there's significant empty space.# Calculate the properties of the echoes.echo_delay_samples = int(fs / params.s8bit_echo_rate_hz)if echo_delay_samples > 0: # Prevent infinite loopsecho_amplitude = start_amp * params.s8bit_echo_decay_factor# Start placing echoes after the first pluck has finished.current_sample_offset = initial_pluck_sampleswhile current_sample_offset < num_samples:# Ensure there's space for a new echo.if current_sample_offset + echo_delay_samples <= num_samples:# Create a very short, plucky envelope for the echo.echo_attack_samples = min(int(0.002 * fs), echo_delay_samples) # 2ms attackecho_decay_samples = echo_delay_samples - echo_attack_samplesif echo_decay_samples > 0:# Create the small echo envelope shape.echo_envelope = np.zeros(echo_delay_samples)echo_envelope[:echo_attack_samples] = np.linspace(0, echo_amplitude, echo_attack_samples)echo_envelope[echo_attack_samples:] = np.linspace(echo_amplitude, 0, echo_decay_samples)# Create a temporary waveform for the echo and apply the envelope.# It reuses the main note's frequency and oscillator phase.# Re-calculating phase here is simpler than tracking, for additive synthesisphase_inc_echo = 2 * np.pi * freq / fsphase_echo = np.cumsum(np.full(echo_delay_samples, phase_inc_echo))if params.s8bit_waveform_type == 'Square':echo_waveform_segment = signal.square(phase_echo, duty=params.s8bit_pulse_width)elif params.s8bit_waveform_type == 'Sawtooth':echo_waveform_segment = signal.sawtooth(phase_echo)else: # Triangleecho_waveform_segment = signal.sawtooth(phase_echo, width=0.5)# Add the enveloped echo on top of the already-enveloped main waveformnote_waveform[current_sample_offset : current_sample_offset + echo_delay_samples] += echo_waveform_segment * echo_envelope# Prepare for the next echo.echo_amplitude *= params.s8bit_echo_decay_factorcurrent_sample_offset += echo_delay_samples# --- END of Echo Sustain Logic ---start_sample = int(note.start * fs)end_sample = start_sample + num_samplesif end_sample > waveform.shape[1]:end_sample = waveform.shape[1]note_waveform = note_waveform[:end_sample-start_sample]# Add the mono note waveform to the stereo buffer with panningwaveform[0, start_sample:end_sample] += note_waveform * pan_lwaveform[1, start_sample:end_sample] += note_waveform * pan_rreturn waveform # Returns a (2, N) numpy array411 unmodified lines# === Stage 2: MIDI Transformation and Rendering Function ===# =================================================================================================def Render_MIDI(*, input_midi_path: str, params: AppParameters):"""Processes and renders a MIDI file according to user-defined settings.Can render using SoundFonts or a custom 8-bit synthesizer.223 unmodified linesmidi_data_for_synth = pretty_midi.PrettyMIDI(midi_to_render_path)# Synthesize the waveform# --- Passing new FX parameters to the synthesis function ---audio = synthesize_8bit_style(midi_data=midi_data_for_synth, fs=srate, params=params)# Normalize and prepare for Gradiopeak_val = np.max(np.abs(audio))if peak_val > 0:490 unmodified linesprint(f"Proceeding to render MIDI file: {os.path.basename(midi_path_for_rendering)}")# Call the rendering function, Pass dictionaries directly to Render_MIDIresults_tuple = Render_MIDI(input_midi_path=midi_path_for_rendering, params=params)# --- Final Audio Merging Logic ---stems_to_merge = []95 unmodified lines# === Gradio UI Wrappers ===# =================================================================================================# --- Thin wrapper for batch processing ---def batch_process_files(input_files, progress=gr.Progress(track_tqdm=True), *args):"""25 unmodified linesinput_path = file_obj.namefilename = os.path.basename(input_path)# --- Nested Progress Logic ---# Define a local function to scale the sub-progress of the pipeline# into the correct slot of the main batch progress bar.def batch_progress_updater(local_fraction, desc):# Calculate the overall progress based on which file we are on (i)# and the progress within that file (local_fraction).progress_per_file = 1 / total_filesoverall_fraction = (i / total_files) + (local_fraction * progress_per_file)progress(overall_fraction, desc=f"({i+1}/{total_files}) {filename}: {desc}")progress(i / total_files, desc=f"Processing {os.path.basename(input_path)} ({i+1}/{total_files})")# --- Pass the batch_timestamp to the pipeline ---results, _ = run_single_file_pipeline(input_path, batch_timestamp, copy.copy(params), progress=batch_progress_updater)if results:if results.get("final_audio_path"):757 unmodified linestranscribe_other_or_accompaniment = gr.Checkbox(label="Transcribe Accompaniment", value=True)gr.Markdown("#### 3. Audio Merging Targets")gr.Markdown("_Select which original stem(s) to re-merge with the final rendered audio._")with gr.Row():merge_vocals_to_render = gr.Checkbox(label="Merge Vocals", value=False)# These two will be hidden/shown dynamically227 unmodified lineslabel="FM Rate",info="Frequency Modulation speed. Low values create a slow 'wobble'. High values create fast modulation, resulting in bright, dissonant harmonics.")# This outer group ensures the checkbox and its settings are visually linked.with gr.Group():s8bit_echo_sustain = gr.Checkbox(18 unmodified lineslabel="Echo Trigger Threshold (x Decay Time)",info="Controls how long a note must be to trigger echoes. This value is a multiplier of the 'Decay Time'. Example: If 'Decay Time' is 0.1s and this threshold is set to 10.0, only notes longer than 1.0s (0.1 * 10.0) will produce echoes.")# Create a dictionary mapping key names to the actual Gradio componentsui_component_map = locals()108 unmodified linesinputs=[soundfont_bank] + all_settings_components,outputs=[preview_sf_player])# Launch the Gradio appapp.queue().launch(inbrowser=True, debug=True)165 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424580 unmodified lines3263273283293303313321 unmodified line3343353363373383393405 unmodified lines3463473483493503513523533543553563573589 unmodified lines368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641411 unmodified lines1053105410551056105710581059223 unmodified lines1283128412851286128712881289490 unmodified lines178017811782178317841785178695 unmodified lines1882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191325 unmodified lines193919401941194219431944194519461947194819491950195119521953195419551956757 unmodified lines2714271527162717271827192720272127222723272427252726227 unmodified lines295429552956295729582959296018 unmodified lines297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017108 unmodified lines312631273128312931303131313231333134313531363137165 unmodified liness8bit_echo_rate_hz: float = 5.0s8bit_echo_decay_factor: float = 0.6s8bit_echo_trigger_threshold: float = 2.5# --- Anti-Aliasing & Quality Parameters ---s8bit_enable_anti_aliasing: bool = True # Main toggle for all new quality featuress8bit_use_additive_synthesis: bool = False # High-quality but CPU-intensive waveform generations8bit_edge_smoothing_ms: float = 0.5 # Mild smoothing for standard waveforms (0 to disable)s8bit_noise_lowpass_hz: float = 9000.0 # Lowpass filter frequency for noises8bit_harmonic_lowpass_factor: float = 12.0 # Multiplier for frequency-dependent lowpass filters8bit_final_gain: float = 0.8 # Final gain/limiter level to prevent clipping# =================================================================================================# === Helper Functions ===# =================================================================================================def one_pole_lowpass(x, cutoff_hz, fs):"""Simple one-pole lowpass filter (causal), stable and cheap."""if cutoff_hz <= 0 or cutoff_hz >= fs/2:return xdt = 1.0 / fsrc = 1.0 / (2 * np.pi * cutoff_hz)alpha = dt / (rc + dt)y = np.empty_like(x)y[0] = alpha * x[0]for n in range(1, len(x)):y[n] = y[n-1] + alpha * (x[n] - y[n-1])return ydef smooth_square_or_saw(note_waveform, fs, smooth_ms=0.6):"""Short triangular smoothing to soften sharp edges (simple anti-alias-ish)."""if smooth_ms <= 0:return note_waveformkernel_len = max(1, int(fs * (smooth_ms/1000.0)))# triangular kernelk = np.convolve(np.ones(kernel_len), np.ones(kernel_len)) # triangle shape length=2*kernel_len-1k = k / k.sum()# pad and convolvey = np.convolve(note_waveform, k, mode='same')return ydef additive_bandlimited_waveform(wave_type, freq, t, fs, max_harmonics_cap=200):"""Simple additive band-limited generator:- saw: sum_{n=1..N} sin(2π n f t)/n- square: sum odd harmonics sin(2π n f t)/nN chosen so n*f < fs/2.This is heavier but yields much less aliasing."""nyq = fs / 2.0max_n = int(nyq // freq)if max_n < 1:return np.zeros_like(t)max_n = min(max_n, max_harmonics_cap)y = np.zeros_like(t)if wave_type == 'Sawtooth':# saw via Fourier seriesfor n in range(1, max_n + 1):y += np.sin(2*np.pi * n * freq * t) / n# normalization to [-1,1]y = - (2/np.pi) * yelse: # squaren = 1while n <= max_n:y += np.sin(2*np.pi * n * freq * t) / nn += 2y = (4/np.pi) * y# clip tiny numerical overshooty = np.clip(y, -1.0, 1.0)return ydef safe_tanh_distortion(x, strength):"""Milder soft clipping: scale then tanh, with adjustable drive."""# make strength between 0..1 typical; map to drive factordrive = 1.0 + strength * 4.0return np.tanh(x * drive) / np.tanh(drive)def prepare_soundfonts():"""Ensures a default set of SoundFonts are downloaded, then scans the 'src/sf2'80 unmodified lines# =================================================================================================# === 8-bit Style Synthesizer (Stereo Enabled) ===# =================================================================================================def synthesize_8bit_style(*, midi_data: pretty_midi.PrettyMIDI, fs: int, params: AppParameters, progress: gr.Progress = None):"""Synthesizes an 8-bit style audio waveform from a PrettyMIDI object.This function generates waveforms manually instead of using a synthesizer like FluidSynth.1 unmodified lineInstruments are panned based on their order in the MIDI file.Instrument 1 -> Left, Instrument 2 -> Right.Now supports graded levels for smoothing and vibrato continuity.This enhanced version includes advanced anti-aliasing and quality features to produce a cleaner, less harsh sound."""total_duration = midi_data.get_end_time()# Initialize a stereo waveform buffer (2 channels: Left, Right)5 unmodified linesosc_phase = {}# Vibrato phase trackingvibrato_phase = 0.0# Retrieve anti-aliasing settings, using getattr for backward compatibilityuse_aa = getattr(params, 's8bit_enable_anti_aliasing', False)# --- Move progress tracking to the note level ---# 1. First, collect all notes from all instruments into a single list.all_notes_with_instrument_info = []for i, instrument in enumerate(midi_data.instruments):# --- Panning Logic ---# Default to center-panned mono9 unmodified lineselif i == 1: # Rightpan_l, pan_r = 0.0, 1.0# Other instruments remain centered# Store each note along with its parent instrument index and panning infofor note in instrument.notes:all_notes_with_instrument_info.append({'note': note, 'instrument_index': i, 'pan_l': pan_l, 'pan_r': pan_r})# Initialize oscillator phase for each instrumentosc_phase[i] = 0.0 # Independent phase tracking for each instrument# 2. Create an iterable for the main note-processing loop.notes_iterable = all_notes_with_instrument_infototal_notes = len(notes_iterable)# 3. Wrap this new iterable with tqdm if a progress object is available.if progress and hasattr(progress, 'tqdm'):notes_iterable = progress.tqdm(notes_iterable,desc="Synthesizing Notes...",total=total_notes)# 4. The main loop now iterates over individual notes, not instruments.for item in notes_iterable:note = item['note']i = item['instrument_index']pan_l = item['pan_l']pan_r = item['pan_r']freq = pretty_midi.note_number_to_hz(note.pitch)note_duration = note.end - note.startnum_samples = int(note_duration * fs)if num_samples <= 0:continuet = np.arange(num_samples) / fs# --- Graded Continuous Vibrato ---# This now interpolates between a fully reset vibrato and a fully continuous one.# Use accumulated phase to avoid vibrato reset per notevib_phase_inc = 2 * np.pi * params.s8bit_vibrato_rate / fsper_note_vib_phase = 2 * np.pi * params.s8bit_vibrato_rate * tcontinuous_vib_phase = vibrato_phase + np.arange(num_samples) * vib_phase_inc# Weighted average of the two phase typesfinal_vib_phase = (per_note_vib_phase * (1 - params.s8bit_continuous_vibrato_level) +continuous_vib_phase * params.s8bit_continuous_vibrato_level)vibrato_lfo = params.s8bit_vibrato_depth * np.sin(final_vib_phase)# Update the global vibrato phase for the next noteif num_samples > 0:vibrato_phase = (continuous_vib_phase[-1] + vib_phase_inc) % (2 * np.pi)# --- Waveform Generation with FM ---fm_lfo = params.s8bit_fm_modulation_depth * np.sin(2 * np.pi * params.s8bit_fm_modulation_rate * t)modulated_freq = freq * (1 + fm_lfo)# --- Waveform Generation (with Anti-Aliasing options) ---use_additive = use_aa and getattr(params, 's8bit_use_additive_synthesis', False)if use_additive and params.s8bit_waveform_type in ['Square', 'Sawtooth']:note_waveform = additive_bandlimited_waveform(params.s8bit_waveform_type, freq, t, fs)else:# --- Waveform Generation (Main Oscillator with phase continuity) ---phase_inc = 2 * np.pi * (modulated_freq + vibrato_lfo) / fsphase = osc_phase[i] + np.cumsum(phase_inc)if num_samples > 0:osc_phase[i] = phase[-1] % (2 * np.pi) # Store last phaseif params.s8bit_waveform_type == 'Square':note_waveform = signal.square(phase, duty=params.s8bit_pulse_width)elif params.s8bit_waveform_type == 'Sawtooth':note_waveform = signal.sawtooth(phase)else: # Triangle (less prone to aliasing)note_waveform = signal.sawtooth(phase, width=0.5)if use_aa and params.s8bit_waveform_type in ['Square', 'Sawtooth']:edge_smooth_ms = getattr(params, 's8bit_edge_smoothing_ms', 0.5)note_waveform = smooth_square_or_saw(note_waveform, fs, smooth_ms=edge_smooth_ms)# --- Bass Boost (Sub-Octave Oscillator) ---if params.s8bit_bass_boost_level > 0:bass_freq = freq / 2.0# Only add bass if the frequency is reasonably audibleif bass_freq > 20:# Bass uses a simple square wave, no vibrato, for stabilitybass_phase_inc = 2 * np.pi * bass_freq / fsbass_phase = np.cumsum(np.full(num_samples, bass_phase_inc))bass_sub_waveform = signal.square(bass_phase, duty=0.5)# Mix the main and bass waveforms.# As bass level increases, slightly decrease main waveform volume to prevent clipping.main_level = 1.0 - (0.5 * params.s8bit_bass_boost_level)note_waveform = (note_waveform * main_level) + (bass_sub_waveform * params.s8bit_bass_boost_level)# --- Noise & Distortion (Reordered and Improved) ---if params.s8bit_noise_level > 0:raw_noise = np.random.uniform(-1, 1, num_samples) * params.s8bit_noise_levelif use_aa:noise_cutoff = getattr(params, 's8bit_noise_lowpass_hz', 9000.0)raw_noise = one_pole_lowpass(raw_noise, cutoff_hz=noise_cutoff, fs=fs)note_waveform += raw_noise# --- Distortion (Wave Shaping) ---if params.s8bit_distortion_level > 0:if use_aa:note_waveform = safe_tanh_distortion(note_waveform, params.s8bit_distortion_level)else: # Original harsher distortion# Using a tanh function for a smoother, "warmer" distortionnote_waveform = np.tanh(note_waveform * (1 + params.s8bit_distortion_level * 5))# --- ADSR Envelope Generation (with improvements) ---start_amp = note.velocity / 127.0envelope = np.zeros(num_samples)min_attack_s = 0.001 # 1 ms minimum attack to prevent clicksif params.s8bit_envelope_type == 'Plucky (AD Envelope)':attack_samples = max(int(min_attack_s * fs), min(int(0.005 * fs), num_samples))# --- Adaptive Decay Logic ---# This ensures short staccato notes have the same initial decay rate# as long notes, fixing the perceived low volume issue.if params.s8bit_adaptive_decay:# 1. Calculate the "ideal" number of decay samples based on the user's setting.ideal_decay_samples = int(params.s8bit_decay_time_s * fs)if ideal_decay_samples <= 0:ideal_decay_samples = 1 # Avoid division by zero.# 2. Create the full, "ideal" decay curve from peak to zero.ideal_decay_curve = np.linspace(start_amp, 0, ideal_decay_samples)# 3. Determine how many decay samples can actually fit in this note's duration.actual_decay_samples = num_samples - attack_samplesif actual_decay_samples > 0:# 4. Take the initial part of the ideal curve, sized to fit the note.num_samples_to_take = min(len(ideal_decay_curve), actual_decay_samples)# Apply the attack portion.envelope[:attack_samples] = np.linspace(0, start_amp, attack_samples)# Apply the truncated decay curve.envelope[attack_samples : attack_samples + num_samples_to_take] = ideal_decay_curve[:num_samples_to_take]# --- Original Decay Logic (Fallback) ---else:decay_samples = min(int(params.s8bit_decay_time_s * fs), num_samples - attack_samples)envelope[:attack_samples] = np.linspace(0, start_amp, attack_samples)if decay_samples > 0:envelope[attack_samples:attack_samples+decay_samples] = np.linspace(start_amp, 0, decay_samples)else: # Sustainedenvelope = np.linspace(start_amp, 0, num_samples)if use_aa and num_samples > 20: # Add a tiny release fade to prevent clicksrelease_samples = int(min(0.005*fs, num_samples // 10))if release_samples > 0:envelope[-release_samples:] *= np.linspace(1.0, 0.0, release_samples)# --- Hybrid Note Smoothing (Proportional with an Absolute Cap) ---# This improved logic calculates the fade duration as a percentage of the note's# length but caps it at a fixed maximum duration. This provides the best of both worlds:# it preserves volume on short notes while ensuring long notes have a crisp attack.if params.s8bit_smooth_notes_level > 0 and num_samples > 10:# 1. Define the maximum allowable fade time in seconds (e.g., 30ms).# This prevents fades from becoming too long on sustained notes.max_fade_duration_s = 0.03# 2. Calculate the proportional fade length based on the note's duration.# At level 1.0, this is 10% of the note's start and 10% of its end.fade_percentage = 0.1 * params.s8bit_smooth_notes_levelproportional_fade_samples = int(num_samples * fade_percentage)# 3. Calculate the absolute maximum fade length in samples.absolute_max_fade_samples = int(fs * max_fade_duration_s)# 4. The final fade_samples is the SMALLEST of the three constraints:# a) The proportional length.# b) The absolute maximum length.# c) Half the note's total length (to prevent overlap).fade_samples = min(proportional_fade_samples, absolute_max_fade_samples, num_samples // 2)if fade_samples > 0:# Apply a fade-in to the attack portion of the envelope.envelope[:fade_samples] *= np.linspace(0.5, 1.0, fade_samples)# Apply a fade-out to the tail portion of the envelope.envelope[-fade_samples:] *= np.linspace(1.0, 0.0, fade_samples)# Apply envelope to the (potentially combined) waveformnote_waveform *= envelope# =========================================================================# === Echo Sustain Logic for Long Plucky Notes (Now works correctly) ===# =========================================================================# This feature fills the silent tail of long notes with decaying echoes.# It is applied only for Plucky envelopes and after the main envelope has been applied.if params.s8bit_envelope_type == 'Plucky (AD Envelope)' and params.s8bit_echo_sustain and num_samples > 0:# The duration of the initial pluck is determined by its decay time.initial_pluck_duration_s = params.s8bit_decay_time_sinitial_pluck_samples = int(initial_pluck_duration_s * fs)# Check if the note is long enough to even need echoes.if num_samples > initial_pluck_samples * params.s8bit_echo_trigger_threshold: # Only trigger if there's significant empty space.# Calculate the properties of the echoes.echo_delay_samples = int(fs / params.s8bit_echo_rate_hz)if echo_delay_samples > 0: # Prevent infinite loopsecho_amplitude = start_amp * params.s8bit_echo_decay_factor# Start placing echoes after the first pluck has finished.current_sample_offset = initial_pluck_sampleswhile current_sample_offset < num_samples:# Ensure there's space for a new echo.if current_sample_offset + echo_delay_samples <= num_samples:# Create a very short, plucky envelope for the echo.echo_attack_samples = min(int(0.002 * fs), echo_delay_samples) # 2ms attackecho_decay_samples = echo_delay_samples - echo_attack_samplesif echo_decay_samples > 0:# Create the small echo envelope shape.echo_envelope = np.zeros(echo_delay_samples)echo_envelope[:echo_attack_samples] = np.linspace(0, echo_amplitude, echo_attack_samples)echo_envelope[echo_attack_samples:] = np.linspace(echo_amplitude, 0, echo_decay_samples)# Create a temporary waveform for the echo and apply the envelope.# It reuses the main note's frequency and oscillator phase.# Re-calculating phase here is simpler than tracking, for additive synthesisphase_inc_echo = 2 * np.pi * freq / fsphase_echo = np.cumsum(np.full(echo_delay_samples, phase_inc_echo))if params.s8bit_waveform_type == 'Square':echo_waveform_segment = signal.square(phase_echo, duty=params.s8bit_pulse_width)elif params.s8bit_waveform_type == 'Sawtooth':echo_waveform_segment = signal.sawtooth(phase_echo)else: # Triangleecho_waveform_segment = signal.sawtooth(phase_echo, width=0.5)# Add the enveloped echo on top of the already-enveloped main waveformnote_waveform[current_sample_offset : current_sample_offset + echo_delay_samples] += echo_waveform_segment * echo_envelope# Prepare for the next echo.echo_amplitude *= params.s8bit_echo_decay_factorcurrent_sample_offset += echo_delay_samples# --- END of Echo Sustain Logic ---# --- Final Processing Stage (Per-Note) ---if use_aa:# 1. Frequency-dependent lowpass filterharm_limit = getattr(params, 's8bit_harmonic_lowpass_factor', 12.0)cutoff = min(fs * 0.45, max(3000.0, freq * harm_limit))note_waveform = one_pole_lowpass(note_waveform, cutoff_hz=cutoff, fs=fs)# 2. Final Gain and Soft Limiterfinal_gain = getattr(params, 's8bit_final_gain', 0.8)note_waveform *= final_gainnote_waveform = np.tanh(note_waveform) # Soft clip/limit# --- Add to main waveform buffer ---start_sample = int(note.start * fs)end_sample = start_sample + num_samplesif end_sample > waveform.shape[1]:end_sample = waveform.shape[1]note_waveform = note_waveform[:end_sample-start_sample]# Add the mono note waveform to the stereo buffer with panningwaveform[0, start_sample:end_sample] += note_waveform * pan_lwaveform[1, start_sample:end_sample] += note_waveform * pan_rreturn waveform # Returns a (2, N) numpy array411 unmodified lines# === Stage 2: MIDI Transformation and Rendering Function ===# =================================================================================================def Render_MIDI(*, input_midi_path: str, params: AppParameters, progress: gr.Progress = None):"""Processes and renders a MIDI file according to user-defined settings.Can render using SoundFonts or a custom 8-bit synthesizer.223 unmodified linesmidi_data_for_synth = pretty_midi.PrettyMIDI(midi_to_render_path)# Synthesize the waveform# --- Passing new FX parameters to the synthesis function ---audio = synthesize_8bit_style(midi_data=midi_data_for_synth, fs=srate, params=params, progress=progress)# Normalize and prepare for Gradiopeak_val = np.max(np.abs(audio))if peak_val > 0:490 unmodified linesprint(f"Proceeding to render MIDI file: {os.path.basename(midi_path_for_rendering)}")# Call the rendering function, Pass dictionaries directly to Render_MIDIresults_tuple = Render_MIDI(input_midi_path=midi_path_for_rendering, params=params, progress=progress)# --- Final Audio Merging Logic ---stems_to_merge = []95 unmodified lines# === Gradio UI Wrappers ===# =================================================================================================class BatchProgressTracker:"""A custom progress tracker for batch processing that can update a mainprogress bar and also create its own tqdm-style sub-progress bars."""def __init__(self, main_progress: gr.Progress, total_files: int, current_file_index: int, filename: str):self._main_progress = main_progressself._total_files = total_filesself._current_file_index = current_file_indexself._filename = filenameself._progress_per_file = 1 / total_files if total_files > 0 else 0def __call__(self, local_fraction: float, desc: str = ""):"""Makes the object callable like a function for simple progress updates."""overall_fraction = (self._current_file_index / self._total_files) + (local_fraction * self._progress_per_file)full_desc = f"({self._current_file_index + 1}/{self._total_files}) {self._filename}: {desc}"# Update the main progress barself._main_progress(overall_fraction, desc=full_desc)def tqdm(self, iterable, desc="", total=None):"""Provides a tqdm method that delegates to the original gr.Progress object."""# The description for the sub-progress bartqdm_desc = f"({self._current_file_index + 1}/{self._total_files}) {self._filename}: {desc}"# Use the original gr.Progress object to create the tqdm iteratorreturn self._main_progress.tqdm(iterable, desc=tqdm_desc, total=total)# --- Thin wrapper for batch processing ---def batch_process_files(input_files, progress=gr.Progress(track_tqdm=True), *args):"""25 unmodified linesinput_path = file_obj.namefilename = os.path.basename(input_path)# --- Use the new BatchProgressTracker class ---# Instead of a simple function, create an instance of our tracker class.# This object can both update the main progress and has a .tqdm method.batch_progress_tracker = BatchProgressTracker(main_progress=progress,total_files=total_files,current_file_index=i,filename=filename)# --- Pass the batch_timestamp to the pipeline ---results, _ = run_single_file_pipeline(input_path, batch_timestamp, copy.copy(params), progress=batch_progress_tracker)if results:if results.get("final_audio_path"):757 unmodified linestranscribe_other_or_accompaniment = gr.Checkbox(label="Transcribe Accompaniment", value=True)gr.Markdown("#### 3. Audio Merging Targets")gr.Markdown("""_Select which **original, unprocessed** audio stems to merge back into the final output.This does **not** use the transcribed MIDI; it uses the raw audio from the initial separation.You can leave all boxes unchecked. This step only affects the final audio file, not the MIDI output._""")with gr.Row():merge_vocals_to_render = gr.Checkbox(label="Merge Vocals", value=False)# These two will be hidden/shown dynamically227 unmodified lineslabel="FM Rate",info="Frequency Modulation speed. Low values create a slow 'wobble'. High values create fast modulation, resulting in bright, dissonant harmonics.")# --- Echo Sustain Feature Block (Visually Grouped) ---# This outer group ensures the checkbox and its settings are visually linked.with gr.Group():s8bit_echo_sustain = gr.Checkbox(18 unmodified lineslabel="Echo Trigger Threshold (x Decay Time)",info="Controls how long a note must be to trigger echoes. This value is a multiplier of the 'Decay Time'. Example: If 'Decay Time' is 0.1s and this threshold is set to 10.0, only notes longer than 1.0s (0.1 * 10.0) will produce echoes.")# --- NEW: Accordion for Anti-Aliasing and Quality Settings ---with gr.Accordion("Audio Quality & Anti-Aliasing (Advanced)", open=False):s8bit_enable_anti_aliasing = gr.Checkbox(value=True,label="Enable All Audio Quality Enhancements",info="Master toggle for all settings below. Disabling may slightly speed up rendering but can result in harsher, more aliased sound.")with gr.Group(visible=True) as anti_aliasing_settings_box:s8bit_use_additive_synthesis = gr.Checkbox(value=False,label="Use Additive Synthesis (High Quality, High CPU)",info="Generates band-limited waveforms to drastically reduce aliasing (harshness). Slower to render but produces a much cleaner sound. Note: The other anti-aliasing settings below will still apply even if this is disabled.")s8bit_edge_smoothing_ms = gr.Slider(0.0, 2.0, value=0.5, step=0.1,label="Waveform Edge Smoothing (ms)",info="Applies a tiny blur to the sharp edges of standard Square/Sawtooth waves to reduce aliasing. A cheap and effective alternative to Additive Synthesis.")s8bit_noise_lowpass_hz = gr.Slider(1000, 20000, value=9000, step=500,label="Noise Lowpass Filter (Hz)",info="Applies a lowpass filter to the white noise, making it sound softer and less harsh. Lower values produce a 'darker' noise.")s8bit_harmonic_lowpass_factor = gr.Slider(4.0, 32.0, value=12.0, step=0.5,label="Harmonic Lowpass Factor",info="Controls a dynamic lowpass filter. The cutoff frequency is (Note Frequency * this factor). Lower values create a darker, more muted sound.")s8bit_final_gain = gr.Slider(0.1, 1.5, value=0.8, step=0.05,label="Final Gain / Limiter Level",info="A final volume adjustment before adding the sound to the mix. Values > 1.0 can introduce soft clipping (distortion).")# Create a dictionary mapping key names to the actual Gradio componentsui_component_map = locals()108 unmodified linesinputs=[soundfont_bank] + all_settings_components,outputs=[preview_sf_player])# Event listener for the new Anti-Aliasing settings boxs8bit_enable_anti_aliasing.change(fn=lambda x: gr.update(visible=x),inputs=s8bit_enable_anti_aliasing,outputs=anti_aliasing_settings_box)# Launch the Gradio appapp.queue().launch(inbrowser=True, debug=True)