|
| 1 | +"""Vocoder Adapter Node |
| 2 | +
|
| 3 | +This node is a minimal adapter to help feed Ace-Step latents or decoded audio into a vocoder. |
| 4 | +It tries to detect the expected input type of the provided vocoder object and calls the right API. |
| 5 | +Supported flows: |
| 6 | +- Latent -> VAE -> waveform -> mel -> vocoder |
| 7 | +- Latent -> mel (if latent appears to be mel) -> vocoder |
| 8 | +- Clean waveform -> vocoder (if vocoder expects waveform for final polish) |
| 9 | +
|
| 10 | +Notes: |
| 11 | +- Vocoder objects must be Python objects exposed to ComfyUI nodes (i.e., selected via a model node). |
| 12 | +- The node supports `mel_transform` using `librosa` if present, otherwise uses Torch-based mel filter. |
| 13 | +""" |
| 14 | +import logging |
| 15 | +import torch |
| 16 | +import numpy as np |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +class AceStepVocoderAdapter: |
| 22 | + @classmethod |
| 23 | + def INPUT_TYPES(cls): |
| 24 | + return { |
| 25 | + "required": { |
| 26 | + "vocoder": ("MODEL",), |
| 27 | + "vae": ("VAE",), |
| 28 | + "latent": ("LATENT",), |
| 29 | + }, |
| 30 | + "optional": { |
| 31 | + "sample_rate": ("INT", {"default": 44100}), |
| 32 | + "n_mels": ("INT", {"default": 128}), |
| 33 | + "n_fft": ("INT", {"default": 2048}), |
| 34 | + "hop_length": ("INT", {"default": 512}), |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + RETURN_TYPES = ("AUDIO",) |
| 39 | + RETURN_NAMES = ("audio",) |
| 40 | + FUNCTION = "adapt" |
| 41 | + CATEGORY = "JK AceStep Nodes/Vocoder" |
| 42 | + |
| 43 | + def _to_mel_torch(self, waveform, sr=44100, n_fft=2048, hop=512, n_mels=128): |
| 44 | + # waveform: [B, C, T] or [T] |
| 45 | + import torch.nn.functional as F |
| 46 | + if waveform.dim() == 3: |
| 47 | + wav = waveform[:, 0] |
| 48 | + elif waveform.dim() == 2: |
| 49 | + wav = waveform[:, 0] |
| 50 | + else: |
| 51 | + wav = waveform.unsqueeze(0) |
| 52 | + try: |
| 53 | + import torchaudio |
| 54 | + mel_spec = torchaudio.transforms.MelSpectrogram(sample_rate=sr, n_fft=n_fft, hop_length=hop, n_mels=n_mels)(wav) |
| 55 | + log_mel = torch.log(torch.clamp(mel_spec, 1e-9)) |
| 56 | + return log_mel |
| 57 | + except Exception: |
| 58 | + # Lowest-effort fallback: compute STFT magnitude and map bins |
| 59 | + stft = torch.stft(wav, n_fft=n_fft, hop_length=hop, return_complex=True) |
| 60 | + mag = torch.abs(stft) |
| 61 | + # naive spectral-to-mel via linear downsampling |
| 62 | + mel = F.interpolate(mag.unsqueeze(1), size=n_mels, mode='linear').squeeze(1) |
| 63 | + return torch.log(torch.clamp(mel, 1e-9)) |
| 64 | + |
| 65 | + def adapt(self, vocoder, vae, latent, sample_rate=44100, n_mels=None, n_fft=2048, hop_length=512): |
| 66 | + # optional parameters set by node UI can be passed through **kwargs later |
| 67 | + # Try to introspect vocoder for n_mels/hop_length/etc |
| 68 | + if n_mels is None: |
| 69 | + n_mels = getattr(vocoder, 'n_mels', None) |
| 70 | + if n_mels is None and hasattr(vocoder, 'config') and getattr(vocoder.config, 'n_mels', None) is not None: |
| 71 | + n_mels = vocoder.config.n_mels |
| 72 | + if n_mels is None: |
| 73 | + n_mels = 128 |
| 74 | + n_fft = getattr(vocoder, 'n_fft', n_fft) |
| 75 | + hop = getattr(vocoder, 'hop_length', hop_length) |
| 76 | + # Step 1: If 'latent' is a dict and contains 'samples', try decode |
| 77 | + audio_wave = None |
| 78 | + if isinstance(latent, dict) and 'samples' in latent: |
| 79 | + try: |
| 80 | + audio_wave = vae.decode(latent['samples']).movedim(-1, 1) |
| 81 | + except Exception as e: |
| 82 | + logger.warning(f"VAE decode failed: {e}") |
| 83 | + audio_wave = None |
| 84 | + |
| 85 | + # Step 1b: If the latent seems to be mel already (many vocoders expect mel) |
| 86 | + latent_is_mel = False |
| 87 | + if isinstance(latent, dict) and 'samples' in latent: |
| 88 | + samples = latent['samples'] |
| 89 | + # Heuristic: if last frequency dim is <= n_mels and reasonably small, it's probably a mel |
| 90 | + if samples.dim() == 4 and samples.shape[-1] <= max(128, n_mels): |
| 91 | + latent_is_mel = True |
| 92 | + elif samples.dim() == 3 and samples.shape[1] == n_mels: |
| 93 | + latent_is_mel = True |
| 94 | + |
| 95 | + # Step 2: Form mel if needed |
| 96 | + mel = None |
| 97 | + if latent_is_mel: |
| 98 | + samples = latent['samples'] |
| 99 | + if samples.dim() == 4: |
| 100 | + # [B, C, T, F] -> collapse C by mean -> [B, T, F], then permute to [B, F, T] |
| 101 | + mel = samples.mean(dim=1).permute(0, 2, 1) |
| 102 | + # interpolate frequencies to n_mels if different |
| 103 | + if mel.shape[1] != n_mels: |
| 104 | + mel = torch.nn.functional.interpolate(mel.unsqueeze(1), size=(n_mels, mel.shape[2]), mode='bilinear', align_corners=False).squeeze(1) |
| 105 | + elif samples.dim() == 3: |
| 106 | + # [B, C, T] - assume channel dim is n_mels |
| 107 | + if samples.shape[1] != n_mels: |
| 108 | + mel = torch.nn.functional.interpolate(samples.unsqueeze(1), size=(n_mels, samples.shape[2]), mode='bilinear', align_corners=False).squeeze(1) |
| 109 | + else: |
| 110 | + mel = samples |
| 111 | + else: |
| 112 | + mel = samples |
| 113 | + elif audio_wave is not None: |
| 114 | + # if needed, resample audio to vocoder sampling rate |
| 115 | + vocoder_sr = getattr(vocoder, 'sampling_rate', getattr(vocoder, 'sample_rate', sample_rate)) |
| 116 | + if audio_wave is not None and hasattr(audio_wave, 'shape') and int(vocoder_sr) != int(sample_rate): |
| 117 | + try: |
| 118 | + import torchaudio |
| 119 | + resampler = torchaudio.transforms.Resample(orig_freq=int(sample_rate), new_freq=int(vocoder_sr)) |
| 120 | + audio_wave = resampler(audio_wave) |
| 121 | + sample_rate = int(vocoder_sr) |
| 122 | + except Exception: |
| 123 | + # fallback: log warning and continue |
| 124 | + logger.warning('Resample failed: torchaudio not available or error during resample') |
| 125 | + mel = self._to_mel_torch(audio_wave, sr=sample_rate, n_fft=n_fft, hop=hop, n_mels=n_mels) |
| 126 | + else: |
| 127 | + # last resort: try using the latent values collapsed |
| 128 | + try: |
| 129 | + s = latent['samples'] |
| 130 | + mel = s.mean(dim=1) if s.dim() >= 4 else s |
| 131 | + except Exception as e: |
| 132 | + logger.error(f"Failed to derive mel: {e}") |
| 133 | + raise RuntimeError("Unable to derive mel from latent") |
| 134 | + |
| 135 | + # Step 3: Try call the vocoder |
| 136 | + if mel is None: |
| 137 | + raise RuntimeError('Failed to produce mel for vocoder input') |
| 138 | + |
| 139 | + # Many vocoders accept (batch, n_mels, T) or (n_mels, T) |
| 140 | + if mel.dim() == 2: |
| 141 | + batched = mel.unsqueeze(0) |
| 142 | + else: |
| 143 | + batched = mel |
| 144 | + |
| 145 | + # Try common method names |
| 146 | + # Several vocoders expect inputs with log mel spec shape [B, n_mels, T] |
| 147 | + # If mel is not yet log-scaled, apply log |
| 148 | + try: |
| 149 | + if batched.min() >= 0: |
| 150 | + batched = torch.log(torch.clamp(batched, min=1e-9)) |
| 151 | + except Exception: |
| 152 | + pass |
| 153 | + |
| 154 | + if hasattr(vocoder, 'infer'): |
| 155 | + try: |
| 156 | + out = vocoder.infer(batched) |
| 157 | + return ({'waveform': out, 'sample_rate': sample_rate},) |
| 158 | + except Exception as e: |
| 159 | + logger.warning(f"vocoder.infer() failed: {e}") |
| 160 | + if hasattr(vocoder, 'synthesize'): |
| 161 | + try: |
| 162 | + out = vocoder.synthesize(batched) |
| 163 | + return ({'waveform': out, 'sample_rate': sample_rate},) |
| 164 | + except Exception as e: |
| 165 | + logger.warning(f"vocoder.synthesize() failed: {e}") |
| 166 | + if hasattr(vocoder, 'decode'): |
| 167 | + try: |
| 168 | + out = vocoder.decode(batched) |
| 169 | + return ({'waveform': out, 'sample_rate': sample_rate},) |
| 170 | + except Exception as e: |
| 171 | + logger.warning(f"vocoder.decode() failed: {e}") |
| 172 | + |
| 173 | + # If vocoder is a function, call it directly |
| 174 | + if callable(vocoder): |
| 175 | + try: |
| 176 | + out = vocoder(batched) |
| 177 | + return ({'waveform': out, 'sample_rate': sample_rate},) |
| 178 | + except Exception as e: |
| 179 | + logger.warning(f"vocoder callable failed: {e}") |
| 180 | + |
| 181 | + logger.error('No known vocoder API found. Please use a vocoder object exposing infer/synthesize/decode or pass a callable.') |
| 182 | + raise RuntimeError('Unsupported vocoder object') |
| 183 | + |
| 184 | + |
| 185 | +NODE_CLASS_MAPPINGS = { |
| 186 | + 'AceStepVocoderAdapter': AceStepVocoderAdapter, |
| 187 | +} |
| 188 | + |
| 189 | +NODE_DISPLAY_NAMES = { |
| 190 | + 'AceStepVocoderAdapter': 'Ace-Step Vocoder Adapter', |
| 191 | +} |
0 commit comments