|
| 1 | +""" |
| 2 | +MIDI Channel Pool Manager. |
| 3 | +
|
| 4 | +MIDI has 16 channels (0-15). Channel 9 is reserved for percussion |
| 5 | +per General MIDI specification. This module manages channel allocation |
| 6 | +to prevent channel overflow and ensure correct drum channel usage. |
| 7 | +""" |
| 8 | + |
| 9 | +from typing import Set, Dict, Optional |
| 10 | + |
| 11 | + |
| 12 | +class ChannelExhaustedError(Exception): |
| 13 | + """Raised when no MIDI channels are available for allocation.""" |
| 14 | + pass |
| 15 | + |
| 16 | + |
| 17 | +class ChannelPool: |
| 18 | + """ |
| 19 | + Manages MIDI channel allocation for instruments. |
| 20 | +
|
| 21 | + MIDI has 16 channels (0-15). Channel 9 is reserved for percussion |
| 22 | + per General MIDI specification. This pool manages melodic channel |
| 23 | + allocation and provides the drum channel separately. |
| 24 | +
|
| 25 | + Example: |
| 26 | + >>> pool = ChannelPool() |
| 27 | + >>> piano_ch = pool.allocate("Piano") # Returns 0 |
| 28 | + >>> bass_ch = pool.allocate("Bass") # Returns 1 |
| 29 | + >>> drums_ch = pool.allocate_drums() # Returns 9 |
| 30 | + >>> pool.release("Piano") # Channel 0 available again |
| 31 | + """ |
| 32 | + |
| 33 | + DRUM_CHANNEL = 9 |
| 34 | + MAX_CHANNELS = 16 |
| 35 | + MELODIC_CHANNELS = set(range(MAX_CHANNELS)) - {DRUM_CHANNEL} |
| 36 | + |
| 37 | + def __init__(self): |
| 38 | + """Initialize the channel pool with all melodic channels available.""" |
| 39 | + self._available: Set[int] = self.MELODIC_CHANNELS.copy() |
| 40 | + self._allocated: Dict[str, int] = {} # instrument_name -> channel |
| 41 | + self._drums_allocated: bool = False |
| 42 | + |
| 43 | + def allocate(self, instrument_name: str) -> int: |
| 44 | + """ |
| 45 | + Allocate a channel for an instrument. |
| 46 | +
|
| 47 | + If the instrument has already been allocated a channel, returns |
| 48 | + the same channel (idempotent). |
| 49 | +
|
| 50 | + Args: |
| 51 | + instrument_name: Unique name/identifier for the instrument. |
| 52 | +
|
| 53 | + Returns: |
| 54 | + Channel number (0-15, excluding 9). |
| 55 | +
|
| 56 | + Raises: |
| 57 | + ChannelExhaustedError: If all 15 melodic channels are in use. |
| 58 | +
|
| 59 | + Example: |
| 60 | + >>> pool = ChannelPool() |
| 61 | + >>> pool.allocate("Acoustic Grand Piano") |
| 62 | + 0 |
| 63 | + >>> pool.allocate("Electric Bass") |
| 64 | + 1 |
| 65 | + """ |
| 66 | + # Return existing allocation if instrument already has a channel |
| 67 | + if instrument_name in self._allocated: |
| 68 | + return self._allocated[instrument_name] |
| 69 | + |
| 70 | + if not self._available: |
| 71 | + raise ChannelExhaustedError( |
| 72 | + f"All {len(self.MELODIC_CHANNELS)} melodic channels exhausted. " |
| 73 | + f"MIDI supports max 15 melodic instruments + 1 drum channel. " |
| 74 | + f"Currently allocated: {list(self._allocated.keys())}" |
| 75 | + ) |
| 76 | + |
| 77 | + # Prefer lower channels for predictability |
| 78 | + channel = min(self._available) |
| 79 | + self._available.remove(channel) |
| 80 | + self._allocated[instrument_name] = channel |
| 81 | + return channel |
| 82 | + |
| 83 | + def allocate_drums(self) -> int: |
| 84 | + """ |
| 85 | + Return the drum channel (always 9). |
| 86 | +
|
| 87 | + The drum channel is separate from the melodic pool and can be |
| 88 | + allocated independently. |
| 89 | +
|
| 90 | + Returns: |
| 91 | + The drum channel (9). |
| 92 | +
|
| 93 | + Example: |
| 94 | + >>> pool = ChannelPool() |
| 95 | + >>> pool.allocate_drums() |
| 96 | + 9 |
| 97 | + """ |
| 98 | + self._drums_allocated = True |
| 99 | + return self.DRUM_CHANNEL |
| 100 | + |
| 101 | + def release(self, instrument_name: str) -> None: |
| 102 | + """ |
| 103 | + Release a channel back to the pool. |
| 104 | +
|
| 105 | + Args: |
| 106 | + instrument_name: The instrument to release. |
| 107 | +
|
| 108 | + Note: |
| 109 | + Releasing an unallocated instrument is a no-op. |
| 110 | + """ |
| 111 | + if instrument_name in self._allocated: |
| 112 | + channel = self._allocated.pop(instrument_name) |
| 113 | + self._available.add(channel) |
| 114 | + |
| 115 | + def release_drums(self) -> None: |
| 116 | + """Release the drum channel.""" |
| 117 | + self._drums_allocated = False |
| 118 | + |
| 119 | + def get_channel(self, instrument_name: str) -> Optional[int]: |
| 120 | + """ |
| 121 | + Get the channel allocated to an instrument without allocating. |
| 122 | +
|
| 123 | + Args: |
| 124 | + instrument_name: The instrument to look up. |
| 125 | +
|
| 126 | + Returns: |
| 127 | + The channel number, or None if not allocated. |
| 128 | + """ |
| 129 | + return self._allocated.get(instrument_name) |
| 130 | + |
| 131 | + def is_allocated(self, instrument_name: str) -> bool: |
| 132 | + """Check if an instrument has been allocated a channel.""" |
| 133 | + return instrument_name in self._allocated |
| 134 | + |
| 135 | + def is_drums_allocated(self) -> bool: |
| 136 | + """Check if the drum channel has been allocated.""" |
| 137 | + return self._drums_allocated |
| 138 | + |
| 139 | + @property |
| 140 | + def available_count(self) -> int: |
| 141 | + """Number of melodic channels still available.""" |
| 142 | + return len(self._available) |
| 143 | + |
| 144 | + @property |
| 145 | + def allocated_count(self) -> int: |
| 146 | + """Number of melodic channels currently allocated.""" |
| 147 | + return len(self._allocated) |
| 148 | + |
| 149 | + @property |
| 150 | + def allocated_instruments(self) -> Dict[str, int]: |
| 151 | + """Copy of the instrument -> channel mapping.""" |
| 152 | + return self._allocated.copy() |
| 153 | + |
| 154 | + def reset(self) -> None: |
| 155 | + """Reset the pool to initial state (all channels available).""" |
| 156 | + self._available = self.MELODIC_CHANNELS.copy() |
| 157 | + self._allocated.clear() |
| 158 | + self._drums_allocated = False |
| 159 | + |
| 160 | + def __repr__(self) -> str: |
| 161 | + return ( |
| 162 | + f"ChannelPool(available={self.available_count}, " |
| 163 | + f"allocated={self.allocated_count}, " |
| 164 | + f"drums={'allocated' if self._drums_allocated else 'free'})" |
| 165 | + ) |
0 commit comments